__init__.py 75 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
from pathlib import Path
12
13

import numpy as np
14
15

import scipy
16
17
18
19
import scipy.interpolate

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

21
from ctapipe.io.eventsource import EventSource
Moritz Huetten's avatar
astyled    
Moritz Huetten committed
22
23
24
25
26
from ctapipe.io.datalevels import DataLevel

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

Alessio Berti's avatar
Alessio Berti committed
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
from ctapipe.containers import (
    ArrayEventContainer,
    SimulatedShowerContainer,
    PointingContainer,
    TelescopePointingContainer,
    TelescopeTriggerContainer,
    MonitoringCameraContainer,
    PedestalContainer,
)

from ctapipe.instrument import (
    TelescopeDescription,
    SubarrayDescription,
    OpticsDescription,
    CameraDescription,
)
43
44
45

__all__ = ['MAGICEventSource']

Moritz Huetten's avatar
astyled    
Moritz Huetten committed
46
LOGGER = logging.getLogger(__name__)
47

Ievgen Vovk's avatar
Ievgen Vovk committed
48

49
# MAGIC telescope positions in m wrt. to the center of CTA simulations
50
51
52
53
54
55
#MAGIC_TEL_POSITIONS = {
#    1: [-27.24, -146.66, 50.00] * u.m,
#    2: [-96.44, -96.77, 51.00] * u.m
#}

# MAGIC telescope positions in m wrt. to the center of MAGIC simulations, from reflector input card
Moritz Huetten's avatar
astyled    
Moritz Huetten committed
56
MAGIC_TEL_POSITIONS = {
57
58
    1: [31.80, -28.10, 0.00] * u.m,
    2: [-31.80, 28.10, 0.00] * u.m
59
}
60

61
# MAGIC telescope description
Moritz Huetten's avatar
astyled    
Moritz Huetten committed
62
OPTICS = OpticsDescription.from_name('MAGIC')
63
64
MAGICCAM = CameraDescription.from_name("MAGICCam")
GEOM = MAGICCAM.geometry
Moritz Huetten's avatar
astyled    
Moritz Huetten committed
65
MAGIC_TEL_DESCRIPTION = TelescopeDescription(
66
    name='MAGIC', tel_type='MAGIC', optics=OPTICS, camera=MAGICCAM)
Moritz Huetten's avatar
astyled    
Moritz Huetten committed
67
MAGIC_TEL_DESCRIPTIONS = {1: MAGIC_TEL_DESCRIPTION, 2: MAGIC_TEL_DESCRIPTION}
68

69
# trigger patterns:
Moritz Huetten's avatar
astyled    
Moritz Huetten committed
70
71
72
73
MC_TRIGGER_PATTERN = 1
PEDESTAL_TRIGGER_PATTERN = 8
DATA_TRIGGER_PATTERN = 128

74
75
76
77
78
79
80
class L3JumpError(Exception):
    """
    Exception raised when L3 trigger number jumps backward.
    """

    def __init__(self, message):
        self.message = message
81

82
83
84
85
86
87
88
89
class MissingDriveReportError(Exception):
    """
    Exception raised when a subrun does not have drive reports.
    """

    def __init__(self, message):
        self.message = message

90
91
92
93
94
95
96
97
98
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

Alessio Berti's avatar
Alessio Berti committed
99
    def __init__(self, input_url=None, config=None, parent=None, **kwargs):
100
101
102
103
104
105
106
107
108
        """
        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.
109
        parent : ctapipe.core.Tool
110
111
112
113
114
115
116
117
118
            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.
        """

119
        super().__init__(input_url=input_url, config=config, parent=parent, **kwargs)
120
121

        # Retrieving the list of run numbers corresponding to the data files
Alessio Berti's avatar
Alessio Berti committed
122
        run_info = self.get_run_info_from_name(str(input_url))
123
124
        run_numbers = run_info[0]
        is_mc_runs = run_info[1]
Moritz Huetten's avatar
Moritz Huetten committed
125

Alessio Berti's avatar
Alessio Berti committed
126
127
        self.run_numbers = run_numbers
        self.is_mc = is_mc_runs
128

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

132
133
134
135
        # # 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
