__init__.py 67.9 KB
Newer Older
Moritz Huetten's avatar
astyled    
Moritz Huetten committed
1
"""
2
3
# Event source for MAGIC calibrated data files.
# Requires uproot package (https://github.com/scikit-hep/uproot).
Moritz Huetten's avatar
astyled    
Moritz Huetten committed
4
5
"""

Moritz Huetten's avatar
Moritz Huetten committed
6
import logging
7
8
9

import glob
import re
Moritz Huetten's avatar
astyled    
Moritz Huetten committed
10
import os.path
11

12
import scipy
13
14
15
16
17
import numpy as np
import scipy.interpolate

from astropy import units as u
from astropy.time import Time
Moritz Huetten's avatar
astyled    
Moritz Huetten committed
18

19
from ctapipe.io.eventsource import EventSource
Moritz Huetten's avatar
astyled    
Moritz Huetten committed
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
from ctapipe.io.datalevels import DataLevel

from ctapipe.core import Container
from ctapipe.core import Field

from ctapipe.containers import DataContainer
from ctapipe.containers import EventAndMonDataContainer
from ctapipe.containers import TelescopePointingContainer
from ctapipe.containers import MonitoringCameraContainer
from ctapipe.containers import PedestalContainer

from ctapipe.instrument import TelescopeDescription
from ctapipe.instrument import SubarrayDescription
from ctapipe.instrument import OpticsDescription
from ctapipe.instrument import CameraGeometry

36
37
38

__all__ = ['MAGICEventSource']

Moritz Huetten's avatar
astyled    
Moritz Huetten committed
39
LOGGER = logging.getLogger(__name__)
40

Ievgen Vovk's avatar
Ievgen Vovk committed
41

42
# MAGIC telescope positions in m wrt. to the center of CTA simulations
Moritz Huetten's avatar
astyled    
Moritz Huetten committed
43
MAGIC_TEL_POSITIONS = {
44
45
46
47
    1: [-27.24, -146.66, 50.00] * u.m,
    2: [-96.44, -96.77, 51.00] * u.m
}
# MAGIC telescope description
Moritz Huetten's avatar
astyled    
Moritz Huetten committed
48
49
50
51
52
OPTICS = OpticsDescription.from_name('MAGIC')
GEOM = CameraGeometry.from_name('MAGICCam')
MAGIC_TEL_DESCRIPTION = TelescopeDescription(
    name='MAGIC', tel_type='MAGIC', optics=OPTICS, camera=GEOM)
MAGIC_TEL_DESCRIPTIONS = {1: MAGIC_TEL_DESCRIPTION, 2: MAGIC_TEL_DESCRIPTION}
53

54
# trigger patterns:
Moritz Huetten's avatar
astyled    
Moritz Huetten committed
55
56
57
58
MC_TRIGGER_PATTERN = 1
PEDESTAL_TRIGGER_PATTERN = 8
DATA_TRIGGER_PATTERN = 128

59

60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
class MAGICEventSource(EventSource):
    """
    EventSource for MAGIC calibrated data.

    This class operates with the MAGIC data run-wise. This means that the files
    corresponding to the same data run are loaded and processed together.
    """
    _count = 0

    def __init__(self, config=None, tool=None, **kwargs):
        """
        Constructor

        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.
            Passes the correct logger to the component.
            Set to None if no Tool to pass.
        kwargs: dict
            Additional parameters to be passed.
            NOTE: The file mask of the data to read can be passed with
            the 'input_url' parameter.
        """

89
        self.file_list = glob.glob(kwargs['input_url'])
90
91
        if len(self.file_list) == 0:
            raise ValueError("Unreadable or wrong wildcard file path given.")
92
        self.file_list.sort()
93
94
95
96
97

        # EventSource can not handle file wild cards as input_url
        # To overcome this we substitute the input_url with first file matching
        # the specified file mask.
        del kwargs['input_url']
98
        super().__init__(input_url=self.file_list[0], **kwargs)
99
100

        # Retrieving the list of run numbers corresponding to the data files
Moritz Huetten's avatar
Moritz Huetten committed
101
102
        run_info = list(map(self._get_run_info_from_name, self.file_list))
        run_numbers = [i[0] for i in run_info]
103
        is_mc_runs = [i[1] for i in run_info]
Moritz Huetten's avatar
Moritz Huetten committed
104
105

        self.run_numbers, indices = np.unique(run_numbers, return_index=True)
106
107
        is_mc_runs = [is_mc_runs[i] for i in indices]
        is_mc_runs = np.unique(is_mc_runs)
Moritz Huetten's avatar
astyled    
Moritz Huetten committed
108

109
110
        # Checking if runt type (data/MC) is consistent:
        if len(is_mc_runs) > 1:
Moritz Huetten's avatar
astyled    
Moritz Huetten committed
111
112
            raise ValueError(
                "Loaded files contain data and MC runs. Please load only data OR Monte Carlos.")
113
        self.is_mc = is_mc_runs[0]
114

Moritz Huetten's avatar
astyled    
Moritz Huetten committed
115
116
117
        # Retrieving the data level (so far HARDCODED Sorcerer)
        self.datalevel = DataLevel.DL1_IMAGES

118
119
120
121
        # # Setting up the current run with the first run present in the data
        # self.current_run = self._set_active_run(run_number=0)
        self.current_run = None

Moritz Huetten's avatar
astyled    
Moritz Huetten committed
122
123
        self._subarray_info = SubarrayDescription(
            'MAGIC', MAGIC_TEL_POSITIONS, MAGIC_TEL_DESCRIPTIONS)
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161

    @staticmethod
    def is_compatible(file_mask):
        """
        This method checks if the specified file mask corresponds
        to MAGIC data files. The result will be True only if all
        the files are of ROOT format and contain an 'Events' tree.

        Parameters
        ----------
        file_mask: str
            A file mask to check

        Returns
        -------
        bool:
            True if the masked files are MAGIC data runs, False otherwise.

        """

        is_magic_root_file = True

        file_list = glob.glob(file_mask)

        for file_path in file_list:
            try:
                import uproot

                try:
                    with uproot.open(file_path) as input_data:
                        if 'Events' not in input_data:
                            is_magic_root_file = False
                except ValueError:
                    # uproot raises ValueError if the file is not a ROOT file
                    is_magic_root_file = False
                    pass

            except ImportError:
Ievgen Vovk's avatar
Ievgen Vovk committed
162
                if re.match(r'.+_m\d_.+root', file_path.lower()) is None:
163
164
165
166
167
                    is_magic_root_file = False

        return is_magic_root_file

    @staticmethod
Moritz Huetten's avatar
Moritz Huetten committed
168
    def _get_run_info_from_name(file_name):
169
        """
Moritz Huetten's avatar
astyled    
Moritz Huetten committed
170
        This internal method extracts the run number and
Moritz Huetten's avatar
Moritz Huetten committed
171
        type (data/MC) from the specified file name.
172
173
174
175
176
177
178
179
180
181
182
183

        Parameters
        ----------
        file_name: str
            A file name to process.

        Returns
        -------
        int:
            A run number of the file.
        """

Moritz Huetten's avatar
Moritz Huetten committed
184
        mask_data = r".*\d+_M\d+_(\d+)\.\d+_Y_.*"
Moritz Huetten's avatar
Moritz Huetten committed
185
186
187
188
189
190
191
192
193
194
195
        mask_mc = r".*_M\d_za\d+to\d+_\d_(\d+)_Y_.*"
        mask_mc_alt = r".*_M\d_\d_(\d+)_.*"
        if len(re.findall(mask_data, file_name)) > 0:
            parsed_info = re.findall(mask_data, file_name)
            is_mc = False
        elif len(re.findall(mask_mc, file_name)) > 0:
            parsed_info = re.findall(mask_mc, file_name)
            is_mc = True
        else:
            parsed_info = re.findall(mask_mc_alt, file_name)
            is_mc = True
196
197
198
199

        try:
            run_number = int(parsed_info[0])
        except IndexError:
Moritz Huetten's avatar
astyled    
Moritz Huetten committed
200
201
202
            raise IndexError(
                'Can not identify the run number and type (data/MC) of the file'
                '{:s}'.format(file_name))
203

