Secure your code as it's written. Use Snyk Code to scan source code in minutes - no build needed - and fix issues immediately.
import os
import numpy as np
import pandas as pd
from tqdm import tqdm
from traitlets import Dict, Int, List
from ctapipe.core.traits import Path
from ctapipe.analysis.camera.charge_resolution import ChargeResolutionCalculator
from ctapipe.calib import CameraCalibrator
from ctapipe.core import Provenance, Tool, traits
from ctapipe.image.extractor import ImageExtractor
from ctapipe.io.simteleventsource import SimTelEventSource
class ChargeResolutionGenerator(Tool):
name = "ChargeResolutionGenerator"
description = (
"Calculate the Charge Resolution from a sim_telarray "
"simulation and store within a HDF5 file."
)
telescopes = List(
Int(),
None,
allow_none=True,
help="Telescopes to include from the event file. Default = All telescopes",
).tag(config=True)
output_path = Path(
default_value="charge_resolution.h5",
directory_ok=False,
help="Path to store the output HDF5 file",
(e.g. length, width, image amplitude, etc.).
"""
import numpy as np
from tqdm import tqdm
from ctapipe.core import Tool
from ctapipe.core.traits import Path, Unicode, List, Dict, Bool
from ctapipe.io import EventSource, HDF5TableWriter
from ctapipe.calib import CameraCalibrator
from ctapipe.utils import get_dataset_path
from ctapipe.image import hillas_parameters, tailcuts_clean
class SimpleEventWriter(Tool):
name = "ctapipe-simple-event-writer"
description = Unicode(__doc__)
infile = Path(
default_value=get_dataset_path(
"lst_prod3_calibration_and_mcphotons.simtel.zst"
),
help="input file to read",
directory_ok=False,
exists=True,
).tag(config=True)
outfile = Path(
help="output file name", directory_ok=False, default_value="output.h5"
).tag(config=True)
progress = Bool(help="display progress bar", default_value=True).tag(config=True)
from ctapipe.image import (
toymodel,
tailcuts_clean,
dilate,
hillas_parameters,
HillasParameterizationError,
)
from ctapipe.instrument import (
TelescopeDescription,
OpticsDescription,
CameraDescription,
)
from ctapipe.visualization import CameraDisplay
class CameraDemo(Tool):
name = "ctapipe-camdemo"
description = "Display fake events in a demo camera"
delay = traits.Int(50, help="Frame delay in ms", min=20).tag(config=True)
cleanframes = traits.Int(
20, help="Number of frames between turning on " "cleaning", min=0
).tag(config=True)
autoscale = traits.Bool(False, help="scale each frame to max if " "True").tag(
config=True
)
blit = traits.Bool(
False,
help="use blit operation to draw on screen ("
"much faster but may cause some draw "
"artifacts)",
).tag(config=True)
cb.ax.yaxis.set_ticks(logticks, minor=True)
cb.ax.yaxis.set_tick_params(which='minor', length=5)
cb.ax.tick_params(length=10)
output_dir = dirname(self.output_path)
if not exists(output_dir):
self.log.info("[output] Creating directory: {}".format(output_dir))
makedirs(output_dir)
self.log.info("[output] {}".format(self.output_path))
warnings.filterwarnings("ignore", module="matplotlib")
with warnings.catch_warnings():
warnings.simplefilter("ignore")
fig.savefig(self.output_path, bbox_inches='tight')
class ChargeResolutionVariationViewer(Tool):
name = "ChargeResolutionVariationViewer"
description = "Plot the charge resolution from " \
"ChargeResolutionCalculator objects restored via " \
"pickled dictionaries."
input_path = Unicode(None, allow_none=True,
help='Path to the hdf5 file produced from'
'ChargeResolutionCalculator.save()'
'').tag(config=True)
aliases = Dict(dict(f='ChargeResolutionVariationViewer.input_path',
O='ChargeResolutionVariationPlotter.output_path',
))
classes = List([ChargeResolutionCalculator,
ChargeResolutionVariationPlotter
])
simtelarray input file.
"""
import numpy as np
from astropy import units as u
from astropy.table import Table
from ctapipe.io import event_source
from ctapipe.core import Provenance, ToolConfigurationError
from ctapipe.core.traits import Unicode, Dict, Bool, Path
from ..core import Tool
MAX_TELS = 1000
class DumpTriggersTool(Tool):
description = Unicode(__doc__)
name = "ctapipe-dump-triggers"
# =============================================
# configuration parameters:
# =============================================
infile = Path(exists=True, directory_ok=False, help="input simtelarray file").tag(
config=True
)
outfile = Path(
default_value="triggers.fits",
directory_ok=False,
help="output filename (*.fits, *.h5)",
).tag(config=True)
subcs.append(self.alias_flags[k])
else:
# eval the KV assignment
self._exec_config_str(k, v)
for subc in subcs:
self._load_flag(subc)
# if self.extra_args:
# sub_parser = KeyValueConfigLoader(log=self.log)
# sub_parser.load_config(self.extra_args)
# self.config.merge(sub_parser.config)
# self.extra_args = sub_parser.extra_args
class FactoryTool(Tool):
"""
Proposal for complete relacement of Tool.
When the factory class is specified in the `factories` Dict inside a `Tool`
the factory discriminator trailet is evaluated, and the resultant product
class is obtained (using `init_product()`) and added to the `classes` List.
All the traitlets of the class is automatically added to the `aliases`
Dict. This allows dynamic definition of command-line arguments depending
on the factory discriminator traitlet.
If help is requested at command line, it is not parsed in the CustomLoader,
but is instead parsed like normal after the factories have been evaluated,
therefore showing all the relavent arguments in the help message (depending
on the factory discriminator chosen in the command line)
The use of config files has not been tested, therefore the current version
event = get_test_event()
nsamples = event.inst.num_samples[telid]
data = np.array(list(event.dl0.tel[telid].adc_samples.values()))
ped = event.mc.tel[telid].pedestal
data_ped = data - np.atleast_3d(ped / nsamples)
data_ped = np.array([data_ped[0], data_ped[0]])
pixel_pos = event.inst.pixel_pos[telid]
optical_foclen = event.inst.optical_foclen[telid]
geom = CameraGeometry.guess(*pixel_pos, optical_foclen)
nei = geom.neighbors
params = get_test_parameters()
class CalTool(Tool):
name = "mytool"
description = "do some things and stuff"
aliases = Dict(dict(extractor='ChargeExtractorFactory.extractor',
window_width='ChargeExtractorFactory.window_width',
))
classes = List([ChargeExtractorFactory])
def setup(self):
print("setting up")
kwargs = dict(config=self.config, tool=self)
self.extractor_factory = ChargeExtractorFactory(**kwargs)
extractor_class = self.extractor_factory.get_class()
self.extractor = extractor_class(**kwargs)
if self.extractor.requires_neighbours():
"""
from matplotlib import pyplot as plt
from matplotlib.patches import Ellipse
from tqdm import tqdm
from ctapipe.calib import CameraCalibrator
from ctapipe.core import Tool
from ctapipe.core.traits import Float, Dict, List, Path
from ctapipe.core.traits import Unicode, Int, Bool
from ctapipe.image import tailcuts_clean, hillas_parameters, HillasParameterizationError
from ctapipe.io import EventSource
from ctapipe.visualization import CameraDisplay
class SingleTelEventDisplay(Tool):
name = "ctapipe-display-televents"
description = Unicode(__doc__)
infile = Path(help="input file to read", exists=True, directory_ok=False).tag(
config=True
)
tel = Int(help="Telescope ID to display", default=0).tag(config=True)
write = Bool(help="Write out images to PNG files", default=False).tag(config=True)
clean = Bool(help="Apply image cleaning", default=False).tag(config=True)
hillas = Bool(help="Apply and display Hillas parametrization", default=False).tag(
config=True
)
samples = Bool(help="Show each sample", default=False).tag(config=True)
display = Bool(
help="Display results in interactive window", default_value=True
).tag(config=True)
from ctapipe.calib.camera.dl1 import CameraDL1Calibrator
from ctapipe.calib.camera.r1 import HessioR1Calibrator
from ctapipe.image.charge_extractors import ChargeExtractorFactory
from ctapipe.coordinates import *
from ctapipe.core import Tool
from ctapipe.image import tailcuts_clean, dilate
from ctapipe.instrument import CameraGeometry
from ctapipe.image import hillas_parameters, HillasParameterizationError
from ctapipe.io.hessio import hessio_event_source
from ctapipe.image import FullIntegrator
from astropy.table import Table
class GetTrainingParams(Tool):
"""
"""
description = "GetTrainingParams"
name = 'ctapipe-get-training-params'
infile = Unicode(help='input simtelarray file').tag(config=True)
outfile = Unicode(help='output fits table').tag(config=True)
telescopes = List(Int, None, allow_none=True,
help='Telescopes to include from the event file. '
'Default = All telescopes').tag(config=True)
aliases = Dict(dict(infile='GetTrainingParams.infile',
outfile='GetTrainingParams.outfile',
from ctapipe.image import tailcuts_clean, dilate
from ctapipe.instrument import CameraGeometry
from ctapipe.reco.ImPACT import ImPACTReconstructor
from ctapipe.image import hillas_parameters, HillasParameterizationError
from ctapipe.io.hessio import hessio_event_source
from ctapipe.reco.hillas_intersection import HillasIntersection
from ctapipe.reco.energy_reco_mva import EnergyReconstructorMVA
from ctapipe.image import FullIntegrator
import ctapipe.visualization as visualization
from ctapipe.plotting.event_viewer import EventViewer
from astropy.table import Table
class ImPACTReconstruction(Tool):
"""
"""
description = "ImPACTReco"
name='ctapipe-ImPACT-reco'
infile = Unicode(help='input simtelarray file').tag(config=True)
outfile = Unicode(help='output fits table').tag(config=True)
telescopes = List(Int, None, allow_none=True,
help='Telescopes to include from the event file. '
'Default = All telescopes').tag(config=True)
max_events = Int(default_value=1000000000,
help="Max number of events to include in analysis").tag(config=True)