Utilities#

In this section you find the reference documentation of the modules contained in the util module.

general#

General functions useful across different parts of the code.

exception utils.general.InvalidConfigDataError[source]#

Exception for invalid configuration data.

exception utils.general.InvalidConfigEntryError[source]#

Exception for invalid configuration entry.

exception utils.general.MissingRequiredConfigEntryError[source]#

Exception for missing required configuration entry.

exception utils.general.UnableToIdentifyConfigEntryError[source]#

Exception for unable to identify configuration entry.

utils.general.change_dict_keys_case(data_dict, lower_case=True)[source]#

Change keys of a dictionary to lower or upper case. Crawls through the dictionary and changes all keys. Takes into account list of dictionaries, as e.g. found in the top level data model.

Parameters:
data_dict: dict

Dictionary to be converted.

lower_case: bool

Change keys to lower (upper) case if True (False).

utils.general.collect_data_from_file_or_dict(file_name, in_dict, allow_empty=False)[source]#

Collect input data from file or dictionary.

Parameters:
file_name: str

Name of the yaml/json/ascii file.

in_dict: dict

Data as dict.

allow_empty: bool

If True, an error won’t be raised in case both file_name and dict are None.

Returns:
data: dict or list

Data as dict or list.

utils.general.collect_final_lines(file, n_lines)[source]#

Collect final lines.

Parameters:
file: str or Path

File to collect the lines from.

n_lines: int

Number of lines to be collected.

Returns:
str

Final lines collected.

utils.general.collect_kwargs(label, in_kwargs)[source]#

Collect kwargs of the type label_* and return them as a dict.

Parameters:
label: str

Label to be collected in kwargs.

in_kwargs: dict

kwargs.

Returns
——-
dict

Dictionary with the collected kwargs.

utils.general.get_log_excerpt(log_file, n_last_lines=30)[source]#

Get an excerpt from a log file, namely the n_last_lines of the file.

Parameters:
log_file: str or Path

Log file to get the excerpt from.

n_last_lines: int

Number of last lines of the file to get.

Returns:
str

Excerpt from log file with header/footer

utils.general.get_log_level_from_user(log_level)[source]#

Map between logging level from the user to logging levels of the logging module.

Parameters:
log_level: str

Log level from the user.

Returns:
logging.LEVEL

The requested logging level to be used as input to logging.setLevel().

utils.general.remove_substring_recursively_from_dict(data_dict, substring='\n')[source]#

Remove substrings from all strings in a dictionary. Recursively crawls through the dictionary This e.g., allows to remove all newline characters from a dictionary.

Parameters:
data_dict: dict

Dictionary to be converted.

substring: str

Substring to be removed.

Raises:
AttributeError:

if input is not a proper dictionary.

utils.general.separate_args_and_config_data(expected_args, **kwargs)[source]#

Separate kwargs into the arguments expected for instancing a class and the dict to be given as config_data. This function is specific for methods from_kwargs in classes which use the validate_config_data system.

Parameters:
expected_args: list of str

List of arguments expected for the class.

**kwargs
Returns:
dict, dict

A dict with the args collected and another one with config_data.

utils.general.set_default_kwargs(in_kwargs, **kwargs)[source]#

Fill in a dict with a set of default kwargs and return it.

Parameters:
in_kwargs: dict

Input dict to be filled in with the default kwargs.

**kwargs:

Default kwargs to be set.

Returns:
dict

Dictionary containing the default kwargs.

utils.general.sort_arrays(*args)[source]#

Sort arrays

Parameters:
*args

Arguments to be sorted.

Returns
——-
list

Sorted args.

utils.general.validate_config_data(config_data, parameters, ignore_unidentified=False, _logger=None)[source]#

Validate a generic config_data dict by using the info given by the parameters dict. The entries will be validated in terms of length, units and names.

See ./tests/resources/test_parameters.yml for an example of the structure of the parameters dict.

Parameters:
config_data: dict

Input config data.

parameters: dict

Parameter information necessary for validation.

ignore_unidentified: bool, optional

If set to True, unidentified parameters provided in config_data are ignored and a debug message is printed. Otherwise, an unidentified parameter leads to an error. Default is False.

_logger: Logger, optional

Logger object for logging messages. If not provided, defaults to printing to console.

Returns:
namedtuple:

Containing the validated config data entries.

Raises:
UnableToIdentifyConfigEntryError

When an entry in config_data cannot be identified among the parameters.

MissingRequiredConfigEntryError

When a parameter without default value is not given in config_data.

InvalidConfigEntryError

When an entry in config_data is invalid (wrong len, wrong unit, …).

geometry#

A collection of functions related to geometrical transformations.

utils.geometry.convert_2d_to_radial_distr(hist_2d, xaxis, yaxis, bins=50, max_dist=1000)[source]#

Convert a 2d histogram of positions, e.g. photon positions on the ground, to a 1D distribution.

Parameters:
hist_2d: numpy.ndarray

The histogram counts.

xaxis: numpy.array

