__init__.py 77 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
27
28
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
29
from ctapipe.containers import PointingContainer, TelescopePointingContainer
Moritz Huetten's avatar
astyled    
Moritz Huetten committed
30
31
32
33
34
35
36
37
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

38
39
40

__all__ = ['MAGICEventSource']

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

Ievgen Vovk's avatar
Ievgen Vovk committed
43

44
# MAGIC telescope positions in m wrt. to the center of CTA simulations
45
46
47
48
49
50
#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
51
MAGIC_TEL_POSITIONS = {
52
53
    1: [31.80, -28.10, 0.00] * u.m,
    2: [-31.80, 28.10, 0.00] * u.m
54
}
55

56
# MAGIC telescope description
Moritz Huetten's avatar
astyled    
Moritz Huetten committed
57
58
59
60
61
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}
62

63
# trigger patterns:
Moritz Huetten's avatar
astyled    
Moritz Huetten committed
64
65
66
67
MC_TRIGGER_PATTERN = 1
PEDESTAL_TRIGGER_PATTERN = 8
DATA_TRIGGER_PATTERN = 128

68
69
70
71
72
73
74
class L3JumpError(Exception):
    """
    Exception raised when L3 trigger number jumps backward.
    """

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

76
77
78
79
80
81
82
83
class MissingDriveReportError(Exception):
    """
    Exception raised when a subrun does not have drive reports.
    """

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

84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
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.
        """

113
114
        file_path = Path(kwargs['input_url'])
        self.file_list = glob.glob(str(file_path.absolute()))
115
        if not self.file_list:
116
            raise ValueError("Unreadable or wrong wildcard file path given.")
117
        self.file_list.sort()
118
119
120
121
122

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

        # Retrieving the list of run numbers corresponding to the data files
126
        run_info = list(map(self.get_run_info_from_name, self.file_list))
Moritz Huetten's avatar
Moritz Huetten committed
127
        run_numbers = [i[0] for i in run_info]
128
        is_mc_runs = [i[1] for i in run_info]
Moritz Huetten's avatar
Moritz Huetten committed
129
130

        self.run_numbers, indices = np.unique(run_numbers, return_index=True)
131
132
        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
133

134
135
        # Checking if runt type (data/MC) is consistent:
        if len(is_mc_runs) > 1:
Moritz Huetten's avatar
astyled    
Moritz Huetten committed
136
137
            raise ValueError(
                "Loaded files contain data and MC runs. Please load only data OR Monte Carlos.")
138
        self.is_mc = is_mc_runs[0]
139

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

143
144
145
146
        # # 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
147
148
        self._subarray_info = SubarrayDescription(
            'MAGIC', MAGIC_TEL_POSITIONS, MAGIC_TEL_DESCRIPTIONS)
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174

    @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:
175
                import uproot3 as uproot
176
177
178
179
180
181
182
183
184
185

                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
186
                if re.match(r'.+_m\d_.+root', file_path.lower()) is None:
187
188
189
190
191
                    is_magic_root_file = False

        return is_magic_root_file

    @staticmethod
192
    def get_run_info_from_name(file_name):
193
        """
Moritz Huetten's avatar
astyled    
Moritz Huetten committed
194
        This internal method extracts the run number and
Moritz Huetten's avatar
Moritz Huetten committed
195
        type (data/MC) from the specified file name.
196
197
198
199
200
201
202
203
204
205
206
207

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

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

Moritz Huetten's avatar
Moritz Huetten committed
208
        mask_data = r".*\d+_M\d+_(\d+)\.\d+_Y_.*"
Moritz Huetten's avatar
Moritz Huetten committed
209
210
        mask_mc = r".*_M\d_za\d+to\d+_\d_(\d+)_Y_.*"
        mask_mc_alt = r".*_M\d_\d_(\d+)_.*"
211
        if re.findall(mask_data, file_name):
Moritz Huetten's avatar
Moritz Huetten committed
212
213
            parsed_info = re.findall(mask_data, file_name)
            is_mc = False
214
        elif re.findall(mask_mc, file_name):
