__init__.py 71.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 numpy as np
13
14

import scipy
15
16
17
18
import scipy.interpolate

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

20
from ctapipe.io.eventsource import EventSource
Moritz Huetten's avatar
astyled    
Moritz Huetten committed
21
22
23
24
25
26
27
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
28
from ctapipe.containers import PointingContainer, TelescopePointingContainer
Moritz Huetten's avatar
astyled    
Moritz Huetten committed
29
30
31
32
33
34
35
36
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

37
38
39

__all__ = ['MAGICEventSource']

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

Ievgen Vovk's avatar
Ievgen Vovk committed
42

43
# MAGIC telescope positions in m wrt. to the center of CTA simulations
Moritz Huetten's avatar
astyled    
Moritz Huetten committed
44
MAGIC_TEL_POSITIONS = {
45
46
47
48
    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
49
50
51
52
53
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}
54

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

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
89
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.
        """

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

        # 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']
99
        super().__init__(input_url=self.file_list[0], **kwargs)
100
101

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

        self.run_numbers, indices = np.unique(run_numbers, return_index=True)
107
108
        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
109

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

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

119
120
121
122
        # # 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
123
124
        self._subarray_info = SubarrayDescription(
            'MAGIC', MAGIC_TEL_POSITIONS, MAGIC_TEL_DESCRIPTIONS)
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

    @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:
151
                import uproot3 as uproot
152
153
154
155
156
157
158
159
160
161

                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
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
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
        mask_mc = r".*_M\d_za\d+to\d+_\d_(\d+)_Y_.*"
        mask_mc_alt = r".*_M\d_\d_(\d+)_.*"
187
        if re.findall(mask_data, file_name):
Moritz Huetten's avatar
Moritz Huetten committed
188
189
            parsed_info = re.findall(mask_data, file_name)
            is_mc = False
190
        elif re.findall(mask_mc, file_name):
Moritz Huetten's avatar
Moritz Huetten committed
191
192
193
194
195
            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
Moritz Huetten committed
220

221
        this_run_mask = os.path.join(self.input_url.parents[0],
Moritz Huetten's avatar
Moritz Huetten committed
222
                                     '*{:d}*root'.format(run_number))
223
224
225
226

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

        return run

232
233
234
235
    @property
    def subarray(self):
        return self._subarray_info

Moritz Huetten's avatar
astyled    
Moritz Huetten committed
236
237
238
239
240
241
242
243
244
245
246
247
    @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

248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
    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
273
274
275
276
        if not self.is_mc:
            data = EventAndMonDataContainer()
        else:
            data = DataContainer()
277
278
279
280
281
282

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

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

            # 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
290
            # Setting the new active run (class MarsRun object)
Moritz Huetten's avatar
Moritz Huetten committed
291
            self.current_run = self._set_active_run(run_number)
292
            
293
294
            # Set monitoring data:
            if not self.is_mc:
Moritz Huetten's avatar
Moritz Huetten committed
295

296
                monitoring_data = self.current_run['data'].monitoring_data
Moritz Huetten's avatar
Moritz Huetten committed
297

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

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

331
                    monitoring_camera.pedestal = pedestal_info
332
                    monitoring_camera.pixel_status = badpixel_info
333
334

                    data.mon.tels_with_data = {1, 2}
335
                    data.mon.tel[tel_i + 1] = monitoring_camera
336
            else:
337
338
                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']
339
                data.mcheader.shower_reuse = self.current_run['data'].mcheader_data['M1']['sim_reuse']
340
341
342
343
344
345
346
                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
347
                else:
348
349
                    data.mcheader.diffuse = False
                    
350

351
352
353
354
355
356
357
358
            # 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
359
360
361
                event_data = self.current_run['data'].get_stereo_event_data(
                    event_i)

362
                data.meta = event_data['mars_meta']
363
364
365

                # Event counter
                data.count = counter
Moritz Huetten's avatar
Moritz Huetten committed
366
367
                data.index.obs_id = obs_id
                data.index.event_id = event_id
368
369
370
371
372
373
374
375
376
377

                # 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()

378
                pointing = PointingContainer()
379
380
381
                # Filling the DL1 container with the event data
                for tel_i, tel_id in enumerate(tels_in_file):
                    # Creating the telescope pointing container
382
383
384
                    pointing_tel = TelescopePointingContainer()
                    
                    pointing_tel.azimuth = np.deg2rad(
Moritz Huetten's avatar
astyled    
Moritz Huetten committed
385
                        event_data['{:s}_pointing_az'.format(tel_id)]) * u.rad
386
387
                    
                    pointing_tel.altitude = np.deg2rad(
Moritz Huetten's avatar
astyled    
Moritz Huetten committed
388
                        90 - event_data['{:s}_pointing_zd'.format(tel_id)]) * u.rad
389
                    
390
                    # pointing.ra = np.deg2rad(
Moritz Huetten's avatar
Moritz Huetten committed
391
                    #    event_data['{:s}_pointing_ra'.format(tel_id)]) * u.rad
392
                    # pointing.dec = np.deg2rad(
Moritz Huetten's avatar
Moritz Huetten committed
393
                    #    event_data['{:s}_pointing_dec'.format(tel_id)]) * u.rad
394

395
                    pointing.tel[tel_i + 1] = pointing_tel
396

Moritz Huetten's avatar
Moritz Huetten committed
397
398
399
400
401
                    # 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]

402
                    # Adding event charge and peak positions per pixel
Moritz Huetten's avatar
astyled    
Moritz Huetten committed
403
404
405
                    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
406
                                 1].peak_time = event_data['{:s}_pulse_time'.format(tel_id)]
407
408
409
410
411
412
                
                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
413

Moritz Huetten's avatar
astyled    
Moritz Huetten committed
414
                if not self.is_mc:
Moritz Huetten's avatar
Moritz Huetten committed
415
                    # Adding the event arrival time
Moritz Huetten's avatar
astyled    
Moritz Huetten committed
416
417
                    time_tmp = Time(
                        event_data['mjd'], scale='utc', format='mjd')
Moritz Huetten's avatar
Moritz Huetten committed
418
                    data.trigger.time = Time(
Moritz Huetten's avatar
astyled    
Moritz Huetten committed
419
                        time_tmp, format='unix', scale='utc', precision=9)
Moritz Huetten's avatar
Moritz Huetten committed
420
421
                else:
                    data.mc.energy = event_data['true_energy'] * u.GeV
422
                    data.mc.alt = (np.pi/2 - event_data['true_zd']) * u.rad
Moritz Huetten's avatar
astyled    
Moritz Huetten committed
423
424
425
426
427
                    # 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
428
429
430
                    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
431
432
433
434
435

                # 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
436
                data.trigger.tels_with_trigger = tels_with_data
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461

                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
462
463
464
465
        if not self.is_mc:
            data = EventAndMonDataContainer()
        else:
            data = DataContainer()
466
467
468
469
470

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

        if telescope not in tels_in_file:
Moritz Huetten's avatar
astyled    
Moritz Huetten committed
471
472
            raise ValueError("Specified telescope {:s} is not in the allowed list {}".format(
                telescope, tels_in_file))
473
474
475
476
477

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

        # Loop over the available data runs
478
        for run_number in self.run_numbers:
479
480
481
482
483
484
485

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

Moritz Huetten's avatar
Moritz Huetten committed
488
489
            # Set monitoring data:
            if not self.is_mc:
Moritz Huetten's avatar
Moritz Huetten committed
490

Moritz Huetten's avatar
Moritz Huetten committed
491
                monitoring_data = self.current_run['data'].monitoring_data
Moritz Huetten's avatar
Moritz Huetten committed
492

Moritz Huetten's avatar
Moritz Huetten committed
493
494
495
                monitoring_camera = MonitoringCameraContainer()
                pedestal_info = PedestalContainer()
                badpixel_info = PixelStatusContainer()
Moritz Huetten's avatar
Moritz Huetten committed
496

Moritz Huetten's avatar
astyled    
Moritz Huetten committed
497
498
499
500
                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)
501
                pedestal_info.n_events = 500 # hardcoded number of pedestal events averaged over
Moritz Huetten's avatar
Moritz Huetten committed
502
                pedestal_info.charge_mean = []
Moritz Huetten's avatar
astyled    
Moritz Huetten committed
503
504
505
506
507
508
                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
509
                pedestal_info.charge_std = []
Moritz Huetten's avatar
astyled    
Moritz Huetten committed
510
511
512
513
514
515
516
517
518
519
520
521
                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
522
                badpixel_info.sample_time_range = t_range
Moritz Huetten's avatar
Moritz Huetten committed
523

Moritz Huetten's avatar
Moritz Huetten committed
524
525
526
527
528
529
                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

530
             #fdp (mono version not fully tested)
531
532
            else:
                data.mcheader.num_showers = self.current_run['data'].mcheader_data[telescope]['sim_nevents'] # total, including reuse
533
                data.mcheader.shower_reuse = self.current_run['data'].mcheader_data[telescope]['sim_reuse']
534
535
536
537
538
                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
                data.mcheader.spectral_index = self.current_run['data'].mcheader_data[telescope]['sim_eslope'] 
                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
539

540

541
542
543
544
545
546
547
548
549
550
551
552
553
            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
554
555
556
                event_data = self.current_run['data'].get_mono_event_data(
                    event_i, telescope=telescope)

557
                data.meta = event_data['mars_meta']
558
559
560

                # Event counter
                data.count = counter
Moritz Huetten's avatar
Moritz Huetten committed
561
562
                data.index.obs_id = obs_id
                data.index.event_id = event_id
563
564
565

                # Setting up the R0 container
                data.r0.tel.clear()
566
                data.r0.tel[tel_i + 1].trigger_type = self.current_run['data'].event_data[telescope]['trigger_pattern'][event_order_number]
567
568
569

                # Setting up the R1 container
                data.r1.tel.clear()
570
                data.r1.tel[tel_i + 1].trigger_type = self.current_run['data'].event_data[telescope]['trigger_pattern'][event_order_number]
571
572
573

                # Setting up the DL0 container
                data.dl0.tel.clear()
574
                data.dl0.tel[tel_i + 1].trigger_type = self.current_run['data'].event_data[telescope]['trigger_pattern'][event_order_number]
575
576
577

                # Creating the telescope pointing container
                pointing = TelescopePointingContainer()
Moritz Huetten's avatar
astyled    
Moritz Huetten committed
578
579
580
581
                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
582
583
                #pointing.ra = np.deg2rad(event_data['pointing_ra']) * u.rad
                #pointing.dec = np.deg2rad(event_data['pointing_dec']) * u.rad
584
585

                # Adding the pointing container to the event data
Moritz Huetten's avatar
Moritz Huetten committed
586
                data.pointing.tel[tel_i + 1] = pointing
587
588
589

                # 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
590
                data.dl1.tel[tel_i + 1].peak_time = event_data['pulse_time']
591

Moritz Huetten's avatar
astyled    
Moritz Huetten committed
592
                if not self.is_mc:
Moritz Huetten's avatar
Moritz Huetten committed
593
                    # Adding the event arrival time
Moritz Huetten's avatar
astyled    
Moritz Huetten committed
594
595
                    time_tmp = Time(
                        event_data['mjd'], scale='utc', format='mjd')
Moritz Huetten's avatar
Moritz Huetten committed
596
                    data.trigger.time = Time(
Moritz Huetten's avatar
astyled    
Moritz Huetten committed
597
                        time_tmp, format='unix', scale='utc', precision=9)
Moritz Huetten's avatar
Moritz Huetten committed
598
599
                else:
                    data.mc.energy = event_data['true_energy'] * u.GeV
600
                    data.mc.alt = (np.pi/2 - event_data['true_zd']) * u.rad
Moritz Huetten's avatar
astyled    
Moritz Huetten committed
601
602
603
604
605
                    # 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
606
607
608
                    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
609
610
611
612
613

                # 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
614
                data.trigger.tels_with_trigger = tels_with_data
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639

                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
640
        data = EventAndMonDataContainer()
641
642
643
644
645

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

        if telescope not in tels_in_file:
Moritz Huetten's avatar
astyled    
Moritz Huetten committed
646
647
            raise ValueError("Specified telescope {:s} is not in the allowed list {}".format(
                telescope, tels_in_file))
648
649
650
651
652

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

        # Loop over the available data runs
653
        for run_number in self.run_numbers:
654
655
656
657
658
659
660

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

Moritz Huetten's avatar
Moritz Huetten committed
663
            monitoring_data = self.current_run['data'].monitoring_data
Moritz Huetten's avatar
Moritz Huetten committed
664

Moritz Huetten's avatar
Moritz Huetten committed
665
666
667
            monitoring_camera = MonitoringCameraContainer()
            pedestal_info = PedestalContainer()
            badpixel_info = PixelStatusContainer()
Moritz Huetten's avatar
Moritz Huetten committed
668

Moritz Huetten's avatar
astyled    
Moritz Huetten committed
669
670
671
672
            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)
673
            pedestal_info.n_events = 500 # hardcoded number of pedestal events averaged over
Moritz Huetten's avatar
Moritz Huetten committed
674
            pedestal_info.charge_mean = []
Moritz Huetten's avatar
astyled    
Moritz Huetten committed
675
676
677
678
679
680
            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
681
            pedestal_info.charge_std = []
Moritz Huetten's avatar
astyled    
Moritz Huetten committed
682
683
684
685
686
687
688
689
690
691
692
693
            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
694
            badpixel_info.sample_time_range = t_range
Moritz Huetten's avatar
Moritz Huetten committed
695

Moritz Huetten's avatar
Moritz Huetten committed
696
697
698
699
700
701
            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

702
703
704
705
706
707
708
709
710
711
712
713
714
            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
715
716
717
                event_data = self.current_run['data'].get_pedestal_event_data(
                    event_i, telescope=telescope)

718
                data.meta = event_data['mars_meta']
719
720
721

                # Event counter
                data.count = counter
Moritz Huetten's avatar
Moritz Huetten committed
722
723
                data.index.obs_id = obs_id
                data.index.event_id = event_id
724

725
726
                # Setting up the R0 container
                data.r0.tel.clear()
727
                data.r0.tel[tel_i + 1].trigger_type = self.current_run['data'].event_data[telescope]['trigger_pattern'][event_order_number]
728
729
730

                # Setting up the R1 container
                data.r1.tel.clear()
731
                data.r1.tel[tel_i + 1].trigger_type = self.current_run['data'].event_data[telescope]['trigger_pattern'][event_order_number]
732
733
734

                # Setting up the DL0 container
                data.dl0.tel.clear()
735
                data.dl0.tel[tel_i + 1].trigger_type = self.current_run['data'].event_data[telescope]['trigger_pattern'][event_order_number]
736
737
738

                # Creating the telescope pointing container
                pointing = TelescopePointingContainer()
Moritz Huetten's avatar
astyled    
Moritz Huetten committed
739
740
741
742
                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
743
744
                #pointing.ra = np.deg2rad(event_data['pointing_ra']) * u.rad
                #pointing.dec = np.deg2rad(event_data['pointing_dec']) * u.rad
745
746

                # Adding the pointing container to the event data
Moritz Huetten's avatar
Moritz Huetten committed
747
                data.pointing.tel[tel_i + 1] = pointing
748
749
750

                # 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
751
                data.dl1.tel[tel_i + 1].peak_time = event_data['pulse_time']
752
753
754

                # Adding the event arrival time
                time_tmp = Time(event_data['mjd'], scale='utc', format='mjd')
Moritz Huetten's avatar
Moritz Huetten committed
755
                data.trigger.time = Time(
Moritz Huetten's avatar
astyled    
Moritz Huetten committed
756
                    time_tmp, format='unix', scale='utc', precision=9)
757
758
759
760
761

                # 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
762
                data.trigger.tels_with_trigger = tels_with_data
763
764
765
766
767
768
769

                yield data
                counter += 1

        return


Moritz Huetten's avatar
Moritz Huetten committed
770
class MarsRun:
771
772
773
774
    """
    This class implements reading of the event data from a single MAGIC data run.
    """

Moritz Huetten's avatar
Moritz Huetten committed
775
    def __init__(self, run_file_mask, filter_list=None):
776
777
778
779
780
781
782
783
784
        """
        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.