The values of the x axis (histogram bin edges) on the ground.

yaxis: numpy.array

The values of the y axis (histogram bin edges) on the ground.

bins: float

Number of bins in distance.

max_dist: float

Maximum distance to consider in the 1D histogram, usually in meters.

Returns:
np.array

The values of the 1D histogram with size = int(max_dist/bin_size).

np.array

The bin edges of the 1D histogram with size = int(max_dist/bin_size) + 1.

utils.geometry.rotate(x, y, rotation_around_z_axis, rotation_around_y_axis=0)[source]#

Transform the x and y coordinates of the telescopes according to two rotations: rotation_angle_around_z_axis gives the rotation on the observation plane (x, y) and rotation_angle_around_y_axis allows to rotate the observation plane in space. The function returns the rotated x and y values in the same unit given. The direction of rotation of the elements in the plane is counterclockwise, i.e., the rotation of the coordinate system is clockwise.

Parameters:
x: numpy.array or list

x positions of the entries (e.g. telescopes), usually in meters.

y: numpy.array or list

y positions of the entries (e.g. telescopes), usually in meters.

rotation_angle_around_z_axis: astropy.units.rad

Angle to rotate the array in the observation plane (around z axis) in radians.

rotation_angle_around_y_axis: astropy.units.rad

Angle to rotate the observation plane around the y axis in radians.

Returns:
2-tuple of list

x and y positions of the rotated entry (e.g. telescopes) positions.

Raises:
TypeError:

If type of x and y parameters are not valid.

RuntimeError:

If the length of x and y are different.

UnitsError:

If the unit of x and y are different.

names#

Validation of names.

utils.names.generate_file_name(file_type, suffix, site, telescope_model_name, zenith_angle, azimuth_angle=None, off_axis_angle=None, source_distance=None, mirror_number=None, label=None, extra_label=None)[source]#

Generate a file name for output, config, or plotting.

Used e.g., to generate camera-efficiency and ray-tracing output files.

Parameters:
file_type: str

Type of file (e.g., config, output, plot)

suffix: str

File suffix

site: str

South or North.

telescope_model_name: str

LSTN-01, MSTS-01, …

zenith_angle: float

Zenith angle (deg).

azimuth_angle: float

Azimuth angle (deg).

off_axis_angle: float

Off-axis angle (deg).

source_distance: float

Source distance (km).

mirror_number: int

Mirror number.

label: str

Instance label.

extra_label: str

Extra label.

Returns:
str

File name.

utils.names.get_site_from_telescope_name(name)[source]#

Get site name from telescope name.

Parameters:
name: str

Telescope name.

Returns:
str

Site name (South or North).

utils.names.get_telescope_type_from_telescope_name(name)[source]#

Get telescope type from name, e.g. “LSTN”, “MSTN”.

Parameters:
telescope_name: str

Telescope name

Returns:
str

Telescope type.

utils.names.layout_telescope_list_file_name(name, label)[source]#

File name for files required at the RayTracing class.

Parameters:
name: str

Name of the array.

label: str

Instance label.

Returns:
str

File name.

utils.names.sanitize_name(name)[source]#

Sanitize name to be a valid Python identifier.

  • Replaces spaces with underscores

  • Converts to lowercase

  • Removes characters that are not alphanumerics or underscores

  • If the name starts with a number, prepend an underscore

Parameters:
name: str

name to be sanitized.

Returns:
str:

Sanitized name.

Raises:
ValueError:

if the string name can not be sanitized.

utils.names.simtel_config_file_name(site, model_version, array_name=None, telescope_model_name=None, label=None, extra_label=None)[source]#

sim_telarray config file name for a telescope.

Parameters:
site: str

South or North.

telescope_model_name: str

LST-1, MST-FlashCam, …

model_version: str

Version of the model.

label: str

Instance label.

extra_label: str

Extra label in case of multiple telescope config files.

Returns:
str

File name.

utils.names.simtel_single_mirror_list_file_name(site, telescope_model_name, model_version, mirror_number, label)[source]#

sim_telarray mirror list file with a single mirror.

Parameters:
site: str

South or North.

telescope_model_name: str

North-LST-1, South-MST-FlashCam, …

model_version: str

Version of the model.

mirror_number: int

Mirror number.

label: str

Instance label.

Returns:
str

File name.

utils.names.validate_site_name(name)[source]#

Validate site name.

Parameters:
name: str

Site name.

Returns:
str

Validated name.

utils.names.validate_telescope_id_name(name)[source]#

Validate telescope ID.

Allowed IDs are - design (for design telescopes or testing) - telescope ID (e.g., 1, 5, 15) - test (for testing)

Parameters:
name: str or int

Telescope ID name.

Returns:
str

Validated telescope ID (added leading zeros, e.g., 1 is converted to 01).

Raises:
ValueError

If name is not valid.

utils.names.validate_telescope_name(name)[source]#

Validate telescope name (e.g., MSTN-design, MSTN-01).

Parameters:
name: str

Telescope name.

Returns:
str

Validated name.