Moritz Huetten's avatar
Moritz Huetten committed
204
        return run_number, is_mc
205

Moritz Huetten's avatar
Moritz Huetten committed
206
    def _set_active_run(self, run_number):
207
208
209
210
211
212
213
214
215
216
        """
        This internal method sets the run that will be used for data loading.

        Parameters
        ----------
        run_number: int
            The run number to use.

        Returns
        -------
Moritz Huetten's avatar
Moritz Huetten committed
217
        MarsRun:
Moritz Huetten's avatar
Moritz Huetten committed
218
            The run to use
219
        """
Moritz Huetten's avatar
astyled    
Moritz Huetten committed
220
        this_run_mask = os.path.join(self.input_url.parents[0], '/*{:d}*root'.format(run_number))
221
222
223
224

        run = dict()
        run['number'] = run_number
        run['read_events'] = 0
Moritz Huetten's avatar
astyled    
Moritz Huetten committed
225
226
        run['data'] = MarsRun(run_file_mask=this_run_mask,
                              filter_list=self.file_list)
227
228
229

        return run

230
231
232
233
    @property
    def subarray(self):
        return self._subarray_info

Moritz Huetten's avatar
astyled    
Moritz Huetten committed
234
235
236
237
238
239
240
241
242
243
244
245
    @property
    def is_simulation(self):
        return self.is_mc

    @property
    def datalevels(self):
        return (self.datalevel, )

    @property
    def obs_id(self):
        return self.run_numbers

246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
    def _generator(self):
        """
        The default event generator. Return the stereo event
        generator instance.

        Returns
        -------

        """

        return self._stereo_event_generator()

    def _stereo_event_generator(self):
        """
        Stereo event generator. Yields DataContainer instances, filled
        with the read event data.

        Returns
        -------

        """

        counter = 0

        # Data container - is initialized once, and data is replaced within it after each yield
271
272
273
274
        if not self.is_mc:
            data = EventAndMonDataContainer()
        else:
            data = DataContainer()
275
276
277
278
279
280

        # Telescopes with data:
        tels_in_file = ["m1", "m2"]
        tels_with_data = {1, 2}

        # Loop over the available data runs
281
        for run_number in self.run_numbers:
282
283
284
285
286
287

            # Removing the previously read data run from memory
            if self.current_run is not None:
                if 'data' in self.current_run:
                    del self.current_run['data']

Moritz Huetten's avatar
Moritz Huetten committed
288
            # Setting the new active run (class MarsRun object)
Moritz Huetten's avatar
Moritz Huetten committed
289
            self.current_run = self._set_active_run(run_number)
290

291
292
            # Set monitoring data:
            if not self.is_mc:
Moritz Huetten's avatar
Moritz Huetten committed
293

294
                monitoring_data = self.current_run['data'].monitoring_data
Moritz Huetten's avatar
Moritz Huetten committed
295

296
297
298
                for tel_i, tel_id in enumerate(tels_in_file):
                    monitoring_camera = MonitoringCameraContainer()
                    pedestal_info = PedestalContainer()
299
                    badpixel_info = PixelStatusContainer()
Moritz Huetten's avatar
Moritz Huetten committed
300

Moritz Huetten's avatar
astyled    
Moritz Huetten committed
301
302
303
304
305
306
                    time_tmp = Time(monitoring_data['M{:d}'.format(
                        tel_i + 1)]['PedestalMJD'], scale='utc', format='mjd')
                    pedestal_info.sample_time = Time(
                        time_tmp, format='unix', scale='utc', precision=9)
                    # hardcoded number of pedestal events averaged over:
                    pedestal_info.n_events = 500
307
                    pedestal_info.charge_mean = []
Moritz Huetten's avatar
astyled    
Moritz Huetten committed
308
309
310
311
312
313
                    pedestal_info.charge_mean.append(
                        monitoring_data['M{:d}'.format(tel_i + 1)]['PedestalFundamental']['Mean'])
                    pedestal_info.charge_mean.append(
                        monitoring_data['M{:d}'.format(tel_i + 1)]['PedestalFromExtractor']['Mean'])
                    pedestal_info.charge_mean.append(monitoring_data['M{:d}'.format(
                        tel_i + 1)]['PedestalFromExtractorRndm']['Mean'])
314
                    pedestal_info.charge_std = []
Moritz Huetten's avatar
astyled    
Moritz Huetten committed
315
316
317
318
319
320
321
322
323
324
325
326
                    pedestal_info.charge_std.append(
                        monitoring_data['M{:d}'.format(tel_i + 1)]['PedestalFundamental']['Rms'])
                    pedestal_info.charge_std.append(
                        monitoring_data['M{:d}'.format(tel_i + 1)]['PedestalFromExtractor']['Rms'])
                    pedestal_info.charge_std.append(
                        monitoring_data['M{:d}'.format(tel_i + 1)]['PedestalFromExtractorRndm']['Rms'])

                    t_range = Time(monitoring_data['M{:d}'.format(
                        tel_i + 1)]['badpixelinfoMJDrange'], scale='utc', format='mjd')

                    badpixel_info.hardware_failing_pixels = monitoring_data['M{:d}'.format(
                        tel_i + 1)]['badpixelinfo']
Moritz Huetten's avatar
Moritz Huetten committed
327
                    badpixel_info.sample_time_range = t_range
328

329
                    monitoring_camera.pedestal = pedestal_info
330
                    monitoring_camera.pixel_status = badpixel_info
331
332

                    data.mon.tels_with_data = {1, 2}
333
334
                    data.mon.tel[tel_i + 1] = monitoring_camera

335
336
337
338
339
340
341
342
            # Loop over the events
            for event_i in range(self.current_run['data'].n_stereo_events):
                # Event and run ids
                event_order_number = self.current_run['data'].stereo_ids[event_i][0]
                event_id = self.current_run['data'].event_data['M1']['stereo_event_number'][event_order_number]
                obs_id = self.current_run['number']

                # Reading event data
Moritz Huetten's avatar
astyled    
Moritz Huetten committed
343
344
345
                event_data = self.current_run['data'].get_stereo_event_data(
                    event_i)

346
                data.meta = event_data['mars_meta']
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369

                # Event counter
                data.count = counter

                # Setting up the R0 container
                data.r0.obs_id = obs_id
                data.r0.event_id = event_id
                data.r0.tel.clear()

                # Setting up the R1 container
                data.r1.obs_id = obs_id
                data.r1.event_id = event_id
                data.r1.tel.clear()

                # Setting up the DL0 container
                data.dl0.obs_id = obs_id
                data.dl0.event_id = event_id
                data.dl0.tel.clear()

                # Filling the DL1 container with the event data
                for tel_i, tel_id in enumerate(tels_in_file):
                    # Creating the telescope pointing container
                    pointing = TelescopePointingContainer()
Moritz Huetten's avatar
astyled    
Moritz Huetten committed
370
371
372
373
374
375
376
377
                    pointing.azimuth = np.deg2rad(
                        event_data['{:s}_pointing_az'.format(tel_id)]) * u.rad
                    pointing.altitude = np.deg2rad(
                        90 - event_data['{:s}_pointing_zd'.format(tel_id)]) * u.rad
                    pointing.ra = np.deg2rad(
                        event_data['{:s}_pointing_ra'.format(tel_id)]) * u.rad
                    pointing.dec = np.deg2rad(
                        event_data['{:s}_pointing_dec'.format(tel_id)]) * u.rad
378
379
380
381

                    # Adding the pointing container to the event data
                    data.pointing[tel_i + 1] = pointing

Moritz Huetten's avatar
Moritz Huetten committed
382
383
384
385
386
                    # Adding trigger id (MAGIC nomenclature)
                    data.r0.tel[tel_i + 1].trigger_type = self.current_run['data'].event_data['M1']['trigger_pattern'][event_order_number]
                    data.r1.tel[tel_i + 1].trigger_type = self.current_run['data'].event_data['M1']['trigger_pattern'][event_order_number]
                    data.dl0.tel[tel_i + 1].trigger_type = self.current_run['data'].event_data['M1']['trigger_pattern'][event_order_number]

387
                    # Adding event charge and peak positions per pixel
