Ejemplo n.º 1
0
    def read_file(cls, filename='fake_data', tel_id=1, attribute='closed'):
        """
        Load all the information about the camera of a given telescope with
        ID `tel_id` from an open file with name `filename`.
        
        Parameters
        ----------
        filename: string
            name of the file, if no file name is given, faked data is produced
        tel_id: int
            ID of the telescope whose optics information should be loaded
        attribute: if file is closed, the attribute 'close' is given, else
            the astropy table with the whole data read from the file is given
        """
        ext = uf.get_file_type(filename)

        if attribute == 'closed':
            load = getattr(uf, "load_%s" % ext)
            instr_table = load(filename)
        else:
            instr_table = attribute

        (cam_class, cam_fov, pix_id, pix_posX, pix_posY, pix_area, pix_type,
         pix_neighbors, fadc_pulsshape) = CD.get_data(instr_table, tel_id)
        cam = cls(cam_class, cam_fov, pix_id, pix_posX, pix_posY, pix_area,
                  pix_type, pix_neighbors, fadc_pulsshape)

        return cam, instr_table
Ejemplo n.º 2
0
    def ctapipe_subarray(self):
        from ctapipe.instrument import TelescopeDescription, SubarrayDescription, \
            CameraGeometry, CameraReadout, CameraDescription, OpticsDescription
        import astropy.units as u

        geom = CameraGeometry("sstcam", self.mapping.pixel.i,
                              u.Quantity(self.mapping.pixel.x, 'm'),
                              u.Quantity(self.mapping.pixel.y, 'm'),
                              u.Quantity(self.mapping.pixel.size, 'm')**2,
                              'square')

        readout = CameraReadout(
            "sstcam", u.Quantity(1 / self.waveform_sample_width, "GHz"),
            self.photoelectron_pulse.amplitude[None, :],
            u.Quantity(self.photoelectron_pulse.sample_width, "ns"))

        camera = CameraDescription("sstcam", geom, readout)
        optics = OpticsDescription.from_name('SST-ASTRI')
        telescope = TelescopeDescription("SST", "SST", optics, camera)
        subarray = SubarrayDescription(
            'toy',
            tel_positions={1: [0, 0, 0] * u.m},
            tel_descriptions={1: telescope},
        )
        return subarray
    def read_file(cls,filename='fake_data',tel_id=1,attribute='closed'):
        """
        Load all the information about the camera of a given telescope with
        ID `tel_id` from an open file with name `filename`.
        
        Parameters
        ----------
        filename: string
            name of the file, if no file name is given, faked data is produced
        tel_id: int
            ID of the telescope whose optics information should be loaded
        attribute: if file is closed, the attribute 'close' is given, else
            the astropy table with the whole data read from the file is given
        """
        ext = uf.get_file_type(filename)

        if attribute == 'closed':
            load = getattr(uf,"load_%s" % ext)
            instr_table = load(filename)
        else:
            instr_table = attribute
        
        (cam_class,cam_fov,pix_id,pix_posX,pix_posY,pix_area,pix_type,
         pix_neighbors,fadc_pulsshape) = CD.get_data(instr_table,tel_id)
        cam = cls(cam_class,cam_fov,pix_id,pix_posX,pix_posY,pix_area,
                pix_type,pix_neighbors,fadc_pulsshape)
        
        return cam,instr_table
Ejemplo n.º 4
0
def read_single_camera_description(filename, camera_name):
    """
    Read a specific camera description from a DL1 file

    Parameters
    ----------
    filename: str
    camera_name: str

    Returns
    -------
    `ctapipe.instrument.camera.description.CameraDescription`
    """
    geom = read_single_camera_geometry(filename, camera_name)
    readout = read_single_camera_readout(filename, camera_name)
    return CameraDescription(camera_name, geometry=geom, readout=readout)
Ejemplo n.º 5
0
    def create_subarray(geometry_version, tel_id=1):
        """
        Obtain the subarray from the EventSource
        Returns
        -------
        ctapipe.instrument.SubarrayDescription
        """

        # camera info from LSTCam-[geometry_version].camgeom.fits.gz file
        camera_geom = load_camera_geometry(version=geometry_version)

        # get info on the camera readout:
        daq_time_per_sample, pulse_shape_time_step, pulse_shapes = read_pulse_shapes(
        )

        camera_readout = CameraReadout(
            'LSTCam',
            1 / daq_time_per_sample,
            pulse_shapes,
            pulse_shape_time_step,
        )

        camera = CameraDescription('LSTCam', camera_geom, camera_readout)

        lst_tel_descr = TelescopeDescription(name='LST',
                                             tel_type='LST',
                                             optics=OPTICS,
                                             camera=camera)

        tel_descriptions = {tel_id: lst_tel_descr}

        # LSTs telescope position taken from MC from the moment
        tel_positions = {tel_id: [50., 50., 16] * u.m}

        subarray = SubarrayDescription(
            name=f"LST-{tel_id} subarray",
            tel_descriptions=tel_descriptions,
            tel_positions=tel_positions,
        )

        return subarray
 def rotate(cls,angle):
     """
     rotates the camera coordinates about the center of the camera by
     specified angle. Modifies the CameraGeometry in-place (so
     after this is called, the pix_x and pix_y arrays are
     rotated).
     
     Note:
     -----
     This is intended only to correct simulated data that are
     rotated by a fixed angle.  For the more general case of
     correction for camera pointing errors (rotations,
     translations, skews, etc), you should use a true coordinate
     transformation defined in `ctapipe.coordinates`.      
     
     Parameters
     ----------
     cls: give the name of the class whose pixel positions should be rotated
     angle: value convertable to an `astropy.coordinates.Angle`
         rotation angle with unit (e.g. 12 * u.deg), or "12d" 
     """
     cls.pix_posX, cls.pix_posY = CD.rotate(cls.pix_posX,cls.pix_posY,angle)