Moritz Huetten's avatar
Moritz Huetten committed
215
216
217
218
219
            parsed_info = re.findall(mask_mc, file_name)
            is_mc = True
        else:
            parsed_info = re.findall(mask_mc_alt, file_name)
            is_mc = True
220
221
222
223

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

Moritz Huetten's avatar
Moritz Huetten committed
228
        return run_number, is_mc
229

Moritz Huetten's avatar
Moritz Huetten committed
230
    def _set_active_run(self, run_number):
231
232
233
234
235
236
237
238
239
240
        """
        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
241
        MarsRun:
Moritz Huetten's avatar
Moritz Huetten committed
242
            The run to use
243
        """
Moritz Huetten's avatar
Moritz Huetten committed
244

245
        this_run_mask = os.path.join(self.input_url.parents[0],
Moritz Huetten's avatar
Moritz Huetten committed
246
                                     '*{:d}*root'.format(run_number))
247
248
249
250

        run = dict()
        run['number'] = run_number
        run['read_events'] = 0
Moritz Huetten's avatar
astyled    
Moritz Huetten committed
251
252
        run['data'] = MarsRun(run_file_mask=this_run_mask,
                              filter_list=self.file_list)
253
254
255

        return run

256
257
258
259
    @property
    def subarray(self):
        return self._subarray_info

Moritz Huetten's avatar
astyled    
Moritz Huetten committed
260
261
262
263
264
265
266
267
268
269
270
271
    @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

272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
    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
297
298
299
300
        if not self.is_mc:
            data = EventAndMonDataContainer()
        else:
            data = DataContainer()
301
302
303
304
305
306

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

        # Loop over the available data runs
307
        for run_number in self.run_numbers:
308
309
310
311
312
313

            # 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
314
            # Setting the new active run (class MarsRun object)
Moritz Huetten's avatar
Moritz Huetten committed
315
            self.current_run = self._set_active_run(run_number)
316
            
317
318
            # Set monitoring data:
            if not self.is_mc:
Moritz Huetten's avatar
Moritz Huetten committed
319

320
                monitoring_data = self.current_run['data'].monitoring_data
Moritz Huetten's avatar
Moritz Huetten committed
321

322
323
324
                for tel_i, tel_id in enumerate(tels_in_file):
                    monitoring_camera = MonitoringCameraContainer()
                    pedestal_info = PedestalContainer()
325
                    badpixel_info = PixelStatusContainer()
Moritz Huetten's avatar
Moritz Huetten committed
326

Moritz Huetten's avatar
astyled    
Moritz Huetten committed
327
328
329
330
331
332
                    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
333
                    pedestal_info.charge_mean = []
Moritz Huetten's avatar
astyled    
Moritz Huetten committed
334
335
336
337
338
339
                    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'])
340
                    pedestal_info.charge_std = []
Moritz Huetten's avatar
astyled    
Moritz Huetten committed
341
342
343
344
345
346
347
348
349
350
351
352
                    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
353
                    badpixel_info.sample_time_range = t_range
354

355
                    monitoring_camera.pedestal = pedestal_info
356
                    monitoring_camera.pixel_status = badpixel_info
357
358

                    data.mon.tels_with_data = {1, 2}
359
                    data.mon.tel[tel_i + 1] = monitoring_camera
360
            else:
361
362
                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']
363
                data.mcheader.shower_reuse = self.current_run['data'].mcheader_data['M1']['sim_reuse']
364
365
366
367
368
369
370
                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
371
                else:
372
373
                    data.mcheader.diffuse = False
                    
374

375
376
377
378
379
380
381
382
            # 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
383
384
385
                event_data = self.current_run['data'].get_stereo_event_data(
                    event_i)

386
                data.meta = event_data['mars_meta']
387
388
389

                # Event counter
                data.count = counter
Moritz Huetten's avatar
Moritz Huetten committed
390
391
                data.index.obs_id = obs_id
                data.index.event_id = event_id
392
393
394
395
396
397
398
399
400
401

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

402
                pointing = PointingContainer()
403
404
405
                # Filling the DL1 container with the event data
                for tel_i, tel_id in enumerate(tels_in_file):
                    # Creating the telescope pointing container