Moritz Huetten's avatar
astyled    
Moritz Huetten committed
388
389
390
391
                    data.dl1.tel[tel_i +
                                 1].image = event_data['{:s}_image'.format(tel_id)]
                    data.dl1.tel[tel_i +
                                 1].pulse_time = event_data['{:s}_pulse_time'.format(tel_id)]
Moritz Huetten's avatar
Moritz Huetten committed
392

Moritz Huetten's avatar
astyled    
Moritz Huetten committed
393
                if not self.is_mc:
Moritz Huetten's avatar
Moritz Huetten committed
394
                    # Adding the event arrival time
Moritz Huetten's avatar
astyled    
Moritz Huetten committed
395
396
397
398
                    time_tmp = Time(
                        event_data['mjd'], scale='utc', format='mjd')
                    data.trig.gps_time = Time(
                        time_tmp, format='unix', scale='utc', precision=9)
Moritz Huetten's avatar
Moritz Huetten committed
399
400
                else:
                    data.mc.energy = event_data['true_energy'] * u.GeV
401
                    data.mc.alt = (np.pi/2 - event_data['true_zd']) * u.rad
Moritz Huetten's avatar
astyled    
Moritz Huetten committed
402
403
404
405
406
                    # check meaning of 7deg transformation (I.Vovk)
                    data.mc.az = -1 * \
                        (event_data['true_az'] - np.deg2rad(180 - 7)) * u.rad
                    data.mc.shower_primary_id = 1 - \
                        event_data['true_shower_primary_id']
Moritz Huetten's avatar
Moritz Huetten committed
407
408
409
                    data.mc.h_first_int = event_data['true_h_first_int'] * u.cm
                    data.mc.core_x = event_data['true_core_x'] * u.cm
                    data.mc.core_y = event_data['true_core_y'] * u.cm
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440

                # Setting the telescopes with data
                data.r0.tels_with_data = tels_with_data
                data.r1.tels_with_data = tels_with_data
                data.dl0.tels_with_data = tels_with_data
                data.trig.tels_with_trigger = tels_with_data

                yield data
                counter += 1

        return

    def _mono_event_generator(self, telescope):
        """
        Mono event generator. Yields DataContainer instances, filled
        with the read event data.

        Parameters
        ----------
        telescope: str
            The telescope for which to return events. Can be either "M1" or "M2".

        Returns
        -------

        """

        counter = 0
        telescope = telescope.upper()

        # Data container - is initialized once, and data is replaced within it after each yield
Moritz Huetten's avatar
Moritz Huetten committed
441
442
443
444
        if not self.is_mc:
            data = EventAndMonDataContainer()
        else:
            data = DataContainer()
445
446
447
448
449

        # Telescopes with data:
        tels_in_file = ["M1", "M2"]

        if telescope not in tels_in_file:
Moritz Huetten's avatar
astyled    
Moritz Huetten committed
450
451
            raise ValueError("Specified telescope {:s} is not in the allowed list {}".format(
                telescope, tels_in_file))
452
453
454
455
456

        tel_i = tels_in_file.index(telescope)
        tels_with_data = {tel_i + 1, }

        # Loop over the available data runs
457
        for run_number in self.run_numbers:
458
459
460
461
462
463
464

            # Removing the previously read data run from memory
            if self.current_run is not None:
                if 'data' in self.current_run:
                    del self.current_run['data']

            # Setting the new active run
Moritz Huetten's avatar
Moritz Huetten committed
465
            self.current_run = self._set_active_run(run_number)
466

Moritz Huetten's avatar
Moritz Huetten committed
467
468
            # Set monitoring data:
            if not self.is_mc:
Moritz Huetten's avatar
Moritz Huetten committed
469

Moritz Huetten's avatar
Moritz Huetten committed
470
                monitoring_data = self.current_run['data'].monitoring_data
Moritz Huetten's avatar
Moritz Huetten committed
471

Moritz Huetten's avatar
Moritz Huetten committed
472
473
474
                monitoring_camera = MonitoringCameraContainer()
                pedestal_info = PedestalContainer()
                badpixel_info = PixelStatusContainer()
Moritz Huetten's avatar
Moritz Huetten committed
475

Moritz Huetten's avatar
astyled    
Moritz Huetten committed
476
477
478
479
480
                time_tmp = Time(monitoring_data['M{:d}'.format(
                    tel_i + 1)]['PedestalMJD'], scale='utc', format='mjd')
                pedestal_info.sample_time = Time(
                    time_tmp, format='unix', scale='utc', precision=9)
                pedestal_info.n_events = 500  # hardcoded number of pedestal events averaged over
Moritz Huetten's avatar
Moritz Huetten committed
481
                pedestal_info.charge_mean = []
Moritz Huetten's avatar
astyled    
Moritz Huetten committed
482
483
484
485
486
487
                pedestal_info.charge_mean.append(
                    monitoring_data['M{:d}'.format(tel_i + 1)]['PedestalFundamental']['Mean'])
                pedestal_info.charge_mean.append(
                    monitoring_data['M{:d}'.format(tel_i + 1)]['PedestalFromExtractor']['Mean'])
                pedestal_info.charge_mean.append(monitoring_data['M{:d}'.format(
                    tel_i + 1)]['PedestalFromExtractorRndm']['Mean'])
Moritz Huetten's avatar
Moritz Huetten committed
488
                pedestal_info.charge_std = []
Moritz Huetten's avatar
astyled    
Moritz Huetten committed
489
490
491
492
493
494
495
496
497
498
499
500
                pedestal_info.charge_std.append(
                    monitoring_data['M{:d}'.format(tel_i + 1)]['PedestalFundamental']['Rms'])
                pedestal_info.charge_std.append(
                    monitoring_data['M{:d}'.format(tel_i + 1)]['PedestalFromExtractor']['Rms'])
                pedestal_info.charge_std.append(
                    monitoring_data['M{:d}'.format(tel_i + 1)]['PedestalFromExtractorRndm']['Rms'])

                t_range = Time(monitoring_data['M{:d}'.format(
                    tel_i + 1)]['badpixelinfoMJDrange'], scale='utc', format='mjd')

                badpixel_info.hardware_failing_pixels = monitoring_data['M{:d}'.format(
                    tel_i + 1)]['badpixelinfo']
Moritz Huetten's avatar
Moritz Huetten committed
501
                badpixel_info.sample_time_range = t_range
Moritz Huetten's avatar
Moritz Huetten committed
502

Moritz Huetten's avatar
Moritz Huetten committed
503
504
505
506
507
508
                monitoring_camera.pedestal = pedestal_info
                monitoring_camera.pixel_status = badpixel_info

                data.mon.tels_with_data = tels_with_data
                data.mon.tel[tel_i + 1] = monitoring_camera

509
510
511
512
513
514
515
516
517
518
519
520
521
            if telescope == 'M1':
                n_events = self.current_run['data'].n_mono_events_m1
            else:
                n_events = self.current_run['data'].n_mono_events_m2

            # Loop over the events
            for event_i in range(n_events):
                # Event and run ids
                event_order_number = self.current_run['data'].mono_ids[telescope][event_i]
                event_id = self.current_run['data'].event_data[telescope]['stereo_event_number'][event_order_number]
                obs_id = self.current_run['number']

                # Reading event data
Moritz Huetten's avatar
astyled    
Moritz Huetten committed
522
523
524
                event_data = self.current_run['data'].get_mono_event_data(
                    event_i, telescope=telescope)

525
                data.meta = event_data['mars_meta']
526
527
528
529
530
531
532
533

                # Event counter
                data.count = counter

                # Setting up the R0 container
                data.r0.obs_id = obs_id
                data.r0.event_id = event_id
                data.r0.tel.clear()
534
                data.r0.tel[tel_i + 1].trigger_type = self.current_run['data'].event_data[telescope]['trigger_pattern'][event_order_number]
535
536
537
538
539

                # Setting up the R1 container
                data.r1.obs_id = obs_id
                data.r1.event_id = event_id
                data.r1.tel.clear()
540
                data.r1.tel[tel_i + 1].trigger_type = self.current_run['data'].event_data[telescope]['trigger_pattern'][event_order_number]
541
542
543
544
545

                # Setting up the DL0 container
                data.dl0.obs_id = obs_id
                data.dl0.event_id = event_id
                data.dl0.tel.clear()