Ejemplo n.º 7
0
def build_camera(cam_settings, pixel_settings, telescope):
    pixel_shape = cam_settings["pixel_shape"][0]
    try:
        pix_type, pix_rotation = CameraGeometry.simtel_shape_to_type(
            pixel_shape)
    except ValueError:
        warnings.warn(
            f"Unkown pixel_shape {pixel_shape} for camera_type {telescope.camera_name}",
            UnknownPixelShapeWarning,
        )
        pix_type = "hexagon"
        pix_rotation = "0d"

    geometry = CameraGeometry(
        telescope.camera_name,
        pix_id=np.arange(cam_settings["n_pixels"]),
        pix_x=u.Quantity(cam_settings["pixel_x"], u.m),
        pix_y=u.Quantity(cam_settings["pixel_y"], u.m),
        pix_area=u.Quantity(cam_settings["pixel_area"], u.m**2),
        pix_type=pix_type,
        pix_rotation=pix_rotation,
        cam_rotation=-Angle(cam_settings["cam_rot"], u.rad),
        apply_derotation=True,
    )
    readout = CameraReadout(
        telescope.camera_name,
        sampling_rate=u.Quantity(1 / pixel_settings["time_slice"], u.GHz),
        reference_pulse_shape=pixel_settings["ref_shape"].astype("float64",
                                                                 copy=False),
        reference_pulse_sample_width=u.Quantity(pixel_settings["ref_step"],
                                                u.ns),
    )

    return CameraDescription(camera_name=telescope.camera_name,
                             geometry=geometry,
                             readout=readout)
Ejemplo n.º 8
0
def build_camera(cam_settings, pixel_settings, telescope):
    pixel_shape = cam_settings['pixel_shape'][0]
    try:
        pix_type, pix_rotation = CameraGeometry.simtel_shape_to_type(
            pixel_shape)
    except ValueError:
        warnings.warn(
            f'Unkown pixel_shape {pixel_shape} for camera_type {telescope.camera_name}',
            UnknownPixelShapeWarning,
        )
        pix_type = 'hexagon'
        pix_rotation = '0d'

    geometry = CameraGeometry(
        telescope.camera_name,
        pix_id=np.arange(cam_settings['n_pixels']),
        pix_x=u.Quantity(cam_settings['pixel_x'], u.m),
        pix_y=u.Quantity(cam_settings['pixel_y'], u.m),
        pix_area=u.Quantity(cam_settings['pixel_area'], u.m**2),
        pix_type=pix_type,
        pix_rotation=pix_rotation,
        cam_rotation=-Angle(cam_settings['cam_rot'], u.rad),
        apply_derotation=True,
    )
    readout = CameraReadout(
        telescope.camera_name,
        sampling_rate=u.Quantity(1 / pixel_settings['time_slice'], u.GHz),
        reference_pulse_shape=pixel_settings['ref_shape'].astype('float64',
                                                                 copy=False),
        reference_pulse_sample_width=u.Quantity(pixel_settings['ref_step'],
                                                u.ns),
    )

    return CameraDescription(camera_name=telescope.camera_name,
                             geometry=geometry,
                             readout=readout)
Ejemplo n.º 9
0
def test_find_neighbor_pixels():
    x, y = np.meshgrid(np.linspace(-5, 5, 5), np.linspace(-5, 5, 5))
    neigh = CD.find_neighbor_pixels(x.ravel(), y.ravel(), rad=3.1)
    assert (set(neigh[11]) == set([16, 6, 10, 12]))
