Ray Tracing#

The ray-tracing modules handle ray tracing simulations, PSF analysis and I/O.

ray_tracing#

Ray tracing simulations and analysis.

class ray_tracing.ray_tracing.RayTracing(telescope_model, site_model, simtel_path, label=None, zenith_angle=<Quantity 20. deg>, off_axis_angle=<Quantity [0.] deg>, source_distance=<Quantity 10. km>, single_mirror_mode=False, use_random_focal_length=False, random_focal_length_seed=None, mirror_numbers='all')[source]#

Ray tracing simulations and analysis.

Parameters:
telescope_model: TelescopeModel

telescope model

site_model: SiteModel

site model

simtel_path: str (or Path)

Location of sim_telarray installation.

label: str

label used for output file naming.

zenith_angle: astropy.units.Quantity

Zenith angle.

off_axis_angle: list of astropy.units.Quantity

Off-axis angles.

source_distance: astropy.units.Quantity

Source distance.

single_mirror_mode: bool

Single mirror mode flag.

use_random_focal_length: bool

Use random focal length flag.

random_focal_length_seed: int

Seed for the random number generator used for focal length variation.

mirror_numbers: list, str

List of mirror numbers (or ‘all’).

analyze(export=True, force=False, use_rx=False, no_tel_transmission=False, containment_fraction=0.8)[source]#

Ray tracing analysis.

Involves the following: read simtel files, compute PSFs and eff areas, store the results in _results.

Parameters:
export: bool

If True, results will be exported to a file automatically. Alternatively, export_results function can be used.

force: bool

If True, existing results files will be removed and analysis will be done again.

use_rx: bool

If True, calculations are done using the rx binary provided by sim_telarray. If False, calculations are done internally, by the module psf_analysis.

no_tel_transmission: bool

If True, the telescope transmission is not applied.

containment_fraction: float

Containment fraction for PSF containment calculation. Allowed values are in the interval [0,1]

export_results()[source]#

Export results to a csv file.

get_mean(key)[source]#

Get mean value of key.

Parameters:
key: str

d80_cm, d80_deg, eff_area or eff_flen

Returns:
float

Mean value of key.

Raises:
KeyError

If key is not among the valid options.

get_std_dev(key)[source]#

Get std dev of key.

Parameters:
key: str

d80_cm, d80_deg, eff_area or eff_flen

Returns:
float

Std deviation of key.

Raises:
KeyError

If key is not among the valid options.

images()[source]#

Get list of PSFImages.

Returns:
List of PSFImages
plot(key, save=False, d80=None, **kwargs)[source]#

Plot key vs off-axis angle and save the figure in pdf.

Parameters:
key: str

d80_cm, d80_deg, eff_area or eff_flen

save: bool

If True, figure will be saved.

d80: float

d80 for cumulative PSF plot.

**kwargs:

kwargs for plt.plot

Raises:
KeyError

If key is not among the valid options.

plot_histogram(key, **kwargs)[source]#

Plot histogram of key.

Parameters:
key: str

d80_cm, d80_deg, eff_area or eff_flen

**kwargs:

kwargs for plt.hist

Raises:
KeyError

If key is not among the valid options.

simulate(test=False, force=False)[source]#

Simulate RayTracing using SimulatorRayTracing.

Parameters:
test: bool

Test flag will make it faster by simulating much fewer photons.

force: bool

Force flag will remove existing files and simulate again.

psf_analysis#

Module to analyse psf images (e.g. results from ray tracing simulations).

Main functionalities are: computing centroids, psf containers etc.

class ray_tracing.psf_analysis.PSFImage(focal_length=None, total_scattered_area=None, containment_fraction=None, simtel_path=None)[source]#

Image composed of list of photon positions (2D).

Load photon list from sim_telarray file and compute centroids, psf containers, effective area, as well as plot the image as a 2D histogram. Internal units: photon positions in cm internally.

Parameters:
focal_length: float

Focal length of the system in cm. If not given, PSF can only be computed in cm.

total_scattered_area: float

Scatter area of all photons in cm^2. If not given, effective area cannot be computed.

containment_fraction: float

Containment fraction for PSF calculation.

simtel_path: str

Path to sim_telarray installation.

get_cumulative_data(radius=None)[source]#

Provide cumulative data (intensity vs radius).

Parameters:
radius: array

Array with radius calculate the cumulative PSF in distance units.

Returns:
(radius, intensity)
get_effective_area(tel_transmission=1.0)[source]#

Return effective area pre calculated.

Parameters:
telescope_transmissionfloat

Telescope transmission parameter.

Returns:
float

Pre-calculated effective area. None if it could not be calculated (e.g because the total scattering area was not set).

get_image_data(centralized=True)[source]#