785
786
787
        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.
788
789
        """

Moritz Huetten's avatar
astyled    
Moritz Huetten committed
790
        self.n_camera_pixels = GEOM.n_pixels
791

792
793
794
795
        self.run_file_mask = run_file_mask

        # Preparing the lists of M1/2 data files
        file_list = glob.glob(run_file_mask)
796
797
798
799
800

        # 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
801
802
803
804
        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))
805
        self.m1_file_list.sort()
806
807
808
        self.m2_file_list.sort()

        # Retrieving the list of run numbers corresponding to the data files
Moritz Huetten's avatar
astyled    
Moritz Huetten committed
809
        run_info = list(
810
            map(MAGICEventSource.get_run_info_from_name, file_list))
Moritz Huetten's avatar
Moritz Huetten committed
811
        run_numbers = [i[0] for i in run_info]
Moritz Huetten's avatar
astyled    
Moritz Huetten committed
812
        is_mc_runs = [i[1] for i in run_info]
813
814
815

        run_numbers = np.unique(run_numbers)
        is_mc_runs = np.unique(is_mc_runs)
Moritz Huetten's avatar
astyled    
Moritz Huetten committed
816
        # Checking if run type (data/MC) is consistent:
817
        if len(is_mc_runs) > 1:
Moritz Huetten's avatar
astyled    
Moritz Huetten committed
818
819
820
            raise ValueError(
                "Run type is not consistently data or MC: {}".format(is_mc_runs))

821
        self.is_mc = is_mc_runs[0]
822
823
824

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

828
        # Reading the data
Moritz Huetten's avatar
astyled    
Moritz Huetten committed
829
830
831
832
833
        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)

834
        # Getting the event data
835
        self.event_data = dict()
836
837
838
839
840
841
842
        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]
843

844
        # Getting the run-wise MC header data
845
        if self.is_mc:
846
847
848
            self.mcheader_data = dict()
            self.mcheader_data['M1'] = m1_data[2]
            self.mcheader_data['M2'] = m2_data[2]
849

850
851
852
853
854
855
856
857
858
859
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
        # 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
886
    def load_events(file_list, is_mc, n_camera_pixels):
887
        """