Ejemplo n.º 10
0
def load_hessio(filename):
    """
    Function to open and load a hessio file
    
    Parameters
    ----------
    filename: string
        name of the file
    """
    print("Hessio file will be opened.")
    h.file_open(filename)
    next(h.move_to_next_event())
    #version = h.get...
    version = 'Feb2016'

    #Creating 3 dictionaries where the instrument configuration will be stored
    #The dictionaries themselves contain astropy.table.Table objects
    telescope = {}
    camera = {}
    optics = {}

    #--------------------------------------------------------------------------
    #Telescope configuration
    tel_table_prime = Table()
    tel_table_prime.meta = {'VERSION': version}

    try:
        tel_id = h.get_telescope_ids()
        tel_table_prime['TelID'] = tel_id
    except:
        pass
    try:
        tel_posX = [h.get_telescope_position(i)[0] for i in tel_id]
        tel_table_prime['TelX'] = tel_posX
        tel_table_prime['TelX'].unit = u.m
        tel_table_prime.meta['TelX_description'] =\
        'x-position of the telescope measured by...'
    except:
        pass
    try:
        tel_posY = [h.get_telescope_position(i)[1] for i in tel_id]
        tel_table_prime['TelY'] = tel_posY
        tel_table_prime['TelY'].unit = u.m
    except:
        pass
    try:
        tel_posZ = [h.get_telescope_position(i)[2] for i in tel_id]
        tel_table_prime['TelZ'] = tel_posZ
        tel_table_prime['TelZ'].unit = u.m
    except:
        pass
    try:
        tel_table['CameraClass'] = [h.get_camera_class(i) for i in tel_id]
    except:
        pass
    try:
        tel_table_prime['MirA'] = [h.get_mirror_area(i) for i in tel_id]
        tel_table_prime['MirA'].unit = u.m**2
    except:
        pass
    try:
        tel_table_prime['MirN'] = [h.get_mirror_number(i) for i in tel_id]
    except:
        pass
    try:
        tel_table_prime['FL'] = [h.get_optical_foclen(i) for i in tel_id]
        tel_table_prime['FL'].unit = u.m
    except:
        pass
    try:
        tel_table_prime.meta['TelNum'] = len(tel_posX)
    except:
        pass

    #Beside other tables containimng telescope configuration data, the main
    #telescope table is written into the telescope dictionary.
    telescope['TelescopeTable_Version%s' % version] = tel_table_prime

    #--------------------------------------------------------------------------
    #Camera and Optics configuration
    try:
        for t in range(len(tel_id)):

            cam_table_prime = Table()
            cam_table_prime.meta = {'TELID': tel_id[t], 'VERSION': version}
            opt_table_prime = Table()
            opt_table_prime.meta = {'TELID': tel_id[t], 'VERSION': version}

            try:
                pix_posX = h.get_pixel_position(tel_id[t])[0]
                pix_id = np.arange(len(pix_posX))
                cam_table_prime['PixID'] = pix_id
                cam_table_prime['PixX'] = pix_posX
                cam_table_prime['PixX'].unit = u.m
                cam_table_prime.meta['PixXDescription'] =\
                'x-position of the pixel measured by...'
            except:
                pass
            try:
                pix_posY = h.get_pixel_position(tel_id[t])[1]
                cam_table_prime['PixY'] = pix_posY
                cam_table_prime['PixY'].unit = u.m
            except:
                pass
            try:
                camera_class = CD.guess_camera_geometry(
                    pix_posX * u.m, pix_posY * u.m)
                pix_area_prime = camera_class.pix_area
                pix_type_prime = camera_class.pix_type
                pix_neighbors_prime = camera_class.pix_neighbors
            except:
                pass

            try:
                pix_area = h.get_pixel_area(tel_id[t])
                cam_table_prime['PixA'] = pix_area
                cam_table_prime['PixA'].unit = u.mm**2
            except:
                try:
                    cam_table_prime['PixA'] = pix_area_prime
                    cam_table_prime['PixA'].unit = u.mm**2
                except:
                    pass
            try:
                pix_type = h.get_pixel_type(tel_id[t])
            except:
                try:
                    pix_type = pix_type_prime
                except:
                    pix_type = 'unknown'
            cam_table_prime.meta['PixType'] = pix_type
            try:
                pix_neighbors = h.get_pixel_neighbor(tel_id[t])
                cam_table_prime['PixNeig'] = pix_neighbors
            except:
                try:
                    cam_table_prime['PixNeig'] = pix_neighbors_prime
                except:
                    pass

            #as long as no mirror IDs are given, use the following:
            opt_table_prime['MirrID'] = [1, 2]
            try:
                opt_table_prime.meta['MirNum'] = h.get_mirror_number(tel_id[t])
            except:
                pass
            try:
                opt_table_prime['MirArea'] = h.get_mirror_area(tel_id[t])
                opt_table_prime['MirArea'].unit = u.m**2
                opt_table_prime.meta['MirAreaDescription'] =\
                'Area of all mirrors'
            except:
                pass
            try:
                opt_table_prime['OptFocLen'] = h.get_optical_foclen(tel_id[t])
                opt_table_prime['OptFocLen'].unit = u.m
            except:
                pass

            #Beside other tables containing camera and optics configuration
            #data, the main  tables are written into the camera and optics
            #dictionary.
            camera['CameraTable_Version%s_TelID%i' % (version,tel_id[t])] \
            = cam_table_prime
            optics['OpticsTable_Version%s_TelID%i' % (version,tel_id[t])] \
            = opt_table_prime
    except:
        pass

    print('Astropy tables have been created.')
    h.close_file()
    print("Hessio file has been closed.")
    return (telescope, camera, optics)
Ejemplo n.º 11
0
def test_make_rectangular_camera_geometry():
    geom = CD.make_rectangular_camera_geometry()
    assert (geom.pix_X.shape == geom.pix_Y.shape)
Ejemplo n.º 12
0
def test_rotate_camera():
    geom = CD.make_rectangular_camera_geometry(10, 10)
    geom.rotate(geom, '10d')
Ejemplo n.º 13
0
def test_make_rectangular_camera_geometry():
    geom = CD.make_rectangular_camera_geometry()
    assert(geom.pix_X.shape == geom.pix_Y.shape)
Ejemplo n.º 14
0
def test_known_camera_names(camera_geometry):
    """ Check that we can get a list of known camera names """
    assert camera_geometry.camera_name in CameraDescription.get_known_camera_names(
    )