546
                data.dl0.tel[tel_i + 1].trigger_type = self.current_run['data'].event_data[telescope]['trigger_pattern'][event_order_number]
547
548
549

                # Creating the telescope pointing container
                pointing = TelescopePointingContainer()
Moritz Huetten's avatar
astyled    
Moritz Huetten committed
550
551
552
553
                pointing.azimuth = np.deg2rad(
                    event_data['pointing_az']) * u.rad
                pointing.altitude = np.deg2rad(
                    90 - event_data['pointing_zd']) * u.rad
554
555
556
557
558
559
560
561
                pointing.ra = np.deg2rad(event_data['pointing_ra']) * u.rad
                pointing.dec = np.deg2rad(event_data['pointing_dec']) * u.rad

                # Adding the pointing container to the event data
                data.pointing[tel_i + 1] = pointing

                # Adding event charge and peak positions per pixel
                data.dl1.tel[tel_i + 1].image = event_data['image']
Ievgen Vovk's avatar
Ievgen Vovk committed
562
                data.dl1.tel[tel_i + 1].pulse_time = event_data['pulse_time']
563

Moritz Huetten's avatar
astyled    
Moritz Huetten committed
564
                if not self.is_mc:
Moritz Huetten's avatar
Moritz Huetten committed
565
                    # Adding the event arrival time
Moritz Huetten's avatar
astyled    
Moritz Huetten committed
566
567
568
569
                    time_tmp = Time(
                        event_data['mjd'], scale='utc', format='mjd')
                    data.trig.gps_time = Time(
                        time_tmp, format='unix', scale='utc', precision=9)
Moritz Huetten's avatar
Moritz Huetten committed
570
571
                else:
                    data.mc.energy = event_data['true_energy'] * u.GeV
572
                    data.mc.alt = (np.pi/2 - event_data['true_zd']) * u.rad
Moritz Huetten's avatar
astyled    
Moritz Huetten committed
573
574
575
576
577
                    # check meaning of 7deg transformation (I.Vovk)
                    data.mc.az = -1 * \
                        (event_data['true_az'] - np.deg2rad(180 - 7)) * u.rad
                    data.mc.shower_primary_id = 1 - \
                        event_data['true_shower_primary_id']
Moritz Huetten's avatar
Moritz Huetten committed
578
579
580
                    data.mc.h_first_int = event_data['true_h_first_int'] * u.cm
                    data.mc.core_x = event_data['true_core_x'] * u.cm
                    data.mc.core_y = event_data['true_core_y'] * u.cm
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611

                # Setting the telescopes with data
                data.r0.tels_with_data = tels_with_data
                data.r1.tels_with_data = tels_with_data
                data.dl0.tels_with_data = tels_with_data
                data.trig.tels_with_trigger = tels_with_data

                yield data
                counter += 1

        return

    def _pedestal_event_generator(self, telescope):
        """
        Pedestal event generator. Yields DataContainer instances, filled
        with the read event data.

        Parameters
        ----------
        telescope: str
            The telescope for which to return events. Can be either "M1" or "M2".

        Returns
        -------

        """

        counter = 0
        telescope = telescope.upper()

        # Data container - is initialized once, and data is replaced within it after each yield
Moritz Huetten's avatar
Moritz Huetten committed
612
        data = EventAndMonDataContainer()
613
614
615
616
617

        # Telescopes with data:
        tels_in_file = ["M1", "M2"]

        if telescope not in tels_in_file:
Moritz Huetten's avatar
astyled    
Moritz Huetten committed
618
619
            raise ValueError("Specified telescope {:s} is not in the allowed list {}".format(
                telescope, tels_in_file))
620
621
622
623
624

        tel_i = tels_in_file.index(telescope)
        tels_with_data = {tel_i + 1, }

        # Loop over the available data runs
625
        for run_number in self.run_numbers:
626
627
628
629
630
631
632

            # Removing the previously read data run from memory
            if self.current_run is not None:
                if 'data' in self.current_run:
                    del self.current_run['data']

            # Setting the new active run
Moritz Huetten's avatar
Moritz Huetten committed
633
            self.current_run = self._set_active_run(run_number)
634

Moritz Huetten's avatar
Moritz Huetten committed
635
            monitoring_data = self.current_run['data'].monitoring_data
Moritz Huetten's avatar
Moritz Huetten committed
636

Moritz Huetten's avatar
Moritz Huetten committed
637
638
639
            monitoring_camera = MonitoringCameraContainer()
            pedestal_info = PedestalContainer()
            badpixel_info = PixelStatusContainer()
Moritz Huetten's avatar
Moritz Huetten committed
640

Moritz Huetten's avatar
astyled    
Moritz Huetten committed
641
642
643
644
645
            time_tmp = Time(monitoring_data['M{:d}'.format(
                tel_i + 1)]['PedestalMJD'], scale='utc', format='mjd')
            pedestal_info.sample_time = Time(
                time_tmp, format='unix', scale='utc', precision=9)
            pedestal_info.n_events = 500  # hardcoded number of pedestal events averaged over
Moritz Huetten's avatar
Moritz Huetten committed
646
            pedestal_info.charge_mean = []
Moritz Huetten's avatar
astyled    
Moritz Huetten committed
647
648
649
650
651
652
            pedestal_info.charge_mean.append(
                monitoring_data['M{:d}'.format(tel_i + 1)]['PedestalFundamental']['Mean'])
            pedestal_info.charge_mean.append(
                monitoring_data['M{:d}'.format(tel_i + 1)]['PedestalFromExtractor']['Mean'])
            pedestal_info.charge_mean.append(monitoring_data['M{:d}'.format(
                tel_i + 1)]['PedestalFromExtractorRndm']['Mean'])
Moritz Huetten's avatar
Moritz Huetten committed
653
            pedestal_info.charge_std = []
Moritz Huetten's avatar
astyled    
Moritz Huetten committed
654
655
656
657
658
659
660
661
662
663
664
665
            pedestal_info.charge_std.append(
                monitoring_data['M{:d}'.format(tel_i + 1)]['PedestalFundamental']['Rms'])
            pedestal_info.charge_std.append(
                monitoring_data['M{:d}'.format(tel_i + 1)]['PedestalFromExtractor']['Rms'])
            pedestal_info.charge_std.append(
                monitoring_data['M{:d}'.format(tel_i + 1)]['PedestalFromExtractorRndm']['Rms'])

            t_range = Time(monitoring_data['M{:d}'.format(
                tel_i + 1)]['badpixelinfoMJDrange'], scale='utc', format='mjd')

            badpixel_info.hardware_failing_pixels = monitoring_data['M{:d}'.format(
                tel_i + 1)]['badpixelinfo']
Moritz Huetten's avatar
Moritz Huetten committed
666
            badpixel_info.sample_time_range = t_range
Moritz Huetten's avatar
Moritz Huetten committed
667

Moritz Huetten's avatar
Moritz Huetten committed
668
669
670
671
672
673
            monitoring_camera.pedestal = pedestal_info
            monitoring_camera.pixel_status = badpixel_info

            data.mon.tels_with_data = tels_with_data
            data.mon.tel[tel_i + 1] = monitoring_camera

674
675
676
677
678
679
680
681
682
683
684
685
686
            if telescope == 'M1':
                n_events = self.current_run['data'].n_pedestal_events_m1
            else:
                n_events = self.current_run['data'].n_pedestal_events_m2

            # Loop over the events
            for event_i in range(n_events):
                # Event and run ids
                event_order_number = self.current_run['data'].pedestal_ids[telescope][event_i]
                event_id = self.current_run['data'].event_data[telescope]['stereo_event_number'][event_order_number]
                obs_id = self.current_run['number']

                # Reading event data
Moritz Huetten's avatar
astyled    
Moritz Huetten committed
687
688
689
                event_data = self.current_run['data'].get_pedestal_event_data(
                    event_i, telescope=telescope)

690
                data.meta = event_data['mars_meta']
691
692
693
694
695
696
697
698

                # Event counter
                data.count = counter

                # Setting up the R0 container
                data.r0.obs_id = obs_id
                data.r0.event_id = event_id
                data.r0.tel.clear()
699
                data.r0.tel[tel_i + 1].trigger_type = self.current_run['data'].event_data[telescope]['trigger_pattern'][event_order_number]