406
407
408
                    pointing_tel = TelescopePointingContainer()
                    
                    pointing_tel.azimuth = np.deg2rad(
Moritz Huetten's avatar
astyled    
Moritz Huetten committed
409
                        event_data['{:s}_pointing_az'.format(tel_id)]) * u.rad
410
411
                    
                    pointing_tel.altitude = np.deg2rad(
Moritz Huetten's avatar
astyled    
Moritz Huetten committed
412
                        90 - event_data['{:s}_pointing_zd'.format(tel_id)]) * u.rad
413
                    
414
                    # pointing.ra = np.deg2rad(
Moritz Huetten's avatar
Moritz Huetten committed
415
                    #    event_data['{:s}_pointing_ra'.format(tel_id)]) * u.rad
416
                    # pointing.dec = np.deg2rad(
Moritz Huetten's avatar
Moritz Huetten committed
417
                    #    event_data['{:s}_pointing_dec'.format(tel_id)]) * u.rad
418

419
                    pointing.tel[tel_i + 1] = pointing_tel
420

Moritz Huetten's avatar
Moritz Huetten committed
421
422
423
424
425
                    # 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]

426
                    # Adding event charge and peak positions per pixel
Moritz Huetten's avatar
astyled    
Moritz Huetten committed
427
428
429
                    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
430
                                 1].peak_time = event_data['{:s}_pulse_time'.format(tel_id)]
431
432
433
434
435
436
                
                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
437

Moritz Huetten's avatar
astyled    
Moritz Huetten committed
438
                if not self.is_mc:
Moritz Huetten's avatar
Moritz Huetten committed
439
                    # Adding the event arrival time
Moritz Huetten's avatar
astyled    
Moritz Huetten committed
440
441
                    time_tmp = Time(
                        event_data['mjd'], scale='utc', format='mjd')
Moritz Huetten's avatar
Moritz Huetten committed
442
                    data.trigger.time = Time(
Moritz Huetten's avatar
astyled    
Moritz Huetten committed
443
                        time_tmp, format='unix', scale='utc', precision=9)
Moritz Huetten's avatar
Moritz Huetten committed
444
445
                else:
                    data.mc.energy = event_data['true_energy'] * u.GeV
446
                    data.mc.alt = (np.pi/2 - event_data['true_zd']) * u.rad
Moritz Huetten's avatar
astyled    
Moritz Huetten committed
447
448
449
450
451
                    # 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
452
                    data.mc.h_first_int = event_data['true_h_first_int'] * u.cm
453
454
455
456
457
458
                    
                    # 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
459
460
461
462
463

                # 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
464
                data.trigger.tels_with_trigger = tels_with_data
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489

                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
490
491
492
493
        if not self.is_mc:
            data = EventAndMonDataContainer()
        else:
            data = DataContainer()
494
495
496
497
498

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

        if telescope not in tels_in_file:
Moritz Huetten's avatar
astyled    
Moritz Huetten committed
499
500
            raise ValueError("Specified telescope {:s} is not in the allowed list {}".format(
                telescope, tels_in_file))
501
502
503
504
505

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

        # Loop over the available data runs
506
        for run_number in self.run_numbers:
507
508
509
510
511
512
513

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

Moritz Huetten's avatar
Moritz Huetten committed
516
517
            # Set monitoring data:
            if not self.is_mc:
Moritz Huetten's avatar
Moritz Huetten committed
518

Moritz Huetten's avatar
Moritz Huetten committed
519
                monitoring_data = self.current_run['data'].monitoring_data
Moritz Huetten's avatar
Moritz Huetten committed
520

Moritz Huetten's avatar
Moritz Huetten committed
521
522
523
                monitoring_camera = MonitoringCameraContainer()
                pedestal_info = PedestalContainer()
                badpixel_info = PixelStatusContainer()
Moritz Huetten's avatar
Moritz Huetten committed
524

Moritz Huetten's avatar
astyled    
Moritz Huetten committed
525
526
527
528
                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)
529
                pedestal_info.n_events = 500 # hardcoded number of pedestal events averaged over
Moritz Huetten's avatar
Moritz Huetten committed
530
                pedestal_info.charge_mean = []