Ejemplo n.º 15
0
class CameraDemo(Tool):
    name = "ctapipe-camdemo"
    description = "Display fake events in a demo camera"

    delay = traits.Int(50, help="Frame delay in ms", min=20).tag(config=True)
    cleanframes = traits.Int(20, help="Number of frames between turning on "
                                       "cleaning", min=0).tag(config=True)
    autoscale = traits.Bool(False, help='scale each frame to max if '
                                        'True').tag(config=True)
    blit = traits.Bool(False, help='use blit operation to draw on screen ('
                                   'much faster but may cause some draw '
                                   'artifacts)').tag(config=True)
    camera = traits.CaselessStrEnum(
        CameraDescription.get_known_camera_names(),
        default_value='NectarCam',
        help='Name of camera to display').tag(config=True)

    optics = traits.CaselessStrEnum(
        OpticsDescription.get_known_optics_names(),
        default_value='MST',
        help='Telescope optics description name'
    ).tag(config=True)

    num_events = traits.Int(0, help='events to show before exiting (0 for '
                                    'unlimited)').tag(config=True)

    display = traits.Bool(True, "enable or disable display (for "
                                "testing)").tag(config=True)

    aliases = traits.Dict({
        'delay': 'CameraDemo.delay',
        'cleanframes': 'CameraDemo.cleanframes',
        'autoscale': 'CameraDemo.autoscale',
        'blit': 'CameraDemo.blit',
        'camera': 'CameraDemo.camera',
        'optics': 'CameraDemo.optics',
        'num-events': 'CameraDemo.num_events'
    })

    def __init__(self):
        super().__init__()
        self._counter = 0
        self.imclean = False

    def start(self):
        self.log.info(f"Starting CameraDisplay for {self.camera}")
        self._display_camera_animation()

    def _display_camera_animation(self):
        # plt.style.use("ggplot")
        fig = plt.figure(num="ctapipe Camera Demo", figsize=(7, 7))
        ax = plt.subplot(111)

        # load the camera
        tel = TelescopeDescription.from_name(optics_name=self.optics,
                                             camera_name=self.camera)
        geom = tel.camera.geometry

        # poor-man's coordinate transform from telscope to camera frame (it's
        # better to use ctapipe.coordiantes when they are stable)
        foclen = tel.optics.equivalent_focal_length.to(geom.pix_x.unit).value
        fov = np.deg2rad(4.0)
        scale = foclen
        minwid = np.deg2rad(0.1)
        maxwid = np.deg2rad(0.3)
        maxlen = np.deg2rad(0.5)

        self.log.debug(f"scale={scale} m, wid=({minwid}-{maxwid})")

        disp = CameraDisplay(
            geom, ax=ax, autoupdate=True,
            title=f"{tel}, f={tel.optics.equivalent_focal_length}"
        )
        disp.cmap = plt.cm.terrain

        def update(frame):
            x, y = np.random.uniform(-fov, fov, size=2) * scale
            width = np.random.uniform(0, maxwid - minwid) * scale + minwid
            length = np.random.uniform(0, maxlen) * scale + width
            angle = np.random.uniform(0, 360)
            intens = np.random.exponential(2) * 500
            model = toymodel.Gaussian(
                x=x * u.m,
                y=y * u.m,
                width=width * u.m,
                length=length * u.m,
                psi=angle * u.deg,
            )
            self.log.debug(
                "Frame=%d width=%03f length=%03f intens=%03d",
                frame, width, length, intens
            )

            image, _, _ = model.generate_image(
                geom,
                intensity=intens,
                nsb_level_pe=3,
            )

            # alternate between cleaned and raw images
            if self._counter == self.cleanframes:
                plt.suptitle("Image Cleaning ON")
                self.imclean = True
            if self._counter == self.cleanframes * 2:
                plt.suptitle("Image Cleaning OFF")
                self.imclean = False
                self._counter = 0
                disp.clear_overlays()

            if self.imclean:
                cleanmask = tailcuts_clean(geom, image,
                                           picture_thresh=10.0,
                                           boundary_thresh=5.0)
                for ii in range(2):
                    dilate(geom, cleanmask)
                image[cleanmask == 0] = 0  # zero noise pixels
                try:
                    hillas = hillas_parameters(geom, image)
                    disp.overlay_moments(hillas, with_label=False,
                                         color='red', alpha=0.7,
                                         linewidth=2, linestyle='dashed')
                except HillasParameterizationError:
                    disp.clear_overlays()
                    pass

            self.log.debug("Frame=%d  image_sum=%.3f max=%.3f",
                           self._counter, image.sum(), image.max())
            disp.image = image

            if self.autoscale:
                disp.set_limits_percent(95)
            else:
                disp.set_limits_minmax(-5, 200)

            disp.axes.figure.canvas.draw()
            self._counter += 1
            return [ax, ]

        frames = None if self.num_events == 0 else self.num_events
        repeat = True if self.num_events == 0 else False

        self.log.info(f"Running for {frames} frames")
        self.anim = FuncAnimation(fig, update,
                                  interval=self.delay,
                                  frames=frames,
                                  repeat=repeat,
                                  blit=self.blit)

        if self.display:
            plt.show()
