Visualization#

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

visualize#

Module for visualization.

visualization.visualize.configure_figure_output(args)[source]#

Set the figure output options of this process (like matplotlib rcParams).

Applications call this once at start with their parsed arguments; save_figure then uses figure_format, figure_dpi and figure_png_palette from them.

visualization.visualize.convert_png_to_palette(png_file)[source]#

Convert a PNG file in place to a 256-color palette image if that makes it smaller.

Parameters:
png_filePath or str

PNG file to convert.

visualization.visualize.figure_output_settings(context=None)[source]#

Return figure output options from the context or from configure_figure_output.

visualization.visualize.pdf_report(path)[source]#

Write figures to a multi-page PDF, closing each figure after it is added.

Parameters:
pathpathlib.Path or str

Destination PDF path.

Yields:
_PdfReport

Report with an add(fig) method.

visualization.visualize.plot_1d(data, **kwargs)[source]#

Produce a high contrast one dimensional plot from multiple data sets.

Parameters:
data: numpy structured array or dict of structured arrays

Columns: x, y and optionally errors. Dict keys are the legend labels; the first entry is the reference for ratio or difference plots.

**kwargs:

Plot options (palette, big_plot, title, no_legend, legend_fontsize, no_markers, empty_markers, plot_ratio, plot_difference, xscale, yscale, xlim, ylim, xtitle, ytitle, error_type, error_label) and any kwargs accepted by plt.plot.

Returns:
pyplot.figure

Figure in which the plot was produced.

Raises:
ValueError

if a ratio or difference is requested with one data set.

visualization.visualize.plot_hist_2d(data, ax=None, **kwargs)[source]#

Produce a two dimensional histogram plot.

Parameters:
data: numpy structured array

Columns are used as the x-axis and y-axis titles.

ax: matplotlib.axes.Axes, optional

Axes to draw on. If not provided, a new figure is created.

**kwargs:

title, cmap and any kwargs accepted by plt.hist2d.

Returns:
pyplot.figure

Figure in which the plot was produced.

visualization.visualize.plot_histogram(data, ax=None, **kwargs)[source]#

Plot a one-dimensional histogram on the provided or current axes.

Parameters:
dataarray-like

Values to plot.

axmatplotlib.axes.Axes, optional

Axes to draw on. If not provided, the current axes are used.

**kwargs

Keyword arguments passed to Axes.hist.

Returns:
matplotlib.figure.Figure

Figure containing the histogram.

visualization.visualize.plot_ratio_difference(ax1, data_dict, plot_ratio, gs, plot_args)[source]#

Plot the ratio or difference plot in the lower panel.

visualization.visualize.plot_table(table, y_title, **kwargs)[source]#

Produce a high contrast one dimensional plot from an astropy.Table.

The first column is the x-axis; each further column is one data set.

Parameters:
table: astropy.Table or astropy.QTable

Table with at least two columns.

y_title: str

The y-axis title.

**kwargs:

Options as for plot_1d().

Returns:
pyplot.fig

Figure instance.

Raises:
ValueError

if table has less than two columns.

visualization.visualize.save_figure(fig, output_file, figure_format=None, log_title='', dpi='figure', close=False, pil_kwargs=None, context=None)[source]#

Save figure to output file(s).

A figure suffix in output_file is replaced by each format; other dots are kept. Formats default to the configured figure_format or PNG. PNG files are converted to a 256-color palette if figure_png_palette is configured.

Parameters:
fig: plt.figure

Figure to save.

output_file: Path, str

Output path, with or without a format suffix.

figure_format: list

List of formats to save the figure.

log_title: str

Title of the figure to be added to the log message.

dpistr or int, optional

DPI for fig.savefig; a configured figure_dpi overrides it for PNG.

closebool, optional

Close the figure after saving. Defaults to False.

pil_kwargsdict, optional

Keyword arguments passed to Pillow when saving PNG files.

visualization.visualize.set_style(palette='default', big_plot=False)[source]#

Set the plotting style (colour palette, font and marker sizes) for following plots.

Parameters:
palette: str

Colour palette: classic (default), modified classic, autumn, purples or greens.

big_plot: bool

If True, fonts and markers are made bigger.

Raises:
KeyError

if provided palette does not exist.

legend_handlers#

Helper functions for legend handlers used for plotting.

class visualization.legend_handlers.BaseLegendHandler(telescope_type=None)[source]#

Base telescope handler that can handle any telescope type.

legend_artist(_, __, ___, handlebox)[source]#

Create the appropriate patch based on telescope type.

class visualization.legend_handlers.EdgePixelObject[source]#

Edge-Pixel Object.

class visualization.legend_handlers.HESSHandler(telescope_type=None)[source]#

Legend handler for HESS telescopes.

class visualization.legend_handlers.HexEdgePixelHandler[source]#

Legend handler class to plot a hexagonal “edge” pixel.

class visualization.legend_handlers.HexOffPixelHandler[source]#

Legend handler class to plot a hexagonal “off” pixel.

class visualization.legend_handlers.HexPixelHandler[source]#

Legend handler class to plot a hexagonal “on” pixel.

class visualization.legend_handlers.LSTHandler(telescope_type=None)[source]#

Legend handler for LST telescopes.

class visualization.legend_handlers.MAGICHandler(telescope_type=None)[source]#

Legend handler for MAGIC telescopes.

class visualization.legend_handlers.MSTHandler(telescope_type=None)[source]#

Legend handler for MST telescopes.

class visualization.legend_handlers.OffPixelObject[source]#

Off-Pixel Object.

class visualization.legend_handlers.PixelObject[source]#

Pixel Object.

class visualization.legend_handlers.SCTHandler(telescope_type=None)[source]#