Provide image data (2D photon positions in cm) as lists.

Parameters:
centralized: bool

Centroid of the image is set to (0, 0) if True.

Returns:
(x, y), the photons positions in cm.
get_psf(fraction=0.8, unit='cm')[source]#

Return PSF.

Parameters:
fraction: float

Fraction of photons within the containing radius.

unit: str

‘cm’ or ‘deg’. ‘deg’ will not work if focal length was not set.

Returns:
float:

Containing diameter for a certain intensity fraction (PSF).

plot_cumulative(file_name=None, d80=None, **kwargs)[source]#

Plot cumulative data (intensity vs radius).

Parameters:
**kwargs:

image_* for the histogram plot and psf_* for the psf circle.

plot_image(centralized=True, file_name=None, **kwargs)[source]#

Plot 2D image as histogram (in cm).

Parameters:
centralized: bool

Centroid of the image is set to (0, 0) if True.

**kwargs:

image_* for the histogram plot and psf_* for the psf circle.

process_photon_list(photon_file, use_rx)[source]#

Read and process a photon list file generated by sim_telarray.

Parameters:
photons_file: str

Name of sim_telarray file with photon list.

use_rx: bool

Use the RX method for analysis.

read_photon_list_from_simtel_file(photons_file)[source]#

Read photon list file generated by sim_telarray and store the photon positions (2D).

Parameters:
photons_file: str

Name of sim_telarray file with photon list.

Raises:
RuntimeError

If photon positions X and Y are not compatible or are empty.

set_effective_area(value)[source]#

Set effective area.

Parameters:
value: float

Effective area

set_psf(value, fraction=0.8, unit='cm')[source]#

Set PSF calculated from other methods.

Parameters:
value: float

PSF value to be set

fraction: float

Fraction of photons within the containing radius.

unit: str

‘cm’ or ‘deg’. ‘deg’ will not work if focal length was not set.

psf_parameter_optimisation#

PSF parameter optimisation and fitting routines for mirror alignment and reflection parameters.

This module provides functions for loading PSF data, generating random parameter sets, running PSF simulations, calculating RMSD, and finding the best-fit parameters for a given telescope model.

PSF (Point Spread Function) describes how a point source of light is spread out by the optical system, and RMSD (Root Mean Squared Deviation) is used as the optimization metric to quantify the difference between measured and simulated PSF curves.

ray_tracing.psf_parameter_optimisation.add_parameters(all_parameters, mirror_reflection, mirror_align, mirror_reflection_fraction=0.15, mirror_reflection_2=0.035)[source]#

Transform and add parameters to the all_parameters list.

Parameters:
mirror_reflectionfloat

The random angle of mirror reflection.

mirror_alignfloat

The random angle for mirror alignment (both horizontal and vertical).

mirror_reflection_fractionfloat, optional

The fraction of the mirror reflection. Default is 0.15.

mirror_reflection_2float, optional

A secondary random angle for mirror reflection. Default is 0.035.

Returns:
None

Updates the all_parameters list in place.

ray_tracing.psf_parameter_optimisation.calculate_rmsd(data, sim)[source]#

Calculate Root Mean Squared Deviation to be used as metric to find the best parameters.

ray_tracing.psf_parameter_optimisation.create_d80_vs_offaxis_plot(tel_model, site_model, args_dict, best_pars, output_dir)[source]#

Create D80 vs off-axis angle plot using the best parameters.

Parameters:
tel_modelTelescopeModel

Telescope model object.

site_modelSiteModel

Site model object.

args_dictdict

Dictionary containing parsed command-line arguments.

best_parsdict

Best parameter set.

output_dirPath

Output directory for saving plots.

ray_tracing.psf_parameter_optimisation.export_psf_parameters(best_pars, tel_model, parameter_version, output_dir)[source]#

Export PSF parameters as simulation model parameter files.

Parameters:
best_parsdict

Best parameter set

tel_modelTelescopeModel

Telescope model object

parameter_versionstr

Parameter version string

output_dirPath

Output directory path

ray_tracing.psf_parameter_optimisation.find_best_parameters(all_parameters, tel_model, site_model, args_dict, data_to_plot, radius, pdf_pages=None)[source]#

Find the best parameters by running simulations for all parameter sets.

Loop over all parameter sets, run the simulation, compute RMSD, and return the best parameters and their RMSD.

ray_tracing.psf_parameter_optimisation.generate_random_parameters(all_parameters, n_runs, args_dict, mrra_0, mfr_0, mrra2_0, mar_0, tel_model)[source]#

Generate random parameters for tuning.

The parameter ranges around the previous values are configurable via module constants.

Parameters:
all_parameterslist

List to store all parameter sets.

n_runsint

Number of random parameter combinations to test.

args_dictdict