700
701
702
703
704

                # Setting up the R1 container
                data.r1.obs_id = obs_id
                data.r1.event_id = event_id
                data.r1.tel.clear()
705
                data.r1.tel[tel_i + 1].trigger_type = self.current_run['data'].event_data[telescope]['trigger_pattern'][event_order_number]
706
707
708
709
710

                # Setting up the DL0 container
                data.dl0.obs_id = obs_id
                data.dl0.event_id = event_id
                data.dl0.tel.clear()
711
                data.dl0.tel[tel_i + 1].trigger_type = self.current_run['data'].event_data[telescope]['trigger_pattern'][event_order_number]
712
713
714

                # Creating the telescope pointing container
                pointing = TelescopePointingContainer()
Moritz Huetten's avatar
astyled    
Moritz Huetten committed
715
716
717
718
                pointing.azimuth = np.deg2rad(
                    event_data['pointing_az']) * u.rad
                pointing.altitude = np.deg2rad(
                    90 - event_data['pointing_zd']) * u.rad
719
720
721
722
723
724
725
726
                pointing.ra = np.deg2rad(event_data['pointing_ra']) * u.rad
                pointing.dec = np.deg2rad(event_data['pointing_dec']) * u.rad

                # Adding the pointing container to the event data
                data.pointing[tel_i + 1] = pointing

                # Adding event charge and peak positions per pixel
                data.dl1.tel[tel_i + 1].image = event_data['image']
Ievgen Vovk's avatar
Ievgen Vovk committed
727
                data.dl1.tel[tel_i + 1].pulse_time = event_data['pulse_time']
728
729
730

                # Adding the event arrival time
                time_tmp = Time(event_data['mjd'], scale='utc', format='mjd')
Moritz Huetten's avatar
astyled    
Moritz Huetten committed
731
732
                data.trig.gps_time = Time(
                    time_tmp, format='unix', scale='utc', precision=9)
733
734
735
736
737
738
739
740
741
742
743
744
745

                # Setting the telescopes with data
                data.r0.tels_with_data = tels_with_data
                data.r1.tels_with_data = tels_with_data
                data.dl0.tels_with_data = tels_with_data
                data.trig.tels_with_trigger = tels_with_data

                yield data
                counter += 1

        return


Moritz Huetten's avatar
Moritz Huetten committed
746
class MarsRun:
747
748
749
750
    """
    This class implements reading of the event data from a single MAGIC data run.
    """

Moritz Huetten's avatar
Moritz Huetten committed
751
    def __init__(self, run_file_mask, filter_list=None):
752
753
754
755
756
757
758
759
760
        """
        Constructor of the class. Defines the run to use and the camera pixel arrangement.

        Parameters
        ----------
        run_file_mask: str
            A path mask for files belonging to the run. Must correspond to a single run
            or an exception will be raised. Must correspond to calibrated ("sorcerer"-level)
            data.
761
762
763
        filter_list: list, optional
            A list of files, to which the run_file_mask should be applied. If None, all the
            files satisfying run_file_mask will be used. Defaults to None.
764
765
        """

Moritz Huetten's avatar
astyled    
Moritz Huetten committed
766
        self.n_camera_pixels = GEOM.n_pixels
767

768
769
770
771
        self.run_file_mask = run_file_mask

        # Preparing the lists of M1/2 data files
        file_list = glob.glob(run_file_mask)
772
773
774
775
776

        # Filtering out extra files if necessary
        if filter_list is not None:
            file_list = list(set(file_list) & set(filter_list))

Moritz Huetten's avatar
astyled    
Moritz Huetten committed
777
778
779
780
        self.m1_file_list = list(
            filter(lambda name: '_M1_' in name, file_list))
        self.m2_file_list = list(
            filter(lambda name: '_M2_' in name, file_list))
781
        self.m1_file_list.sort()
782
783
784
        self.m2_file_list.sort()

        # Retrieving the list of run numbers corresponding to the data files
Moritz Huetten's avatar
astyled    
Moritz Huetten committed
785
786
        run_info = list(
            map(MAGICEventSource._get_run_info_from_name, file_list))
Moritz Huetten's avatar
Moritz Huetten committed
787
        run_numbers = [i[0] for i in run_info]
Moritz Huetten's avatar
astyled    
Moritz Huetten committed
788
        is_mc_runs = [i[1] for i in run_info]
789
790
791

        run_numbers = np.unique(run_numbers)
        is_mc_runs = np.unique(is_mc_runs)
Moritz Huetten's avatar
astyled    
Moritz Huetten committed
792
        # Checking if run type (data/MC) is consistent:
793
        if len(is_mc_runs) > 1:
Moritz Huetten's avatar
astyled    
Moritz Huetten committed
794
795
796
            raise ValueError(
                "Run type is not consistently data or MC: {}".format(is_mc_runs))

797
        self.is_mc = is_mc_runs[0]
798
799
800

        # Checking if a single run is going to be read
        if len(run_numbers) > 1:
Moritz Huetten's avatar
astyled    
Moritz Huetten committed
801
802
            raise ValueError(
                "Run mask corresponds to more than one run: {}".format(run_numbers))
803

804
        # Reading the data
Moritz Huetten's avatar
astyled    
Moritz Huetten committed
805
806
807
808
809
        m1_data = self.load_events(
            self.m1_file_list, self.is_mc, self.n_camera_pixels)
        m2_data = self.load_events(
            self.m2_file_list, self.is_mc, self.n_camera_pixels)

810
        # Getting the event data
811
        self.event_data = dict()
812
813
814
815
816
817
818
        self.event_data['M1'] = m1_data[0]
        self.event_data['M2'] = m2_data[0]

        # Getting the monitoring data
        self.monitoring_data = dict()
        self.monitoring_data['M1'] = m1_data[1]
        self.monitoring_data['M2'] = m2_data[1]
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855

        # Detecting pedestal events
        self.pedestal_ids = self._find_pedestal_events()
        # Detecting stereo events
        self.stereo_ids = self._find_stereo_events()
        # Detecting mono events
        self.mono_ids = self._find_mono_events()

    @property
    def n_events_m1(self):
        return len(self.event_data['M1']['MJD'])

    @property
    def n_events_m2(self):
        return len(self.event_data['M2']['MJD'])

    @property
    def n_stereo_events(self):
        return len(self.stereo_ids)

    @property
    def n_mono_events_m1(self):
        return len(self.mono_ids['M1'])

    @property
    def n_mono_events_m2(self):
        return len(self.mono_ids['M2'])

    @property
    def n_pedestal_events_m1(self):
        return len(self.pedestal_ids['M1'])

    @property
    def n_pedestal_events_m2(self):
        return len(self.pedestal_ids['M2'])

    @staticmethod
856
    def load_events(file_list, is_mc, n_camera_pixels):
857
        """
858
        This method loads events and monitoring data from the pre-defiled file and returns them as a dictionary.
859
860
861
862
863

        Parameters
        ----------
        file_name: str
            Name of the MAGIC calibrated file to use.
864
865
866
867
        is_mc: boolean
            Specify whether Monte Carlo (True) or data (False) events are read
        n_camera_pixels: int
            Number of MAGIC camera pixels (not hardcoded, but specified solely via ctapipe.instrument.CameraGeometry)
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884

        Returns
        -------
        dict:
            A dictionary with the even properties: charge / arrival time data, trigger, direction etc.
        """

        try:
            import uproot
        except ImportError:
            msg = "The `uproot` python module is required to access the MAGIC data"
            raise ImportError(msg)

        event_data = dict()

        event_data['charge'] = []
        event_data['arrival_time'] = []
885
886
        event_data['trigger_pattern'] = scipy.array([], dtype=np.int32)
        event_data['stereo_event_number'] = scipy.array([], dtype=np.int32)
887
888
889
890
891
        event_data['pointing_zd'] = scipy.array([])
        event_data['pointing_az'] = scipy.array([])
        event_data['pointing_ra'] = scipy.array([])
        event_data['pointing_dec'] = scipy.array([])
        event_data['MJD'] = scipy.array([])
Moritz Huetten's avatar
Moritz Huetten committed
892
        event_data['mars_meta'] = []
893

