sim_telarray#

Support modules for running sim_telarray. Model parameters are exported to sim_telarray configuration files; importing model parameters from sim_telarray configuration files is not supported.

bias-curve-generator#

Generate bias curves from NSB and proton trigger rates.

simtel.bias_curve_generator.generate_bias_curves(args, context=None)[source]#

Generate bias curves from NSB/proton reduced event-data HDF5 files.

nsb-trigger-calculator#

Calculate NSB trigger rates from reduced event-data HDF5 files.

simtel.nsb_trigger_calculator.calculate_statistics(grouped_data, time_window)[source]#

Calculate statistics for each threshold.

Parameters:
grouped_datadict

Data grouped by threshold and run.

time_windowfloat, optional

Time window per event in seconds.

Returns:
dict

Statistics for each threshold with keys: - ‘runs’: dict of {run_number: triggers} - ‘total_triggers’: sum of all triggers - ‘total_events’: sum of all events - ‘time_s’: total time in seconds - ‘rate_hz’: trigger rate in Hz - ‘rate_khz’: trigger rate in kHz - ‘error_hz’: exposure-weighted standard error of run rates in Hz - ‘num_runs’: number of runs

simtel.nsb_trigger_calculator.derive_nsb_triggers(args)[source]#

Derive NSB trigger rates from reduced event-data HDF5 files.

Parameters:
argsdict

Configuration parameters with keys: - root_dir: Root directory to search for reduced event-data HDF5 files - pattern: Glob pattern for HDF5 files, default: *.reduced_event_data.hdf5 - output: Output ECSV file path (optional, if None, no file is written) - time_window: Time window per event in seconds (required; telescope-dependent) - verbose: Enable verbose logging (optional)

Returns:
dict

Statistics dictionary with threshold as keys, containing: - rate_hz: trigger rate in Hz - rate_khz: trigger rate in kHz - error_hz: standard error in Hz - total_triggers: total number of triggers - num_runs: number of runs

Raises:
FileNotFoundError

If root directory doesn’t exist or no matching HDF5 files are found.

ValueError

If time_window is missing/invalid or if no files could be parsed successfully.

simtel.nsb_trigger_calculator.extract_run_number(file_path)[source]#

Extract run number from the FILE_INFO table in the HDF5 file.

simtel.nsb_trigger_calculator.extract_threshold(file_path)[source]#

Extract threshold from the FILE_INFO table in the HDF5 file.

simtel.nsb_trigger_calculator.find_hdf5_files(root_dir, pattern='*.reduced_event_data.hdf5')[source]#

Recursively find reduced event-data HDF5 files matching the pattern.

simtel.nsb_trigger_calculator.generate_ecsv_output(statistics, output_file, time_window)[source]#

Generate ECSV table from statistics.

Parameters:
statisticsdict

Statistics dictionary from calculate_statistics().

output_filePath or str

Output file path for ECSV table.

time_windowfloat, optional

Time window per event in seconds for metadata.

simtel.nsb_trigger_calculator.group_by_threshold_and_run(data)[source]#

Organize parsed data into a structure grouped by threshold and run.

Parameters:
datalist of dict

List of parsed HDF5 file data.

Returns:
dict

Nested dictionary: {threshold: {run: {‘triggers’: int, ‘events’: int}}}

simtel.nsb_trigger_calculator.parse_nsb_hdf5_file(file_path)[source]#

Parse one NSB reduced event-data HDF5 file.

Parameters:
file_pathPath or str

Path to the HDF5 file.

Returns:
dict or None

Dictionary with keys: ‘run’, ‘threshold’, ‘triggers’, ‘events’, ‘file_path’. Returns None if critical information cannot be extracted.

simtel.nsb_trigger_calculator.parse_nsb_hdf5_files(file_list)[source]#

Parse multiple NSB reduced event-data HDF5 files.

Parameters:
file_listlist of Path

List of HDF5 file paths to parse.

Returns:
list of dict

List of parsed data dictionaries. Failed parses are excluded.

Raises:
ValueError

If no files could be parsed successfully.

simtel_config_writer#

Configuration file writer for sim_telarray.

class simtel.simtel_config_writer.SimtelConfigWriter(site, model_version, layout_name=None, telescope_model_name=None, telescope_design_model=None, label=None, model_reader=None, context=None)[source]#

SimtelConfigWriter writes sim_telarray configuration files.

It is designed to be used by model classes (TelescopeModel and ArrayModel) only.

Parameters:
site: str

South or North.

model_version: str

Model version.

telescope_model_name: str

Telescope model name.

layout_name: str

Layout name.

label: str