Dictionary containing parsed command-line arguments.

mrra_0float

Initial value of mirror_reflection_random_angle.

mfr_0float

Initial value of mirror_reflection_fraction.

mrra2_0float

Initial value of the second mirror_reflection_random_angle.

mar_0float

Initial value of mirror_align_random_horizontal/vertical.

tel_modelTelescopeModel

Telescope model object to check if it’s a dual mirror telescope.

ray_tracing.psf_parameter_optimisation.get_previous_values(tel_model)[source]#

Retrieve previous parameter values from the telescope model.

Parameters:
tel_modelTelescopeModel

Telescope model object.

Returns:
tuple

Tuple containing the previous values of mirror_reflection_random_angle (first entry), mirror_reflection_fraction, second entry), mirror_reflection_random_angle (third entry), and mirror_align_random_horizontal/vertical.

ray_tracing.psf_parameter_optimisation.load_and_process_data(args_dict)[source]#

Load and process data if specified in the command-line arguments.

Returns:
  • data_to_plot: OrderedDict containing loaded and processed data.
  • radius: Radius data from loaded data (if available).
ray_tracing.psf_parameter_optimisation.load_psf_data(data_file)[source]#

Load data from a text file containing cumulative PSF measurements.

Parameters:
data_filestr

Name of the data file with the measured cumulative PSF. Expected format: Column 0: radial distance in mm Column 2: cumulative PSF values

Returns:
numpy.ndarray

Loaded and processed data with radius in cm and normalized cumulative PSF.

ray_tracing.psf_parameter_optimisation.run_psf_optimization_workflow(tel_model, site_model, args_dict, output_dir)[source]#

Run the complete PSF parameter optimization workflow.

This function consolidates the main optimization logic to make the application lighter.

Parameters:
tel_modelTelescopeModel

Telescope model object

site_modelSiteModel

Site model object

args_dictdict

Dictionary containing parsed command-line arguments

output_dirPath

Output directory path

Returns:
None

All results are saved to files and printed to console

ray_tracing.psf_parameter_optimisation.run_psf_simulation(tel_model, site_model, args_dict, pars, data_to_plot, radius, pdf_pages=None, is_best=False, return_simulated_data=False)[source]#

Run the simulation for one set of parameters and return D80, RMSD.

Parameters:
tel_modelTelescopeModel

Telescope model object.

site_modelSiteModel

Site model object.

args_dictdict

Dictionary containing parsed command-line arguments.

parsdict

Parameter set dictionary.

data_to_plotdict

Data dictionary for plotting.

radiusarray-like

Radius data.

pdf_pagesPdfPages, optional

PDF pages object for plotting. If None, no plotting is done.

is_bestbool, optional

Whether this is the best parameter set for highlighting in plots.

return_simulated_databool, optional

If True, returns simulated data as third element in return tuple.

Returns:
tuple

(d80, rmsd) if return_simulated_data=False (d80, rmsd, simulated_data) if return_simulated_data=True

ray_tracing.psf_parameter_optimisation.write_tested_parameters_to_file(results, best_pars, best_d80, output_dir, tel_model)[source]#

Write all tested parameters and their metrics to a text file.

Parameters:
resultslist

List of (pars, rmsd, d80, simulated_data) tuples

best_parsdict

Best parameter set

best_d80float

Best D80 value

output_dirPath

Output directory path

tel_modelTelescopeModel

Telescope model object for filename generation

mirror_panel_psf#

Mirror panel PSF calculation.

class ray_tracing.mirror_panel_psf.MirrorPanelPSF(label, args_dict, db_config)[source]#

Mirror panel PSF and random reflection angle calculation.

This class is used to derive the random reflection angle for the mirror panels in the telescope.

Known limitations: single Gaussian PSF model, no support for multiple PSF components (as allowed in the model parameters).

Parameters:
label: str

Application label.

args_dict: dict

Dictionary with input arguments.

db_config:

Dictionary with database configuration.

derive_random_reflection_angle(save_figures=False)[source]#

Minimize the difference between measured and simulated PSF for reflection angle.

Main loop of the optimization process. The method iterates over different values of the random reflection angle until the difference in the mean value of the D80 containment is minimal.

print_results()[source]#

Print results to stdout.

run_simulations_and_analysis(rnda, save_figures=False)[source]#

Run ray tracing simulations and analysis for one given value of rnda.

Parameters:
rnda: float

Random reflection angle in degrees.

save_figures: bool

Save figures.

Returns:
mean_d80: float

Mean value of D80 in cm.

sig_d80: float

Standard deviation of D80 in cm.

write_optimization_data()[source]#

Write optimization results to an astropy table (ecsv file).

Used mostly for debugging of the optimization process. The first entry of the table is the best fit result.