894
895
        # monitoring information (updated from time to time)
        monitoring_data = dict()
Moritz Huetten's avatar
astyled    
Moritz Huetten committed
896

Moritz Huetten's avatar
Moritz Huetten committed
897
898
        monitoring_data['badpixelinfo'] = []
        monitoring_data['badpixelinfoMJDrange'] = []
899
900
901
902
903
904
905
906
907
908
909
        monitoring_data['PedestalMJD'] = scipy.array([])
        monitoring_data['PedestalFundamental'] = dict()
        monitoring_data['PedestalFundamental']['Mean'] = []
        monitoring_data['PedestalFundamental']['Rms'] = []
        monitoring_data['PedestalFromExtractor'] = dict()
        monitoring_data['PedestalFromExtractor']['Mean'] = []
        monitoring_data['PedestalFromExtractor']['Rms'] = []
        monitoring_data['PedestalFromExtractorRndm'] = dict()
        monitoring_data['PedestalFromExtractorRndm']['Mean'] = []
        monitoring_data['PedestalFromExtractorRndm']['Rms'] = []

910
911
        event_data['file_edges'] = [0]

912
913
914
915
        degrees_per_hour = 15.0
        seconds_per_day = 86400.0
        seconds_per_hour = 3600.

Moritz Huetten's avatar
Moritz Huetten committed
916
        evt_common_list = [
Moritz Huetten's avatar
astyled    
Moritz Huetten committed
917
            'MCerPhotEvt.fPixels.fPhot',
Moritz Huetten's avatar
Moritz Huetten committed
918
919
            'MArrivalTime.fData',
            'MTriggerPattern.fPrescaled',
Moritz Huetten's avatar
astyled    
Moritz Huetten committed
920
            'MRawEvtHeader.fStereoEvtNumber',
Moritz Huetten's avatar
Moritz Huetten committed
921
            'MRawEvtHeader.fDAQEvtNumber',
Moritz Huetten's avatar
astyled    
Moritz Huetten committed
922
923
924
        ]

        # Separately, because only used with pre-processed MARS data
Moritz Huetten's avatar
Moritz Huetten committed
925
926
        # to create MPointingPos container
        pointing_array_list = [
Moritz Huetten's avatar
astyled    
Moritz Huetten committed
927
928
929
930
            'MPointingPos.fZd',
            'MPointingPos.fAz',
            'MPointingPos.fRa',
            'MPointingPos.fDec',
Moritz Huetten's avatar
Moritz Huetten committed
931
            'MPointingPos.fDevZd',
Moritz Huetten's avatar
astyled    
Moritz Huetten committed
932
933
            'MPointingPos.fDevAz',
            'MPointingPos.fDevHa',
Moritz Huetten's avatar
Moritz Huetten committed
934
            'MPointingPos.fDevDec',
Moritz Huetten's avatar
astyled    
Moritz Huetten committed
935
936
        ]

Moritz Huetten's avatar
Moritz Huetten committed
937
938
939
940
        # Info only applicable for data:
        time_array_list = [
            'MTime.fMjd',
            'MTime.fTime.fMilliSec',
Moritz Huetten's avatar
astyled    
Moritz Huetten committed
941
942
943
            'MTime.fNanoSec',
        ]

Moritz Huetten's avatar
Moritz Huetten committed
944
945
946
947
948
949
        drive_array_list = [
            'MReportDrive.fMjd',
            'MReportDrive.fCurrentZd',
            'MReportDrive.fCurrentAz',
            'MReportDrive.fRa',
            'MReportDrive.fDec'
Moritz Huetten's avatar
astyled    
Moritz Huetten committed
950
        ]
Moritz Huetten's avatar
Moritz Huetten committed
951

952
953
954
955
956
957
958
959
960
961
        pedestal_array_list = [
            'MTimePedestals.fMjd',
            'MTimePedestals.fTime.fMilliSec',
            'MTimePedestals.fNanoSec',
            'MPedPhotFundamental.fArray.fMean',
            'MPedPhotFundamental.fArray.fRms',
            'MPedPhotFromExtractor.fArray.fMean',
            'MPedPhotFromExtractor.fArray.fRms',
            'MPedPhotFromExtractorRndm.fArray.fMean',
            'MPedPhotFromExtractorRndm.fArray.fRms'
Moritz Huetten's avatar
astyled    
Moritz Huetten committed
962
        ]
963

Moritz Huetten's avatar
Moritz Huetten committed
964
965
966
967
968
969
970
971
        # Info only applicable for MC:
        mc_list = [
            'MMcEvt.fEnergy',
            'MMcEvt.fTheta',
            'MMcEvt.fPhi',
            'MMcEvt.fPartId',
            'MMcEvt.fZFirstInteraction',
            'MMcEvt.fCoreX',
Moritz Huetten's avatar
astyled    
Moritz Huetten committed
972
973
            'MMcEvt.fCoreY',
        ]
Moritz Huetten's avatar
Moritz Huetten committed
974
975
976
977
978
979
980
981
982

        # Metadata, currently not strictly required
        metainfo_array_list = [
            'MRawRunHeader.fRunNumber',
            'MRawRunHeader.fRunType',
            'MRawRunHeader.fSubRunIndex',
            'MRawRunHeader.fSourceRA',
            'MRawRunHeader.fSourceDEC',
            'MRawRunHeader.fTelescopeNumber']
983

984
985
986
987
        for file_name in file_list:

            input_file = uproot.open(file_name)

Moritz Huetten's avatar
Moritz Huetten committed
988
            events = input_file['Events'].arrays(evt_common_list)
989

990
            # Reading the info common to MC and real data
991
992
993
994
            charge = events[b'MCerPhotEvt.fPixels.fPhot']
            arrival_time = events[b'MArrivalTime.fData']
            trigger_pattern = events[b'MTriggerPattern.fPrescaled']
            stereo_event_number = events[b'MRawEvtHeader.fStereoEvtNumber']
995

Moritz Huetten's avatar
Moritz Huetten committed
996
997
            # Reading run-wise meta information (same for all events in subrun):
            mars_meta = dict()
Moritz Huetten's avatar
Moritz Huetten committed
998

Moritz Huetten's avatar
Moritz Huetten committed
999
            mars_meta['is_simulation'] = is_mc
Moritz Huetten's avatar
Moritz Huetten committed
1000

Moritz Huetten's avatar
Moritz Huetten committed
1001
1002
1003
1004
            # Reading event timing information:
            if not is_mc:
                event_times = input_file['Events'].arrays(time_array_list)
                # Computing the event arrival time
Moritz Huetten's avatar
astyled    
Moritz Huetten committed
1005

Moritz Huetten's avatar
Moritz Huetten committed
1006
1007
1008
                event_mjd = event_times[b'MTime.fMjd']
                event_millisec = event_times[b'MTime.fTime.fMilliSec']
                event_nanosec = event_times[b'MTime.fNanoSec']
Moritz Huetten's avatar
Moritz Huetten committed
1009

Moritz Huetten's avatar
astyled    
Moritz Huetten committed
1010
1011
1012
1013
                event_mjd = event_mjd + \
                    (event_millisec / 1e3 + event_nanosec / 1e9) / seconds_per_day
                event_data['MJD'] = scipy.concatenate(
                    (event_data['MJD'], event_mjd))
Moritz Huetten's avatar
Moritz Huetten committed
1014

Moritz Huetten's avatar
Moritz Huetten committed
1015
            # try to read RunHeaders tree (soft fail if not present, to pass current tests)
Moritz Huetten's avatar
Moritz Huetten committed
1016
            try:
Moritz Huetten's avatar
astyled    
Moritz Huetten committed
1017
1018
1019
                meta_info = input_file['RunHeaders'].arrays(
                    metainfo_array_list)

Moritz Huetten's avatar
Moritz Huetten committed
1020
1021
                mars_meta['origin'] = "MAGIC"
                mars_meta['input_url'] = file_name
Moritz Huetten's avatar
Moritz Huetten committed
1022