Instance label. Important for output file naming.

property label#

Return the label used for generated configuration files.

write_array_config_file(config_file_path, telescope_model, site_model, additional_metadata=None)[source]#

Write the sim_telarray config file for an array of telescopes.

Parameters:
config_file_path: str or Path

Path of the file to write on.

telescope_model: dict of TelescopeModel

Dictionary of TelescopeModel’s instances as used by the ArrayModel instance.

site_model: Site model

Site model.

additional_metadata: dict

Dictionary with additional metadata to include.

Raises:
FileExistsError

If the config file already exists.

write_dummy_telescope_configuration_file(parameters, config_file_path, telescope_name)[source]#

Write ‘dummy’ telescope configuration file used as zeroth telescope in sim_telarray.

Replaces key telescope configuration values with dummy values.

Parameters:
parameters: dict

Telescope parameters used as template.

config_file_path: str or Path

Path of the dummy configuration file to write on.

telescope_name: str

Name of the telescope.

write_single_mirror_list_file(mirror_number, mirrors, single_mirror_list_file, set_focal_length_to_zero=False)[source]#

Write the sim_telarray mirror list file for a single mirror.

Parameters:
mirror_number: int

Mirror number.

mirrors: Mirrors

Instance of Mirrors.

single_mirror_list_file: str or Path

Path of the file to write on.

set_focal_length_to_zero: bool

Flag to set the focal length to zero.

write_telescope_config_file(config_file_path, parameters, telescope_name=None, telescope_design_model=None)[source]#

Write the sim_telarray config file for a single telescope.

Parameters:
config_file_path: str or Path

Path of the file to write on.

parameters: dict

Model parameters

telescope_name: str

Name of the telescope (use self._telescope_model_name if None)

telescope_design_model: str

Telescope design model.

sim_telarray_metadata#

The CTAO DataProducts metadata bridge maps resolved production settings to the installed model’s FITS keywords; the module also validates sim_telarray metadata against the meta-parameter registry.

sim_telarray metadata: CTAO FITS metadata builder and meta-parameter registry validation.

simtel.sim_telarray_metadata.get_ctao_metadata_registry()[source]#

Build validator definitions from the installed model’s FITS serialization.

simtel.sim_telarray_metadata.get_ctao_simtel_metadata(args, site_model=None, created=None)[source]#

Build CTAO metadata for a sim_telarray configuration.

Parameters:
argsdict

Resolved simulation arguments.

site_modelModelParameter, optional

Site model providing the NSB scaling factor when args does not override it.

createdastropy.time.Time, optional

Timestamp used for the product creation and activity start fields.

Returns:
dict

FITS keywords and serialized values ready for sim_telarray metaparam lines.

simtel.sim_telarray_metadata.get_meta_parameter_registry(schema_version=None, validate=True, source_type='all')[source]#

Return the expanded sim_telarray meta-parameter registry.

Parameters:
schema_versionstr, optional

Version of the registry schema to load.

validatebool, optional

Whether to validate the loaded registry against the metaschema.

source_typestr, optional

Metadata source filter: all, generated, model_parameter, or ctao_datamodel.

simtel.sim_telarray_metadata.validate_metadata(meta_parameters)[source]#

Validate emitted sim_telarray metadata lines against the registry.

Parameters:
meta_parameterslist of str

Emitted sim_telarray metadata lines.

simtel.sim_telarray_metadata.validate_metadata_values(metadata)[source]#

Validate known decoded sim_telarray metadata values against the registry.

Parameters:
metadatadict

Decoded sim_telarray metadata values, keyed by emitted name.

metadata_reader#

Read sim_telarray metadata as format-neutral input-metadata fields.

simtel.metadata_reader.read_metadata(metadata_file_name)[source]#

Return input-metadata fields of a sim_telarray file (see MetadataCollector).

simtel_seeds#

Seeds for sim_telarray simulations.

class simtel.simtel_seeds.SimtelSeeds(output_path=None, site=None, model_version=None, zenith_angle=None, azimuth_angle=None, context=None)[source]#

Manage seeds for sim_telarray simulations.

initialize_seeds(site, model_version, zenith_angle, azimuth_angle)[source]#

Initialize seeds based on provided parameters.

simtel.simtel_seeds.instance_seed_pairs(instances=1, context=None)[source]#

Instrument and simulation seed of each random instrument instance.

Uses the configured instrument_seed and simulation_seed (two values: instrument and simulation seed, for testing); seeds not configured are drawn at random. A single instance uses the seeds themselves, more instances derive theirs from them (as the instrument seed file does). Used by both ray-tracing backends.