Legend handler for SCT telescopes.

class visualization.legend_handlers.SSTHandler(telescope_type=None)[source]#

Legend handler for SST telescopes.

class visualization.legend_handlers.SquareEdgePixelHandler[source]#

Legend handler class to plot a square “edge” pixel.

class visualization.legend_handlers.SquareOffPixelHandler[source]#

Legend handler class to plot a square “off” pixel.

class visualization.legend_handlers.SquarePixelHandler[source]#

Legend handler class to plot a square “on” pixel.

class visualization.legend_handlers.VERITASHandler(telescope_type=None)[source]#

Legend handler for VERITAS telescopes.

visualization.legend_handlers.calculate_center(handlebox, width_factor=3, height_factor=3)[source]#

Calculate the center of the handlebox based on given factors.

visualization.legend_handlers.get_telescope_config(telescope_type)[source]#

Return the configuration for a given telescope type.

Try both site-dependent and site-independent configurations (e.g. “MSTS” and “MST”).

Parameters:
telescope_typestr, None

The type of the telescope (e.g., “LSTN”, “MSTS”).

Returns:
dict

The configuration dictionary for the telescope type.

plot_array_layout#

Plot array elements for a layout.

class visualization.plot_array_layout.PlotBounds(x_lim, y_lim)[source]#

Axis-aligned bounds for the layout in meters.

Attributes:
x_limtuple[float, float]

Min/max for x (meters).

y_limtuple[float, float]

Min/max for y (meters).

x_lim#

Alias for field number 0

y_lim#

Alias for field number 1

visualization.plot_array_layout.create_patches(telescopes, scale, show_label, ax, grayed_out_elements=None, highlighted_elements=None)[source]#

Create telescope patches and labels.

Parameters:
telescopesTable

Telescope data table.

scalefloat

Marker size scale factor.

show_labelbool

Show telescope labels.

axAxes

Matplotlib axes object.

grayed_out_elementslist or None

List of telescope names to plot as gray circles.

highlighted_elementslist or None

List of telescope names to plot with red circles around them.

Returns:
patcheslist

Shape patches.

radiilist

Telescope radii.

highlighted_patcheslist

List of highlighted telescope patches.

text_objectslist

List of text objects for labels.

visualization.plot_array_layout.finalize_plot(ax, patches, x_title, y_title, x_lim=None, y_lim=None, highlighted_patches=None)[source]#

Finalize plot appearance and limits.

visualization.plot_array_layout.generate_plot_combinations(args_dict, model_reader=None, *, context=None)[source]#

Yield model version and site combinations for plotting.

Parameters:
args_dictdict

Dictionary with command line arguments.

Yields:
tuple

Pair of (model_version, site) values.

visualization.plot_array_layout.get_patches(ax, telescopes, show_tel_label, axes_range, marker_scaling, grayed_out_elements=None, highlighted_elements=None, filter_x_lim=None, filter_y_lim=None)[source]#

Get plot patches and axis range.

Parameters:
axAxes

Matplotlib axes object.

telescopesTable

Telescope data table.

show_tel_labelbool

Show telescope labels.

axes_rangefloat or None

Axis range, auto if None.

marker_scalingfloat

Marker size scale factor.

grayed_out_elementslist or None

List of telescope names to plot as gray circles.

highlighted_elementslist or None

List of telescope names to plot with red circles around them.

Returns:
patcheslist

List of telescope patches.

axes_rangefloat

Calculated or input symmetric axis range (meters).

highlighted_patcheslist

List of highlighted telescope patches.

boundsPlotBounds

Min/max for x and y in meters.

text_objectslist

List of text objects for labels.

visualization.plot_array_layout.get_positions(telescopes)[source]#

Get X/Y positions depending on coordinate system.

For ground coordinates, rotates the positions by 90 degrees.

Returns:
x_rot, y_rotQuantity

Position coordinates.

visualization.plot_array_layout.get_sphere_radius(tel)[source]#

Get telescope sphere radius.

Returns:
radiusQuantity

Radius with units.

visualization.plot_array_layout.get_telescope_name(tel)[source]#

Get telescope name.

Returns:
namestr

Telescope name or fallback identifier.

visualization.plot_array_layout.get_telescope_patch(tel_type, x, y, radius, is_grayed_out=False)[source]#

Create patch for a telescope.

Parameters:
tel_type: str

Telescope type.

xQuantity

X position.

yQuantity

Y position.

radiusQuantity

Telescope radius.

is_grayed_outbool

Whether to plot telescope in gray.

Returns:
patchPatch

Circle or rectangle patch.

visualization.plot_array_layout.plot_array_layout(telescopes, show_tel_label=False, axes_range=None, marker_scaling=1.0, background_telescopes=None, grayed_out_elements=None, highlighted_elements=None, legend_location='best', bounds_mode='exact', padding=0.1, x_lim=None, y_lim=None)[source]#

Plot telescope array layout.

Parameters:
telescopesTable

Telescope data table.

show_tel_labelbool

Show telescope labels (default False).

axes_rangefloat or None

Axis range, auto if None.

marker_scalingfloat

Marker size scale factor.

background_telescopesTable or None

Optional background telescope table.

grayed_out_elementslist or None

List of telescope names to plot as gray circles.

highlighted_elementslist or None

List of telescope names to plot with red circles around them.

legend_locationstr

Location of the legend (default “best”).

Returns:
figFigure

Matplotlib figure object.

Other Parameters:
bounds_mode{“symmetric”, “exact”}

Controls axis limits calculation. “symmetric” uses +-R where R is the padded maximum extent (default), while “exact” uses individual x/y min/max bounds.

paddingfloat

Fractional padding applied around computed extents (used for both modes).