Moritz Huetten's avatar
astyled    
Moritz Huetten committed
531
532
533
534
535
536
                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
537
                pedestal_info.charge_std = []
Moritz Huetten's avatar
astyled    
Moritz Huetten committed
538
539
540
541
542
543
544
545
546
547
548
549
                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
550
                badpixel_info.sample_time_range = t_range
Moritz Huetten's avatar
Moritz Huetten committed
551

Moritz Huetten's avatar
Moritz Huetten committed
552
553
554
555
556
557
                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

558
             #fdp (mono version not fully tested)
559
560
            else:
                data.mcheader.num_showers = self.current_run['data'].mcheader_data[telescope]['sim_nevents'] # total, including reuse
561
                data.mcheader.shower_reuse = self.current_run['data'].mcheader_data[telescope]['sim_reuse']
562
563
564
565
566
                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
567

568

569
570
571
572
573
574
575
576
577
578
579
580
581
            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
582
583
584
                event_data = self.current_run['data'].get_mono_event_data(
                    event_i, telescope=telescope)

585
                data.meta = event_data['mars_meta']
586
587
588

                # Event counter
                data.count = counter
Moritz Huetten's avatar
Moritz Huetten committed
589
590
                data.index.obs_id = obs_id
                data.index.event_id = event_id
591
592
593

                # Setting up the R0 container
                data.r0.tel.clear()
594
                data.r0.tel[tel_i + 1].trigger_type = self.current_run['data'].event_data[telescope]['trigger_pattern'][event_order_number]
595
596
597

                # Setting up the R1 container
                data.r1.tel.clear()
598
                data.r1.tel[tel_i + 1].trigger_type = self.current_run['data'].event_data[telescope]['trigger_pattern'][event_order_number]
599
600
601

                # Setting up the DL0 container
                data.dl0.tel.clear()
602
                data.dl0.tel[tel_i + 1].trigger_type = self.current_run['data'].event_data[telescope]['trigger_pattern'][event_order_number]
603
604

                # Creating the telescope pointing container
605
606
607
608
                pointing = PointingContainer()
                pointing_tel = TelescopePointingContainer()

                pointing_tel.azimuth = np.deg2rad(
Moritz Huetten's avatar
astyled    
Moritz Huetten committed
609
                    event_data['pointing_az']) * u.rad
610
                pointing_tel.altitude = np.deg2rad(
Moritz Huetten's avatar
astyled    
Moritz Huetten committed
611
                    90 - event_data['pointing_zd']) * u.rad
Moritz Huetten's avatar
Moritz Huetten committed
612
613
                #pointing.ra = np.deg2rad(event_data['pointing_ra']) * u.rad
                #pointing.dec = np.deg2rad(event_data['pointing_dec']) * u.rad
614
615
616
617
618
619
620
621
622
                
                pointing.tel[tel_i + 1] = pointing_tel
                
                pointing.array_azimuth = np.deg2rad(event_data['pointing_az']) * u.rad
                pointing.array_altitude = np.deg2rad(90 - event_data['pointing_zd']) * u.rad
                pointing.array_ra = np.deg2rad(event_data['pointing_ra']) * u.rad
                pointing.array_dec = np.deg2rad(90 - event_data['pointing_dec']) * u.rad
                
                data.pointing = pointing
623
624
625

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

Moritz Huetten's avatar
astyled    
Moritz Huetten committed
628
                if not self.is_mc:
Moritz Huetten's avatar
Moritz Huetten committed
629
                    # Adding the event arrival time
Moritz Huetten's avatar
astyled    
Moritz Huetten committed
630
631
                    time_tmp = Time(
                        event_data['mjd'], scale='utc', format='mjd')
Moritz Huetten's avatar
Moritz Huetten committed
632
                    data.trigger.time = Time(
Moritz Huetten's avatar
astyled    
Moritz Huetten committed
633
                        time_tmp, format='unix', scale='utc', precision=9)
Moritz Huetten's avatar
Moritz Huetten committed
634
635
                else:
                    data.mc.energy = event_data['true_energy'] * u.GeV
636
                    data.mc.alt = (np.pi/2 - event_data['true_zd']) * u.rad