136
137
        self._subarray_info = SubarrayDescription(
            'MAGIC', MAGIC_TEL_POSITIONS, MAGIC_TEL_DESCRIPTIONS)
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163

    @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:
Alessio Berti's avatar
Alessio Berti committed
164
                import uproot
165
166
167
168
169
170
171
172
173
174

                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

            except ImportError:
Ievgen Vovk's avatar
Ievgen Vovk committed
175
                if re.match(r'.+_m\d_.+root', file_path.lower()) is None:
176
177
178
179
180
                    is_magic_root_file = False

        return is_magic_root_file

    @staticmethod
181
    def get_run_info_from_name(file_name):
182
        """
Moritz Huetten's avatar
astyled    
Moritz Huetten committed
183
        This internal method extracts the run number and
Moritz Huetten's avatar
Moritz Huetten committed
184
        type (data/MC) from the specified file name.
185
186
187
188
189
190
191
192
193
194
195
196

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

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

Moritz Huetten's avatar
Moritz Huetten committed
197
        mask_data = r".*\d+_M\d+_(\d+)\.\d+_Y_.*"
Moritz Huetten's avatar
Moritz Huetten committed
198
199
        mask_mc = r".*_M\d_za\d+to\d+_\d_(\d+)_Y_.*"
        mask_mc_alt = r".*_M\d_\d_(\d+)_.*"
200
        if re.findall(mask_data, file_name):
Moritz Huetten's avatar
Moritz Huetten committed
201
202
            parsed_info = re.findall(mask_data, file_name)
            is_mc = False
203
        elif re.findall(mask_mc, file_name):
Moritz Huetten's avatar
Moritz Huetten committed
204
205
206
207
208
            parsed_info = re.findall(mask_mc, file_name)
            is_mc = True
        else:
            parsed_info = re.findall(mask_mc_alt, file_name)
            is_mc = True
209
210
211
212

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

Moritz Huetten's avatar
Moritz Huetten committed
217
        return run_number, is_mc
218

Moritz Huetten's avatar
Moritz Huetten committed
219
    def _set_active_run(self, run_number):
220
221
222
223
224
225
226
227
228
229
        """
        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
230
        MarsRun:
Moritz Huetten's avatar
Moritz Huetten committed
231
            The run to use