888
        This method loads events and monitoring data from the pre-defiled file and returns them as a dictionary.
889
890
891
892
893

        Parameters
        ----------
        file_name: str
            Name of the MAGIC calibrated file to use.
894
895
896
897
        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)
898
899
900
901
902
903
904
905

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

        try:
906
            import uproot3 as uproot
907
908
909
910
911
912
913
914
        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'] = []
915
916
        event_data['trigger_pattern'] = scipy.array([], dtype=np.int32)
        event_data['stereo_event_number'] = scipy.array([], dtype=np.int32)
917
918
919
920
921
        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
922
        event_data['mars_meta'] = []
923

924
925
        # monitoring information (updated from time to time)
        monitoring_data = dict()
Moritz Huetten's avatar
astyled    
Moritz Huetten committed
926

Moritz Huetten's avatar
Moritz Huetten committed
927
928
        monitoring_data['badpixelinfo'] = []
        monitoring_data['badpixelinfoMJDrange'] = []
929
930
931
932
933
934
935
936
937
938
939
        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'] = []

940
941
942
        #MC Header information, dictionary always created, but filled only in case of MC run
        mcheader_data = dict()
    
943
944
        event_data['file_edges'] = [0]

945
946
947
948
        degrees_per_hour = 15.0
        seconds_per_day = 86400.0
        seconds_per_hour = 3600.