Ejemplo n.º 16
0
# TODO: use io.fits instead and make the table be variable length
# TODO: make this a tool (ctapipe-eventio2tels)

if __name__ == '__main__':

    filename = sys.argv.pop(1)

    with open_hessio(filename) as h:
        event = h.move_to_next_event()
        next(event)

        for telid in range(1, h.get_num_telescope()):
            try:
                px, py = h.get_pixel_position(telid)
                camtab = Table(names=['PIX_POS_X', 'PIX_POS_Y'],
                               data=[px * u.m, py * u.m])
                camtab.meta['N_PIX'] = h.get_num_pixels(telid)
                camtab.meta['N_SAMPS'] = h.get_num_samples(telid)
                camtab.meta['N_TIMES'] = h.get_pixel_timing_num_times_types(telid)
                camtab.meta['MIR_AREA'] = h.get_mirror_area(telid)
                geom = CameraDescription.guess_camera_geometry(px * u.m, py * u.m)
                #camtab.meta['TELCLASS'] = geom.cam_id
                camtab.meta['PIXTYPE'] = geom.pix_type

                filename = "cam_{:03d}.fits".format(telid)
                camtab.write(filename)
                print("WROTE ", filename)
            except HessioTelescopeIndexError:
                break
    print('Camera FOV of the first telescope of fits file.',
          'Returned, when only the camera data is read from the file:')
    print('{0:.2f}'.format(cam10.cam_fov))
    print('Rotate the Camera by 180 degree, i.e. the x- & y-positions will be',
          'rotated by 190 degree:')
    print('x-position of the camera before using the rotate method:')
    print(cam10.pix_posX)
    print('x-position of the camera after using the rotate method:')
    cam10.rotate(cam10, 180 * u.degree)
    print(cam10.pix_posX)
    print('FADC pulse shape over time of ASCII file')
    plt.plot(cam30.fadc_pulsshape[0], cam30.fadc_pulsshape[1], '+')
    plt.show()
    print('----------------------------')

    print('Print imported camera data as a table:')
    table = CD.write_table(1, cam10.cam_class, cam10.pix_id[:1],
                           cam10.pix_posX, cam10.pix_posY, cam10.pix_area,
                           cam10.pix_type)
    print(table)
    print('---------------------------')

    opt10 = ID.Optics.from_file(filename1, 1)
    opt30 = ID.Optics.from_file(filename3, 1)
    print('Mirror Area of the first telescope of fits file.',
          'Returned, when only the optics data is read from the file:')
    print('{0:.2f}'.format(opt10.mir_area))
    print('Mirror reflection over wavelength [nm]')
    plt.plot(opt30.mir_reflection[0].value, opt30.mir_reflection[1], '+')
    plt.show()
    print('----------------------------')
    def __init__(self, **kwargs):
        """
        Constructor

        Parameters
        ----------
        kwargs: dict
            Parameters to be passed.
            NOTE: The file mask of the data to read can be passed with
            the 'input_url' parameter.
        """
        try:
            import uproot
        except ImportError:
            raise ImportError(
                "The 'uproot' package is required for the DLMAGICEventSource class."
            )

        self.file_list = glob.glob(kwargs["input_url"])
        self.file_list.sort()

        # Since EventSource can not handle file wild cards as input_url
        # We substitute the input_url with first file matching
        # the specified file mask.
        del kwargs["input_url"]
        super().__init__(input_url=self.file_list[0], **kwargs)

        # Translate MAGIC shower primary id to CTA convention
        self.magic_to_cta_shower_primary_id = {
            1: 0,  # gamma
            14: 101,  # MAGIC proton
            3: 1,  # MAGIC electron
        }
        # MAGIC telescope positions in m wrt. to the center of CTA simulations
        self.magic_tel_positions = {
            1: [-27.24, -146.66, 50.00] * u.m,
            2: [-96.44, -96.77, 51.00] * u.m,
        }
        self.magic_tel_positions = self.magic_tel_positions
        # MAGIC telescope description
        optics = OpticsDescription.from_name("MAGIC")
        geom = CameraGeometry.from_name("MAGICCam")
        # Camera Readout for NectarCam used as a placeholder
        readout = CameraReadout(
            "MAGICCam",
            sampling_rate=u.Quantity(1, u.GHz),
            reference_pulse_shape=np.array([norm.pdf(np.arange(96), 48, 6)]),
            reference_pulse_sample_width=u.Quantity(1, u.ns),
        )
        camera = CameraDescription("MAGICCam", geom, readout)
        self.magic_tel_description = TelescopeDescription(name="MAGIC",
                                                          tel_type="LST",
                                                          optics=optics,
                                                          camera=camera)
        self.magic_tel_descriptions = {
            1: self.magic_tel_description,
            2: self.magic_tel_description,
        }
        self.magic_subarray = SubarrayDescription("MAGIC",
                                                  self.magic_tel_positions,
                                                  self.magic_tel_descriptions)
        # Open ROOT files
        self.calib_M1, self.calib_M2, self.star_M1, self.star_M2, self.superstar = (
            None,
            None,
            None,
            None,
            None,
        )
        for file in self.file_list:
            uproot_file = uproot.open(file)
            if "_Y_" in file:
                if "_M1_" in file:
                    self.calib_M1 = uproot_file["Events"]
                    self.meta = uproot_file["RunHeaders"]
                elif "_M2_" in file:
                    self.calib_M2 = uproot_file["Events"]
            if "_I_" in file:
                if "_M1_" in file:
                    self.star_M1 = uproot_file["Events"]
                elif "_M2_" in file:
                    self.star_M2 = uproot_file["Events"]
            if "_S_" in file:
                self.superstar = uproot_file["Events"]
                self.meta = uproot_file["RunHeaders"]

        # figure out if MC or Data run
        self.mc = "MMcCorsikaRunHeader." in self.meta.keys()

        # get the run number directly from the root file
        if self.mc:
            self.run_number = int(
                uproot_file["RunHeaders"]["MMcCorsikaRunHeader."]
                ["MMcCorsikaRunHeader.fRunNumber"].array()[0])
        else:
            self.run_number = int(uproot_file["RunHeaders"]["MRawRunHeader_1."]
                                  ["MRawRunHeader_1.fRunNumber"].array()[0])

        self._header = self._parse_header()