232
        """
Moritz Huetten's avatar
Moritz Huetten committed
233

234
235
236
        run = dict()
        run['number'] = run_number
        run['read_events'] = 0
Alessio Berti's avatar
Alessio Berti committed
237
        run['data'] = MarsRun(run_file_mask=str(self.input_url))
238
239
240

        return run

241
242
243
244
    @property
    def subarray(self):
        return self._subarray_info

Moritz Huetten's avatar
astyled    
Moritz Huetten committed
245
246
247
248
249
250
251
252
253
    @property
    def is_simulation(self):
        return self.is_mc

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

    @property
254
    def obs_ids(self):
Moritz Huetten's avatar
astyled    
Moritz Huetten committed
255
256
        return self.run_numbers

257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
    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
282
        data = ArrayEventContainer()
283
284
285
286
287
288

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

        # Loop over the available data runs
289
        for run_number in self.run_numbers:
290
291
292
293
294
295

            # 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
296
            # Setting the new active run (class MarsRun object)
Moritz Huetten's avatar
Moritz Huetten committed
297
            self.current_run = self._set_active_run(run_number)
298
            
299
300
            # Set monitoring data:
            if not self.is_mc:
Moritz Huetten's avatar
Moritz Huetten committed
301

302
                monitoring_data = self.current_run['data'].monitoring_data
Moritz Huetten's avatar
Moritz Huetten committed
303

304
305
306
                for tel_i, tel_id in enumerate(tels_in_file):
                    monitoring_camera = MonitoringCameraContainer()
                    pedestal_info = PedestalContainer()
307
                    badpixel_info = PixelStatusContainer()
Moritz Huetten's avatar
Moritz Huetten committed
308

Moritz Huetten's avatar
astyled    
Moritz Huetten committed
309
310
311
312
313
314
                    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
315
                    pedestal_info.charge_mean = []
Moritz Huetten's avatar
astyled    
Moritz Huetten committed
316
317
318
319
320
321
                    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'])
322
                    pedestal_info.charge_std = []
Moritz Huetten's avatar
astyled    
Moritz Huetten committed
323
324
325
326
327
328
329
330
331
332
333
334
                    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
335
                    badpixel_info.sample_time_range = t_range
336

337
                    monitoring_camera.pedestal = pedestal_info
338
                    monitoring_camera.pixel_status = badpixel_info
339
340

                    data.mon.tels_with_data = {1, 2}
341
                    data.mon.tel[tel_i + 1] = monitoring_camera
342
            else:
343
344
                assert self.current_run['data'].mcheader_data['M1'] == self.current_run['data'].mcheader_data['M2'], "Simulation configurations are different for M1 and M2 !!!"
                data.mcheader.num_showers = self.current_run['data'].mcheader_data['M1']['sim_nevents']
345
                data.mcheader.shower_reuse = self.current_run['data'].mcheader_data['M1']['sim_reuse']
346
347
348
349
350
351
352
                data.mcheader.energy_range_min = (self.current_run['data'].mcheader_data['M1']['sim_emin']).to(u.TeV) # GeV->TeV
                data.mcheader.energy_range_max = (self.current_run['data'].mcheader_data['M1']['sim_emax']).to(u.TeV) # GeV->TeV
                data.mcheader.spectral_index = self.current_run['data'].mcheader_data['M1']['sim_eslope']
                data.mcheader.max_scatter_range = (self.current_run['data'].mcheader_data['M1']['sim_max_impact']).to(u.m) # cm->m
                data.mcheader.max_viewcone_radius = (self.current_run['data'].mcheader_data['M1']['sim_conesemiangle']).to(u.deg)# deg->deg
                if data.mcheader.max_viewcone_radius != 0.:
                    data.mcheader.diffuse = True
353
                else:
354
355
                    data.mcheader.diffuse = False
                    
356

357
358
359
360
361
362
363
364
            # 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
365
366
367
                event_data = self.current_run['data'].get_stereo_event_data(
                    event_i)

368
                data.meta = event_data['mars_meta']
369
370
371

                # Event counter
                data.count = counter
Moritz Huetten's avatar
Moritz Huetten committed
372
373
                data.index.obs_id = obs_id
                data.index.event_id = event_id
374
375
376
377
378
379
380
381
382
383

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

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

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

Alessio Berti's avatar
Alessio Berti committed
384
385
386
                # Setting up the DL1 container
                data.dl1.tel.clear()

387
                pointing = PointingContainer()
388
389
390
                # Filling the DL1 container with the event data
                for tel_i, tel_id in enumerate(tels_in_file):
                    # Creating the telescope pointing container
391
392
393
                    pointing_tel = TelescopePointingContainer()
                    
                    pointing_tel.azimuth = np.deg2rad(
Moritz Huetten's avatar
astyled    
Moritz Huetten committed
394
                        event_data['{:s}_pointing_az'.format(tel_id)]) * u.rad
395
396
                    
                    pointing_tel.altitude = np.deg2rad(
Moritz Huetten's avatar
astyled    
Moritz Huetten committed
397
                        90 - event_data['{:s}_pointing_zd'.format(tel_id)]) * u.rad
398
                    
399
                    # pointing.ra = np.deg2rad(
Moritz Huetten's avatar
Moritz Huetten committed
400
                    #    event_data['{:s}_pointing_ra'.format(tel_id)]) * u.rad
401
                    # pointing.dec = np.deg2rad(
Moritz Huetten's avatar
Moritz Huetten committed
402
                    #    event_data['{:s}_pointing_dec'.format(tel_id)]) * u.rad
403

404
                    pointing.tel[tel_i + 1] = pointing_tel
405

Moritz Huetten's avatar
Moritz Huetten committed
406
407
408
409
410
                    # 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]

411
                    # Adding event charge and peak positions per pixel
Moritz Huetten's avatar
astyled    
Moritz Huetten committed
412
413
414
                    data.dl1.tel[tel_i +
                                 1].image = event_data['{:s}_image'.format(tel_id)]
                    data.dl1.tel[tel_i +
Moritz Huetten's avatar
Moritz Huetten committed
415
                                 1].peak_time = event_data['{:s}_pulse_time'.format(tel_id)]
416
417
418
419
420
421
                
                pointing.array_azimuth = np.deg2rad(event_data['m1_pointing_az']) * u.rad
                pointing.array_altitude = np.deg2rad(90 - event_data['m1_pointing_zd']) * u.rad
                pointing.array_ra = np.deg2rad(event_data['m1_pointing_ra']) * u.rad
                pointing.array_dec = np.deg2rad(90 - event_data['m1_pointing_dec']) * u.rad
                data.pointing = pointing
Moritz Huetten's avatar
Moritz Huetten committed
422

Moritz Huetten's avatar
astyled    
Moritz Huetten committed
423
                if not self.is_mc:
Moritz Huetten's avatar
Moritz Huetten committed
424
                    # Adding the event arrival time
Moritz Huetten's avatar
astyled    
Moritz Huetten committed
425
426
                    time_tmp = Time(
                        event_data['mjd'], scale='utc', format='mjd')
Moritz Huetten's avatar
Moritz Huetten committed
427
                    data.trigger.time = Time(
Moritz Huetten's avatar
astyled    
Moritz Huetten committed
428
                        time_tmp, format='unix', scale='utc', precision=9)
Moritz Huetten's avatar
Moritz Huetten committed
429
430
                else:
                    data.mc.energy = event_data['true_energy'] * u.GeV
431
                    data.mc.alt = (np.pi/2 - event_data['true_zd']) * u.rad
Moritz Huetten's avatar
astyled    
Moritz Huetten committed
432
433
434
435
436
                    # 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
437
                    data.mc.h_first_int = event_data['true_h_first_int'] * u.cm
438
439
440
441
442
443
                    
                    # adding a 7deg rotation between the orientation of corsika (x axis = magnetic north) and MARS (x axis = geographical north) frames
                    # magnetic north is 7 deg westward w.r.t. geographical north
                    rot_corsika = 7 *u.deg
                    data.mc.core_x = (event_data['true_core_x']*np.cos(rot_corsika) - event_data['true_core_y']*np.sin(rot_corsika))* u.cm
                    data.mc.core_y = (event_data['true_core_x']*np.sin(rot_corsika) + event_data['true_core_y']*np.cos(rot_corsika))* u.cm
444
445
446
447
448

                # 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
Moritz Huetten's avatar
Moritz Huetten committed
449
                data.trigger.tels_with_trigger = tels_with_data
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474

                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
475
        data = ArrayEventContainer()
476
477
478
479
480

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

        if telescope not in tels_in_file:
Moritz Huetten's avatar
astyled    
Moritz Huetten committed
481
482
            raise ValueError("Specified telescope {:s} is not in the allowed list {}".format(
                telescope, tels_in_file))
483
484
485
486

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

Alessio Berti's avatar
Alessio Berti committed
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
        # 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
        self.current_run = self._set_active_run(self.run_numbers)

        # Set monitoring data:
        if not self.is_mc:

            monitoring_data = self.current_run['data'].monitoring_data

            monitoring_camera = MonitoringCameraContainer()
            pedestal_info = PedestalContainer()
            badpixel_info = PixelStatusContainer()

            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
            pedestal_info.charge_mean = []
            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'])
            pedestal_info.charge_std = []
            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']
            badpixel_info.sample_time_range = t_range

            monitoring_camera.pedestal = pedestal_info
            monitoring_camera.pixel_status = badpixel_info

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

Alessio Berti's avatar
Alessio Berti committed
536
        #fdp (mono version not fully tested)
Alessio Berti's avatar
Alessio Berti committed
537
538
539
540
541
        else:
            data.mcheader.num_showers = self.current_run['data'].mcheader_data[telescope]['sim_nevents'] # total, including reuse
            data.mcheader.shower_reuse = self.current_run['data'].mcheader_data[telescope]['sim_reuse']
            data.mcheader.energy_range_min = (self.current_run['data'].mcheader_data[telescope]['sim_emin']).to(u.TeV) # GeV->TeV
            data.mcheader.energy_range_max = (self.current_run['data'].mcheader_data[telescope]['sim_emax']).to(u.TeV) # GeV->TeV
Alessio Berti's avatar
Alessio Berti committed
542
            data.mcheader.spectral_index = self.current_run['data'].mcheader_data[telescope]['sim_eslope']
Alessio Berti's avatar
Alessio Berti committed
543
544
            data.mcheader.max_scatter_range = (self.current_run['data'].mcheader_data[telescope]['sim_max_impact']).to(u.m) # cm->m
            data.mcheader.max_viewcone_radius = (self.current_run['data'].mcheader_data[telescope]['sim_conesemiangle']).to(u.deg) # deg->deg
545

Alessio Berti's avatar
Alessio Berti committed
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
        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
            event_data = self.current_run['data'].get_mono_event_data(
                event_i, telescope=telescope)

            data.meta = event_data['mars_meta']
Alessio Berti's avatar
Alessio Berti committed
563
564
            data.meta["max_events"] = self.max_events

Alessio Berti's avatar
Alessio Berti committed
565
            data.trigger.event_type = self.current_run['data'].event_data[telescope]['trigger_pattern'][event_order_number]
Alessio Berti's avatar
Alessio Berti committed
566
567
568
569
570
571
572
573
574
575
576
577
            data.trigger.tels_with_trigger = tels_with_data
            if self.allowed_tels:
                data.trigger.tels_with_trigger = np.intersect1d(
                    data.trigger.tels_with_trigger,
                    self.subarray.tel_ids,
                    assume_unique=True,)
            if not self.is_mc:
                # Adding the event arrival time
                time_tmp = Time(
                    event_data['mjd'], scale='utc', format='mjd')
                data.trigger.tel[tel_i + 1] = TelescopeTriggerContainer(time=Time(
                    time_tmp, format='unix', scale='utc', precision=9))
Alessio Berti's avatar
Alessio Berti committed
578
579
580
581
582
583
584
585
586
587
588

            # Event counter
            data.count = counter
            data.index.obs_id = obs_id
            data.index.event_id = event_id

            # Setting up the R0 container
            data.r0.tel.clear()
            data.r1.tel.clear()
            data.dl0.tel.clear()
            data.dl1.tel.clear()
Alessio Berti's avatar
Alessio Berti committed
589
            data.pointing.tel.clear()
Alessio Berti's avatar
Alessio Berti committed
590
591
592

            # Creating the telescope pointing container
            pointing = PointingContainer()
Alessio Berti's avatar
Alessio Berti committed
593
594
595
596
597
598
            pointing_tel = TelescopePointingContainer(
                azimuth = np.deg2rad(
                event_data['pointing_az']) * u.rad,
                altitude = np.deg2rad(
                90 - event_data['pointing_zd']) * u.rad,)

Alessio Berti's avatar
Alessio Berti committed
599
            pointing.tel[tel_i + 1] = pointing_tel
Alessio Berti's avatar
Alessio Berti committed
600
601

            pointing.array_azimuth  = np.deg2rad(event_data['pointing_az']) * u.rad
Alessio Berti's avatar
Alessio Berti committed
602
            pointing.array_altitude = np.deg2rad(90 - event_data['pointing_zd']) * u.rad
Alessio Berti's avatar
Alessio Berti committed
603
604
605
            pointing.array_ra       = np.deg2rad(event_data['pointing_ra']) * u.rad
            pointing.array_dec      = np.deg2rad(90 - event_data['pointing_dec']) * u.rad

Alessio Berti's avatar
Alessio Berti committed
606
            data.pointing = pointing
Moritz Huetten's avatar
Moritz Huetten committed
607

Alessio Berti's avatar
Alessio Berti committed
608
609
610
            # Adding event charge and peak positions per pixel
            data.dl1.tel[tel_i + 1].image = event_data['image']
            data.dl1.tel[tel_i + 1].peak_time = event_data['pulse_time']
Moritz Huetten's avatar
Moritz Huetten committed
611

Alessio Berti's avatar
Alessio Berti committed
612
613
            if self.is_mc:
                rot_corsika = 7 *u.deg
Alessio Berti's avatar
Alessio Berti committed
614
615
616
                # check meaning of 7deg transformation (I.Vovk)
                # adding a 7deg rotation between the orientation of corsika (x axis = magnetic north) and MARS (x axis = geographical north) frames
                # magnetic north is 7 deg westward w.r.t. geographical north
Alessio Berti's avatar
Alessio Berti committed
617
618
619
620
621
622
623
624
625
                data.simulation.shower = SimulatedShowerContainer(
                    energy = u.Quantity(event_data['true_energy'], u.GeV),
                    alt = Angle((np.pi/2 - event_data['true_zd']), u.rad),
                    az = Angle(-1 * (event_data['true_az'] - np.deg2rad(180 - 7)), u.rad),
                    shower_primary_id = 1 - event_data['true_shower_primary_id'],
                    h_first_int = u.Quantity(event_data['true_h_first_int'], u.cm),
                    core_x = u.Quantity((event_data['true_core_x']*np.cos(rot_corsika) - event_data['true_core_y']*np.sin(rot_corsika)), u.cm),
                    core_y = u.Quantity((event_data['true_core_x']*np.sin(rot_corsika) + event_data['true_core_y']*np.cos(rot_corsika)), u.cm),
                )
Alessio Berti's avatar
Alessio Berti committed
626
627
628

            yield data
            counter += 1
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650

        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
651
        data = EventAndMonDataContainer()
652
653
654
655
656

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

        if telescope not in tels_in_file:
Moritz Huetten's avatar
astyled    
Moritz Huetten committed
657
658
            raise ValueError("Specified telescope {:s} is not in the allowed list {}".format(
                telescope, tels_in_file))
659
660
661
662
663

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

        # Loop over the available data runs
664
        for run_number in self.run_numbers:
665
666
667
668
669
670
671

            # 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
672
            self.current_run = self._set_active_run(run_number)
673

Moritz Huetten's avatar
Moritz Huetten committed
674
            monitoring_data = self.current_run['data'].monitoring_data
Moritz Huetten's avatar
Moritz Huetten committed
675

Moritz Huetten's avatar
Moritz Huetten committed
676
677
678
            monitoring_camera = MonitoringCameraContainer()
            pedestal_info = PedestalContainer()
            badpixel_info = PixelStatusContainer()
Moritz Huetten's avatar
Moritz Huetten committed
679

Moritz Huetten's avatar
astyled    
Moritz Huetten committed
680
681
682
683
            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)
684
            pedestal_info.n_events = 500 # hardcoded number of pedestal events averaged over
Moritz Huetten's avatar
Moritz Huetten committed
685
            pedestal_info.charge_mean = []
Moritz Huetten's avatar
astyled    
Moritz Huetten committed
686
687
688
689
690
691
            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
692
            pedestal_info.charge_std = []
Moritz Huetten's avatar
astyled    
Moritz Huetten committed
693
694
695
696
697
698
699
700
701
702
703
704
            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
705
            badpixel_info.sample_time_range = t_range
Moritz Huetten's avatar
Moritz Huetten committed
706

Moritz Huetten's avatar
Moritz Huetten committed
707
708
709
710
711
712
            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

713
714
715
716
717
718
719
720
721
722
723
724
725
            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
726
727
728
                event_data = self.current_run['data'].get_pedestal_event_data(
                    event_i, telescope=telescope)

729
                data.meta = event_data['mars_meta']
730
731
732

                # Event counter
                data.count = counter
Moritz Huetten's avatar
Moritz Huetten committed
733
734
                data.index.obs_id = obs_id
                data.index.event_id = event_id
735

736
737
                # Setting up the R0 container
                data.r0.tel.clear()
738
                data.r0.tel[tel_i + 1].trigger_type = self.current_run['data'].event_data[telescope]['trigger_pattern'][event_order_number]
739
740
741

                # Setting up the R1 container
                data.r1.tel.clear()
742
                data.r1.tel[tel_i + 1].trigger_type = self.current_run['data'].event_data[telescope]['trigger_pattern'][event_order_number]
743
744
745

                # Setting up the DL0 container
                data.dl0.tel.clear()
746
                data.dl0.tel[tel_i + 1].trigger_type = self.current_run['data'].event_data[telescope]['trigger_pattern'][event_order_number]
747
748
749

                # Creating the telescope pointing container
                pointing = TelescopePointingContainer()
Moritz Huetten's avatar
astyled    
Moritz Huetten committed
750
751
752
753
                pointing.azimuth = np.deg2rad(
                    event_data['pointing_az']) * u.rad
                pointing.altitude = np.deg2rad(
                    90 - event_data['pointing_zd']) * u.rad
Moritz Huetten's avatar
Moritz Huetten committed
754
755
                #pointing.ra = np.deg2rad(event_data['pointing_ra']) * u.rad
                #pointing.dec = np.deg2rad(event_data['pointing_dec']) * u.rad
756
757

                # Adding the pointing container to the event data
Moritz Huetten's avatar
Moritz Huetten committed
758
                data.pointing.tel[tel_i + 1] = pointing
759
760
761

                # Adding event charge and peak positions per pixel
                data.dl1.tel[tel_i + 1].image = event_data['image']
Moritz Huetten's avatar
Moritz Huetten committed
762
                data.dl1.tel[tel_i + 1].peak_time = event_data['pulse_time']
763
764
765

                # Adding the event arrival time
                time_tmp = Time(event_data['mjd'], scale='utc', format='mjd')
Moritz Huetten's avatar
Moritz Huetten committed
766
                data.trigger.time = Time(
Moritz Huetten's avatar
astyled    
Moritz Huetten committed
767
                    time_tmp, format='unix', scale='utc', precision=9)
768
769
770
771
772

                # 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
Moritz Huetten's avatar
Moritz Huetten committed
773
                data.trigger.tels_with_trigger = tels_with_data
774
775
776
777
778
779
780

                yield data
                counter += 1

        return


Moritz Huetten's avatar
Moritz Huetten committed
781
class MarsRun:
782
783
784
785
    """
    This class implements reading of the event data from a single MAGIC data run.
    """

Moritz Huetten's avatar
Moritz Huetten committed
786
    def __init__(self, run_file_mask, filter_list=None):
787
788
789
790
791
792
793
794
795
        """
        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.