Moritz Huetten's avatar
Moritz Huetten committed
949
        evt_common_list = [
Moritz Huetten's avatar
astyled    
Moritz Huetten committed
950
            'MCerPhotEvt.fPixels.fPhot',
Moritz Huetten's avatar
Moritz Huetten committed
951
952
            'MArrivalTime.fData',
            'MTriggerPattern.fPrescaled',
Moritz Huetten's avatar
astyled    
Moritz Huetten committed
953
            'MRawEvtHeader.fStereoEvtNumber',
Moritz Huetten's avatar
Moritz Huetten committed
954
            'MRawEvtHeader.fDAQEvtNumber',
Moritz Huetten's avatar
astyled    
Moritz Huetten committed
955
956
957
        ]

        # Separately, because only used with pre-processed MARS data
Moritz Huetten's avatar
Moritz Huetten committed
958
959
        # to create MPointingPos container
        pointing_array_list = [
Moritz Huetten's avatar
astyled    
Moritz Huetten committed
960
961
962
963
            'MPointingPos.fZd',
            'MPointingPos.fAz',
            'MPointingPos.fRa',
            'MPointingPos.fDec',
Moritz Huetten's avatar
Moritz Huetten committed
964
            'MPointingPos.fDevZd',
Moritz Huetten's avatar
astyled    
Moritz Huetten committed
965
966
            'MPointingPos.fDevAz',
            'MPointingPos.fDevHa',
Moritz Huetten's avatar
Moritz Huetten committed
967
            'MPointingPos.fDevDec',
Moritz Huetten's avatar
astyled    
Moritz Huetten committed
968
969
        ]