Moritz Huetten's avatar
astyled    
Moritz Huetten committed
1023
1024
1025
1026
1027
1028
1029
1030
                mars_meta['number'] = int(
                    meta_info[b'MRawRunHeader.fRunNumber'][0])
                mars_meta['number_subrun'] = int(
                    meta_info[b'MRawRunHeader.fSubRunIndex'][0])
                mars_meta['source_ra'] = meta_info[b'MRawRunHeader.fSourceRA'][0] / \
                    seconds_per_hour * degrees_per_hour * u.deg
                mars_meta['source_dec'] = meta_info[b'MRawRunHeader.fSourceDEC'][0] / \
                    seconds_per_hour * u.deg
Moritz Huetten's avatar
Moritz Huetten committed
1031
1032
1033
1034
1035
1036

                is_mc_check = int(meta_info[b'MRawRunHeader.fRunType'][0])
                if is_mc_check == 0:
                    is_mc_check = False
                elif is_mc_check == 256:
                    is_mc_check = True
Moritz Huetten's avatar
Moritz Huetten committed
1037
1038
                else:
                    msg = "Run type (Data or MC) of MAGIC data file not recognised."
Moritz Huetten's avatar
astyled    
Moritz Huetten committed
1039
                    LOGGER.error(msg)
Moritz Huetten's avatar
Moritz Huetten committed
1040
                    raise ValueError(msg)
Moritz Huetten's avatar
Moritz Huetten committed
1041
                if is_mc_check != is_mc:
Moritz Huetten's avatar
Moritz Huetten committed
1042
                    msg = "Inconsistent run type (data or MC) between file name and runheader content."
Moritz Huetten's avatar
astyled    
Moritz Huetten committed
1043
                    LOGGER.error(msg)
Moritz Huetten's avatar
Moritz Huetten committed
1044
                    raise ValueError(msg)
Moritz Huetten's avatar
Moritz Huetten committed
1045

Moritz Huetten's avatar
Moritz Huetten committed
1046
                # Reading the info only contained in real data
Moritz Huetten's avatar
Moritz Huetten committed
1047
                if not is_mc:
Moritz Huetten's avatar
astyled    
Moritz Huetten committed
1048
1049
                    badpixelinfo = input_file['RunHeaders']['MBadPixelsCam.fArray.fInfo'].array(
                        uproot.asjagged(uproot.asdtype(np.int32))).flatten().reshape((4, 1183), order='F')
Moritz Huetten's avatar
Moritz Huetten committed
1050
1051
                    # now we have 4 axes:
                    # 0st axis: empty (?)
Moritz Huetten's avatar
Moritz Huetten committed
1052
1053
1054
1055
                    # 1st axis: Unsuitable pixels
                    # 2nd axis: Uncalibrated pixels (says why pixel is unsuitable)
                    # 3rd axis: Bad hardware pixels (says why pixel is unsuitable)
                    # Each axis cointains a 32bit integer encoding more information about the specific problem, see MARS software, MBADPixelsPix.h
Moritz Huetten's avatar
astyled    
Moritz Huetten committed
1056
1057
                    # take first axis
                    unsuitable_pix_bitinfo = badpixelinfo[1][:n_camera_pixels]
Moritz Huetten's avatar
Moritz Huetten committed
1058
                    # extract unsuitable bit:
Moritz Huetten's avatar
astyled    
Moritz Huetten committed
1059
                    unsuitable_pix = np.zeros(n_camera_pixels, dtype=np.bool)
Moritz Huetten's avatar
Moritz Huetten committed
1060
                    for i in range(n_camera_pixels):
Moritz Huetten's avatar
astyled    
Moritz Huetten committed
1061
1062
                        unsuitable_pix[i] = int('\t{0:08b}'.format(
                            unsuitable_pix_bitinfo[i] & 0xff)[-2])
1063
                    monitoring_data['badpixelinfo'].append(unsuitable_pix)
Moritz Huetten's avatar
Moritz Huetten committed
1064
                    # save time interval of badpixel info:
Moritz Huetten's avatar
astyled    
Moritz Huetten committed
1065
1066
                    monitoring_data['badpixelinfoMJDrange'].append(
                        [event_mjd[0], event_mjd[-1]])
1067

Moritz Huetten's avatar
Moritz Huetten committed
1068
            except KeyError:
Moritz Huetten's avatar
astyled    
Moritz Huetten committed
1069
1070
                LOGGER.warning(
                    "RunHeaders tree not present in file. Cannot read meta information - will assume it is a real data run.")
Moritz Huetten's avatar
Moritz Huetten committed
1071
                is_mc = False
1072

1073
            # try to read Pedestals tree (soft fail if not present)
Moritz Huetten's avatar
Moritz Huetten committed
1074
            if not is_mc:
1075
                try:
Moritz Huetten's avatar
astyled    
Moritz Huetten committed
1076
1077
                    pedestal_info = input_file['Pedestals'].arrays(
                        pedestal_array_list)
Moritz Huetten's avatar
Moritz Huetten committed
1078

1079
1080
1081
1082
                    pedestal_mjd = pedestal_info[b'MTimePedestals.fMjd']
                    pedestal_millisec = pedestal_info[b'MTimePedestals.fTime.fMilliSec']
                    pedestal_nanosec = pedestal_info[b'MTimePedestals.fNanoSec']
                    n_pedestals = len(pedestal_mjd)
Moritz Huetten's avatar
astyled    
Moritz Huetten committed
1083
1084
1085
1086
1087
                    pedestal_mjd = pedestal_mjd + \
                        (pedestal_millisec / 1e3 +
                         pedestal_nanosec / 1e9) / seconds_per_day
                    monitoring_data['PedestalMJD'] = scipy.concatenate(
                        (monitoring_data['PedestalMJD'], pedestal_mjd))
1088
1089
                    for quantity in ['Mean', 'Rms']:
                        for i_pedestal in range(n_pedestals):
Moritz Huetten's avatar
astyled    
Moritz Huetten committed
1090
1091
1092
1093
1094
1095
                            monitoring_data['PedestalFundamental'][quantity].append(
                                pedestal_info['MPedPhotFundamental.fArray.f{:s}'.format(quantity).encode()][i_pedestal][:n_camera_pixels])
                            monitoring_data['PedestalFromExtractor'][quantity].append(
                                pedestal_info['MPedPhotFromExtractor.fArray.f{:s}'.format(quantity).encode()][i_pedestal][:n_camera_pixels])
                            monitoring_data['PedestalFromExtractorRndm'][quantity].append(
                                pedestal_info['MPedPhotFromExtractorRndm.fArray.f{:s}'.format(quantity).encode()][i_pedestal][:n_camera_pixels])
Moritz Huetten's avatar
Moritz Huetten committed
1096

1097
                except KeyError:
Moritz Huetten's avatar
astyled    
Moritz Huetten committed
1098
1099
                    LOGGER.warning(
                        "Pedestals tree not present in file. Cleaning algorithm may fail.")
1100

1101
            # Reading pointing information (in units of degrees):
1102
1103
            if 'MPointingPos.' in input_file['Events']:
                # Retrieving the telescope pointing direction
1104
1105
                pointing = input_file['Events'].arrays(pointing_array_list)

Moritz Huetten's avatar
astyled    
Moritz Huetten committed
1106
1107
1108
1109
1110
1111
1112
1113
1114
                pointing_zd = pointing[b'MPointingPos.fZd'] - \
                    pointing[b'MPointingPos.fDevZd']
                pointing_az = pointing[b'MPointingPos.fAz'] - \
                    pointing[b'MPointingPos.fDevAz']
                # N.B. the positive sign here, as HA = local sidereal time - ra
                pointing_ra = (pointing[b'MPointingPos.fRa'] +
                               pointing[b'MPointingPos.fDevHa']) * degrees_per_hour
                pointing_dec = pointing[b'MPointingPos.fDec'] - \
                    pointing[b'MPointingPos.fDevDec']
1115
1116
            else:
                # Getting the telescope drive info
1117
1118
1119
1120
1121
                drive = input_file['Drive'].arrays(drive_array_list)

                drive_mjd = drive[b'MReportDrive.fMjd']
                drive_zd = drive[b'MReportDrive.fCurrentZd']
                drive_az = drive[b'MReportDrive.fCurrentAz']