796
797
798
        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.
799
800
        """

Moritz Huetten's avatar
astyled    
Moritz Huetten committed
801
        self.n_camera_pixels = GEOM.n_pixels
802

803
804
805
806
        self.run_file_mask = run_file_mask

        # Preparing the lists of M1/2 data files
        file_list = glob.glob(run_file_mask)
807
808
809
810
811

        # 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
812
813
814
815
        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))
816
        self.m1_file_list.sort()
817
818
819
        self.m2_file_list.sort()

        # Retrieving the list of run numbers corresponding to the data files
Moritz Huetten's avatar
astyled    
Moritz Huetten committed
820
        run_info = list(
821
            map(MAGICEventSource.get_run_info_from_name, file_list))
Moritz Huetten's avatar
Moritz Huetten committed
822
        run_numbers = [i[0] for i in run_info]
Moritz Huetten's avatar
astyled    
Moritz Huetten committed
823
        is_mc_runs = [i[1] for i in run_info]
824
825
826

        run_numbers = np.unique(run_numbers)
        is_mc_runs = np.unique(is_mc_runs)
Moritz Huetten's avatar
astyled    
Moritz Huetten committed
827
        # Checking if run type (data/MC) is consistent:
828
        if len(is_mc_runs) > 1:
Moritz Huetten's avatar
astyled    
Moritz Huetten committed
829
830
831
            raise ValueError(
                "Run type is not consistently data or MC: {}".format(is_mc_runs))

832
        self.is_mc = is_mc_runs[0]
833
834
835

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

839
        # Reading the data
Moritz Huetten's avatar
astyled    
Moritz Huetten committed
840
841
842
843
844
        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)

845
        # Getting the event data
846
        self.event_data = dict()
847
848
849
850
851
852
853
        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]
854

855
        # Getting the run-wise MC header data
856
        if self.is_mc:
857
858
859
            self.mcheader_data = dict()
            self.mcheader_data['M1'] = m1_data[2]
            self.mcheader_data['M2'] = m2_data[2]
860

861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
        # 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
897
    def load_events(file_list, is_mc, n_camera_pixels):
898
        """