Moritz Huetten's avatar
Moritz Huetten committed
970
971
972
973
        # Info only applicable for data:
        time_array_list = [
            'MTime.fMjd',
            'MTime.fTime.fMilliSec',
Moritz Huetten's avatar
astyled    
Moritz Huetten committed
974
975
976
            'MTime.fNanoSec',
        ]

Moritz Huetten's avatar
Moritz Huetten committed
977
978
979
980
981
982
        drive_array_list = [
            'MReportDrive.fMjd',
            'MReportDrive.fCurrentZd',
            'MReportDrive.fCurrentAz',
            'MReportDrive.fRa',
            'MReportDrive.fDec'
Moritz Huetten's avatar
astyled    
Moritz Huetten committed
983
        ]
Moritz Huetten's avatar
Moritz Huetten committed
984

985
986
987
988
989
990
991
992
993
994
        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
995
        ]
996

Moritz Huetten's avatar
Moritz Huetten committed
997
998
999
1000
1001
1002
1003
1004
        # Info only applicable for MC:
        mc_list = [
            'MMcEvt.fEnergy',
            'MMcEvt.fTheta',
            'MMcEvt.fPhi',
            'MMcEvt.fPartId',
            'MMcEvt.fZFirstInteraction',
            'MMcEvt.fCoreX',
1005
            'MMcEvt.fCoreY'
Moritz Huetten's avatar
astyled    
Moritz Huetten committed
1006
        ]
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
        
        mcheader_list = [
            #'MMcRunHeader.fNumSimulatedShowers',
            'MMcRunHeader.fNumEvents',
            'MMcCorsikaRunHeader.fELowLim', #GeV
            'MMcCorsikaRunHeader.fEUppLim', #GeV
            'MMcCorsikaRunHeader.fSlopeSpec',
            'MMcRunHeader.fImpactMax', #cm
            #'MMcCorsikaRunHeader.fViewconeAngles',
            'MMcRunHeader.fRandomPointingConeSemiAngle' # deg
        ]