Parameters:
instancesint

Number of random instrument instances.

Returns:
list of tuple of int

(instrument seed, simulation seed) of each instance.

segmentation#

sim_telarray segmentation serializer and historical-file adapter.

simtel.segmentation.write_mirror_segmentation(records, output_path, parameter_name, schema_version)[source]#

Serialize validated segmentation records in sim_telarray syntax.

photon_bunch_file#

Photon bunch files for sim_telarray (CORSIKA IACT EventIO format).

sim_telarray reads Cherenkov photons as photon bunches in the EventIO format of the CORSIKA IACT interface. This module writes such files for light that simtools makes itself (e.g. calibration light traced by obdeect), with the minimal set of objects sim_telarray needs, filled as the sim_telarray LightEmission programs (ff-1m, xyzls) fill them for artificial light.

One telescope at the origin of the array frame; one photon bunch object per event. camera_bunches hands photons at the camera entrance to sim_telarray with its optics bypassed (Bypass_Optics).

simtel.photon_bunch_file.bypass_optics_level(dual_mirror)[source]#

Return the sim_telarray Bypass_Optics value for photons at the camera entrance.

simtel.photon_bunch_file.camera_bunches(photons, *, dual_mirror, emission_altitude_m, camera_rotation_deg=0.0)[source]#

Photon bunches of photons at the camera entrance, for sim_telarray with its optics bypassed.

The photons cross the camera plane (through the focal-surface vertex, normal to the optical axis) in the telescope frame (+z along the optical axis, towards the sky).

  • Single-mirror telescopes (Bypass_Optics=1): sim_telarray reads a bunch (x, y) as the camera position M (x, y) with M = [[cos r, -sin r], [-sin r, -cos r]] (camera rotation r), whereas its own optics give R(-r) (x, y) of the telescope frame. Since M R(-r) = diag(1, -1), the telescope frame is turned by pi about x, for any camera rotation: (x, y, z) -> (x, -y, -z).

  • Dual-mirror telescopes (Bypass_Optics=2): sim_telarray reads bunches in its camera frame, the telescope frame rotated by r about the optical axis; the light travels to -z.

Parameters:
photons: dict

position_m (n, 2 or 3), direction (n, 3), time_ns, weight and wavelength_nm of the photons.

dual_mirror: bool

Dual-mirror telescope.

emission_altitude_m: float or numpy.ndarray

Altitude a.s.l. sim_telarray takes as the emission point.

camera_rotation_deg: float

Camera rotation (dual-mirror telescopes) [deg].

Returns:
numpy.ndarray

Photon bunches (BUNCH_DTYPE); the photons per bunch are the weights.

simtel.photon_bunch_file.write_photon_bunches(path, events, *, observation_level_m, telescope_radius_m, atmospheric_profile, run_number=1)[source]#

Write photon bunches of one telescope, one array of bunches per event.

Parameters:
path: str or Path

Output file; gzip compressed if its name ends with .gz.

events: iterable of numpy.ndarray

Photon bunches of each event, structured as BUNCH_DTYPE.

observation_level_m: float

Altitude of the observation level (CORSIKA) a.s.l. [m].

telescope_radius_m: float

Radius of the telescope’s fiducial sphere [m].

atmospheric_profile: astropy.table.Table

Atmospheric profile (atmospheric_profile model parameter), written into the file.

run_number: int

Run number.

Returns:
int

Number of events written.

simtel_file_writer#

Writer for sim_telarray files.

simtel.simtel_file_writer.write_angular_distribution_table_lambertian(file_path, max_angle_deg, n_samples=100)[source]#

Write a Lambertian angular distribution table (intensity ~ cos(angle)).

Parameters:
file_pathstr or Path

Destination path of the ASCII table. Parent directory must exist.

max_angle_degfloat

Upper bound of the angular range in degrees.

n_samplesint, optional

Number of equally spaced samples from 0 to max_angle_deg.

Returns:
Path

Path to the created angular distribution table.

simtel.simtel_file_writer.write_ascii_angle_distribution_table(file_path, angles, intensities)[source]#

Write a two-column (angle, relative intensity) ASCII angular distribution table.

Parameters:
file_pathstr or Path

Destination path.

anglesarray-like

Angle values in degrees.

intensitiesarray-like

Relative intensity values.

Returns:
Path

Path to the written file.

simtel.simtel_file_writer.write_ascii_pulse_table(file_path, t, y)[source]#

Write a two-column (time, amplitude) ASCII pulse table.

Parameters:
file_pathstr or Path

Destination path.

tarray-like

Time values in ns.

yarray-like

