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.fit_bias_curve(thresholds, rates)[source]#
Fit log10(rate) as a linear function of threshold.
- Parameters:
- thresholdsarray-like
Trigger thresholds.
- ratesarray-like
Trigger rates; only finite positive values are used.
- Returns:
- tuple or None
Valid thresholds and fit coefficients (slope, intercept), or None if fewer than two distinct finite thresholds have corresponding finite, positive rates.
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]#
Read the common active telescope threshold from SIMULATION_METADATA.
- Parameters:
- file_pathPath or str
Reduced event-data HDF5 file containing SIMULATION_METADATA.
- Returns:
- int or float or None
Common active threshold, or None for missing, invalid, or inconsistent metadata.
- 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 CTAO FITS keywords written by simtools.
- 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
argsdoes 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
metaparamlines.
- 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, orctao_datamodel.
metadata_reader#
Read sim_telarray metadata as format-neutral input-metadata fields.
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.
- simtel.simtel_seeds.instance_seed_pairs(instances=1, context=None)[source]#
Instrument and simulation seed of each random instrument instance.
Uses the configured
instrument_seedandsimulation_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.
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.
Telescopes are at the origin of the array frame and are identified by their telescope
id in the photon bunch objects. Each event has one event header and one photon bunch
object (EventIO type 1204) per telescope block. camera_bunches hands photons at the
camera entrance to sim_telarray with its optics bypassed (Bypass_Optics).
- class simtel.photon_bunch_file.PhotonBunchEvent(number, blocks)[source]#
Photon bunches of one event with a block of bunches per telescope.
- Parameters:
- number: int
Event number, written to the event header and the event end.
- blocks: sequence of (int, numpy.ndarray)
Telescope id and photon bunches (
BUNCH_DTYPE) of each telescope block.
- simtel.photon_bunch_file.bypass_optics_level(dual_mirror)[source]#
Return the sim_telarray
Bypass_Opticsvalue 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,weightandwavelength_nmof 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, corsika_card=None, reuses=1)[source]#
Write photon bunches of telescopes, one event per item.
As CORSIKA does, each event has one event header and one photon bunch object (1204) per telescope block, holding the photon bunches (1205) with the telescope id of the block.
- Parameters:
- path: str, Path or binary stream
Output file; gzip compressed if its name ends with
.gz."-"writes to stdout, and a binary stream (e.g.io.BytesIO) is written uncompressed and left open.- events: iterable
One item per event, each either
a numpy.ndarray of photon bunches (
BUNCH_DTYPE) of telescope 0; the event number is the position of the event (1, 2, …),a sequence of
(telescope_id, bunches)pairs, one per telescope block; the event number is the position of the event, ora
PhotonBunchEventwith its own event number.
- 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_profilemodel parameter), written into the file.- run_number: int
Run number.
- corsika_card: list of str or None
Lines of the CORSIKA input card (written as the card object, which holds the number of showers of the run for sim_telarray); None writes no card.
- reuses: int
Number of core reuses per shower (one telescope offset array per reuse).
- Returns:
- int
Number of events written.
- simtel.photon_bunch_file.write_shower_photon_stream(path, objects)[source]#
Write input objects with replacement camera bunches and return the event count.
Each item contains an EventIO object, its raw bytes, and either None or the replacement (telescope id, bunches) pairs for a telescope-array object.
shower_transmission#
Python port of sim_telarray’s atmospheric transmission lookup.
Faithful to the C code in RT/sim_telarray/common (sim_telarray 2025-11-30 tree):
read_trans() sim_absorb.c:111-237 (grid file reader)
rpol() / interp() rpolator.c:2388, 2290-2358
atmospheric_transmission() sim_absorb.c:655-675 (SIMPLE_ATMOSPHERIC_TRANSMISSION)
atmospheric_transmission2() sim_absorb.c:763-791 (default in sim_telarray.c:2860)
telescope optical depths sim_telarray.c:1859-1870 (od2tel, od2focus)
airmass sim_telarray.c:2713 (1/
|cz|of the bunch direction)
Units follow the C code: altitudes in cm inside the lookup (log10 cm), the optical depth table is indexed by integer wavelength in nm.
The table is read from the sim_telarray grid file (# H2= ..., H1= ... header,
one line per wavelength), i.e. the file that simtools’ exporter writes for the
atmospheric_transmission model parameter. Cells missing in the ECSV are
written as missing_value (99999, schema
atmospheric_transmission.schema.yml, incomplete_grid_policy: opaque)
and sim_telarray reads them as optical depth.
- class simtel.shower_transmission.SimtelTransmission(grid_file, altitude_m)[source]#
Atmospheric transmission tables as read by sim_telarray’s read_trans().
- atmospheric_transmission(iwl, zem_cm, airmass)[source]#
Port of atmospheric_transmission() (sim_absorb.c:655-675).
- atmospheric_transmission2(iwl, zem_cm, airmass, od2tel, od2focus)[source]#
Port of atmospheric_transmission2() (sim_absorb.c:763-791), the default path.
- telescope_optical_depths(iwl, ztel_cm, pathlen_cm, observation_cm=None)[source]#
Port of the per-telescope setup (sim_telarray.c:1859-1870, 1889-1890 aside).
ztel_cm is the telescope height above the observation level [cm] (array.ztel). observation_cm is the run’s observation level, or the table level if omitted. Returns (od_tel, od_focus) for wavelength iwl.
- transmission(wavelength_nm, emission_altitude_m, telescope_altitude_m, airmass, pathlen_m=0.0, observation_level_m=None)[source]#
sim_telarray’s bunch-loop transmission p1 (sim_telarray.c:2860-2862) for one bunch.
telescope_altitude_m is the telescope height above the observation level [m]. With pathlen_m=0 the instrument term od2focus vanishes. observation_level_m is the run’s observation level; if omitted, the table level is used.
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_componentsis a mapping containingrotate,pixel_types,pixelsand optionaltriggers/trigger_memberssequences. 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_nsorexp_decay_nsis 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.
- 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=] 2and anANGLE=row. sim_telarray reads these mirror/filter tables with degree-valued angle coordinates and itsyscale=deg2radoption; 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.
simtel_io_metadata#
Read metadata from sim_telarray files.
- simtools.sim_events.simtel_io_metadata.corsika_source_tag_for_build_id(build_id, catalog)[source]#
Return the CORSIKA source tag matching a legacy build identifier.
- simtools.sim_events.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.
- simtools.sim_events.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.
- simtools.sim_events.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_tagfromsimtools_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.
- simtools.sim_events.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_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_idsis 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.
Nonereads 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, script_writer=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 or astropy.table.Table, optional
Structured visibility records with
illuminator_id,telescope_id, andvisiblekeys. 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.
- script_writercallable, optional
Writes the run script of a simulation chain other than the default one, called as
script_writer(calibration, script_file). Must be picklable. None writes the default chain.
- 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, bypass_optics=None, atmospheric_transmission=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
- bypass_optics: int (optional)
Value of sim_telarray’s Bypass_Optics for photons given at the camera entrance; None (default) leaves the option out of the command.
- atmospheric_transmission: str or Path (optional)
Transmission table that sim_telarray reads instead of the model’s table (e.g. a table with optical depth 0 when an upstream stage applies the extinction).
- 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.
Single-mirror telescopes: focal length + focus offset - flasher z. Dual-mirror telescopes: focal-surface vertex height + focus offset, and the absolute separation from the flasher (the flasher sits on either side of the focal surface).
- Returns:
- astropy.units.Quantity
Distance between calibration device and focal plane.
- execute_script(run_script)[source]#
Run a script of this simulation, logging to the submission output files.
- flasher_above_focal_surface()[source]#
Return True if a dual-mirror telescope’s flasher sits above the focal surface.
- 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.
- static iact_file_check(iact_output)[source]#
Return the shell command that stops the script if the IACT file is missing or empty.
- light_emission_command(iact_output=None)[source]#
Return the LightEmission program command writing the IACT file of this run.
- make_run_command(run_number=None, input_file=None)[source]#
Return the lines of the default run script: LightEmission program, then sim_telarray.
- make_sim_telarray_command(input_file=None, bypass_optics=None, atmospheric_transmission=None)[source]#
Return the command to run sim_telarray on a file of photons.
- Parameters:
- input_filestr or Path, optional
Photon file (default: the IACT file of the LightEmission program of this run).
- bypass_opticsint, optional
Bypass_Optics level, 0 for none (default: 1 for flat fielding, else 0).
- atmospheric_transmissionstr or Path, optional
Transmission table read by sim_telarray (default: the table of the site model), e.g. a zero-depth table when an upstream stage applies the extinction.
- Returns:
- str
Environment and command line, ending with a new line.
- prepare_run(script_writer=None)[source]#
Write the bash run script and return its path.
- Parameters:
- script_writercallable, optional
Writes the run script of a simulation chain other than the default one, called as
script_writer(calibration, script_file). None writes the default chain.
- Returns:
- Path
Path of the run script.
- run_script_file()[source]#
Return the path of the run script, after checking that the output does not exist.
- Raises:
- FileExistsError
If the sim_telarray output file of this simulation exists.
- simulate(script_writer=None)[source]#
Simulate light emission.
- Parameters:
- script_writercallable, optional
Writes the run script of a simulation chain other than the default one, called as
script_writer(calibration, script_file). None writes the default chain.
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.
- 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_angleand zenithzenith_angle; the telescope pointsoff_axis_xupwards (camera x points down) andoff_axis_ysideways (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_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.
- simtel.model_writer.get_model_writer(model, simulation_software='sim_telarray', context=None)[source]#
Return the selected model configuration writer, retaining its table cache.
- Parameters:
- modelModelParameter or ArrayModel
Resolved simulation model.
- simulation_softwarestr
Registered configuration writer.
- contextRunContext, optional
Run context; the model’s own context is used if not given.
- Returns:
- object
Software-specific model writer.
- Raises:
- ValueError
If the selected software is not registered.
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_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_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
pulse_response#
Characterize tabulated pulses and raw gain-resolved flasher waveforms.
- simtools.simtel.pulse_response.flasher_responses(files, illuminations, events_per_level, telescope, pixels, width_fraction=0.95, threshold_adc=None, pedestal=None)[source]#
Measure raw HG/LG flasher traces, using requested photons as the scan axis.
- Parameters:
- fileslist of path-like
One file per intensity, or one file containing the entire ordered scan.
- illuminationslist of float
Requested photon counts, one per scan step, not detected p.e.
- events_per_levellist of int
Expected event counts per intensity; one count broadcasts to all steps.
- telescopestr
Telescope name stored in the file metadata.
- pixelslist of int
Fixed pixel IDs to measure independently.
- width_fractionfloat
Fraction of peak for the width.
- threshold_adcfloat, optional
Absolute width threshold above pedestal.
- pedestalfloat, optional
Explicit per-sample pedestal for both gains. Otherwise use gain-specific monitoring pedestals; missing monitoring is an error.
- Returns:
- astropy.table.Table, list
Per-event metrics and mean-waveform dictionaries for each step, pixel and gain. All events must match the declared ordered scan; missing events are errors.
- simtools.simtel.pulse_response.summarize_response(table)[source]#
Aggregate event metrics per intensity, gain and pixel, retaining dispersion.
- Parameters:
- tableastropy.table.Table
Response measurements.
- Returns:
- astropy.table.Table
Mean metrics, population standard deviations, counts and truncation counts.
- simtools.simtel.pulse_response.template_responses(model, illuminations, width_fraction=0.95, threshold_adc=None)[source]#
Measure model pulse tables and a clipped-linear control at requested p.e. levels.
- Parameters:
- modelTelescopeModel
Model supplying pulse tables and nominal ADC conversion parameters.
- illuminationsarray-like
Positive illumination levels in p.e.
- width_fractionfloat
Fraction of peak used for the pulse width.
- threshold_adcfloat, optional
Absolute width threshold overriding the fractional threshold.
- Returns:
- astropy.table.Table, list
Metrics and waveform dictionaries for both gains. Nonlinear responses are included when intensity-dependent templates are available. This is direct linear interpolation of the input tables, not a reproduction of the simulator’s internal rpolator resampling or stochastic digitization.
- simtools.simtel.pulse_response.write_response(table, waves, output_directory, name)[source]#
Write response measurements, aggregate statistics, and diagnostic plots.
- Parameters:
- tableastropy.table.Table
Per-event or per-template response measurements.
- waveslist of dict
Waveforms with gain, illumination, response, time and waveform entries.
- output_directorypath-like
Directory receiving ECSV tables and PDF figures.
- namestr
Output filename stem.
- Returns:
- pathlib.Path
Path to the per-event or per-template ECSV table.