Source code for ctapipe.io.datawriter

"""
Class to write DL1 (a,b) and DL2 (a) data from an event stream
"""

import pathlib
from collections import defaultdict

import astropy.units as u
import ctao_datamodel.models.dataproducts as dp
import numpy as np
import tables
from astropy.coordinates import Longitude
from astropy.stats import circmean
from astropy.time import Time
from ctao_datamodel.models.common import SiteID
from traitlets import Dict, Instance

from ..containers import (
    SubarrayEventContainer,
    TelescopeConfigurationIndexContainer,
    TelescopeEventContainer,
)
from ..core import Component, Container, Field, Provenance, ToolConfigurationError
from ..core.provenance import _ActivityProvenance
from ..core.traits import Bool, CaselessStrEnum, Float, Int, Path, Unicode
from ..instrument import SubarrayDescription
from . import metadata as meta
from .astropy_helpers import write_table
from .datalevels import DataLevel
from .eventsource import EventSource
from .hdf5tableio import HDF5TableWriter
from .tableio import FixedPointColumnTransform, TelListToMaskTransform

__all__ = ["DataWriter", "DATA_MODEL_VERSION"]

tables.parameters.NODE_CACHE_SLOTS = 3000  # fixes problem with too many datasets

DL2_SUBLEVELS = {
    "geometry": dp.ProcessingSublevel.GEOMETRY,
    "energy": dp.ProcessingSublevel.ENERGY,
    "particle_type": dp.ProcessingSublevel.GAMMANESS,
}


# define the version of the data model written here. This should be updated
# when necessary:
# - increase the major number if there is a breaking change to the model
#   (meaning readers need to update scripts)
# - increase the minor number if new columns or datasets are added
# - increase the patch number if there is a small bugfix to the model.
DATA_MODEL_VERSION = "v8.0.0"
DATA_MODEL_CHANGE_HISTORY = """
- v8.0.0: - Trigger information is moved from DL1 to DL0
          - Added field tels_with_data to SubarrayTriggerContainer and thus
            /dl0/event/subarray/trigger table to be compliant with CTAO DL0 data model
            and allow better treatment of busy triggers.
- v7.7.0: - Add pixel_status field to DL1CameraContainer.
          - Add field "nsb_scaling_factor" to the simulation configuration
- v7.6.0: - Add new monitoring group for pixel histograms: DL1_PIXEL_HISTOGRAMS_GROUP.
- v7.5.0: - Add new field pixel_time_shift in R1CameraContainer and DL0CameraContainer
- v7.4.0: - Add new data quality and top-level monitoring groups for DL0 and DL1 data.
- v7.3.0: - Add possibility to attach monitoring data to the event HDF5 file.
          - Add the event type to the telescope trigger container.
- v7.2.0: - Added new monitoring groups: DL1_TEL_[OPTICAL_PSF, MUON_THROUGHPUT, ILLUMINATOR_THROUGHPUT]_GROUP
            and DL2_SUBARRAY_[MONITORING, INTER_CALIBRATION, CROSS_CALIBRATION]_GROUP
          - Change field name in ``ReconstructedContainer`` from 'classification' to 'particle_type'.
- v7.1.0: - Two new fields for the hillas parameters, uncertainties on psi and the transversal cog coordinate.
- v7.0.0: - Use high resolution timestamps for times. CTAO high resolution times
            are stored as two uint32: seconds and quarter nanoseconds since 1970-01-01T00:00:00 TAI.
- v6.0.0: - Change R1- and DL0-waveform shape from (n_pixels, n_samples) to be always
            (n_channels, n_pixels, n_samples).
- v5.1.0: - Remove redundant 'is_valid' column in ``DispContainer``.
          - Rename content of ``DispContainer`` from 'norm' to 'parameter' and use the same
            default prefix ('disp') for all containers filled by ``DispReconstructor``.
- v5.0.0: - Change DL2 telescope-wise container prefixes from {algorithm}_tel to {algorithm}_tel_{kind}.
            As of now, this only changes 'tel_distance' to 'tel_impact_distance'
- v4.0.0: - Changed how ctapipe-specific metadata is stored in hdf5 attributes.
            This breaks backwards and forwards compatibility for almost everything.
          - Container prefixes are now included for reconstruction algorithms
            and true parameters.
          - Telescope Impact Parameters were added.
          - Effective focal length and nominal focal length are both included
            in the optics description now. Moved ``TelescopeDescription.type``
            to ``OpticsDescription.size_type``. Added ``OpticsDescription.reflector_shape``.
          - n_samples, n_samples_long, n_channels and n_pixels are now part
            of CameraReadout.
          - The reference_location (EarthLocation origin of the telescope coordinates)
            is now included in SubarrayDescription
          - Only unique optics are stored in the optics table
          - include observation configuration
- v3.0.0: reconstructed core uncertainties split in their X-Y components
- v2.2.0: added R0 and R1 outputs
- v2.1.0: hillas and timing parameters are per default saved in telescope frame (degree) as opposed to camera frame (m)
- v2.0.0: Match optics and camera tables using indices instead of names
- v1.2.0: change to more general data model, including also DL2 (DL1 unchanged)
- v1.1.0: images and peak_times can be stored as scaled integers
- v1.0.3: true_image dtype changed from float32 to int32
"""