Amplitude values.

Returns:
Path

Path to the written file.

simtel.simtel_file_writer.write_camera_file(camera_components, output_path)[source]#

Write validated camera components in sim_telarray camera syntax.

camera_components is a mapping containing rotate, pixel_types, pixels and optional triggers/trigger_members sequences. The function deliberately accepts plain mappings so model-repository values can be passed without an intermediate bespoke class.

simtel.simtel_file_writer.write_light_pulse_table_gauss_exp_conv(file_path, width_ns, exp_decay_ns, fadc_sum_bins, dt_ns=0.1, rise_range=(0.1, 0.9), fall_range=(0.9, 0.1), time_margin_ns=10.0)[source]#

Write a pulse table for a Gaussian convolved with a causal exponential.

Parameters:
file_pathstr or Path

Destination path of the ASCII pulse table. Parent directory must exist.

width_nsfloat

Rise time in ns between the fractional levels defined by rise_range.

exp_decay_nsfloat

Fall time in ns between the fractional levels defined by fall_range.

fadc_sum_binsint

FADC integration window length in bins, used to set the time range.

dt_nsfloat, optional

Time sampling step in ns.

rise_rangetuple[float, float], optional

Fractional amplitude bounds (low, high) for rise-time definition.

fall_rangetuple[float, float], optional

Fractional amplitude bounds (high, low) for fall-time definition.

time_margin_nsfloat, optional

Extra margin in ns added to both ends of the time window.

Returns:
Path

Path to the created pulse table file.

Raises:
ValueError

If width_ns or exp_decay_ns is None.

table_serializers#

Schema-declared contracts determine the column selection, units, ordering, and numeric representation of temporary sim_telarray tables. The serializers reject incomplete contracts and invalid matrix grids before creating a configuration.

Contract-driven serializers for sim_telarray tabular inputs.

class simtel.table_serializers.AtmosphericTransmissionWriter[source]#

Serialize atmospheric transmission matrices.

static write(table, output_path, contract)[source]#

Write an altitude header and wavelength matrix.

Missing wavelength-altitude cells are written with the contract’s explicit opaque optical-depth sentinel. sim_telarray interprets every matrix entry as an optical depth, so this policy is deterministic but must only be used for cells known to represent zero transmission.

class simtel.table_serializers.PlainTableWriter[source]#

Serialize positional whitespace-separated tables.

static write(table, output_path, contract)[source]#

Write the selected sorted rows.

class simtel.table_serializers.RpolMatrixWriter[source]#

Serialize wavelength and incidence-angle response matrices.

static write(table, output_path, contract)[source]#

Write a one-dimensional response or sim_telarray’s RPOL matrix dialect.

Two-dimensional output starts with #@RPOL@[ANGLE=] 2 and an ANGLE= row. sim_telarray reads these mirror/filter tables with degree-valued angle coordinates and its yscale=deg2rad option; one-dimensional input remains a normal wavelength-response table.

class simtel.table_serializers.SimtelTableWriter[source]#

Write validated model tables using a declared sim_telarray contract.

classmethod register(format_name)[source]#

Register a table-format adapter.

classmethod write(table, destination, contract, output_name)[source]#

Validate and serialize one table using its schema contract.

simtel.table_serializers.validate_simtel_serialization(table, contract)[source]#

Validate positional, unit, and matrix invariants before serialization.

simtel.table_serializers.write_simtel_table(table, destination, contract, output_name=None)[source]#

Write a table with its required schema serialization contract.

simtel_io_metadata#

Read metadata from sim_telarray files.

simtel.simtel_io_metadata.get_sim_telarray_telescope_id(telescope_name, file)[source]#

Return the telescope ID for a given telescope name in a sim_telarray file.

Translates e.g. ‘LSTN-01’ to the corresponding telescope ID.

Parameters:
telescope_name: str

Name of the telescope.

file: str

Path to the sim_telarray file.

Returns:
int, None

Telescope ID. Returns None if not found.

simtel.simtel_io_metadata.get_sim_telarray_telescope_id_to_telescope_name_mapping(file)[source]#

Return a mapping of telescope IDs to telescope names from a sim_telarray file.

Parameters:
file: str

Path to the sim_telarray file.

Returns:
dict

Dictionary mapping telescope IDs to telescope names.

simtel.simtel_io_metadata.normalize_sim_telarray_metadata(metadata, dependency_catalog=None)[source]#

Convert legacy sim_telarray metadata names to canonical names.

Unknown metadata keys are preserved. When a dependency catalog is supplied, a legacy CORSIKA build identifier is also used to recover its source tag.

Parameters:
metadatadict