x_lim, y_limtuple(float, float), optional

Explicit axis limits in meters. If provided, these override axes_range and bounds_mode for the respective axis. If only one is provided, the other axis is derived per mode.

visualization.plot_array_layout.plot_array_layouts(args_dict, output_path, layouts, background_layout=None)[source]#

Plot multiple array layouts.

Parameters:
args_dictdict

Application arguments.

output_pathPath

Output path for figures.

layoutsdict

Dictionary of layout name to telescope table.

background_layoutTable or None

Optional background telescope table.

Returns:
figsdict

Dictionary of layout name to matplotlib figure object.

visualization.plot_array_layout.update_legend(ax, telescopes, grayed_out_elements=None, legend_location='best')[source]#

Add legend for telescope types and counts.

plot_camera#

Plot camera pixel layout and trigger patches.

Model data (camera, trigger tables) are passed in by the caller so that this module does not import the model package.

visualization.plot_camera.parse_pixel_ids_to_print(print_pixels_id_arg, camera)[source]#

Parse the print_pixels_id argument into an integer pixel count.

Parameters:
print_pixels_id_argstr or int

Integer, 0 (suppress) or ‘All’.

cameraCamera

Camera used to determine the total pixel count for ‘All’.

Returns:
int

Number of pixel IDs to print; -1 when printing should be suppressed.

Raises:
ValueError

If the argument is not an integer string or ‘All’.

visualization.plot_camera.plot_pixel_layout(camera, camera_in_sky_coor=False, pixels_id_to_print=50)[source]#

Plot the pixel layout for an observer facing the camera.

Includes edge pixels, off pixels, pixel IDs (up to pixels_id_to_print), coordinate axes, the focal length, the average edge radius and the FoV.

Parameters:
cameraCamera

Camera object to plot.

camera_in_sky_coorbool, optional

Plot the camera in the sky coordinate system.

pixels_id_to_printint, optional

Number of pixel IDs to print in the plot.

Returns:
matplotlib.figure.Figure

Figure with the pixel layout.

visualization.plot_camera.plot_pixel_layout_with_image(camera, image=None, colormap='viridis', norm='lin', ax=None, vmin=None, vmax=None, add_color_bar=True, color_bar_label='Pixel Value', **kwargs)[source]#

Plot pixel layout with optional per-pixel values as colors.

Used to display DL1 images (e.g., integrated signal, peak timing) on the camera.

Parameters:
cameraCamera

Camera object with pixel geometry.

imagenp.ndarray, optional

Per-pixel values to display as colors (shape: n_pix,). If None, plot layout without colored values.

colormapstr, optional

Colormap name (default “viridis”).

normstr, optional

Normalization type: “lin” (linear), “log”, or “symlog” (default “lin”).

axplt.Axes, optional

Existing axes to plot on. If None, create new figure.

vmin, vmaxfloat, optional

Value range for normalization. If None, use data range.

add_color_barbool, optional

Whether to add a color bar (default True).

color_bar_labelstr, optional

Label for the color bar (default “Pixel Value”).

**kwargs

Additional arguments passed to plt.subplots() if ax is None.

Returns:
plt.Figure

Figure with the pixel layout and optional image overlay.

visualization.plot_camera.plot_selected_trigger_patches(camera, groups, sky_coordinates)[source]#

Draw selected trigger groups on a camera overview and a labelled close-up of their union.

Parameters:
cameraCamera

Camera object.

groupsdict

Mapping of group ID to its set of pixel IDs (see read_selected_trigger_patches()).

sky_coordinatesbool

Plot in sky coordinates (no vertical flip for single-mirror telescopes).

Returns:
matplotlib.figure.Figure

The generated figure.

visualization.plot_camera.read_selected_trigger_patches(definitions, members, patch_ids, camera_pixels)[source]#

Resolve the selected trigger groups into their pixel sets, with validation.

Parameters:
definitionsastropy.table.Table

Trigger group definitions with a group_id column.

membersastropy.table.Table

Trigger memberships with group_id and pixel_id columns.

patch_idslist of int

Selected trigger-group IDs.

camera_pixelsset of int

Pixel IDs present in the camera.

Returns:
dict

Mapping of group ID to its set of pixel IDs.

visualization.plot_camera.trigger_patches_for_pixel(members, pixel_id, camera_pixels)[source]#

Find the distinct trigger-group IDs containing a camera pixel.

Parameters:
membersastropy.table.Table

Trigger memberships with group_id and pixel_id columns.

pixel_idint

Camera pixel ID.

camera_pixelsset of int

Pixel IDs present in the camera.

Returns:
list of int

Sorted trigger-group IDs.

plot_telescope_structure#

Plot the optical structure of a telescope: mirrors, camera housing and telescope structure.

The geometry is read from the model parameters with the nominal positions, that is without the random alignment errors of a particular instrument. Only simtools is needed. With shadowing, the structure is coloured by the light each element stops on its own; that needs the obdeect package.

visualization.plot_telescope_structure.plot_telescope_structure(geometry, output_file, shares=None)[source]#

Plot the telescope seen from the sky (x, y) and from the side (x, z).

Parameters:
geometry: TelescopeGeometry

Elements to draw (see telescope_geometry).

output_file: Path or str

Output file name without suffix (see save_figure).

shares: dict, optional

Element name -> (share of light stopped alone in per cent, photons crossing it), as from shadowing_shares. Without it, all structure elements are grey.

plot_corsika_histograms#

Visualize Cherenkov photon distributions from CORSIKA.

visualization.plot_corsika_histograms.export_all_photon_figures_pdf(histograms_instance, pdf_file_name, labels=None)[source]#

Build and save all photon histogram figures into a single PDF.