Moritz Huetten's avatar
astyled    
Moritz Huetten committed
637
638
639
640
641
                    # 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
642
                    data.mc.h_first_int = event_data['true_h_first_int'] * u.cm
643
644
645
646
647
648

                    # 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
649
650
651
652
653

                # 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
654
                data.trigger.tels_with_trigger = tels_with_data
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679

                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
680
        data = EventAndMonDataContainer()
681
682
683
684
685

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

        if telescope not in tels_in_file:
Moritz Huetten's avatar
astyled    
Moritz Huetten committed
686
687
            raise ValueError("Specified telescope {:s} is not in the allowed list {}".format(
                telescope, tels_in_file))
688
689
690
691
692

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

        # Loop over the available data runs
693
        for run_number in self.run_numbers:
694
695
696
697
698
699
700

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

Moritz Huetten's avatar
Moritz Huetten committed
703
            monitoring_data = self.current_run['data'].monitoring_data
Moritz Huetten's avatar
Moritz Huetten committed
704

Moritz Huetten's avatar
Moritz Huetten committed
705
706
707
            monitoring_camera = MonitoringCameraContainer()
            pedestal_info = PedestalContainer()
            badpixel_info = PixelStatusContainer()
Moritz Huetten's avatar
Moritz Huetten committed
708

Moritz Huetten's avatar
astyled    
Moritz Huetten committed
709
710
711
712
            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)
713
            pedestal_info.n_events = 500 # hardcoded number of pedestal events averaged over
Moritz Huetten's avatar
Moritz Huetten committed
714
            pedestal_info.charge_mean = []
Moritz Huetten's avatar
astyled    
Moritz Huetten committed
715
716
717
718
719
720
            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
721
            pedestal_info.charge_std = []
Moritz Huetten's avatar
astyled    
Moritz Huetten committed
722
723
724
725
726
727
728
729
730
731
732
733
            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
734
            badpixel_info.sample_time_range = t_range
Moritz Huetten's avatar
Moritz Huetten committed
735

Moritz Huetten's avatar
Moritz Huetten committed
736
737
738
739
740
741
            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

742
743
744
745
746
747
748
749
750
751
752
753
754
            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
755
756
757
                event_data = self.current_run['data'].get_pedestal_event_data(
                    event_i, telescope=telescope)

758
                data.meta = event_data['mars_meta']
759
760
761

                # Event counter
                data.count = counter
Moritz Huetten's avatar
Moritz Huetten committed
762
763
                data.index.obs_id = obs_id
                data.index.event_id = event_id
764

765
766
                # Setting up the R0 container
                data.r0.tel.clear()
767
                data.r0.tel[tel_i + 1].trigger_type = self.current_run['data'].event_data[telescope]['trigger_pattern'][event_order_number]
768
769
770

                # Setting up the R1 container
                data.r1.tel.clear()
771
                data.r1.tel[tel_i + 1].trigger_type = self.current_run['data'].event_data[telescope]['trigger_pattern'][event_order_number]
772
773
774

                # Setting up the DL0 container
                data.dl0.tel.clear()
775
                data.dl0.tel[tel_i + 1].trigger_type = self.current_run['data'].event_data[telescope]['trigger_pattern'][event_order_number]
776
777
778

                # Creating the telescope pointing container
                pointing = TelescopePointingContainer()
Moritz Huetten's avatar
astyled    
Moritz Huetten committed
779
780
781
782
                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
783
784
                #pointing.ra = np.deg2rad(event_data['pointing_ra']) * u.rad
                #pointing.dec = np.deg2rad(event_data['pointing_dec']) * u.rad
785
786

                # Adding the pointing container to the event data
Moritz Huetten's avatar
Moritz Huetten committed
787
                data.pointing.tel[tel_i + 1] = pointing
788
789
790

                # 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
791
                data.dl1.tel[tel_i + 1].peak_time = event_data['pulse_time']
792
793
794

                # Adding the event arrival time
                time_tmp = Time(event_data['mjd'], scale='utc', format='mjd')
Moritz Huetten's avatar
Moritz Huetten committed
795
                data.trigger.time = Time(
Moritz Huetten's avatar
astyled    
Moritz Huetten committed
796
                    time_tmp, format='unix', scale='utc', precision=9)
