def main():
    script = os.path.splitext(os.path.basename(__file__))[0]
    log.info("[SCRIPT] {}".format(script))

    parser = argparse.ArgumentParser(
        description='Display each event in the file')
    parser.add_argument('-f',
                        '--file',
                        dest='input_path',
                        action='store',
                        default=get_path('gamma_test.simtel.gz'),
                        help='path to the input file. '
                        'Default = gamma_test.simtel.gz')
    parser.add_argument('-O',
                        '--origin',
                        dest='origin',
                        action='store',
                        default='hessio',
                        help='origin of the file: {}. Default = hessio'.format(
                            InputFile.origin_list()))
    parser.add_argument('-D',
                        dest='display',
                        action='store_true',
                        default=False,
                        help='display the camera events')
    parser.add_argument('--pdf',
                        dest='output_path',
                        action='store',
                        default=None,
                        help='path to store a pdf output of the plots')
    parser.add_argument('-t',
                        '--telescope',
                        dest='tel',
                        action='store',
                        type=int,
                        default=None,
                        help='telecope to view. '
                        'Default = All')

    calibration_arguments(parser)

    logger_detail = parser.add_mutually_exclusive_group()
    logger_detail.add_argument('-q',
                               '--quiet',
                               dest='quiet',
                               action='store_true',
                               default=False,
                               help='Quiet mode')
    logger_detail.add_argument('-v',
                               '--verbose',
                               dest='verbose',
                               action='store_true',
                               default=False,
                               help='Verbose mode')
    logger_detail.add_argument('-d',
                               '--debug',
                               dest='debug',
                               action='store_true',
                               default=False,
                               help='Debug mode')

    args = parser.parse_args()
    print('DEBUG type(args) {}'.format(type(args)))
    print('DEBUG args {}'.format(args))
    params = calibration_parameters(args)

    if args.quiet:
        log.setLevel(40)
    if args.verbose:
        log.setLevel(20)
    if args.debug:
        log.setLevel(10)

    log.debug("[file] Reading file")
    input_file = InputFile(args.input_path, args.origin)
    source = input_file.read()

    # geom_dict is a dictionary of CameraGeometry, with keys of
    # (num_pixels, focal_length), the parameters that are used to guess the
    # geometry of the telescope. By using these keys, the geometry is
    # calculated only once per telescope type as needed, reducing computation
    # time.
    # Creating a geom_dict at this point is optional, but is recommended, as
    # the same geom_dict can then be shared between the calibration and
    # CameraPlotter, again reducing computation time.
    # The dictionary becomes filled as a result of a dictionary's mutable
    # nature.
    geom_dict = {}

    # Calibrate events and fill geom_dict

    calibrated_source = calibrate_source(source, params, geom_dict)

    fig = plt.figure(figsize=(16, 7))
    if args.display:
        plt.show(block=False)
    pp = PdfPages(args.output_path) if args.output_path is not None else None
    for event in calibrated_source:
        tels = list(event.dl0.tels_with_data)
        if args.tel is None:
            tel_loop = tels
        else:
            if args.tel not in tels:
                continue
            tel_loop = [args.tel]
        log.debug(tels)
        for tel_id in tel_loop:
            display_telescope(event, tel_id, args.display, geom_dict, pp, fig)
    if pp is not None:
        pp.close()

    log.info("[COMPLETE]")