Parameters:
histograms_instance: corsika.corsika_histograms.CorsikaHistograms or list

Single histogram instance or list of CorsikaHistograms instances from multiple files. When a list is provided, 1D histograms from all files are combined into single plots with different colors, while 2D histograms of the same type are plotted sequentially.

pdf_file_name: str or Path

Name of the output pdf file to save the histograms.

labels: list or None

Optional list of labels for the input files. If None, file names are used as labels. The order should match the order of histograms_instance if it’s a list.

plot_tables#

Plot tabular data.

visualization.plot_tables.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.

visualization.plot_tables.generate_plot_configurations(parameter, parameter_version, site, telescope, output_path, plot_type, model_reader=None, model_version=None, *, context=None)[source]#

Generate plot configurations for a model parameter from schema files.

Parameters:
parameter: str

Model parameter name.

parameter_version: str

Parameter version.

site: str

Site name.

telescope: str

Telescope name.

output_path: str or Path

Output path for the plots.

plot_type: str

Plot type or “all” for all plots.

model_version: str, optional

Exact model version used to read the table data.

Returns:
tuple or None

List of plot configurations and list of output file names, or None if no plot configurations are found.

visualization.plot_tables.plot(config, output_file, data_path=None, model_reader=None, *, context=None)[source]#

Plot tabular data from data or from model parameter files.

Parameters:
config: dict

Configuration dictionary for plotting.

output_file: str

Output file.

data_path: Path or str, optional

Path to the data files. All files are expected in the same directory.

visualization.plot_tables.plot_bias_curves(nsb_stats, proton_stats, config, output_path, trigger_threshold=None)[source]#

Plot NSB and proton bias curves.

Parameters:
nsb_statsdict

NSB statistics by threshold.

proton_statsdict

Proton statistics by threshold.

configdict

Plot configuration with title, ymin, ymax, and scaling_factor.

output_pathPath or str

Output path for plot image.

trigger_thresholdfloat, optional

Trigger threshold value to annotate on the plot.

visualization.plot_tables.read_table_data(config, data_path=None, model_reader=None, *, context=None)[source]#

Read table data from file or parameter repository.

Parameters:
config: dict

Configuration dictionary for plotting.

data_path: Path or str, optional

Path to the data files. All files are expected in the same directory.

Returns:
Dict

Dict with table data (numpy structured arrays).

visualization.plot_tables.resolve_plot_output_path(output, file_name='bias_curve.png')[source]#

Resolve output as either an explicit plot file or an output directory.

plot_pixels#

Functions for plotting pixel layout information.

The camera (simtools.model.camera.Camera) and its raw pixel data are built by the caller, so this module does not import the model package.

visualization.plot_pixels.plot(output_file, camera, raw_pixels, *, rotate_angle=None, pixels_id_to_print=80)[source]#

Plot a pixel layout and save it to file.

Parameters:
output_filestr or Path

Path where to save the plot.

cameraCamera

Camera with pixel geometry (pixels, telescope_name, get_edge_pixels).

raw_pixelsdict

Unrotated pixel data with keys x, y and rotate_angle (radians).

rotate_angleastropy.units.Quantity, optional

Rotation applied to the telescope-specific pixel transform (default: from raw_pixels).

pixels_id_to_printint, optional

Pixel IDs below this value are printed.

visualization.plot_pixels.plot_pixel_layout(camera, raw_pixels, *, rotate_angle=None, pixels_id_to_print=50)[source]#

Create the pixel layout figure.

Parameters:
cameraCamera

Camera with pixel geometry; its pixel positions are transformed in place.

raw_pixelsdict

Unrotated pixel data with keys x, y and rotate_angle (radians).

rotate_angleastropy.units.Quantity, optional

Rotation applied to the telescope-specific pixel transform.

pixels_id_to_printint, optional

Pixel IDs below this value are printed.

Returns:
matplotlib.figure.Figure

The generated figure.

visualization.plot_pixels.raw_pixels_from_configuration(configuration)[source]#

Return unrotated pixel data from resolved camera components.

Parameters:
configurationdict

Output of resolve_camera_components().

Returns:
dict

Keys x, y (cm) and rotate_angle (radians).

visualization.plot_pixels.resolve_camera_components(model_reader, parameters)[source]#

Resolve camera component model parameters for plotting.

plot_trigger_patches#

Analyze and plot camera trigger-patch configuration.

visualization.plot_trigger_patches.analyze_trigger_patch_configuration(camera, trigger_groups, trigger_members)[source]#

Calculate per-pixel patch distances and per-group spatial summaries.

Parameters:
cameraCamera

Camera geometry with pixel IDs and neighbor lookup.

trigger_groupsastropy.table.Table

Group definitions with group_id and kind columns.

trigger_membersastropy.table.Table

Memberships with group_id and pixel_id columns.

Returns:
tuple of astropy.table.Table

Per-pixel and per-group diagnostics. Distances are in camera-plane centimeters; undefined distances are NaN.

Raises:
ValueError

If the camera or trigger tables contain inconsistent identifiers.

visualization.plot_trigger_patches.format_trigger_patch_summary(pixel_table, group_table)[source]#

Format the page-two summary for both the report and application log.

Parameters:
pixel_tableastropy.table.Table

Per-pixel diagnostics.

group_tableastropy.table.Table

Per-group diagnostics.

Returns:
str

Multi-line summary text.

visualization.plot_trigger_patches.write_trigger_patch_report(camera, pixel_table, group_table, pdf_path)[source]#

Write a two-page PDF for trigger-patch diagnostics.

Parameters:
cameraCamera

Camera geometry used for both pages.

pixel_tableastropy.table.Table

Per-pixel output from analyze_trigger_patch_configuration().

group_tableastropy.table.Table