797
798
799
800
801

                # 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
802
                data.trigger.tels_with_trigger = tels_with_data
803
804
805
806
807
808
809

                yield data
                counter += 1

        return


Moritz Huetten's avatar
Moritz Huetten committed
810
class MarsRun:
811
812
813
814
    """
    This class implements reading of the event data from a single MAGIC data run.
    """

Moritz Huetten's avatar
Moritz Huetten committed
815
    def __init__(self, run_file_mask, filter_list=None):
816
817
818
819
820
821
822
823
824
        """
        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.
825
826
827
        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.
828
829
        """

Moritz Huetten's avatar
astyled    
Moritz Huetten committed
830
        self.n_camera_pixels = GEOM.n_pixels
831

832
833
834
835
        self.run_file_mask = run_file_mask

        # Preparing the lists of M1/2 data files
        file_list = glob.glob(run_file_mask)
836
837
838
839
840

        # 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
841
842
843
844
        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))
845
        self.m1_file_list.sort()
846
847
848
        self.m2_file_list.sort()

        # Retrieving the list of run numbers corresponding to the data files
Moritz Huetten's avatar
astyled    
Moritz Huetten committed
849
        run_info = list(
850
            map(MAGICEventSource.get_run_info_from_name, file_list))
Moritz Huetten's avatar
Moritz Huetten committed
851
        run_numbers = [i[0] for i in run_info]
Moritz Huetten's avatar
astyled    
Moritz Huetten committed
852
        is_mc_runs = [i[1] for i in run_info]
853
854
855

        run_numbers = np.unique(run_numbers)
        is_mc_runs = np.unique(is_mc_runs)
Moritz Huetten's avatar
astyled    
Moritz Huetten committed
856
        # Checking if run type (data/MC) is consistent:
857
        if len(is_mc_runs) > 1:
Moritz Huetten's avatar
astyled    
Moritz Huetten committed
858
859
860
            raise ValueError(
                "Run type is not consistently data or MC: {}".format(is_mc_runs))

861
        self.is_mc = is_mc_runs[0]
862
863
864

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

868
        # Reading the data
Moritz Huetten's avatar
astyled    
Moritz Huetten committed
869
870
871
872
873
        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)

874
        # Getting the event data
875
        self.event_data = dict()
876
877
878
879
880
881
882
        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]
883

884
        # Getting the run-wise MC header data
885
        if self.is_mc:
886
887
888
            self.mcheader_data = dict()
            self.mcheader_data['M1'] = m1_data[2]
            self.mcheader_data['M2'] = m2_data[2]
889

890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
        # 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
926
    def load_events(file_list, is_mc, n_camera_pixels):
927
        """
928
        This method loads events and monitoring data from the pre-defiled file and returns them as a dictionary.
929
930
931
932
933

        Parameters
        ----------
        file_name: str
            Name of the MAGIC calibrated file to use.
934
935
936
937
        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)
938
939
940
941
942
943
944
945

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

        try:
946
            import uproot3 as uproot
947
948
949
950
951
952
953
954
        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'] = []
955
956
        event_data['trigger_pattern'] = scipy.array([], dtype=np.int32)
        event_data['stereo_event_number'] = scipy.array([], dtype=np.int32)
957
958
959
960
961
        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
962
        event_data['mars_meta'] = []
963

964
965
        # monitoring information (updated from time to time)
        monitoring_data = dict()
Moritz Huetten's avatar
astyled    
Moritz Huetten committed
966

Moritz Huetten's avatar
Moritz Huetten committed
967
968
        monitoring_data['badpixelinfo'] = []
        monitoring_data['badpixelinfoMJDrange'] = []
969
970
971
972
973
974
975
976
977
978
979
        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'] = []

980
981
        #MC Header information, dictionary always created, but filled only in case of MC run
        mcheader_data = dict()
982

983
984
        event_data['file_edges'] = [0]

985
986
987
988
989
        # 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

990
991
992
993
994
995
996
        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([])

997
998
999
1000
        degrees_per_hour = 15.0
        seconds_per_day = 86400.0
        seconds_per_hour = 3600.