1122
                drive_ra = drive[b'MReportDrive.fRa'] * degrees_per_hour
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
                drive_dec = drive[b'MReportDrive.fDec']

                # Finding only non-repeating drive entries
                # Repeating entries lead to failure in pointing interpolation
                non_repeating = scipy.diff(drive_mjd) > 0
                non_repeating = scipy.concatenate((non_repeating, [True]))

                # Filtering out the repeating ones
                drive_mjd = drive_mjd[non_repeating]
                drive_zd = drive_zd[non_repeating]
                drive_az = drive_az[non_repeating]
                drive_ra = drive_ra[non_repeating]
                drive_dec = drive_dec[non_repeating]

                if len(drive_zd) > 2:
                    # If there are enough drive data, creating azimuth and zenith angles interpolators
Moritz Huetten's avatar
astyled    
Moritz Huetten committed
1139
1140
1141
1142
                    drive_zd_pointing_interpolator = scipy.interpolate.interp1d(
                        drive_mjd, drive_zd, fill_value="extrapolate")
                    drive_az_pointing_interpolator = scipy.interpolate.interp1d(
                        drive_mjd, drive_az, fill_value="extrapolate")
1143
1144

                    # Creating azimuth and zenith angles interpolators
Moritz Huetten's avatar
astyled    
Moritz Huetten committed
1145
1146
1147
1148
                    drive_ra_pointing_interpolator = scipy.interpolate.interp1d(
                        drive_mjd, drive_ra, fill_value="extrapolate")
                    drive_dec_pointing_interpolator = scipy.interpolate.interp1d(
                        drive_mjd, drive_dec, fill_value="extrapolate")
1149
1150

                    # Interpolating the drive pointing to the event time stamps
1151
1152
1153
1154
                    pointing_zd = drive_zd_pointing_interpolator(event_mjd)
                    pointing_az = drive_az_pointing_interpolator(event_mjd)
                    pointing_ra = drive_ra_pointing_interpolator(event_mjd)
                    pointing_dec = drive_dec_pointing_interpolator(event_mjd)
1155
1156
1157

                else:
                    # Not enough data to interpolate the pointing direction.
1158
1159
1160
1161
                    pointing_zd = scipy.repeat(-1, len(event_mjd))
                    pointing_az = scipy.repeat(-1, len(event_mjd))
                    pointing_ra = scipy.repeat(-1, len(event_mjd))
                    pointing_dec = scipy.repeat(-1, len(event_mjd))
1162

Moritz Huetten's avatar
wip    
Moritz Huetten committed
1163
            # check for bit flips in the stereo event ID:
1164
            dx = np.diff(stereo_event_number.astype(np.int))
1165
            dx_flip_ids_before = np.where(dx < 0)[0]
1166
            dx_flip_ids_after = dx_flip_ids_before + 1
1167
1168
1169
            dx_flipzero_ids_first = np.where(dx == 0)[0]
            dx_flipzero_ids_second = dx_flipzero_ids_first + 1
            if not is_mc:
Moritz Huetten's avatar
astyled    
Moritz Huetten committed
1170
1171
                pedestal_ids = np.where(
                    trigger_pattern == PEDESTAL_TRIGGER_PATTERN)[0]
1172
                # sort out pedestals events from zero-difference steps:
Moritz Huetten's avatar
astyled    
Moritz Huetten committed
1173
1174
1175
1176
                dx_flipzero_ids_second = np.array(
                    list(set(dx_flipzero_ids_second) - set(pedestal_ids)))
                dx_flip_ids_after = np.array(np.union1d(
                    dx_flip_ids_after, dx_flipzero_ids_second), dtype=np.int)
1177
1178
            else:
                # for MC, sort out stereo_event_number = 0:
1179
                orphan_ids = np.where(stereo_event_number == 0)[0]
Moritz Huetten's avatar
astyled    
Moritz Huetten committed
1180
1181
                dx_flip_ids_after = np.array(
                    list(set(dx_flip_ids_after) - set(orphan_ids)))
1182
1183
            dx_flip_ids_before = dx_flip_ids_after - 1
            if len(dx_flip_ids_before) > 0:
Moritz Huetten's avatar
astyled    
Moritz Huetten committed
1184
1185
                LOGGER.warning("Warning: detected %d bitflips in file %s. Flag affected events as unsuitable" % (
                    len(dx_flip_ids_before), file_name))
1186
                for i in dx_flip_ids_before:
1187
1188
                    trigger_pattern[i] = -1
                    trigger_pattern[i+1] = -1
Moritz Huetten's avatar
wip    
Moritz Huetten committed
1189

1190
1191
            event_data['charge'].append(charge)
            event_data['arrival_time'].append(arrival_time)
Moritz Huetten's avatar
Moritz Huetten committed
1192
            event_data['mars_meta'].append(mars_meta)
Moritz Huetten's avatar
astyled    
Moritz Huetten committed
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
            event_data['trigger_pattern'] = scipy.concatenate(
                (event_data['trigger_pattern'], trigger_pattern))
            event_data['stereo_event_number'] = scipy.concatenate(
                (event_data['stereo_event_number'], stereo_event_number))
            event_data['pointing_zd'] = scipy.concatenate(
                (event_data['pointing_zd'], pointing_zd))
            event_data['pointing_az'] = scipy.concatenate(
                (event_data['pointing_az'], pointing_az))
            event_data['pointing_ra'] = scipy.concatenate(
                (event_data['pointing_ra'], pointing_ra))
            event_data['pointing_dec'] = scipy.concatenate(
                (event_data['pointing_dec'], pointing_dec))
1205
1206

            # Reading MC only information:
Moritz Huetten's avatar
Moritz Huetten committed
1207
            if is_mc:
Moritz Huetten's avatar
Moritz Huetten committed
1208
                mc_info = input_file['Events'].arrays(mc_list)
Moritz Huetten's avatar
Moritz Huetten committed
1209
                # N.B.: For MC, there is only one subrun, so do not need to 'append'
Moritz Huetten's avatar
Moritz Huetten committed
1210
1211
1212
1213
1214
1215
1216
                event_data['true_energy'] = mc_info[b'MMcEvt.fEnergy']
                event_data['true_zd'] = mc_info[b'MMcEvt.fTheta']
                event_data['true_az'] = mc_info[b'MMcEvt.fPhi']
                event_data['true_shower_primary_id'] = mc_info[b'MMcEvt.fPartId']
                event_data['true_h_first_int'] = mc_info[b'MMcEvt.fZFirstInteraction']
                event_data['true_core_x'] = mc_info[b'MMcEvt.fCoreX']
                event_data['true_core_y'] = mc_info[b'MMcEvt.fCoreY']
1217
1218
1219

            event_data['file_edges'].append(len(event_data['trigger_pattern']))

Moritz Huetten's avatar
Moritz Huetten committed
1220
        if not is_mc:
Moritz Huetten's avatar
astyled    
Moritz Huetten committed
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
            monitoring_data['badpixelinfo'] = np.array(
                monitoring_data['badpixelinfo'])
            monitoring_data['badpixelinfoMJDrange'] = np.array(
                monitoring_data['badpixelinfoMJDrange'])
            # sort monitoring data:
            order = np.argsort(monitoring_data['PedestalMJD'])
            monitoring_data['PedestalMJD'] = monitoring_data['PedestalMJD'][order]

            for quantity in ['Mean', 'Rms']:
                monitoring_data['PedestalFundamental'][quantity] = np.array(
                    monitoring_data['PedestalFundamental'][quantity])
                monitoring_data['PedestalFromExtractor'][quantity] = np.array(
                    monitoring_data['PedestalFromExtractor'][quantity])
                monitoring_data['PedestalFromExtractorRndm'][quantity] = np.array(
                    monitoring_data['PedestalFromExtractorRndm'][quantity])
Moritz Huetten's avatar
Moritz Huetten committed
1236

1237
        return event_data, monitoring_data
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252

    def _find_pedestal_events(self):
        """
        This internal method identifies the IDs (order numbers) of the
        pedestal events in the run.

        Returns
        -------
        dict:
            A dictionary of pedestal event IDs in M1/2 separately.
        """

        pedestal_ids = dict()

        for telescope in self.event_data:
Moritz Huetten's avatar
astyled    
Moritz Huetten committed
1253
1254
            ped_triggers = np.where(
                self.event_data[telescope]['trigger_pattern'] == PEDESTAL_TRIGGER_PATTERN)
1255
1256
1257
1258
1259
1260