899
        This method loads events and monitoring data from the pre-defiled file and returns them as a dictionary.
900
901
902
903
904

        Parameters
        ----------
        file_name: str
            Name of the MAGIC calibrated file to use.
905
906
907
908
        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)
909
910
911
912
913
914
915
916

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

        try:
Alessio Berti's avatar
Alessio Berti committed
917
            import uproot
918
919
920
921
922
923
924
925
        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'] = []
Alessio Berti's avatar
Alessio Berti committed
926
927
928
929
930
931
932
        event_data['trigger_pattern'] = np.array([], dtype=np.int32)
        event_data['stereo_event_number'] = np.array([], dtype=np.int32)
        event_data['pointing_zd'] = np.array([])
        event_data['pointing_az'] = np.array([])
        event_data['pointing_ra'] = np.array([])
        event_data['pointing_dec'] = np.array([])
        event_data['MJD'] = np.array([])
Moritz Huetten's avatar
Moritz Huetten committed
933
        event_data['mars_meta'] = []
934

935
936
        # monitoring information (updated from time to time)
        monitoring_data = dict()
Moritz Huetten's avatar
astyled    
Moritz Huetten committed
937

Moritz Huetten's avatar
Moritz Huetten committed
938
939
        monitoring_data['badpixelinfo'] = []
        monitoring_data['badpixelinfoMJDrange'] = []