Decoded sim_telarray metadata keyed by parameter name.

dependency_catalogdict, optional

Dependency catalog used to resolve simtools_corsika_source_tag from simtools_corsika_build_id.

Returns:
dict

A new dictionary using canonical metadata names.

Raises:
ValueError

If both a legacy key and its canonical key are present with different values.

simtel.simtel_io_metadata.read_sim_telarray_metadata(file, encoding='utf8')[source]#

Return global and per-telescope metadata from sim_telarray file.

Cached to avoid re-reading the file multiple times.

Parameters:
file: str

Path to the sim_telarray file.

encoding: str

Encoding to use for decoding metadata. Default is ‘utf8’.

Returns:
global_meta: dict

Global metadata dictionary.

telescope_meta: dict

Dictionary of telescope metadata, keyed by telescope ID.

file_inspector#

Inspect sim_telarray output files.

simtel.file_inspector.inspect_sim_telarray_file(file_path, max_entries=50, format_report=True)[source]#

Inspect one sim_telarray file and return a report.

simtel_event_reader#

Event reader for sim_telarray.

simtel.simtel_event_reader.read_events(file_name, telescope, event_ids, max_events=1, verbose=False)[source]#

Read events from a sim_telarray file for a given telescope.

Parameters:
file_namestr or Path

Path to the sim_telarray file.

telescopestr

Telescope type to filter events.

event_idsint or list of int, optional

Specific event ID or list of event IDs to include. If None, all events are considered (subject to max_events).

max_eventsint, optional

Maximum total number of events to read. If event_ids is provided, only those IDs are included, up to this limit.

verbosebool, optional

If True, log detailed information about the reading process.

Returns:
tuple

A 3-tuple containing: - ids_with_data (list of int): List of event IDs that were read. - tel_desc (dict): Telescope description dictionary. - events (list): List of telescope events. Returns (None, None, None) if telescope not found or no events available.

simtel.simtel_event_reader.read_events_for_telescopes(file_name, telescopes, event_ids=None, max_events=None, verbose=False)[source]#

Read events for several telescopes while scanning a file once.

Parameters:
file_namestr or Path

Path to the sim_telarray file.

telescopeslist[str]

Telescope names to read.

event_idsint or list of int, optional

Specific event IDs to include.

max_eventsint, optional

Maximum number of events to read for each telescope. None reads all.

verbosebool, optional

If True, log detailed information about events without selected telescope data.

Returns:
tuple

Event IDs, telescope descriptions by name, and events by telescope name. Returns (None, None, None) if a requested telescope is unavailable.

multi_illuminator_simulator#

Multi-illuminator simulation orchestration with parallel execution.

class simtel.multi_illuminator_simulator.MultiIlluminatorSimulator(config, visibility_data=None, label=None, max_workers=None, backend='local', backend_config=None, model_reader=None, context=None)[source]#

Orchestrate parallel simulations of multiple illuminator-telescope pairs.

This class manages simulations for all valid illuminator-telescope combinations defined in a visibility table, running them in parallel across multiple CPU cores.

Parameters:
configdict

Base configuration for light emission simulations. Will be updated for each illuminator-telescope pair. Should contain: - site: str (North/South) - model_version: str - number_of_events: int - other SimulatorLightEmission parameters

visibility_datalist of dict, optional

Structured visibility records with illuminator_id, telescope_id, and visible keys. If not provided, the visibility table is retrieved from the site model using the site and model_version from config.

labelstr, optional

Base label for all simulations. Pair-specific labels will be appended.

max_workersint or None, optional

Maximum number of parallel worker processes. If None, uses 60% of CPU cores. If <= 0, uses all available cores.

simulate(wavelengths=None, illuminators=None, telescopes=None)[source]#

Run simulations for all valid illuminator-telescope pairs in parallel.

Optionally simulate across multiple wavelengths. If wavelengths are not specified and not in base_config, all model wavelengths will be used.

Parameters:
wavelengthslist of astropy.units.Quantity, optional

List of wavelengths to simulate. If None, uses wavelength from base_config if present, otherwise all model wavelengths.

illuminatorslist of str, optional

Restrict simulations to specific illuminators. If None, simulate all.

telescopeslist of str, optional

Restrict simulations to specific telescopes. If None, simulate all.

Returns:
list of dict

List of simulation results. Each dict contains: - illuminator: str - telescope: str - wavelength: astropy.units.Quantity (if wavelength simulation) - success: bool - error: str or None

simulator_array#

Simulation runner for array simulations.

class simtel.simulator_array.SimulatorArray(simulation_parameters, array_model, label=None, context=None)[source]#