Ejemplo n.º 19
0
def test_known_camera_names():
    """ Check that we can get a list of known camera names """
    cams = CameraDescription.get_known_camera_names()
    assert len(cams) > 4
    assert "FlashCam" in cams
    assert "NectarCam" in cams
Ejemplo n.º 20
0
def get_camera(cam_name: str) -> CameraDescription:
    if cameras.get(cam_name) is None:
        cameras[cam_name] = CameraDescription.from_name(cam_name)
    return cameras[cam_name]
 cam30 = ID.Camera.from_file(filename3,1)
 print('Camera FOV of the first telescope of fits file.',
       'Returned, when only the camera data is read from the file:')
 print('{0:.2f}'.format(cam10.cam_fov))
 print('Rotate the Camera by 180 degree, i.e. the x- & y-positions will be',
       'rotated by 190 degree:')
 print('x-position of the camera before using the rotate method:')
 print(cam10.pix_posX)
 print('x-position of the camera after using the rotate method:')
 cam10.rotate(cam10,180*u.degree)
 print(cam10.pix_posX)
 print('FADC pulse shape over time of ASCII file')
 plt.plot(cam30.fadc_pulsshape[0],cam30.fadc_pulsshape[1],'+')
 plt.show()    
 print('----------------------------')
 
 print('Print imported camera data as a table:')
 table = CD.write_table(1,cam10.cam_class,cam10.pix_id[:1],cam10.pix_posX,
                        cam10.pix_posY,cam10.pix_area,cam10.pix_type)
 print(table)
 print('---------------------------')
 
 opt10 = ID.Optics.from_file(filename1,1)
 opt30 = ID.Optics.from_file(filename3,1)
 print('Mirror Area of the first telescope of fits file.',
       'Returned, when only the optics data is read from the file:')
 print('{0:.2f}'.format(opt10.mir_area))
 print('Mirror reflection over wavelength [nm]')
 plt.plot(opt30.mir_reflection[0].value,opt30.mir_reflection[1],'+')
 plt.show()
 print('----------------------------')
