How to use the ctapipe.core.Component function in ctapipe

To help you get started, we’ve selected a few ctapipe examples, based on popular ways it is used in public projects.

Secure your code as it's written. Use Snyk Code to scan source code in minutes - no build needed - and fix issues immediately.

github cta-observatory / ctapipe / ctapipe / pipeline / algorithms / list_tels_with_data.py View on Github external
from time import sleep
from ctapipe.core import Component


class ListTelsWithData(Component):

    """`ListTelsWithData` class represents a Stage for pipeline.
        It receives  a hessio event and return a list containing
        telescope id of triggered telescopes for this event.
    """

    def init(self):
        self.log.info("--- ListTelsWithData init ---")

    def run(self, event):
        if event is not None:
            res = list(event.dl0.tels_with_data)
            yield((res,event))

    def finish(self):
        self.log.info("--- ListTelsWithData finish ---")
github cta-observatory / ctapipe / ctapipe / flow / multiprocessus / consumer_zmq.py View on Github external
# Licensed under a 3-clause BSD style license - see LICENSE.rst
# coding: utf8
import zmq
from multiprocessing import Process
from multiprocessing import Value
from pickle import loads
from ctapipe.core import Component

class ConsumerZMQ(Process, Component):
    """`ConsumerZMQ` class represents a Consumer pipeline Step.
    It is derived from Process class. It receives
    new input from its prev stage, thanks to its ZMQ REQ socket,
    and executes its coroutine objet's run method by passing
    input as parameter.
    The processus is launched by calling run method.
    init() method is call by run method.
    The processus is stopped by setting share data stop to True
    """
    def __init__(
            self, coroutine, sock_consumer_port, _name=""):
        """
        Parameters
        ----------
        coroutine : Class instance that contains init, run and finish methods
        sock_consumer_port: str
github cta-observatory / ctapipe / ctapipe / flow / algorithms / prepare_display_step.py View on Github external
from ctapipe.core import Component
from ctapipe.plotting.camera import CameraPlotter
import numpy as np
from matplotlib import colors
from matplotlib import pyplot as plt


class PrepareDisplayStep(Component):
    """PrepareDisplayStep` class represents a Stage for pipeline.
        it prepares Display for the next stage
        This stage is time comsuming, so in multiprocess mode you should
        activate several process for it i.e.("nb_process" : 4)
    """

    def init(self):
        self.log.debug("--- PrepareDisplayStep init ---")
        self.fig = plt.figure(figsize=(16, 7))
        return True

    def run(self, inputs):
        self.log.debug("--- PrepareDisplayStep RUN ---")
        calibrated_event, geom_dict = inputs
        for tel_id in calibrated_event.dl0.tels_with_data:
            self.fig.clear()
github cta-observatory / ctapipe / ctapipe / flow / algorithms / lst_dump.py View on Github external
from ctapipe.utils.datasets import get_path
import ctapipe.instrument.InstrumentDescription as ID
from ctapipe.core import Component
from traitlets import Unicode
from time import sleep


class LSTDump(Component):
    """LSTDump` class represents a Stage for pipeline.
        it dumps RawCameraData contents to a string
    """


    def init(self):
        self.log.info("--- LSTDump init ---")
        return True

    def run(self, raw_camera_data):
        if raw_camera_data != None:
            self.log.debug("LSTDump receive {}".format(raw_camera_data))
            return('LSTDump START-> {} <- LSTDump END'.format(str(raw_camera_data)))

    def finish(self):
        self.log.info("--- LSTDump finish ---")
github cta-observatory / ctapipe / ctapipe / flow / algorithms / calibration_step.py View on Github external
from ctapipe.calib.camera.dl1 import calibrate_event
from ctapipe.core import Component
from traitlets import Unicode
from traitlets import Int
from traitlets import Float
from traitlets import List


class CalibrationStep(Component):
    """CalibrationStep` class represents a Stage for pipeline.
        it executes ctapipe.calib.camera.calibrators.calibrate_event
        it return calibrated_event and geom_dict
    """
    integrator = Unicode('nb_peak_integration',
                         help=("integration scheme to be used" 
                               "to extract the charge")).tag(
                                   config=True)
    integration_window = List([7, 3], help='Set integration window width \
        and offset (to before the peak) respectively').tag(
        config=True)
    integration_sigamp = List([2, 4], help='Amplitude in ADC counts above \
        pedestal at which a signal is considered as significant, and used \
        for peak finding. (separate for high gain/low gain)').tag(
        config=True)
    integration_clip_amp = Int(default_value=None, allow_none=True, help='Amplitude in p.e. above which \
github cta-observatory / ctapipe / examples / tool_example.py View on Github external
class AComponent(Component):
    """
    A class that has configurable, typed attributes.
    """

    i = Int(0, help="The integer i.").tag(config=True)
    j = Int(1, help="The integer j.").tag(config=True)
    name = Unicode("Brian", help="First name.").tag(config=True)

    def __call__(self):
        self.log.info("CALLED FOO")


class BComponent(Component):
    """ Some Other Component """

    enabled = Bool(True, help="Enable bar.").tag(config=True)


class MyTool(Tool):
    """ My Tool """

    name = Unicode("myapp")
    running = Bool(False, help="Is the app running?").tag(config=True)
    classes = List([BComponent, AComponent])

    aliases = Dict(
        dict(
            i="Foo.i",
            j="Foo.j",
github cta-observatory / ctapipe / ctapipe / io / eventseeker.py View on Github external
"""
Handles seeking to a particular event in a
`ctapipe.io.eventfilereader.EventFileReader`
"""
from copy import deepcopy
from ctapipe.core import Component

__all__ = [
    "EventSeeker",
]


class EventSeeker(Component):
    """
    Provides the functionality to seek through a
    `ctapipe.io.eventfilereader.EventSource` to find a particular event.

    By default, this will loop through events from the start of the file
    (unless the requested event is the same as the previous requested event,
    or occurs later in the file). However if the
    `ctapipe.io.eventfilereader.EventSource` has defined a `__getitem__`
    method itself, then it will use that method, thereby taking advantage of
    the random event access some file formats provide.

    To create an instance of an EventSeeker you must provide it a sub-class of
    `ctapipe.io.eventfilereader.EventSource` (such as
    `ctapipe.io.hessiofilereader.HessioFileReader`), which will be used to
    loop through the file and provide the event container, filled with the
    event information using the methods defined in the event_source for that
github cta-observatory / ctapipe / ctapipe / io / tableio.py View on Github external
import re
from abc import ABCMeta, abstractmethod
from collections import defaultdict

from ctapipe.core import Component, Container

__all__ = ['TableReader', 'TableWriter']


class TableWriter(Component, metaclass=ABCMeta):
    """
    Base class for writing  Container classes as rows of an output table,
    where each `Field` becomes a column. Subclasses of this implement
    specific output types.

    See Also
    --------
    - `ctapipe.io.HDF5TableWriter`
    """

    def __init__(self, parent=None, add_prefix=False, **kwargs):
        super().__init__(parent=parent, **kwargs)
        self._transforms = defaultdict(dict)
        self._exclusions = defaultdict(list)
        self.add_prefix = add_prefix
github cta-observatory / ctapipe / ctapipe / tools / plot_charge_resolution_variation_hist.py View on Github external
from os.path import dirname, exists, splitext, basename
from os import makedirs
from math import ceil, floor
from matplotlib import pyplot as plt
from math import log10
import warnings
import numpy as np
from matplotlib.colors import LogNorm
from traitlets import Dict, List, Unicode
from ctapipe.core import Tool, Component
from ctapipe.analysis.camera.chargeresolution import ChargeResolutionCalculator


class ChargeResolutionVariationPlotter(Component):
    output_path = Unicode(None, allow_none=True,
                          help='Output path to save the '
                               'plot.').tag(config=True)

    def __init__(self, config=None, tool=None, **kwargs):
        """
        Calculator of charge resolution.

        Parameters
        ----------
        config : traitlets.loader.Config
            Configuration specified by config file or cmdline arguments.
            Used to set traitlet values.
            Set to None if no configuration to pass.
        tool : ctapipe.core.Tool
            Tool executable that is calling this component.
github cta-observatory / ctapipe / ctapipe / io / tableio.py View on Github external
    @abstractmethod
    def close(self):
        pass

    def _apply_col_transform(self, table_name, col_name, value):
        """
        apply value transform function if it exists for this column
        """
        if col_name in self._transforms[table_name]:
            tr = self._transforms[table_name][col_name]
            value = tr(value)
        return value


class TableReader(Component, metaclass=ABCMeta):
    """
    Base class for row-wise table readers. Generally methods that read a
    full table at once are preferred to this method, since they are faster,
    but this can be used to re-play a table row by row into a
    `ctapipe.core.Container` class (the opposite of TableWriter)
    """

    def __init__(self):
        super().__init__()
        self._cols_to_read = defaultdict(list)
        self._transforms = defaultdict(dict)

    def __enter__(self):
        return self

    def __exit__(self, exc_type, exc_val, exc_tb):