How to use the strax.Plugin function in strax

To help you get started, we’ve selected a few strax 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 AxFoundation / strax / tests / test_overlap_plugin.py View on Github external
def test_overlap_plugin(input_peaks, split_i):
    """Counting the number of nearby peaks should not depend on how peaks are
    chunked.
    """
    chunks = np.split(input_peaks, [split_i])
    chunks = [c for c in chunks]

    class Peaks(strax.Plugin):
        depends_on = tuple()
        dtype = strax.interval_dtype

        def compute(self, chunk_i):
            return chunks[chunk_i]

        # Hack to make peak output stop after a few chunks
        def is_ready(self, chunk_i):
            return chunk_i < len(chunks)

        def source_finished(self):
            return True

    window = 10

    # Note we must apply this to endtime, not time, since
github AxFoundation / strax / strax / testutils.py View on Github external
r = np.zeros(recs_per_chunk, self.dtype)
        r['time'] = chunk_i + self.config['secret_time_offset']
        r['length'] = r['dt'] = 1
        r['channel'] = np.arange(len(r))
        return r


class SomeCrash(Exception):
    pass


@strax.takes_config(
    strax.Option('base_area', default=0),
    strax.Option('give_wrong_dtype', default=False),
    strax.Option('bonus_area', default_by_run=[(0, 0), (1, 1)]))
class Peaks(strax.Plugin):
    provides = 'peaks'
    data_kind = 'peaks'
    depends_on = ('records',)
    dtype = strax.peak_dtype()
    parallel = True

    def compute(self, records):
        if self.config['give_wrong_dtype']:
            return np.zeros(5, [('a', np.int), ('b', np.float)])
        p = np.zeros(len(records), self.dtype)
        p['time'] = records['time']
        p['length'] = p['dt'] = 1
        p['area'] = self.config['base_area'] + self.config['bonus_area']
        return p
github AxFoundation / strax / strax / xenon / cut_plugins.py View on Github external
class S1LowEnergyRange(strax.Plugin):
    """Pass only events with cs1<200"""
    depends_on = ('events', 'corrected_areas')
    dtype = [('cut_s1_low_energy_range', np.bool, "Event under 200pe")]

    def compute(self, events):
        ret = np.all([events['cs1'] < 200], axis=0)
        return dict(cut_s1_low_energy_range=ret)


class SR1Cuts(strax.MergeOnlyPlugin):
    depends_on = ['fiducial_cylinder_1t', 's1_max_pmt', 's1_low_energy_range']
    save_when = strax.SaveWhen.ALWAYS


class FiducialEvents(strax.Plugin):
    depends_on = ['event_info', 'fiducial_cylinder_1t']
    data_kind = 'fiducial_events'

    def infer_dtype(self):
        return strax.merged_dtype([self.deps[d].dtype
                                   for d in self.depends_on])

    def compute(self, events):
        return events[events['cut_fiducial_cylinder']]
github AxFoundation / strax / strax / xenon / plugins.py View on Github external
parallel = True
    rechunk_on_save = False
    dtype = strax.record_dtype()

    def compute(self, raw_records):
        r = strax.exclude_tails(raw_records, to_pe)
        hits = strax.find_hits(r)
        strax.cut_outside_hits(r, hits)
        return r


@export
@strax.takes_config(
    strax.Option('diagnose_sorting', track=False, default=False,
                 help="Enable runtime checks for sorting and disjointness"))
class Peaks(strax.Plugin):
    depends_on = ('records',)
    data_kind = 'peaks'
    parallel = True
    rechunk_on_save = True
    dtype = strax.peak_dtype(n_channels=len(to_pe))

    def compute(self, records):
        r = records
        hits = strax.find_hits(r)       # TODO: Duplicate work
        hits = strax.sort_by_time(hits)

        peaks = strax.find_peaks(hits, to_pe,
                                 result_dtype=self.dtype)
        strax.sum_waveform(peaks, r, to_pe)

        peaks = strax.split_peaks(peaks, r, to_pe)