def load_hessio(filename):
    """
    Function to open and load a hessio file
    
    Parameters
    ----------
    filename: string
        name of the file
    """
    print("Hessio file will be opened.")    
    h.file_open(filename)
    next(h.move_to_next_event())
    #version = h.get...
    version = 'Feb2016'
    
    #Creating 3 dictionaries where the instrument configuration will be stored
    #The dictionaries themselves contain astropy.table.Table objects
    telescope = {}
    camera = {}
    optics = {}  
    
    #--------------------------------------------------------------------------
    #Telescope configuration
    tel_table_prime = Table()
    tel_table_prime.meta = {'VERSION': version}    
    
    try: 
        tel_id = h.get_telescope_ids()
        tel_table_prime['TelID']= tel_id
    except: pass    
    try:
        tel_posX = [h.get_telescope_position(i)[0] for i in tel_id]
        tel_table_prime['TelX'] = tel_posX
        tel_table_prime['TelX'].unit = u.m
        tel_table_prime.meta['TelX_description'] =\
        'x-position of the telescope measured by...'
    except: pass
    try:
        tel_posY = [h.get_telescope_position(i)[1] for i in tel_id]
        tel_table_prime['TelY'] = tel_posY
        tel_table_prime['TelY'].unit = u.m
    except: pass
    try:
        tel_posZ = [h.get_telescope_position(i)[2] for i in tel_id]
        tel_table_prime['TelZ'] = tel_posZ
        tel_table_prime['TelZ'].unit = u.m
    except: pass
    try: tel_table['CameraClass'] = [h.get_camera_class(i) for i in tel_id]
    except: pass
    try:
        tel_table_prime['MirA'] = [h.get_mirror_area(i) for i in tel_id]
        tel_table_prime['MirA'].unit = u.m**2
    except: pass
    try:  tel_table_prime['MirN'] = [h.get_mirror_number(i) for i in tel_id]
    except: pass    
    try: 
        tel_table_prime['FL'] = [h.get_optical_foclen(i) for i in tel_id]
        tel_table_prime['FL'].unit = u.m
    except: pass
    try: tel_table_prime.meta['TelNum'] =  len(tel_posX)
    except: pass
    
    #Beside other tables containimng telescope configuration data, the main
    #telescope table is written into the telescope dictionary.
    telescope['TelescopeTable_Version%s' % version] = tel_table_prime
    
    #--------------------------------------------------------------------------
    #Camera and Optics configuration
    try:    
        for t in range(len(tel_id)):       
            
            cam_table_prime = Table()
            cam_table_prime.meta = {'TELID': tel_id[t], 'VERSION': version}
            opt_table_prime = Table()
            opt_table_prime.meta = {'TELID': tel_id[t], 'VERSION': version}
            
            try:
                pix_posX = h.get_pixel_position(tel_id[t])[0]
                pix_id = np.arange(len(pix_posX))
                cam_table_prime['PixID'] = pix_id                
                cam_table_prime['PixX'] = pix_posX
                cam_table_prime['PixX'].unit = u.m
                cam_table_prime.meta['PixXDescription'] =\
                'x-position of the pixel measured by...'
            except: pass
            try:
                pix_posY = h.get_pixel_position(tel_id[t])[1]
                cam_table_prime['PixY'] = pix_posY
                cam_table_prime['PixY'].unit = u.m
            except: pass
            try:
                camera_class = CD.guess_camera_geometry(pix_posX*u.m,pix_posY*u.m)
                pix_area_prime = camera_class.pix_area
                pix_type_prime = camera_class.pix_type
                pix_neighbors_prime = camera_class.pix_neighbors
            except: pass        
    
            try:
                pix_area = h.get_pixel_area(tel_id[t])
                cam_table_prime['PixA'] = pix_area
                cam_table_prime['PixA'].unit = u.mm**2
            except:
                try:
                    cam_table_prime['PixA'] = pix_area_prime
                    cam_table_prime['PixA'].unit = u.mm**2
                except: pass
            try: pix_type = h.get_pixel_type(tel_id[t])
            except:
                try: pix_type = pix_type_prime
                except: pix_type = 'unknown'
            cam_table_prime.meta['PixType'] = pix_type
            try:
                pix_neighbors = h.get_pixel_neighbor(tel_id[t])
                cam_table_prime['PixNeig'] = pix_neighbors
            except:
                try: cam_table_prime['PixNeig'] = pix_neighbors_prime
                except: pass       
            
            #as long as no mirror IDs are given, use the following:
            opt_table_prime['MirrID'] = [1,2]
            try:
                opt_table_prime.meta['MirNum'] = h.get_mirror_number(tel_id[t])
            except: pass
            try:
                opt_table_prime['MirArea'] = h.get_mirror_area(tel_id[t])
                opt_table_prime['MirArea'].unit = u.m**2
                opt_table_prime.meta['MirAreaDescription'] =\
                'Area of all mirrors'
            except: pass
            try:
                opt_table_prime['OptFocLen'] = h.get_optical_foclen(tel_id[t])
                opt_table_prime['OptFocLen'].unit = u.m
            except: pass
            
            #Beside other tables containing camera and optics configuration
            #data, the main  tables are written into the camera and optics
            #dictionary.
            camera['CameraTable_Version%s_TelID%i' % (version,tel_id[t])] \
            = cam_table_prime
            optics['OpticsTable_Version%s_TelID%i' % (version,tel_id[t])] \
            = opt_table_prime
    except: pass
        
    print('Astropy tables have been created.')
    h.close_file()
    print("Hessio file has been closed.")
    return(telescope,camera,optics)
Ejemplo n.º 23
0
def test_rotate_camera():
    geom = CD.make_rectangular_camera_geometry(10, 10)
    geom.rotate(geom,'10d')
Ejemplo n.º 24
0
    def __init__(self, **kwargs):
        """
        Constructor

        Parameters
        ----------
        kwargs: dict
            Parameters to be passed.
            NOTE: The file mask of the data to read can be passed with
            the 'input_url' parameter.
        """
        try:
            import uproot
        except ImportError:
            raise ImportError(
                "The 'uproot' package is required for the DLMAGICEventSource class."
            )

        self.file_list = glob.glob(kwargs['input_url'])
        self.file_list.sort()

        # Since EventSource can not handle file wild cards as input_url
        # We substitute the input_url with first file matching
        # the specified file mask.
        del kwargs['input_url']
        super().__init__(input_url=self.file_list[0], **kwargs)

        # get run number
        mask = r".*_za\d+to\d+_\d_(\d+)_([A-Z]+)_.*"
        parsed_info = re.findall(mask, self.file_list[0])
        self.run_number = parsed_info[0][0]

        # MAGIC telescope positions in m wrt. to the center of CTA simulations
        self.magic_tel_positions = {
            1: [-27.24, -146.66, 50.00] * u.m,
            2: [-96.44, -96.77, 51.00] * u.m
        }
        self.magic_tel_positions = self.magic_tel_positions
        # MAGIC telescope description
        optics = OpticsDescription.from_name('MAGIC')
        geom = CameraGeometry.from_name('MAGICCam')
        # Camera Readout for NectarCam used as a placeholder
        readout = CameraReadout(
            'MAGICCam',
            sampling_rate=u.Quantity(1, u.GHz),
            reference_pulse_shape=np.array([norm.pdf(np.arange(96), 48, 6)]),
            reference_pulse_sample_width=u.Quantity(1, u.ns))
        camera = CameraDescription('MAGICCam', geom, readout)
        self.magic_tel_description = TelescopeDescription(name='MAGIC',
                                                          tel_type='LST',
                                                          optics=optics,
                                                          camera=camera)
        self.magic_tel_descriptions = {
            1: self.magic_tel_description,
            2: self.magic_tel_description
        }
        self.magic_subarray = SubarrayDescription('MAGIC',
                                                  self.magic_tel_positions,
                                                  self.magic_tel_descriptions)
        # Open ROOT files
        self.calib_M1, self.calib_M2, self.star_M1, self.star_M2, self.superstar = None, None, None, None, None
        for file in self.file_list:
            uproot_file = uproot.open(file)
            if "_Y_" in file:
                if "_M1_" in file:
                    self.calib_M1 = uproot_file["Events"]
                    self.meta = uproot_file["RunHeaders"]
                elif "_M2_" in file:
                    self.calib_M2 = uproot_file["Events"]
            if "_I_" in file:
                if "_M1_" in file:
                    self.star_M1 = uproot_file["Events"]
                elif "_M2_" in file:
                    self.star_M2 = uproot_file["Events"]
            if "_S_" in file:
                self.superstar = uproot_file["Events"]
                self.meta = uproot_file["RunHeaders"]
        self._mc_header = self._parse_mc_header()