SimulatorArray is the interface with sim_telarray to perform array simulations.

Parameters:
simulation_parametersSimulationParameters

Physical run settings.

array_modelArrayModel

Telescope and site models.

label: str

Instance label.

static get_power_law_for_sim_telarray_histograms(primary)[source]#

Get the power law index for sim_telarray.

Events will be filled in histograms in sim_telarray with a weight according to the difference between this exponent and the one used for the shower simulations.

Parameters:
primary: str

Primary particle.

Returns:
float

Power law index.

make_run_command(run_number=None, input_file=None)[source]#

Build and return the command to run sim_telarray.

Parameters:
input_file: str

Full path of the input CORSIKA file

run_number: int (optional)

run number

Returns:
list

Command to run sim_telarray.

simulator_light_emission#

Light emission simulation (e.g. illuminators or flashers).

class simtel.simulator_light_emission.SimulatorLightEmission(light_emission_config, telescope=None, label=None, model_reader=None, context=None)[source]#

Light emission simulation (e.g. illuminators or flashers).

Uses the sim_telarray LightEmission package to simulate the light emission.

Parameters:
light_emission_configdict, optional

Configuration for the light emission (e.g. number of events, model names)

telescopestr, optional

Telescope name.

labelstr, optional

Label for the simulation

build_flasher_event_and_photon_sequences()[source]#

Build ff-1m-compatible events/photons sequences.

calculate_distance_focal_plane_calibration_device()[source]#

Return the distance between the focal plane and a flasher (focal length + focus offset - z).

Returns:
astropy.units.Quantity

Distance between calibration device and focal plane.

static get_available_wavelengths_from_config(config, model_reader=None, context=None)[source]#

Get available wavelengths from model configuration without full initialization.

This is a lightweight method that only initializes the calibration model to retrieve wavelengths, without telescope/site models or file I/O.

Parameters:
configdict

Configuration dictionary with site, light_source, and model_version

Returns:
list of astropy.units.Quantity

List of available wavelengths with units

Raises:
ValueError

If required configuration keys are missing

static get_file_name_token(value)[source]#

Return a filename token for a light source or telescope name.

get_illuminator_pointing_vector(pos=None)[source]#

Return illuminator pointing vector; prefer explicit config if available.

get_illuminator_position()[source]#

Return the illuminator emission position in ground coordinates.

make_run_command(run_number=None, input_file=None)[source]#

Light emission and sim_telarray run command (a backend writes the photons beforehand).

prepare_run()[source]#

Write the bash run script with the light-emission command and return its path.

simulate()[source]#

Simulate light emission.

static uses_telescope_position_file(pointing_vector)[source]#

Return False for the downward beam used with an artificial telescope at the origin.

validate_simulations()[source]#

Validate that the simulations were successful.

write_telescope_position_file(illuminator_position=None)[source]#

Write the telescope positions to a telescope_position file.

The file will contain lines in the format: x y z r in cm

Returns:
Path

The path to the generated telescope_position file.

simulator_ray_tracing#

Simulation runner for ray tracing simulations.

class simtel.simulator_ray_tracing.SimulatorRayTracing(telescope_model, site_model, label=None, config_data=None, force_simulate=False, test=False, context=None)[source]#

Perform ray tracing simulations with sim_telarray.

Parameters:
telescope_model: TelescopeModel

telescope model

site_model: SiteModel

site model

label: str

label used for output file naming.

config_data: namedtuple

namedtuple containing the configurable parameters as values (expected units in brackets): zenith_angle (deg), off_axis_x (deg), off_axis_y (deg), source_distance (km), single_mirror_mode, mirror_numbers, photons_per_run, parameter_changes (model-parameter values replacing those of the model) and seeds (instrument and simulation seed of each run).

force_simulate: bool

Remove existing files and force re-running of the ray-tracing simulation.

test: bool

If activated, application will be faster by simulating fewer photons.

make_run_command(run_number=None, input_file=None)[source]#

Generate sim_telarray run command. Export sim_telarray configuration file(s).

The run_number and input_file parameters are not relevant for the ray tracing simulation.

simtel.simulator_ray_tracing.telescope_pointing(zenith_angle, off_axis_x, off_axis_y, azimuth_angle=0.0)[source]#

Telescope zenith and azimuth angles [deg] for a star offset in the camera.

The star is at azimuth azimuth_angle and zenith zenith_angle; the telescope points off_axis_x upwards (camera x points down) and off_axis_y sideways (camera y points right).

pulse_shapes#

Pulse shape computations for light emission simulations for flasher.