PROV = Provenance()


[docs] class DataWriter(Component): """Serialize a sequence of events into the ctapipe HDF5 format. Examples -------- inside a Tool: .. code-block:: python with DataWriter(parent=self) as write_data: for event in source: calibrate(event) process_images(event) write_data(event) """ # pylint: disable=too-many-instance-attributes contact_info = Instance( meta.Contact, kw={}, help="Contact information for the output data product.", ).tag(config=True) curation_info = Instance( meta.Curation, kw={}, help="Curation information for the output data product.", ).tag(config=True) product_info = Instance( meta.ProductMetadata, kw={}, help="Product information for the output data product.", ).tag(config=True) context_metadata = Dict( help=( "Additional metadata keywords and values that describe this data. " "This should be a dictionary where the keys will be appended to the " "CONTEXT section of the output file's attributes. Keys can be hierarchical " "by using a space between each level, e.g. ``SIMULATION PRODUCTION`` " "would make a key PRODUCTION grouped under the key SIMULATION" ) ).tag(config=True) output_path = Path( help="output filename", default_value=pathlib.Path("events.dl1.h5") ).tag(config=True) write_r0_waveforms = Bool( help="Store R0 waveforms; requires R0 input", default_value=False ).tag(config=True) write_r1_waveforms = Bool( help="Store R1 waveforms; requires R1 input", default_value=False ).tag(config=True) write_dl1_images = Bool( help="Store DL1 Images if available", default_value=False ).tag(config=True) write_dl1_parameters = Bool( help="Store DL1 image parameters if available", default_value=True ).tag(config=True) write_dl2 = Bool( help="Store DL2 stereo shower parameters if available", default_value=False ).tag(config=True) write_muon_parameters = Bool( help="Store muon parameters if available", default_value=False ).tag(config=True) compression_level = Int( help="compression level, 0=None, 9=maximum", default_value=5, min=0, max=9 ).tag(config=True) compression_type = CaselessStrEnum( values=["blosc:zstd", "zlib"], help="compressor algorithm to use. ", default_value="blosc:zstd", ).tag(config=True) overwrite = Bool(help="overwrite output file if it exists").tag(config=True) transform_waveform = Bool(default_value=False).tag(config=True) waveform_dtype = Unicode(default_value="int32").tag(config=True) waveform_offset = Int(default_value=0).tag(config=True) waveform_scale = Float(default_value=1000.0).tag(config=True) transform_image = Bool(default_value=False).tag(config=True) image_dtype = Unicode(default_value="int32").tag(config=True) image_offset = Int(default_value=0).tag(config=True) image_scale = Float(default_value=10.0).tag(config=True) transform_peak_time = Bool(default_value=False).tag(config=True) peak_time_dtype = Unicode(default_value="int16").tag(config=True) peak_time_offset = Int(default_value=0).tag(config=True) peak_time_scale = Float(default_value=100.0).tag(config=True) def __init__(self, event_source: EventSource, config=None, parent=None, **kwargs): """ Parameters ---------- event_source : EventSource parent event source, which provides header information for the subarray, observation, simulation configuration, and the obs_id config : , optional configuration class parent : , optional parent of this component in the config hierarchy (this supersedes the config option) **kwargs : other options, such as parameters passed to parent. """ super().__init__(config=config, parent=parent, **kwargs) for option, level in ( ("write_r0_waveforms", DataLevel.R0), ("write_r1_waveforms", DataLevel.R1), ): if getattr(self, option) and level not in event_source.datalevels: raise ToolConfigurationError( f"DataWriter.{option} is True but the input does not provide {level.name} data" ) self.contact_info = meta.Contact(parent=self) self.curation_info = meta.Curation(parent=self) self.product_info = meta.ProductMetadata(parent=self) # Validate metadata before creating the output file. self.contact_info.to_model() self.curation_info.to_model() self.product_info.validate_meta() self.event_source = event_source self._at_least_one_event = False self._is_simulation = event_source.is_simulation self._subarray: SubarrayDescription = event_source.subarray self._hdf5_filters = None self._processing_sublevels = dp.ProcessingSublevel(0) self._setup_output_path() self._setup_compression() self._setup_writer() self._setup_outputfile() # store per-ob for which telescopes we've already written the fixed pointing self._constant_telescope_pointing_written = defaultdict(set) def _setup_outputfile(self): self._subarray.to_hdf(self._writer.h5file) self._write_scheduling_and_observation_blocks() if self._is_simulation: self._write_simulation_configuration() self._write_atmosphere_profile( "/simulation/service/atmosphere_density_profile" ) def __enter__(self): return self def __exit__(self, exc_type, exc_value, exc_traceback): self.finish()
[docs] def __call__(self, event: SubarrayEventContainer): """ Write a single event to the output file. """ self._validate_event(event) self._at_least_one_event = True self.log.debug("WRITING EVENT %s", event.index) self._write_simulation_subarray(event) self._write_dl0_subarray(event) if self.write_dl2: self._write_dl2_subarray(event) for tel_event in event.tel.values(): self._write_telescope_event(tel_event)
def _validate_event(self, event): """Check requested outputs before writing any part of an event.""" if event.dl0 is None or event.dl0.trigger is None: raise ValueError("DataWriter requires subarray DL0 trigger information") for tel_id, tel_event in event.tel.items(): if tel_event.dl0 is None or tel_event.dl0.trigger is None: raise ValueError( f"DataWriter requires DL0 trigger information for telescope {tel_id}" ) for option, level, field in ( ("write_r0_waveforms", "r0", "waveform"), ("write_r1_waveforms", "r1", "waveform"), ("write_dl1_images", "dl1", "image"), ("write_dl1_parameters", "dl1", "parameters"), ("write_muon_parameters", "muon", None), ): if not getattr(self, option): continue container = getattr(tel_event, level) if container is None or ( field is not None and getattr(container, field) is None ): raise ValueError( f"DataWriter.{option} is True but telescope {tel_id} " f"does not contain {level.upper()} {field or 'results'}" ) if ( self.write_dl2 and event.dl2 is None and not any(tel_event.dl2 is not None for tel_event in event.tel.values()) ): raise ValueError( "DataWriter.write_dl2 is True but the event contains no DL2 data" ) def _write_simulation_subarray(self, event): if event.simulation is not None and event.simulation.shower is not None: self._writer.write( table_name="simulation/event/subarray/shower", containers=[event.index, event.simulation.shower], ) def _write_dl0_subarray(self, event): self._writer.write( table_name="dl0/event/subarray/trigger", containers=[event.index, event.dl0.trigger], ) def _write_telescope_event(self, tel_event): table_name = self.table_name(tel_event.index.tel_id) if tel_event.simulation is not None: self._writer.write( f"simulation/event/telescope/impact/{table_name}", [tel_event.index, tel_event.simulation.impact], ) self._write_simulation_telescope(tel_event) self._write_constant_pointing(tel_event) if self.write_r0_waveforms: self._write_r0_telescope(tel_event) if self.write_r1_waveforms: self._write_r1_telescope(tel_event) # always write dl0, contains needed trigger info etc. self._write_dl0_telescope(tel_event) if self.write_dl1_images or self.write_dl1_parameters: self._write_dl1_telescope(tel_event) if self.write_dl2: self._write_dl2_telescope(tel_event) if self.write_muon_parameters: self._write_muon_telescope(tel_event) def _write_r0_telescope(self, tel_event: TelescopeEventContainer): table_name = self.table_name(tel_event.index.tel_id) tel_event.r0.prefix = "" self._writer.write( f"r0/event/telescope/{table_name}", [tel_event.index, tel_event.r0], ) def _write_r1_telescope(self, tel_event: TelescopeEventContainer): table_name = self.table_name(tel_event.index.tel_id) tel_event.r1.prefix = "" self._writer.write( f"r1/event/telescope/{table_name}", [tel_event.index, tel_event.r1], ) def _write_dl0_telescope(self, tel_event: TelescopeEventContainer): self._writer.write( "dl0/event/telescope/trigger", [tel_event.index, tel_event.dl0.trigger], ) def _write_dl1_telescope(self, tel_event: TelescopeEventContainer): tel_index = tel_event.index tel_id = tel_index.tel_id table_name = self.table_name(tel_id) tel_event.dl1.prefix = "" # don't want a prefix for this container if self.write_dl1_parameters and tel_event.dl1.parameters is not None: self._writer.write( table_name=f"dl1/event/telescope/parameters/{table_name}", containers=[tel_index, *tel_event.dl1.parameters.values()], ) if self.write_dl1_images: if tel_event.dl1.image is None: raise ValueError( "DataWriter.write_dl1_images is True but event does not contain image" ) self._writer.write( table_name=f"dl1/event/telescope/images/{table_name}", containers=[tel_index, tel_event.dl1], ) def _write_simulation_telescope(self, tel_event: TelescopeEventContainer): tel_index = tel_event.index tel_id = tel_index.tel_id table_name = self.table_name(tel_id) # always write this, so that at least the sum is included self._writer.write( f"simulation/event/telescope/images/{table_name}", [tel_index, tel_event.simulation], ) has_true_parameters = ( tel_event.simulation is not None and tel_event.simulation.true_parameters is not None ) if self.write_dl1_parameters and has_true_parameters: true_parameters = tel_event.simulation.true_parameters # only write the available containers, no peak time related # features for true image available. self._writer.write( f"simulation/event/telescope/parameters/{table_name}", [ tel_index, true_parameters.hillas, true_parameters.leakage, true_parameters.concentration, true_parameters.morphology, true_parameters.intensity_statistics, ], ) def _write_muon_telescope(self, tel_event: TelescopeEventContainer): table_name = self.table_name(tel_event.index.tel_id) muon = tel_event.muon self._writer.write( f"dl1/event/telescope/muon/{table_name}", [tel_event.index, muon.ring, muon.parameters, muon.efficiency], ) def _write_dl2_telescope(self, tel_event: TelescopeEventContainer): """ write per-telescope DL2 shower information. Currently this writes to a single table per type of shower reconstruction and per algorithm, with all telescopes combined. """ if tel_event.dl2 is None: return table_name = self.table_name(tel_event.index.tel_id) for container_name, algorithm_map in tel_event.dl2.items(): if algorithm_map: sublevel = DL2_SUBLEVELS.get(container_name) if sublevel is not None: self._processing_sublevels |= sublevel for algorithm, container in algorithm_map.items(): name = f"dl2/event/telescope/{container_name}/{algorithm}/{table_name}" self._writer.write( table_name=name, containers=[tel_event.index, container] ) def _write_dl2_subarray(self, event: SubarrayEventContainer): """ write per-telescope DL2 shower information to e.g. `/dl2/event/stereo/{geometry,energy,classification}/<algorithm_name>` """ if event.dl2 is None: return for container_name, algorithm_map in event.dl2.items(): if algorithm_map: sublevel = DL2_SUBLEVELS.get(container_name) if sublevel is not None: self._processing_sublevels |= sublevel for algorithm, container in algorithm_map.items(): # note this will only write info if the particular algorithm # generated it (otherwise the algorithm map is empty, and no # data will be written) self._writer.write( table_name=f"dl2/event/subarray/{container_name}/{algorithm}", containers=[event.index, container], ) def _write_constant_pointing(self, tel_event): """ Write pointing configuration from event data assuming fixed pointing over the OB. This function mainly exists due to a limitation of sim_telarray files. Pointing information is only written as part of triggered array events, even though it is constant over the run. It also is not written for all telescopes, only for those for which it is "known", which seem to be all telescopes that participated in an array event at least once. So we write the first pointing information for each telescope into the configuration table. """ obs_id = tel_event.index.obs_id tel_id = tel_event.index.tel_id if tel_id in self._constant_telescope_pointing_written[obs_id]: return index = TelescopeConfigurationIndexContainer( obs_id=obs_id, tel_id=tel_id, ) table_name = self.table_name(tel_id) self._writer.write( f"configuration/telescope/pointing/{table_name}", (index, tel_event.monitoring.pointing), ) self._constant_telescope_pointing_written[obs_id].add(tel_id)
[docs] def finish(self): """called after all events are done""" self.log.info("Finishing output") if not self._at_least_one_event: self.log.warning("No events have been written to the output file") self._write_product_metadata_headers() self._write_context_metadata_headers() self._writer.close() PROV.add_output_file(str(self.output_path), role="DL1/Event")
@property def datalevels(self): """returns a list of data levels requested""" data_levels = [] if self.write_dl1_images: data_levels.append(DataLevel.DL1_IMAGES) if self.write_dl1_parameters: data_levels.append(DataLevel.DL1_PARAMETERS) if self.write_muon_parameters: data_levels.append(DataLevel.DL1_MUON) if self.write_dl2: data_levels.append(DataLevel.DL2) if self.write_r0_waveforms: data_levels.append(DataLevel.R0) if self.write_r1_waveforms: data_levels.append(DataLevel.R1) return data_levels def _setup_compression(self): """setup HDF5 compression""" self._hdf5_filters = tables.Filters( complevel=self.compression_level, complib=self.compression_type, fletcher32=True, # attach a checksum to each chunk for error correction ) self.log.debug("compression filters: %s", self._hdf5_filters) def _setup_output_path(self): """Validate the output path and prevent overwriting the input file.""" self.output_path = self.output_path.expanduser() if self.output_path.exists(): activity = Provenance().current_activity if activity is not None: for input_ in activity.input: input_path = pathlib.Path(input_["url"]) if input_path.exists() and self.output_path.samefile(input_path): raise ToolConfigurationError( "Input and output files must not be the same." ) if self.overwrite: self.log.warning("Overwriting %s", self.output_path) self.output_path.unlink() else: raise ToolConfigurationError( f"Output file {self.output_path} exists" ", use the `overwrite` option or choose another `output_path` " ) self.log.debug("output path: %s", self.output_path) # check that options make sense writable_things = [ self.write_dl1_parameters, self.write_dl1_images, self.write_dl2, self.write_r1_waveforms, self.write_muon_parameters, ] if not any(writable_things): self.log.warning( "No processing results were selected for writing" ", only writing trigger and simulation information" ) def _setup_writer(self): """ Create a TableWriter and setup any column exclusions When complete, self._writer should be initialized """ writer = HDF5TableWriter( str(self.output_path), parent=self, mode="a", add_prefix=True, filters=self._hdf5_filters, ) tr_tel_list_to_mask = TelListToMaskTransform(self._subarray) for col in ("tels_with_trigger", "tels_with_data"): writer.add_column_transform( table_name="dl0/event/subarray/trigger", col_name=col, transform=tr_tel_list_to_mask, ) writer.exclude("/dl0/event/telescope/trigger", "trigger_pixels") writer.exclude("/dl1/event/telescope/images/.*", "parameters") writer.exclude("/simulation/event/telescope/images/.*", "true_parameters") if not self.write_dl1_images: writer.exclude("/simulation/event/telescope/images/.*", "true_image") if not self.write_dl1_parameters: writer.exclude("/dl1/event/telescope/images/.*", "image_mask") # Set up transforms if self.transform_image: transform = FixedPointColumnTransform( scale=self.image_scale, offset=self.image_offset, source_dtype=np.float32, target_dtype=np.dtype(self.image_dtype), ) writer.add_column_transform_regexp( "dl1/event/telescope/images/.*", "image", transform ) if self.transform_waveform: transform = FixedPointColumnTransform( scale=self.waveform_scale, offset=self.waveform_offset, source_dtype=np.float32, target_dtype=np.dtype(self.waveform_dtype), ) writer.add_column_transform_regexp( "r1/event/telescope/.*", "waveform", transform ) if self.transform_peak_time: transform = FixedPointColumnTransform( scale=self.peak_time_scale, offset=self.peak_time_offset, source_dtype=np.float32, target_dtype=np.dtype(self.peak_time_dtype), ) writer.add_column_transform_regexp( "dl1/event/telescope/images/.*", "peak_time", transform ) # set up DL2 transforms: # - the single-tel output has no list of telescopes # - the stereo output telescope list needs to be transformed to a pattern writer.exclude("dl2/event/telescope/.*", ".*telescopes") writer.add_column_transform_regexp( table_regexp="dl2/event/subarray/.*", col_regexp=".*telescopes", transform=tr_tel_list_to_mask, ) # final initialization self._writer = writer self.log.debug("Writer initialized: %s", self._writer) def _write_scheduling_and_observation_blocks(self): """write out SB and OB info""" self.log.debug( "writing %d sbs and %d obs", len(self.event_source.scheduling_blocks.values()), len(self.event_source.observation_blocks.values()), ) for sb in self.event_source.scheduling_blocks.values(): self._writer.write("configuration/observation/scheduling_block", sb) for ob in self.event_source.observation_blocks.values(): self._writer.write("configuration/observation/observation_block", ob) def _write_simulation_configuration(self): """ Write the simulation headers to a single row of a table. Later if this file is merged with others, that table will grow. Note that this function should be run first """ self.log.debug("Writing simulation configuration") class ExtraSimInfo(Container): """just to contain obs_id""" default_prefix = "" obs_id = Field(0, "Simulation Run Identifier") for obs_id, config in self.event_source.simulation_config.items(): extramc = ExtraSimInfo(obs_id=obs_id) config.prefix = "" self._writer.write("configuration/simulation/run", [extramc, config])
[docs] def write_simulated_shower_distributions(self, distributions): """Write the distribution of thrown showers.""" self.log.debug("Writing simulation histograms") for container in distributions.values(): self._writer.write( table_name="simulation/service/shower_distribution", containers=container, )
[docs] def table_name(self, tel_id): """Create table name for a telescope-wise table for given ``tel_id``""" return f"tel_{tel_id:03d}"
def _write_context_metadata_headers(self): """write out any user-defined metadata in the context_metadata field to the headers. This will create a set of headers that start with CONTEXT <KEY> = value Keys can be hierarchical separated by spaces """ # first append CONTEXT to each key in the dict context_dict = {} for key, value in self.context_metadata.items(): key = " ".join(["CONTEXT", key]) context_dict[key] = value meta.write_to_hdf5(context_dict, self._writer.h5file) def _get_data_level(self) -> dp.DataLevel: """Return the highest CTAO data level of the output product.""" if self.datalevels: level = meta.to_ctao_data_level(self.datalevels) if level is not None: return level if self.event_source.datalevels: level = meta.to_ctao_data_level(self.event_source.datalevels) if level is not None: return level if self._is_simulation: return dp.DataLevel.SIM raise ValueError("Cannot determine CTAO data level for output") def _get_provenance_activity(self) -> _ActivityProvenance | None: """Return the current or most recently finished provenance activity.""" if PROV.current_activity is not None: return PROV.current_activity if PROV.finished_activities: return PROV.finished_activities[-1] return None def _get_input_product( self, prov_activity: _ActivityProvenance | None, ) -> dp.Product | None: """Return the first input product stored in provenance.""" if prov_activity is None: return None reference_meta = next( ( input_["reference_meta"] for input_ in prov_activity.input if input_.get("reference_meta") is not None ), None, ) if reference_meta is None: return None return dp.Product.model_validate(reference_meta) def _get_product_type( self, input_product: dp.Product | None, ) -> dp.ProductType: """Return the CTAO product type of the output.""" if input_product is not None: data_type = input_product.data.type else: data_type = ( dp.DataType.OBSERVATION_SIM if self._is_simulation else dp.DataType.OBSERVATION ) return dp.ProductType( level=self._get_data_level(), division=dp.DataDivision.EVENT, association=dp.DataAssociation.SUBARRAY, type=data_type, ) def _get_facility_name( self, input_product: dp.Product | None, ) -> dp.FacilityName: """Return the facility name, preferring input metadata.""" if input_product is not None: facility_name = input_product.instance.facility_name if facility_name is not None: return facility_name return ( dp.FacilityName.SIMULATED_CTAO if self._is_simulation else dp.FacilityName.CTAO ) def _get_site_id( self, input_product: dp.Product | None, location: dp.GeodeticEarthLocation | None = None, ) -> SiteID | None: """Return the site identifier without inferring it from a dummy location.""" if input_product is not None: site_id = input_product.instance.site_id if site_id is not None: return site_id if location is None: return None # This inference assumes the data belongs to one of the two CTAO sites. latitude = location.latitude.to_value(u.deg) return SiteID.CTAO_NORTH if latitude > 0 else SiteID.CTAO_SOUTH def _get_instance_identifier( self, input_product: dp.Product | None, location: dp.GeodeticEarthLocation | None = None, ) -> dp.InstanceIdentifier: """Create the instance identifier for the output product.""" obs_ids = self.event_source.obs_ids obs_id = obs_ids[0] if len(obs_ids) == 1 else None return dp.InstanceIdentifier( obs_id=obs_id, facility_name=self._get_facility_name(input_product), sublevel_id=self._get_processing_sublevel(), site_id=self._get_site_id(input_product, location), ) def _get_observation_metadata( self, input_product: dp.Product | None, ) -> dp.Observation | None: """Return observation metadata, adding a valid subarray location if needed.""" observation = None if input_product is not None and input_product.observation is not None: observation = input_product.observation.model_copy(deep=True) if observation.location is not None: return observation location = self._subarray.reference_location if location is None: return observation lon = location.lon.to(u.deg) lat = location.lat.to(u.deg) height = location.height.to(u.m) if not np.all(np.isfinite([lon.value, lat.value, height.value])): return observation # Older SimTel and HDF5 inputs use a dummy (lon, lat) = (0, 0) # when the actual reference location is unavailable. if np.isclose(lon.value, 0.0, rtol=0.0, atol=1e-10) and np.isclose( lat.value, 0.0, rtol=0.0, atol=1e-10 ): return observation geodetic_location = dp.GeodeticEarthLocation( longitude=lon, latitude=lat, height=height, ) if observation is None: return dp.Observation(location=geodetic_location) return observation.model_copy(update={"location": geodetic_location}) def _get_simulation_metadata( self, input_product: dp.Product | None, ) -> dp.Simulation | None: """Return simulation metadata for the output product.""" if not self._is_simulation: return None obs_ids = self.event_source.obs_ids simulation_configs = self.event_source.simulation_config or {} simulation_config = simulation_configs.get(obs_ids[0]) if input_product is not None and input_product.simulation is not None: simulation = input_product.simulation.model_copy(deep=True) else: node = None if simulation_config is not None: altitude = (simulation_config.min_alt + simulation_config.max_alt) / 2 azimuth = Longitude( circmean( u.Quantity([simulation_config.min_az, simulation_config.max_az]) ) ) nsb_factor = simulation_config.nsb_scaling_factor # not needed anymore after fix in ctao_datamodel #54 if nsb_factor is None: nsb_factor = self.product_info.simulation.get("node", {}).get( "nsb_factor", 1 ) node = dp.SimulationGridNode( zenith=(90 * u.deg - altitude).to(u.deg), azimuth=azimuth.to(u.deg), hour_angle=None, declination=None, nsb_factor=nsb_factor, ) # There is currently no reliable way to get the Simulation.production_name from production_name = self.product_info.simulation.get( "production_name", "unknown" ) simulation = dp.Simulation( production_name=production_name, node=node, ) return simulation def _get_processing_sublevel(self) -> dp.ProcessingSublevel | None: """Return the CTAO processing-sublevel flags present in the output.""" sublevel = self._processing_sublevels if self.write_dl1_images: sublevel |= dp.ProcessingSublevel.IMAGES if self.write_dl1_parameters: sublevel |= dp.ProcessingSublevel.PARAMETERS return sublevel or None def _write_product_metadata_headers(self) -> None: """Write CTAO product metadata to the output file.""" prov_activity = self._get_provenance_activity() input_product = self._get_input_product(prov_activity) simulation = self._get_simulation_metadata(input_product) observation = self._get_observation_metadata(input_product) product = self.product_info.to_model( creation_time=Time.now(), data=self._get_product_type(input_product), instance=self._get_instance_identifier( input_product=input_product, location=observation.location if observation is not None else None, ), curation=self.curation_info.to_model(), model=dp.DataModel( name="ctapipe", version=DATA_MODEL_VERSION, url=None, ), contact=self.contact_info.to_model(), activity=( meta.activity_from_provenance(prov_activity) if prov_activity is not None else None ), simulation=simulation, observation=observation, ) meta.write_product_metadata_hdf5(product, self._writer.h5file) def _write_atmosphere_profile(self, path): """ write atmosphere profiles if they are in a tabular format Parameters ---------- path: str path in the HDF5 file where to place the profile """ profile = self.event_source.atmosphere_density_profile if profile: if hasattr(profile, "table"): write_table( table=profile.table, h5file=self._writer.h5file, path=path, append=False, ) else: self.logger.warning( f"The AtmosphereDensityProfile type '{profile.__class__.__name__}' " "is not serializable. No atmosphere profile will be stored in the " "output file" )