Ejemplo n.º 25
0
def test_find_neighbor_pixels():
    x, y = np.meshgrid(np.linspace(-5, 5, 5), np.linspace(-5, 5, 5))
    neigh = CD.find_neighbor_pixels(x.ravel(), y.ravel(), rad=3.1)
    assert(set(neigh[11]) == set([16, 6, 10, 12]))
Ejemplo n.º 26
0
import numpy as np
from matplotlib import pyplot as plt

from ctapipe.instrument import CameraDescription, CameraGeometry
from ctapipe.visualization import CameraDisplay

if __name__ == "__main__":

    plt.style.use("bmh")

    camera_names = CameraDescription.get_known_camera_names()
    n_tels = len(camera_names)
    n_rows = np.trunc(np.sqrt(n_tels)).astype(int)
    n_cols = np.ceil(n_tels / n_rows).astype(int)
    plt.figure(figsize=(15, 6))

    for ii, name in enumerate(sorted(camera_names)):
        print("plotting", name)
        geom = CameraGeometry.from_name(name)
        ax = plt.subplot(n_rows, n_cols, ii + 1)
        disp = CameraDisplay(geom)
        disp.image = np.random.uniform(size=geom.pix_id.shape)
        disp.cmap = "viridis"
        plt.xlabel("")
        plt.ylabel("")

    plt.tight_layout()
    plt.show()
Ejemplo n.º 27
0
    def _build_telescope_description(self, file, tel_id):
        pix_x, pix_y = u.Quantity(file.get_pixel_position(tel_id), u.m)
        focal_length = u.Quantity(file.get_optical_foclen(tel_id), u.m)
        n_pixels = len(pix_x)

        try:
            telescope = guess_telescope(n_pixels, focal_length)
        except ValueError:
            telescope = UNKNOWN_TELESCOPE

        pixel_shape = file.get_pixel_shape(tel_id)[0]
        try:
            pix_type, pix_rot = CameraGeometry.simtel_shape_to_type(
                pixel_shape)
        except ValueError:
            warnings.warn(
                f'Unkown pixel_shape {pixel_shape} for tel_id {tel_id}',
                UnknownPixelShapeWarning,
            )
            pix_type = 'hexagon'
            pix_rot = '0d'

        pix_area = u.Quantity(file.get_pixel_area(tel_id), u.m**2)

        mirror_area = u.Quantity(file.get_mirror_area(tel_id), u.m**2)
        num_tiles = file.get_mirror_number(tel_id)
        cam_rot = file.get_camera_rotation_angle(tel_id)
        num_mirrors = file.get_mirror_number(tel_id)
        sampling_rate = u.Quantity(1 / file.get_time_slice(tel_id), u.GHz)
        reference_pulse_shape = file.get_ref_shapes(tel_id)
        reference_pulse_sample_width = u.Quantity(file.get_ref_step(tel_id),
                                                  u.ns)

        geometry = CameraGeometry(
            telescope.camera_name,
            pix_id=np.arange(n_pixels),
            pix_x=pix_x,
            pix_y=pix_y,
            pix_area=pix_area,
            pix_type=pix_type,
            pix_rotation=pix_rot,
            cam_rotation=-Angle(cam_rot, u.rad),
            apply_derotation=True,
        )
        readout = CameraReadout(
            telescope.camera_name,
            sampling_rate=sampling_rate,
            reference_pulse_shape=reference_pulse_shape,
            reference_pulse_sample_width=reference_pulse_sample_width,
        )
        camera = CameraDescription(camera_name=telescope.camera_name,
                                   geometry=geometry,
                                   readout=readout)

        optics = OpticsDescription(
            name=telescope.name,
            num_mirrors=num_mirrors,
            equivalent_focal_length=focal_length,
            mirror_area=mirror_area,
            num_mirror_tiles=num_tiles,
        )

        return TelescopeDescription(name=telescope.name,
                                    tel_type=telescope.type,
                                    optics=optics,
                                    camera=camera)