Per-group output from analyze_trigger_patch_configuration().

pdf_pathpathlib.Path or str

Destination PDF path.

Returns:
str

The page-two summary text for application logging.

plot_simtel_events#

Plot sim_telarray events.

class visualization.plot_simtel_events.EventData(event_id, adc_samples=None, number_of_pixels=0, n_samples=0, pedestals=None, image=None)[source]#

Event data for plotting.

class visualization.plot_simtel_events.PlotSimtelEvent(file_name, telescope, event_ids=None, max_events=None)[source]#

Plot a single sim_telarray event.

Parameters:
file_namestr | pathlib.Path

Path to the sim_telarray file.

telescopestr

Telescope name or ID to process.

event_idsint or list of int, optional

IDs of the event(s) to process.

max_eventsint, optional

Maximum number of events to process.

make_output_paths(ioh, base)[source]#

Return output file path based on base name and input file.

plot(plots, args, output_file, save_png=False, dpi=300)[source]#

Generate all requested plots for the event.

Parameters:
plotslist of str

List of plot names to generate.

argsdict

Additional arguments for plot functions.

output_filePath

Base output file path for saving plots.

save_pngbool

Whether to save individual PNG files per plot.

dpiint

DPI for saved PNG files.

plot_peak_timing(event_index, sum_threshold=10.0, timing_bins=None)[source]#

Peak finding per pixel; plot histogram of peak sample times.

Parameters:
event_indexint

Event index.

sum_thresholdfloat, optional

Minimum sum over samples for a pixel to be considered.

timing_binsint | None, optional

Number of histogram bins. If None, use unit-width bins.

Returns:
matplotlib.figure.Figure | None

The created figure, or None if no pixels exceed threshold.

plot_pedestals(event_index)[source]#

Plot pedestal values for all pixels.

plot_signals(event_index)[source]#

Plot integrated trace values.

plot_step_traces(event_index, pixel_step=10, max_pixels=None)[source]#

Plot step-style R1 traces for regularly sampled pixels (0, N, 2N, …).

Parameters:
event_indexint

Event index.

pixel_stepint, optional

Interval between pixel indices to plot.

max_pixelsint | None, optional

Maximum number of pixels to plot. If None, plot all selected by pixel_step.

Returns:
matplotlib.figure.Figure

The created figure.

plot_time_traces(event_index, number_of_pixels=3)[source]#

Plot R1 time traces for pixels with highest signal.

Parameters:
event_indexint

Event index.

number_of_pixelsint, optional

Number of pixels with highest signal to plot.

Returns:
matplotlib.figure.Figure

The created figure.

plot_waveforms(event_index, vmax=None, pixel_step=None)[source]#

Create a pseudocolor image of R1 waveforms (sample index vs. pixel id).

Parameters:
event_indexint

Event index.

vmaxfloat | None, optional

Upper limit for color normalization. If None, determined automatically.

pixel_stepint | None, optional

Step between plotted pixel ids (e.g., 1 plots all, 2 plots every second pixel).

Returns:
matplotlib.figure.Figure

The created figure.

save(args, output_file)[source]#

Save generated plots to files.

visualization.plot_simtel_events.generate_and_save_plots(plots, args, ioh)[source]#

Generate events plots from a sim-telarray file and save a multi-page PDF per input.

Writes additionally metadata.

Parameters:
plotslist of str

List of plot names to generate.

argsdict

Additional arguments for plot functions.

iohOutputPaths

Paths used for output files and metadata.

plot_simtel_event_histograms#

Plot simtel event histograms filled with EventDataHistograms.

visualization.plot_simtel_event_histograms.plot(histograms, output_path=None, limits=None, array_name=None, add_distance_projections=False, use_broad_range_limits=False)[source]#

Plot simtel event histograms.

Parameters:
histograms: EventDataHistograms

Instance containing the histograms to plot.

output_path: Path or str, optional

Directory to save plots. If None, plots will be displayed.

limits: dict, optional

Dictionary containing limits for plotting. Keys can include: - “upper_radius_limit”: Upper limit for core distance - “lower_energy_limit”: Lower limit for energy - “viewcone_radius”: Radius for the viewcone

array_name: str, optional

Name of the telescope array configuration.

add_distance_projections: bool, optional

Add overall and sliced x/y projections to raw distance-vs-energy plots.

use_broad_range_limits: bool, optional

Restrict plot axes to the broad-range simulation limits in limits.

visualization.plot_simtel_event_histograms.plot_monte_carlo_statistics_diagnostics(output_dir, array_name, file_info, energy_edges, angular_edges, expected_counts, relative_uncertainty)[source]#

Write Monte Carlo statistics diagnostic plots.

Parameters:
output_dirstr or pathlib.Path

Directory to write plot files.

array_namestr

Array or telescope-selection name used in plot titles and filenames.

file_infodict, optional

Simulation metadata (zenith, azimuth, nsb_level) to make filenames unique per setup.

energy_edgesarray-like

Energy bin edges in TeV.

angular_edgesarray-like

Angular-distance bin edges in deg.

expected_countsnumpy.ndarray

Expected triggered events per angular-distance and energy bin.

relative_uncertaintynumpy.ndarray

Poisson relative uncertainty per angular-distance and energy bin.

visualization.plot_simtel_event_histograms.plot_trigger_histograms(loaded_histograms, output_dir)[source]#

Plot loaded trigger histograms, writing one directory per array layout.

Parameters:
loaded_histogramsiterable

Loaded histogram records, each paired with its array layout.

output_dirstr or pathlib.Path

Base directory where plot files will be written.

plot_production_comparison#

Plot event-level and signal-level comparisons across simulation productions.

visualization.plot_production_comparison.annotate_comparison_statistics(ax, statistics)[source]#