Moritz Huetten's avatar
Moritz Huetten committed
1018
1019
1020
1021
1022
1023
1024
1025
1026

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

1028
1029
1030
1031
        for file_name in file_list:

            input_file = uproot.open(file_name)

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

1034
            # Reading the info common to MC and real data
1035
1036
1037
1038
            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']
1039

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

Moritz Huetten's avatar
Moritz Huetten committed
1043
            mars_meta['is_simulation'] = is_mc
Moritz Huetten's avatar
Moritz Huetten committed
1044

1045
            if is_mc:
1046
1047
                mc_header_info = input_file['RunHeaders'].arrays(mcheader_list)
                mcheader_data['sim_nevents']=int(mc_header_info[b'MMcRunHeader.fNumEvents'][0]) #std: 5000
1048
                mcheader_data['sim_reuse']= 1 #this value is not written in the magic root file, but since the sim_events already include shower reuse we artificially set it to 1 (actually every shower reused 5 times for std MAGIC MC)
1049
1050
1051
1052
1053
                mcheader_data['sim_emin']=mc_header_info[b'MMcCorsikaRunHeader.fELowLim'][0]*u.GeV
                mcheader_data['sim_emax']=mc_header_info[b'MMcCorsikaRunHeader.fEUppLim'][0]*u.GeV
                mcheader_data['sim_eslope']=mc_header_info[b'MMcCorsikaRunHeader.fSlopeSpec'][0] #std: -1.6
                mcheader_data['sim_max_impact']=mc_header_info[b'MMcRunHeader.fImpactMax'][0]*u.cm
                mcheader_data['sim_conesemiangle']=mc_header_info[b'MMcRunHeader.fRandomPointingConeSemiAngle'][0]*u.deg #std: 2.5 deg, also corsika viewcone is defined by "half of the cone angle".
1054

Moritz Huetten's avatar
Moritz Huetten committed
1055
1056
1057
1058
            # 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
1059

Moritz Huetten's avatar
Moritz Huetten committed
1060
1061
1062
                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
1063

Moritz Huetten's avatar
astyled    
Moritz Huetten committed
1064
1065
1066
1067
                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
1068