github AxFoundation / strax / strax / xenon / plugins.py View on Github external
help="S1 relative LCE(x,y,z) map",
        default_by_run=[
            (0, pax_file('XENON1T_s1_xyz_lce_true_kr83m_SR0_pax-680_fdc-3d_v0.json')),  # noqa
            (first_sr1_run, pax_file('XENON1T_s1_xyz_lce_true_kr83m_SR1_pax-680_fdc-3d_v0.json'))]),  # noqa
    strax.Option(
        's2_relative_lce_map',
        help="S2 relative LCE(x, y) map",
        default_by_run=[
            (0, pax_file('XENON1T_s2_xy_ly_SR0_24Feb2017.json')),
            (170118_1327, pax_file('XENON1T_s2_xy_ly_SR1_v2.2.json'))]),
    strax.Option(
        'electron_lifetime',
        help="Electron lifetime (ns)",
        default_by_run=get_elife)
)
class CorrectedAreas(strax.Plugin):
    depends_on = ['event_basics', 'event_positions']
    dtype = [('cs1', np.float32, 'Corrected S1 area (PE)'),
             ('cs2', np.float32, 'Corrected S2 area (PE)')]

    def setup(self):
        from .itp_map import InterpolatingMap
        self.s1_map = InterpolatingMap(
            get_resource(self.config['s1_relative_lce_map']))
        self.s2_map = InterpolatingMap(
            get_resource(self.config['s2_relative_lce_map']))

    def compute(self, events):
        event_positions = np.vstack([events['x'], events['y'], events['z']]).T
        s2_positions = np.vstack([events['x_s2'], events['y_s2']]).T
        lifetime_corr = np.exp(
            events['drift_time'] / self.config['electron_lifetime'])
github AxFoundation / strax / strax / context.py View on Github external
def _set_plugin_config(self, p, run_id, tolerant=True):
        # Explicit type check, since if someone calls this with
        # plugin CLASSES, funny business might ensue
        assert isinstance(p, strax.Plugin)
        config = self.config.copy()
        for opt in p.takes_config.values():
            try:
                opt.validate(config,
                             run_id=run_id,
                             run_defaults=self.run_defaults(run_id))
            except strax.InvalidConfiguration:
                if not tolerant:
                    raise
        p.config = {k: v for k, v in config.items()
                    if k in p.takes_config}
github AxFoundation / strax / strax / processor.py View on Github external
import strax
export, __all__ = strax.exporter()

try:
    import npshmex
    SHMExecutor = npshmex.ProcessPoolExecutor
    npshmex.register_array_wrapper(strax.Chunk, 'data')
except ImportError:
    # This is allowed to fail, it only crashes if allow_shm = True
    SHMExecutor = None


@export
class ProcessorComponents(ty.NamedTuple):
    """Specification to assemble a processor"""
    plugins: ty.Dict[str, strax.Plugin]
    loaders: ty.Dict[str, callable]
    savers:  ty.Dict[str, ty.List[strax.Saver]]
    targets: ty.Tuple[str]


class MailboxDict(dict):
    def __init__(self, *args, lazy=False, **kwargs):
        super().__init__(*args, **kwargs)
        self.lazy = lazy

    def __missing__(self, key):
        res = self[key] = strax.Mailbox(name=key + '_mailbox',
                                        lazy=self.lazy)
        return res
github AxFoundation / strax / strax / xenon / plugins.py View on Github external
peaks = strax.split_peaks(peaks, r, to_pe)

        strax.compute_widths(peaks)

        if self.config['diagnose_sorting']:
            assert np.diff(r['time']).min() >= 0, "Records not sorted"
            assert np.diff(hits['time']).min() >= 0, "Hits not sorted"
            assert np.all(peaks['time'][1:]
                          >= strax.endtime(peaks)[:-1]), "Peaks not disjoint"

        return peaks


@export
class PeakBasics(strax.Plugin):
    __version__ = "0.0.1"
    parallel = True
    depends_on = ('peaks',)
    dtype = [
        (('Start time of the peak (ns since unix epoch)',
          'time'), np.int64),
        (('End time of the peak (ns since unix epoch)',
          'endtime'), np.int64),
        (('Peak integral in PE',
            'area'), np.float32),
        (('Number of PMTs contributing to the peak',
            'n_channels'), np.int16),
        (('PMT number which contributes the most PE',
            'max_pmt'), np.int16),
        (('Area of signal in the largest-contributing PMT (PE)',
            'max_pmt_area'), np.int32),
github AxFoundation / strax / strax / xenon / plugins.py View on Github external
strax.Option(
        'g1',
        help="S1 gain in PE / photons produced",
        default_by_run=[(0, 0.1442),
                        (first_sr1_run, 0.1426)]),
    strax.Option(
        'g2',
        help="S2 gain in PE / electrons produced",
        default_by_run=[(0, 11.52),
                        (first_sr1_run, 11.55)]),
    strax.Option(
        'lxe_w',
        help="LXe work function in quanta/eV",
        default=13.7e-3),
)
class EnergyEstimates(strax.Plugin):
    depends_on = ['corrected_areas']
    dtype = [
        ('e_light', np.float32, 'Energy in light signal (keV)'),
        ('e_charge', np.float32, 'Energy in charge signal (keV)'),
        ('e_ces', np.float32, 'Energy estimate (keV_ee)')]

    def compute(self, events):
        w = self.config['lxe_w']
        el = w * events['cs1'] / self.config['g1']
        ec = w * events['cs2'] / self.config['g2']
        return dict(e_light=el,
                    e_charge=ec)


class EventInfo(strax.MergeOnlyPlugin):
    depends_on = ['events',