Overlay comparison metric values for baseline-vs-candidate comparisons on a plot.

visualization.plot_production_comparison.plot_event_level_comparison(metrics_per_production, output_path=None, array_layout_name=None, bins=40, figure_format=None, report_mode='diagnostic', compact_figures=None, comparison_title=None, comparison_context=None, *, context=None)[source]#

Create all event-level production comparison plots.

Parameters:
metrics_per_productionlist[ProductionEventMetrics]

Aggregated metrics per production.

output_pathpathlib.Path, optional

Output directory for the generated plots. Falls back to the current application output directory when omitted.

array_layout_namestr, optional

Array-layout selection used to collect the metrics. When set, plots are written into a subdirectory with that name.

binsint, optional

Number of bins for 1D histograms.

figure_formatlist[str] or str, optional

Figure formats to write. Formats supported by Matplotlib can be used. Defaults to the configured formats or ["png"].

comparison_titlestr, optional

Context heading shown above each plot, such as the configuration of a matched production pair.

comparison_contextdict, optional

Baseline and candidate configuration metadata. Compact reports omit fixed-energy and on-axis angular distributions when both configurations establish those conditions.

Returns:
pathlib.Path

Path to the JSON file containing the comparison statistics.

visualization.plot_production_comparison.plot_signal_level_comparison(metrics_by_telescope, output_path, bins=40, figure_format=None)[source]#

Create signal comparison plots for every telescope in a layout.

Parameters:
metrics_by_telescopedict[str, list[ProductionSignalMetrics]]

Metrics grouped by telescope name and ordered by production.

output_pathpathlib.Path

Base output directory.

binsint, optional

Number of histogram bins.

figure_formatlist[str] or str, optional

Figure formats to write. Defaults to the configured formats or ["png"].

Returns:
list[pathlib.Path]

Paths to the comparison statistics JSON files.

plot_resource_requirements#

Plot normalized CORSIKA and sim_telarray resource requirements.

visualization.plot_resource_requirements.plot(rows, output_path, figure_format=None, report_mode='diagnostic')[source]#

Write resource plots versus energy.

Parameters:
rowsiterable[dict]

Normalized process rows returned by the resource collector.

output_pathstr or pathlib.Path

Destination directory for the figures.

figure_formatiterable[str], optional

File formats passed to visualization.visualize.save_figure().

report_modestr, optional

"diagnostic" writes one figure per metric and role, "compact" a multipage PDF, and "none" writes nothing.

Returns:
list[pathlib.Path]

Base paths of the written figures.

Notes

Byte-based quantities are plotted in MB or GB, selected from the largest value in each plot, using decimal units. Per-run plots use the *_bytes and raw time columns; per-event and per-triggered-event plots use their normalized columns. When both baseline and candidate rows are present, additional plots show candidate-to-baseline ratios for matching primary, site, layout, and model-version configurations.

plot_psf#

Optical PSF plotting functions for parameter optimization visualization.

This module provides plotting functionality for PSF parameter optimization, including parameter comparison plots, convergence plots, and PSF diameter vs off-axis plots.

visualization.plot_psf.create_gradient_descent_convergence_plot(gd_results, threshold, output_file, fraction=0.8, use_ks_statistic=False)[source]#

Create convergence plot during gradient descent.

Parameters:
gd_resultslist

List of (params, metric, p_value, psf_diameter, simulated_data) tuples.

thresholdfloat

Optimization metric threshold used for convergence.

output_filePath

Output file path for saving the plot.

fractionfloat, optional

PSF containment fraction for labeling (default: 0.8).

use_ks_statisticbool

Whether to use KS statistic or RMSD labels and titles.

visualization.plot_psf.create_monte_carlo_uncertainty_plot(mc_results, output_file, fraction=0.8, use_ks_statistic=False)[source]#

Create uncertainty analysis plots showing optimization metric and p-value distributions.

Parameters:
mc_resultstuple

(mean_metric, std_metric, metric_values, mean_p, std_p, p_values, mean_psf_diameter, std_psf_diameter, psf_diameter_values) from the Monte Carlo analysis.

output_filePath

Output file path; its suffix is replaced by _ks or _rmsd.

fractionfloat, optional

PSF containment fraction for labeling (default: 0.8).

use_ks_statisticbool, optional

Whether KS statistic mode is being used (affects filename suffix).

visualization.plot_psf.create_psf_parameter_plot(data_to_plot, pars, psf_diameter, metric, is_best, pdf_pages, fraction=0.8, p_value=None, use_ks_statistic=False, second_metric=None)[source]#

Add a cumulative PSF plot of one parameter set to a PDF report.

Parameters:
data_to_plotdict

Data dictionary for plotting.

parsdict

Parameter set dictionary.

psf_diameter, metricfloat

PSF diameter and metric (RMSD, or KS statistic if use_ks_statistic).

is_bestbool

Whether this is the best parameter set.

pdf_pagesPDF report object

Open report for adding plots.

fraction, p_value, use_ks_statistic, second_metricoptional

PSF containment fraction, KS p-value, KS mode flag and second metric.

visualization.plot_psf.get_psf_diameter_label(fraction, unit='cm')[source]#

Generate PSF diameter label from the containment fraction, e.g. “D80 (cm)”.

Parameters:
fractionfloat

PSF containment fraction (0.8 for D80).

unitstr, optional

Unit appended in parentheses (default: “cm”).

Returns:
str

Label such as “D80 (cm)”, or “D80” if unit is empty.

visualization.plot_psf.get_significance_label(p_value)[source]#

Get significance label for p-value: GOOD (>0.05), FAIR (>0.01) or POOR.