Moritz Huetten's avatar
Moritz Huetten committed
1069
            # try to read RunHeaders tree (soft fail if not present, to pass current tests)
Moritz Huetten's avatar
Moritz Huetten committed
1070
            try:
Moritz Huetten's avatar
astyled    
Moritz Huetten committed
1071
1072
1073
                meta_info = input_file['RunHeaders'].arrays(
                    metainfo_array_list)

Moritz Huetten's avatar
Moritz Huetten committed
1074
1075
                mars_meta['origin'] = "MAGIC"
                mars_meta['input_url'] = file_name
Moritz Huetten's avatar
Moritz Huetten committed
1076

Moritz Huetten's avatar
astyled    
Moritz Huetten committed
1077
1078
1079
1080
1081
1082
1083
1084
                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
1085
1086
1087
1088
1089
1090

                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
1091
1092
                else:
                    msg = "Run type (Data or MC) of MAGIC data file not recognised."
Moritz Huetten's avatar
astyled    
Moritz Huetten committed
1093
                    LOGGER.error(msg)
Moritz Huetten's avatar
Moritz Huetten committed
1094
                    raise ValueError(msg)
Moritz Huetten's avatar
Moritz Huetten committed
1095
                if is_mc_check != is_mc:
Moritz Huetten's avatar
Moritz Huetten committed
1096
                    msg = "Inconsistent run type (data or MC) between file name and runheader content."
Moritz Huetten's avatar
astyled    
Moritz Huetten committed
1097
                    LOGGER.error(msg)
Moritz Huetten's avatar
Moritz Huetten committed
1098
                    raise ValueError(msg)
Moritz Huetten's avatar
Moritz Huetten committed
1099

Moritz Huetten's avatar
Moritz Huetten committed
1100
                # Reading the info only contained in real data
Moritz Huetten's avatar
Moritz Huetten committed
1101
                if not is_mc:
Moritz Huetten's avatar
astyled    
Moritz Huetten committed
1102
1103
                    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
1104
1105
                    # now we have 4 axes:
                    # 0st axis: empty (?)
Moritz Huetten's avatar
Moritz Huetten committed
1106
1107
1108
1109
                    # 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
1110
1111
                    # take first axis
                    unsuitable_pix_bitinfo = badpixelinfo[1][:n_camera_pixels]
Moritz Huetten's avatar
Moritz Huetten committed
1112
                    # extract unsuitable bit:
Moritz Huetten's avatar
astyled    
Moritz Huetten committed
1113
                    unsuitable_pix = np.zeros(n_camera_pixels, dtype=np.bool)
Moritz Huetten's avatar
Moritz Huetten committed
1114
                    for i in range(n_camera_pixels):
Moritz Huetten's avatar
astyled    
Moritz Huetten committed
1115
1116
                        unsuitable_pix[i] = int('\t{0:08b}'.format(
                            unsuitable_pix_bitinfo[i] & 0xff)[-2])
1117
                    monitoring_data['badpixelinfo'].append(unsuitable_pix)
Moritz Huetten's avatar
Moritz Huetten committed
1118
                    # save time interval of badpixel info:
Moritz Huetten's avatar
astyled    
Moritz Huetten committed
1119
1120
                    monitoring_data['badpixelinfoMJDrange'].append(
                        [event_mjd[0], event_mjd[-1]])
1121

Moritz Huetten's avatar
Moritz Huetten committed
1122
            except KeyError:
Moritz Huetten's avatar
astyled    
Moritz Huetten committed
1123
1124
                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
1125
                is_mc = False
1126

1127
            # try to read Pedestals tree (soft fail if not present)
Moritz Huetten's avatar
Moritz Huetten committed
1128
            if not is_mc:
1129
                try:
Moritz Huetten's avatar
astyled    
Moritz Huetten committed
1130
1131
                    pedestal_info = input_file['Pedestals'].arrays(
                        pedestal_array_list)
Moritz Huetten's avatar
Moritz Huetten committed
1132

1133
1134
1135
1136
                    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
1137
1138
1139
1140
1141
                    pedestal_mjd = pedestal_mjd + \
                        (pedestal_millisec / 1e3 +
                         pedestal_nanosec / 1e9) / seconds_per_day
                    monitoring_data['PedestalMJD'] = scipy.concatenate(
                        (monitoring_data['PedestalMJD'], pedestal_mjd))