simtel.pulse_shapes.generate_gauss_expconv_pulse(sigma_ns, tau_ns, dt_ns=0.1, t_start_ns=-10, t_stop_ns=25, center_on_peak=False)[source]#

Generate a Gaussian convolved with a causal exponential.

Parameters:
sigma_nsfloat

Gaussian standard deviation (ns).

tau_nsfloat

Exponential decay constant (ns).

dt_nsfloat, optional

Time sampling step (ns). Default is 0.1 ns.

t_start_nsfloat

Together with t_stop_ns, defines the explicit start of the time grid for pulse generation (ns).

t_stop_nsfloat

Together with t_start_ns, defines the explicit end of the time grid for pulse generation (ns).

center_on_peakbool, optional

If True, shift the returned time array so the pulse maximum is at t=0. Default is False.

Returns:
tuple[numpy.ndarray, numpy.ndarray]

Tuple (t, y) with time samples in ns and normalized pulse amplitude (peak 1).

simtel.pulse_shapes.generate_pulse_from_rise_fall_times(rise_width_ns, fall_width_ns, dt_ns=0.1, rise_range=(0.1, 0.9), fall_range=(0.9, 0.1), t_start_ns=-10, t_stop_ns=25, center_on_peak=False)[source]#

Generate pulse from rise/fall time specifications.

Parameters:
rise_width_nsfloat
Target rise time (ns) between the fractional levels defined by ``rise_range``.
Defaults correspond to 10-90% rise time.
fall_width_nsfloat
Target fall time (ns) between the fractional levels defined by ``fall_range``.
Defaults correspond to 90-10% fall time.
dt_nsfloat, optional

Time sampling step (ns). Default is 0.1 ns.

rise_rangetuple[float, float], optional

Fractional amplitudes (low, high) for rise-time definition. Default (0.1, 0.9).

fall_rangetuple[float, float], optional

Fractional amplitudes (high, low) for fall-time definition. Default (0.9, 0.1).

t_start_nsfloat, optional

Start time (ns) for the internal solver sampling window and output grid. Default -10.

t_stop_nsfloat, optional

Stop time (ns) for the internal solver sampling window and output grid. Default 25.

center_on_peakbool, optional

If True, shift the returned time array so the pulse maximum is at t=0. Default is False.

Returns:
tuple[numpy.ndarray, numpy.ndarray]

Tuple (t, y) with time samples in ns and normalized pulse amplitude (peak 1).

Notes

The model is a Gaussian convolved with an exponential. The parameters (sigma, tau) are solved via least-squares such that the resulting pulse matches the requested rise and fall times measured on monotonic segments relative to the peak.

simtel.pulse_shapes.solve_sigma_tau_from_rise_fall(rise_width_ns, fall_width_ns, dt_ns=0.1, rise_range=(0.1, 0.9), fall_range=(0.9, 0.1), t_start_ns=-10, t_stop_ns=25)[source]#

Solve (sigma, tau) so convolved pulse matches target rise/fall widths.

Parameters:
rise_width_nsfloat

Desired width on the rising edge in ns between rise_range=(low, high) fractions.

fall_width_nsfloat

Desired width on the falling edge in ns between fall_range=(high, low) fractions.

dt_nsfloat

Time step for internal pulse sampling in ns.

rise_rangetuple[float, float]

Fractional amplitudes (low, high) for the rising width, defaults to (0.1, 0.9).

fall_rangetuple[float, float]

Fractional amplitudes (high, low) for the falling width, defaults to (0.9, 0.1).

t_start_nsfloat

Optional start time (ns) for the internal sampling window. If provided together with t_stop_ns, overrides the default window.

t_stop_nsfloat

Optional stop time (ns) for the internal sampling window. If provided together with t_start_ns, overrides the default window.

Returns:
tuple[float, float]

Tuple (sigma_ns, tau_ns) giving the Gaussian sigma and exponential tau in ns.

Native configuration and file formats#

Write sim_telarray configuration and native tables from simulation models.

class simtel.model_writer.SimtelModelWriter(model, context=None)[source]#

Export a resolved model in sim_telarray configuration formats.

Parameters:
modelModelParameter or ArrayModel

Model providing validated parameters, tables, and output paths.

export_all_simtel_config_files()[source]#

Export sim_telarray config file for the array and for each individual telescope.

Config files are exported into the output model directory.

export_atmospheric_transmission_file(model_directory)[source]#

Export the atmospheric profile source and sim_telarray table files.

Parameters:
model_directory: Path

Model directory to export the file to.

export_config_files()[source]#

Write array and telescope configurations in sim_telarray format.