visualization.plot_psf.plot_psf_histogram(measured, simulated, args_dict)[source]#

Write histogram comparing measured vs simulated PSF diameter distributions.

plot_ray_tracing_psf#

Shared PSF plotting helpers for ray-tracing workflows.

visualization.plot_ray_tracing_psf.create_annotated_psf_image_figure(data, off_x, off_y, psf, containment_radius, image_range, bins=150, cmap=None, psf_kwargs=None, telescope_name=None)[source]#

Create a PSF image figure annotated with offset and PSF information.

Parameters:
datanumpy.ndarray

Structured array with X and Y columns, in the display unit.

off_x, off_yfloat

Off-axis components in degrees.

psfastropy.units.Quantity

PSF diameter; its unit sets the axis labels and annotation.

containment_radiusastropy.units.Quantity

Containment radius in the same unit as psf.

image_rangelist

Range passed to Axes.hist2d.

binsint

Number of histogram bins.

cmapmatplotlib colormap, optional

Colormap passed to Axes.hist2d.

psf_kwargsdict, optional

Keyword arguments passed to matplotlib.patches.Circle.

telescope_namestr, optional

Telescope name shown in the annotation box.

Returns:
matplotlib.figure.Figure

Created figure.

visualization.plot_ray_tracing_psf.create_cumulative_psf_figure(data, radius_key, cumulative_key, containment_radius_cm, psf_diameter_cm=None, **plot_kwargs)[source]#

Create a cumulative PSF plot.

Parameters:
datanumpy.ndarray

Structured array with radius and cumulative PSF columns.

radius_key, cumulative_keystr

Column names of the radius and cumulative PSF values.

containment_radius_cmfloat

Containment marker radius in cm.

psf_diameter_cmfloat, optional

PSF diameter marker in cm.

**plot_kwargs

Passed to Axes.plot.

Returns:
tuple

Figure and axes.

visualization.plot_ray_tracing_psf.create_psf_image_figure(data, containment_radius, center, psf_kwargs=None, use_current_axes=False, **hist_kwargs)[source]#

Create a 2D histogram plot of a PSF image with the containment circle.

Parameters:
datanumpy.ndarray

Structured array with X and Y columns.

containment_radiusfloat

Radius of the containment circle, in the same unit as the data.

centertuple

Center of the PSF circle, in the same unit as the data.

psf_kwargsdict, optional

Keyword arguments passed to matplotlib.patches.Circle.

use_current_axesbool

Draw on the current axes instead of a new figure.

**hist_kwargs

Passed to visualize.plot_hist_2d (image_range is an alias of range).

Returns:
tuple

Figure and axes.

visualization.plot_ray_tracing_psf.save_and_close_figure(fig, file_name)[source]#

Save a figure to an exact path and close it.

plot_mirrors#

Functions for plotting mirror panel layout information.

visualization.plot_mirrors.plot(config, output_file, data_file_path, mirrors=None)[source]#

Plot mirror panel layout based on configuration.

Parameters:
configdict

Keys parameter (e.g., “mirror_list”, “primary_mirror_segmentation”) and telescope (e.g., “LSTN-01”).

output_filestr or Path

Path where to save the plot (without extension).

data_file_pathstr or Path

Exported mirror or segmentation file.

mirrorsMirrors, optional

Parsed mirror data; required for mirror lists.

visualization.plot_mirrors.plot_mirror_layout(mirrors, mirror_file_path, telescope_model_name)[source]#

Plot the mirror panel layout from a Mirrors object.

Parameters:
mirrorsMirrors

Mirror panel positions, diameters, focal lengths and shape types.

mirror_file_pathPath or str

Mirror list file (its header provides the statistics).

telescope_model_namestr

Telescope model name (e.g., “LSTN-01”, “MSTN-01”).

Returns:
matplotlib.figure.Figure

The generated figure object.

visualization.plot_mirrors.plot_mirror_ring_segmentation(data_file_path, telescope_model_name, parameter_type)[source]#

Plot mirror ring segmentation layout (polar view).

Parameters:
data_file_pathPath or str

Segmentation file with ring <nseg> <rmin> <rmax> <dphi> <phi0> lines.

telescope_model_namestr

Telescope model name (e.g., “LSTN-01”).

parameter_typestr

Segmentation parameter (e.g., “primary_mirror_segmentation”).

Returns:
matplotlib.figure.Figure or None

The generated figure object, or None if no ring data is found.

visualization.plot_mirrors.plot_mirror_segmentation(data_file_path, telescope_model_name, parameter_type)[source]#

Plot mirror segmentation layout from a standard segmentation file.

Parameters:
data_file_pathPath or str

Segmentation file with positions, diameters, shape types and segment IDs.

telescope_model_namestr

Telescope model name (e.g., “LSTN-01”).

parameter_typestr

Segmentation parameter (e.g., “primary_mirror_segmentation”).

Returns:
matplotlib.figure.Figure

The generated figure object.

visualization.plot_mirrors.plot_mirror_shape_segmentation(data_file_path, telescope_model_name, parameter_type)[source]#

Plot mirror shape segmentation layout (explicit hex and yhex shapes).

Parameters:
data_file_pathPath or str

Segmentation file with explicit shape definitions (hex, yhex).

telescope_model_namestr

Telescope model name (e.g., “LSTN-01”, “MSTN-design”).

parameter_typestr

Segmentation parameter (e.g., “primary_mirror_segmentation”).

Returns:
matplotlib.figure.Figure

The generated figure object.

plot_incident_angles#

Plot incident angle histograms for focal, primary, and secondary mirrors.

Plots the primary-mirror hit radius if available.

members:

camera_plot_utils#

Shared helpers for camera pixel plotting.