Alessio Berti's avatar
Alessio Berti committed
940
        monitoring_data['PedestalMJD'] = np.array([])
941
942
943
944
945
946
947
948
949
950
        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'] = []

951
952
        #MC Header information, dictionary always created, but filled only in case of MC run
        mcheader_data = dict()
953

954
955
        event_data['file_edges'] = [0]

956
957
958
959
960
        # if no file in the list (e.g. when reading mono information), then simply
        # return empty dicts/array
        if len(file_list) == 0:
            return event_data, monitoring_data, mcheader_data

961
962
963
964
965
966
967
        drive_data = dict()
        drive_data['mjd'] = np.array([])
        drive_data['zd']  = np.array([])
        drive_data['az']  = np.array([])
        drive_data['ra']  = np.array([])
        drive_data['dec'] = np.array([])

968
969
970
971
        degrees_per_hour = 15.0
        seconds_per_day = 86400.0
        seconds_per_hour = 3600.

Moritz Huetten's avatar
Moritz Huetten committed
972
        evt_common_list = [
Moritz Huetten's avatar
astyled    
Moritz Huetten committed
973
            'MCerPhotEvt.fPixels.fPhot',
Moritz Huetten's avatar
Moritz Huetten committed
974
975
            'MArrivalTime.fData',
            'MTriggerPattern.fPrescaled',
Moritz Huetten's avatar
astyled    
Moritz Huetten committed
976
            'MRawEvtHeader.fStereoEvtNumber',
Moritz Huetten's avatar
Moritz Huetten committed
977
            'MRawEvtHeader.fDAQEvtNumber',
Moritz Huetten's avatar
astyled    
Moritz Huetten committed
978
979
980
        ]

        # Separately, because only used with pre-processed MARS data
Moritz Huetten's avatar
Moritz Huetten committed
981
982
        # to create MPointingPos container
        pointing_array_list = [
Moritz Huetten's avatar
astyled    
Moritz Huetten committed
983
984
985
986
            'MPointingPos.fZd',
            'MPointingPos.fAz',
            'MPointingPos.fRa',
            'MPointingPos.fDec',
Moritz Huetten's avatar
Moritz Huetten committed
987
            'MPointingPos.fDevZd',
Moritz Huetten's avatar
astyled    
Moritz Huetten committed
988
989
            'MPointingPos.fDevAz',
            'MPointingPos.fDevHa',
Moritz Huetten's avatar
Moritz Huetten committed
990
            'MPointingPos.fDevDec',
Moritz Huetten's avatar
astyled    
Moritz Huetten committed
991
992
        ]

Moritz Huetten's avatar
Moritz Huetten committed
993
994
995
996
        # Info only applicable for data:
        time_array_list = [
            'MTime.fMjd',
            'MTime.fTime.fMilliSec',
Moritz Huetten's avatar
astyled    
Moritz Huetten committed
997
998
999
            'MTime.fNanoSec',
        ]

Moritz Huetten's avatar
Moritz Huetten committed
1000
        drive_array_list = [