export_model_parameter_as_simtel_file(parameter_name, model_directory, table_format, output_name)[source]#

Export an ECSV model parameter in the native sim_telarray format.

export_nsb_spectrum_to_telescope_altitude_correction_file(model_directory)[source]#

Export the NSB correction table and its native source file.

Camera-efficiency calculations correct the NSB spectrum from the original altitude used in the Benn & Ellison model to the telescope altitude. The correction table is a simulation-software parameter and is not included in the ordinary model-parameter export. This method exports both the source file and the native table used by the calculation.

Parameters:
model_directory: Path

Model directory to export the file to.

export_sim_telarray_config_file()[source]#

Export sim_telarray configuration file for the array into the model directory.

export_simtel_telescope_config_files()[source]#

Export sim_telarray configuration files for all telescopes into the model directory.

export_single_mirror_list_file(mirror_number, set_focal_length_to_zero)[source]#

Export a mirror list file with a single mirror in it.

Parameters:
mirror_number: int

Number index of the mirror.

set_focal_length_to_zero: bool

Set the focal length to zero if True.

get_atmospheric_profile_file_name(parameter=None)[source]#

Return the native filename used for the CORSIKA atmospheric profile.

get_single_mirror_list_file(mirror_number, set_focal_length_to_zero=False)[source]#

Return the native single-mirror file, writing it from the mirror model.

Parameters:
mirror_numberint

Mirror index.

set_focal_length_to_zerobool

Write zero focal length for the selected mirror.

Returns:
pathlib.Path

Single-mirror configuration file.

initialize_seeds(zenith_angle=None, azimuth_angle=None)[source]#

Initialize sim_telarray seeds for instrument and shower simulations.

write_config_file(additional_models=None, label=None)[source]#

Write telescope or calibration configuration in sim_telarray format.

Parameters:
additional_modelsModelParameter or dict, optional

Additional models included in the configuration.

labelstr, optional

File naming label.

Returns:
pathlib.Path

Written native configuration file.

write_sim_telarray_config_file(additional_models=None, label=None)[source]#

Write the sim_telarray configuration file.

Parameters:
additional_models: TelescopeModel or SiteModel

Model object for additional parameter to be written to the config file.

label: str or None

Optional label override used for output file naming.

Translate calibration-source settings into LightEmission configuration.

class simtel.light_emission_config_writer.LightEmissionConfigWriter(simulation)[source]#

Write settings and tables for ff-1m and xyzls.

Parameters:
simulationSimulatorLightEmission

Physical source configuration, model parameters, and geometry helpers.

add_flasher_command_options()[source]#

Add flasher options for all telescope types (ff-1m style).

add_illuminator_command_options()[source]#

Get illuminator-specific command options for light emission script.

generate_lambertian_angular_distribution_table()[source]#

Generate Lambertian angular distribution table and return path.

Uses a pure cosine profile normalized to 1 at 0 deg and spans 0..max_angle_deg.

get_angular_distribution_string_for_sim_telarray()[source]#

Get the angular distribution string for sim_telarray.

Returns:
str

The angular distribution string.

get_light_emission_application_name()[source]#

Return the LightEmission application and mode from type.

Returns:
str

app_name

get_light_source_command()[source]#

Return light-source specific command options.

get_pulse_shape_argument_for_sim_telarray()[source]#

Get the pulse shape argument for sim_telarray.

For Gauss-Exponential shapes, writes a DAT file and returns the file path. For other shapes, returns a string token representation.

Returns:
str

The pulse shape argument (either a file path or a token string).

get_pulse_shape_string_token(shape_name, width_ns, exp_ns)[source]#

Get the pulse shape string token for sim_telarray.

Parameters:
shape_namestr

Name of the pulse shape.

width_nsfloat

Width parameter in nanoseconds.

exp_nsfloat

Exponential decay parameter in nanoseconds.

Returns:
str

The pulse shape token string.

get_site_command(app_name, config_directory, corsika_observation_level)[source]#

Return site command with altitude, atmosphere and telescope_position handling.

make_command(iact_output)[source]#

Create the light emission command to run the light emission package.

Require the specified pre-compiled light emission package application in the sim_telarray/LightEmission/ path.

Parameters:
iact_output: str or Path

The output iact file path.

Returns:
str

The commands to run the Light Emission package

prepare_flasher_atmosphere_files(config_directory, model_id=1)[source]#

Prepare canonical atmosphere aliases for ff-1m and return model id.

The ff-1m tool requires atmosphere files atmprof1.dat or atm_profile_model_1.dat and as configuration parameter the atmosphere id (’–atmosphere id’).