visualization.camera_plot_utils.add_pixel_legend(ax, on_pixels, off_pixels)[source]#

Add the pixel, edge pixel and disabled pixel legend.

Parameters:
axmatplotlib.axes.Axes

Axes object to add the legend to.

on_pixelslist

Enabled pixel patches (selects hexagonal or square legend handlers).

off_pixelslist

Disabled pixel patches.

visualization.camera_plot_utils.add_pixel_patch_collections(ax, on_pixels, edge_pixels, off_pixels)[source]#

Add patch collections for on, edge and off pixels to the axes.

Parameters:
axmatplotlib.axes.Axes

Axes object to add the patch collections to.

on_pixels, edge_pixels, off_pixelslist

Pixel patches (see create_pixel_patches_by_type()).

visualization.camera_plot_utils.create_pixel_patches_by_type(camera)[source]#

Create pixel patches categorized by type.

Parameters:
cameraCamera

Camera object containing pixel positions and status.

Returns:
tuple of (list, list, list)

Patches for enabled inner pixels, enabled edge pixels and disabled pixels.

visualization.camera_plot_utils.pixel_shape(camera, x, y)[source]#

Return the matplotlib patch of one pixel.

Parameters:
cameraCamera

Camera object containing pixel configuration.

x, yfloat

Coordinates of the pixel center.

Returns:
matplotlib.patches.Patch or None

Hexagon or rectangle patch; None if the pixel shape is not recognized.

visualization.camera_plot_utils.setup_camera_axis_properties(ax, camera, grid=False, axis_below=False, grid_alpha=None, y_scale_factor=1.0, padding=0)[source]#

Set up common axis properties for camera plots.

Parameters:
axmatplotlib.axes.Axes

Axes object to configure.

cameraCamera

Camera object containing pixel positions.

grid, axis_belowbool, optional

Show grid lines; place axis below the plot elements.

grid_alphafloat, optional

Transparency of grid lines (default grid alpha if None).

y_scale_factorfloat, optional

Scaling factor for y-axis limits.

paddingfloat, optional

Padding around the camera extent.

plot_science_comparison#

Plot telescope-throughput science-result comparisons into PDF pages.

visualization.plot_science_comparison.plot_components(baseline_table, candidate_table, title, labels, pdf_pages)[source]#

Add absolute and relative pages for each optical efficiency component.

Parameters:
baseline_table, candidate_tablestr or pathlib.Path

Wavelength tables of one channel.

titlestr

Page title prefix.

labelstuple of str

Baseline and candidate legend labels.

pdf_pagesPDF report object

Open PDF report.

Returns:
str or None

Reason the components could not be compared.

visualization.plot_science_comparison.plot_metric_changes(changes, title, pdf_pages)[source]#

Add a page with scalar values and their relative change.

Parameters:
changesdict

Metric changes as returned by telescope_throughput.compare_results.

titlestr

Page title.

pdf_pagesPDF report object

Open PDF report.

visualization.plot_science_comparison.plot_spectra(baseline_tables, candidate_tables, title, labels, pdf_pages)[source]#

Add a page comparing the detected spectrum of each common channel.

Parameters:
baseline_tables, candidate_tablesdict

Wavelength-table paths by channel.

titlestr

Page title.

labelstuple of str

Baseline and candidate legend labels.

pdf_pagesPDF report object

Open PDF report.

Returns:
list of str

Channels that could not be compared.

plot_production_grid#

Plot production-grid points on sky coordinate projections.

class visualization.plot_production_grid.ProductionGridPlotter(grid_points_file, output_path)[source]#

Plot production grid points on sky coordinate projections.

Parameters:
grid_points_filestr or Path

Path to the ECSV file containing grid points.

output_pathstr or Path

Path to save output plots.

normalize_grid_points()[source]#

Return normalized grid points for plotting and validation.

plot_azimuth_zenith_projection_with_color_scale(value_key, value_label, output_file_stem, plot_points=None)[source]#

Plot azimuth/zenith points with a color scale for one value column.

plot_limit_projections()[source]#

Plot all supported production-grid limit values.

plot_shower_statistics_vs_zenith(azimuth_center=180.0, azimuth_width=1.0)[source]#

Plot total and per-run showers against zenith angle.

Parameters:
azimuth_centerfloat, optional

Center of the azimuth interval used for the selected-azimuth plot.

azimuth_widthfloat, optional

Width in degrees of the selected azimuth interval.

Raises:
ValueError

If azimuth_width is not positive.

plot_sky_projection()[source]#

Create sky projection plots with Alt/Az and HA/Dec grid points.

plot_zenith_limits_for_azimuths(value_key, value_label, output_file_stem, azimuth_targets=(0.0, 180.0), azimuth_tolerance_deg=1e-06, plot_points=None)[source]#

Plot value versus zenith for selected azimuth pointings.

plot_corsika_limits#

Plotting utilities for CORSIKA limits tables.

visualization.plot_corsika_limits.plot_limits(limits_table, output_dir)[source]#

Create plots of derived CORSIKA limits for each array and primary particle.

NSB levels are distinguished by color. Azimuth directions share a plot and use filled and open markers in ascending azimuth order.

Parameters:
limits_table (Table)

An astropy Table containing the CORSIKA limits data.

output_dir (str or Path)

Directory where the generated plots will be saved.

Returns:
list of Path

List of file paths to the generated plots.

matplotlib_backend#

Configure the Matplotlib backend used by simtools visualizations.

visualization.matplotlib_backend.lazy_module(module_name)[source]#

Return a proxy that imports a plotting dependency on first use.

Parameters:
module_namestr

Fully qualified name of the plotting module to import lazily.

Returns:
_MatplotlibModuleProxy

Proxy that loads module_name when an attribute or item is accessed.