def calculate_charge_resolutions(parser, chargeres_cmdlines):

    run = 0
    num_runs = len(chargeres_cmdlines)
    chargeres_dict = {}

    for name, cmdline in chargeres_cmdlines.items():

        args, excess_args = parser.parse_known_args(cmdline)

        run += 1
        log.info("[run] Calculating charge resolution {}/{}"
                 .format(run, num_runs))

        # Print event/args values
        log.info("[files] {}".format(args.input_paths))
        telescopes = "All" if args.tel is None else args.tel
        log.info("[origin] {}".format(args.origin))
        log.info("[telescopes] {}".format(telescopes))

        # Obtain InputFiles (to check files exist)
        input_file_list = []
        for filepath in args.input_paths:
            tilde_filepath = os.path.expanduser(filepath)
            for globfile in glob.glob(tilde_filepath):
                input_file_list.append(InputFile(globfile, args.origin))

        # Find maxpe
        maxpe = args.maxpe
        if maxpe is None:
            maxpe = 0
            for input_file in input_file_list:
                file_maxpe = input_file.find_max_true_npe(args.tel)
                if file_maxpe > maxpe:
                    maxpe = file_maxpe
        log.info("[maxpe] {}".format(maxpe))

        params, unknown_args = calibration_parameters(excess_args,
                                                      args.origin,
                                                      args.calib_help)

        chargeres = ChargeResolution(maxpe)

        for input_file in input_file_list:
            source = input_file.read()
            calibrated_source = calibrate_source(source, params)
            chargeres.add_source(calibrated_source, args.tel)

        # Plot comparison graphs
        if args.comparison is not None:
            hist = chargeres.variation_hist
            hist[hist == 0.0] = np.nan
            xedges = chargeres.variation_xedges
            yedges = chargeres.variation_yedges

            fig = plt.figure(figsize=(10, 7))
            ax = fig.add_subplot(111)
            ax.set_title(name)
            x, y = np.meshgrid(xedges, yedges)
            x = np.power(10, x)
            y = np.power(10, y)
            hist_mask = np.ma.masked_where(np.isnan(hist), hist)
            im = ax.pcolormesh(x, y, hist_mask, norm=LogNorm(),
                               cmap=plt.cm.viridis)
            cb = plt.colorbar(im)
            ax.set_aspect('equal')
            ax.grid()
            ax.set_xscale('log')
            ax.set_yscale('log')
            ax.set_xlabel(r'True Charge $Q_T$ (p.e.)')
            ax.set_ylabel(r'Measured Charge $Q_M$ (p.e.)')
            cb.ax.set_ylabel("Count")

            line = np.linspace(*ax.get_xlim(), 100)
            ax.plot(line, line, c='0.75', ls='--')

            # Add minor ticks
            lmin = floor(log10(hist_mask.min()))
            lmax = ceil(log10(hist_mask.max()))
            logticks = np.tile(np.arange(lmin, 10), lmax) * (
                np.power(10, np.arange(lmax * 10) // 10))
            logticks = im.norm(logticks[(logticks != 0) &
                                        (logticks >= hist_mask.min()) &
                                        (logticks <= hist_mask.max())])
            cb.ax.yaxis.set_ticks(logticks, minor=True)
            cb.ax.yaxis.set_tick_params(which='minor', length=5)
            cb.ax.tick_params(length=10)

            args.comparison = os.path.expanduser(args.comparison)
            output_dir = dirname(args.comparison)
            if not os.path.exists(output_dir):
                log.info("[output] Creating directory: {}".format(output_dir))
                os.makedirs(output_dir)
            log.info("[output] {}".format(args.comparison))
            warnings.filterwarnings("ignore", module="matplotlib")
            with warnings.catch_warnings():
                warnings.simplefilter("ignore")
                fig.savefig(args.comparison, bbox_inches='tight')

        chargeres_dict[name] = chargeres

    log.info('[run] Charge resolution calculations finished')

    return chargeres_dict
Beispiel #3
0
def calculate_charge_resolutions(parser, chargeres_cmdlines):

    run = 0
    num_runs = len(chargeres_cmdlines)
    chargeres_dict = {}

    for name, cmdline in chargeres_cmdlines.items():

        args, excess_args = parser.parse_known_args(cmdline)

        run += 1
        log.info("[run] Calculating charge resolution {}/{}".format(
            run, num_runs))

        # Print event/args values
        log.info("[files] {}".format(args.input_paths))
        telescopes = "All" if args.tel is None else args.tel
        log.info("[origin] {}".format(args.origin))
        log.info("[telescopes] {}".format(telescopes))

        # Obtain InputFiles (to check files exist)
        input_file_list = []
        for filepath in args.input_paths:
            tilde_filepath = os.path.expanduser(filepath)
            for globfile in glob.glob(tilde_filepath):
                input_file_list.append(InputFile(globfile, args.origin))

        # Find maxpe
        maxpe = args.maxpe
        if maxpe is None:
            maxpe = 0
            for input_file in input_file_list:
                file_maxpe = input_file.find_max_true_npe(args.tel)
                if file_maxpe > maxpe:
                    maxpe = file_maxpe
        log.info("[maxpe] {}".format(maxpe))

        params, unknown_args = calibration_parameters(excess_args, args.origin,
                                                      args.calib_help)

        chargeres = ChargeResolution(maxpe)

        for input_file in input_file_list:
            source = input_file.read()
            calibrated_source = calibrate_source(source, params)
            chargeres.add_source(calibrated_source, args.tel)

        # Plot comparison graphs
        if args.comparison is not None:
            hist = chargeres.variation_hist
            hist[hist == 0.0] = np.nan
            xedges = chargeres.variation_xedges
            yedges = chargeres.variation_yedges

            fig = plt.figure(figsize=(10, 7))
            ax = fig.add_subplot(111)
            ax.set_title(name)
            x, y = np.meshgrid(xedges, yedges)
            x = np.power(10, x)
            y = np.power(10, y)
            hist_mask = np.ma.masked_where(np.isnan(hist), hist)
            im = ax.pcolormesh(x,
                               y,
                               hist_mask,
                               norm=LogNorm(),
                               cmap=plt.cm.viridis)
            cb = plt.colorbar(im)
            ax.set_aspect('equal')
            ax.grid()
            ax.set_xscale('log')
            ax.set_yscale('log')
            ax.set_xlabel(r'True Charge $Q_T$ (p.e.)')
            ax.set_ylabel(r'Measured Charge $Q_M$ (p.e.)')
            cb.ax.set_ylabel("Count")

            line = np.linspace(*ax.get_xlim(), 100)
            ax.plot(line, line, c='0.75', ls='--')

            # Add minor ticks
            lmin = floor(log10(hist_mask.min()))
            lmax = ceil(log10(hist_mask.max()))
            logticks = np.tile(np.arange(lmin, 10), lmax) * (np.power(
                10,
                np.arange(lmax * 10) // 10))
            logticks = im.norm(
                logticks[(logticks != 0) & (logticks >= hist_mask.min()) &
                         (logticks <= hist_mask.max())])
            cb.ax.yaxis.set_ticks(logticks, minor=True)
            cb.ax.yaxis.set_tick_params(which='minor', length=5)
            cb.ax.tick_params(length=10)

            args.comparison = os.path.expanduser(args.comparison)
            output_dir = dirname(args.comparison)
            if not os.path.exists(output_dir):
                log.info("[output] Creating directory: {}".format(output_dir))
                os.makedirs(output_dir)
            log.info("[output] {}".format(args.comparison))
            warnings.filterwarnings("ignore", module="matplotlib")
            with warnings.catch_warnings():
                warnings.simplefilter("ignore")
                fig.savefig(args.comparison, bbox_inches='tight')

        chargeres_dict[name] = chargeres

    log.info('[run] Charge resolution calculations finished')

    return chargeres_dict
def main():
    script = os.path.splitext(os.path.basename(__file__))[0]
    log.info("[SCRIPT] {}".format(script))

    parser = argparse.ArgumentParser(
        description='Display each event in the file')
    parser.add_argument('-f', '--file', dest='input_path', action='store',
                        default=get_path('gamma_test.simtel.gz'),
                        help='path to the input file. '
                             'Default = gamma_test.simtel.gz')
    parser.add_argument('-O', '--origin', dest='origin', action='store',
                        default='hessio',
                        help='origin of the file: {}. Default = hessio'
                        .format(origin_list()))
    parser.add_argument('-D', dest='display', action='store_true',
                        default=False, help='display the camera events')
    parser.add_argument('--pdf', dest='output_path', action='store',
                        default=None,
                        help='path to store a pdf output of the plots')
    parser.add_argument('-t', '--telescope', dest='tel', action='store',
                        type=int, default=None, help='telecope to view. '
                                                     'Default = All')

    calibration_arguments(parser)

    logger_detail = parser.add_mutually_exclusive_group()
    logger_detail.add_argument('-q', '--quiet', dest='quiet',
                               action='store_true', default=False,
                               help='Quiet mode')
    logger_detail.add_argument('-v', '--verbose', dest='verbose',
                               action='store_true', default=False,
                               help='Verbose mode')
    logger_detail.add_argument('-d', '--debug', dest='debug',
                               action='store_true', default=False,
                               help='Debug mode')

    args = parser.parse_args()
    params = calibration_parameters(args)

    if args.quiet:
        log.setLevel(40)
    if args.verbose:
        log.setLevel(20)
    if args.debug:
        log.setLevel(10)

    log.debug("[file] Reading file")
    input_file = InputFile(args.input_path, args.origin)
    source = input_file.read()

    # geom_dict is a dictionary of CameraGeometry, with keys of
    # (num_pixels, focal_length), the parameters that are used to guess the
    # geometry of the telescope. By using these keys, the geometry is
    # calculated only once per telescope type as needed, reducing computation
    # time.
    # Creating a geom_dict at this point is optional, but is recommended, as
    # the same geom_dict can then be shared between the calibration and
    # CameraPlotter, again reducing computation time.
    # The dictionary becomes filled as a result of a dictionary's mutable
    # nature.
    geom_dict = {}

    # Calibrate events and fill geom_dict
    calibrated_source = calibrate_source(source, params, geom_dict)

    fig = plt.figure(figsize=(16, 7))
    if args.display:
        plt.show(block=False)
    pp = PdfPages(args.output_path) if args.output_path is not None else None
    for event in calibrated_source:
        tels = list(event.dl0.tels_with_data)
        if args.tel is None:
            tel_loop = tels
        else:
            if args.tel not in tels:
                continue
            tel_loop = [args.tel]
        log.debug(tels)
        for tel_id in tel_loop:
            display_telescope(event, tel_id, args.display, geom_dict, pp, fig)
    if pp is not None:
        pp.close()

    log.info("[COMPLETE]")
 def start(self):
     self.log.info("Running the calibration pipeline...")
     # Calibrate events and fill geom_dict
     self.calibrated_source = calibrate_source(self.source,
                                               self.params, self.geom_dict)