def remove_star_and_run(self, list_of_file, max_events,
                            noise_pixels_id_list):
        signal_place_after_clean = np.zeros(1855)
        sum_ped_ev = 0
        alive_ped_ev = 0

        for input_file in list_of_file:
            print(input_file)

            r0_r1_calibrator = LSTR0Corrections(pedestal_path=None,
                                                r1_sample_start=3,
                                                r1_sample_end=39)
            reader = LSTEventSource(input_url=input_file,
                                    max_events=max_events)
            for i, ev in enumerate(reader):
                r0_r1_calibrator.calibrate(ev)
                if i % 10000 == 0:
                    print(ev.r0.event_id)

                if ev.lst.tel[1].evt.tib_masked_trigger == 32:
                    sum_ped_ev += 1
                    self.r1_dl1_calibrator(ev)

                    img = ev.dl1.tel[1].image
                    img[noise_pixels_id_list] = 0

                    geom = ev.inst.subarray.tel[1].camera
                    clean = tailcuts_clean(geom, img,
                                           **self.cleaning_parameters)

                    cleaned = img.copy()
                    cleaned[~clean] = 0.0

                    signal_place_after_clean[np.where(clean == True)] += 1

                    if np.sum(cleaned > 0) > 0:
                        alive_ped_ev += 1

        fig, ax = plt.subplots(figsize=(10, 8))
        geom = ev.inst.subarray.tel[1].camera

        disp0 = CameraDisplay(geom, ax=ax)
        disp0.image = signal_place_after_clean / sum_ped_ev
        disp0.highlight_pixels(noise_pixels_id_list, linewidth=3)
        disp0.add_colorbar(ax=ax,
                           label="N times signal remain after cleaning [%]")
        disp0.cmap = 'gnuplot2'
        ax.set_title("{} \n {}/{}".format(
            input_file.split("/")[-1][8:21], alive_ped_ev, sum_ped_ev),
                     fontsize=25)

        print("{}/{}".format(alive_ped_ev, sum_ped_ev))

        ax.set_xlabel(" ")
        ax.set_ylabel(" ")
        plt.tight_layout()
        plt.show()
    def check_interleave_pedestal_cleaning(self, list_of_file, max_events,
                                           sigma, dl1_file):

        high_gain = 0
        ped_mean_pe, ped_rms_pe = get_bias_and_rms(dl1_file)
        bad_pixel_ids = np.where(ped_rms_pe[1, high_gain, :] == 0)[0]
        print(bad_pixel_ids)
        th = get_threshold(ped_mean_pe[1, high_gain, :],
                           ped_rms_pe[1, high_gain, :], sigma)

        make_camera_binary_image(th, sigma,
                                 self.cleaning_parameters['picture_thresh'],
                                 bad_pixel_ids)

        signal_place_after_clean = np.zeros(1855)
        sum_ped_ev = 0
        alive_ped_ev = 0

        for input_file in list_of_file:
            print(input_file)

            r0_r1_calibrator = LSTR0Corrections(pedestal_path=None,
                                                r1_sample_start=3,
                                                r1_sample_end=39)

            reader = LSTEventSource(input_url=input_file,
                                    max_events=max_events)

            for i, ev in enumerate(reader):
                r0_r1_calibrator.calibrate(ev)
                if i % 10000 == 0:
                    print(ev.r0.event_id)

                if ev.lst.tel[1].evt.tib_masked_trigger == 32:
                    sum_ped_ev += 1
                    self.r1_dl1_calibrator(ev)

                    img = ev.dl1.tel[1].image
                    img[bad_pixel_ids] = 0
                    geom = ev.inst.subarray.tel[1].camera
                    clean = tailcuts_pedestal_clean(geom, img, th,
                                                    **self.cleaning_parameters)

                    cleaned = img.copy()
                    cleaned[~clean] = 0.0

                    signal_place_after_clean[np.where(clean == True)] += 1
                    if np.sum(cleaned > 0) > 0:
                        alive_ped_ev += 1

        noise_remain = signal_place_after_clean / sum_ped_ev

        self.plot_camera_display(noise_remain, input_file, bad_pixel_ids,
                                 alive_ped_ev, sum_ped_ev)
Пример #3
0
    def setup(self):
        kwargs = dict(parent=self)
        self.log.info("Setup")
        self.eventsource = EventSource.from_config(**kwargs)
        self.extractor = FixedWindowSum(**kwargs)

        self.n = int(self.n_cap / self.n_combine)
        self.timeCorr = TimeCalCorr(self.n_combine, self.n_harm, self.n_cap, offset=400)
        self.lst_r0 = LSTR0Corrections(**kwargs)

        self.log.info(self.n_harm)

        self.log.info(self.extractor.window_start)
def main():
    log.setLevel(logging.INFO)
    handler = logging.StreamHandler()
    logging.getLogger().addHandler(handler)

    log.info(f'Input file: {args.input_file}')
    log.info(f'Number of events in each subrun: {args.max_events}')
    path_list = sorted(glob.glob(args.input_file))
    log.info(f'list of files: {path_list}')

    config_dic = {}
    if args.config_file is not None:
        try:
            config_dic = read_configuration_file(args.config_file)
        except ("Custom configuration could not be loaded !!!"):
            pass
    # read the configuration file
    config = Config(config_dic)

    # declare the pedestal calibrator
    lst_r0 = LSTR0Corrections(pedestal_path=args.pedestal_file, config=config)

    reader = LSTEventSource(input_url=path_list[0], max_events=args.max_events)
    # declare the time corrector
    timeCorr = TimeCorrectionCalculate(calib_file_path=args.output_file,
                                       config=config,
                                       subarray=reader.subarray)

    tel_id = timeCorr.tel_id

    for i, path in enumerate(path_list):
        log.info(f'File {i+1} out of {len(path_list)}')
        log.info(f'Processing: {path}')
        reader = LSTEventSource(input_url=path, max_events=args.max_events)
        for event in reader:
            if event.index.event_id % 5000 == 0:
                log.info(f'event id = {event.index.event_id}')
            lst_r0.calibrate(event)

            # Cut in signal to avoid cosmic events
            if event.r1.tel[tel_id].trigger_type == 4 or (np.median(
                    np.sum(event.r1.tel[tel_id].waveform[0], axis=1)) > 300):

                timeCorr.calibrate_peak_time(event)

    # write output
    timeCorr.finalize()
Пример #5
0
def main():
    print("--> Input file: {}".format(args.input_file))
    print("--> Number of events: {}".format(args.max_events))
    reader = event_source(input_url=args.input_file, max_events=args.max_events)
    print("--> Number of files", reader.multi_file.num_inputs())

    seeker = EventSeeker(reader)
    ev = seeker[0]
    tel_id = ev.r0.tels_with_data[0]
    n_modules = ev.lst.tel[tel_id].svc.num_modules

    config = Config({
        "LSTR0Corrections": {
            "tel_id": tel_id
        }
    })
    lst_r0 = LSTR0Corrections(config=config)

    pedestal = DragonPedestal(tel_id=tel_id, n_module=n_modules, r0_sample_start=args.start_r0_waveform)

    if args.deltaT:
        print("DeltaT correction active")
        for i, event in enumerate(reader):
            for tel_id in event.r0.tels_with_data:
                lst_r0.time_lapse_corr(event, tel_id)
                pedestal.fill_pedestal_event(event)
                if i%500 == 0:
                    print("i = {}, ev id = {}".format(i, event.r0.event_id))
    else:
        print("DeltaT correction no active")
        for i, event in enumerate(reader):
            pedestal.fill_pedestal_event(event)
            if i%500 == 0:
                print("i = {}, ev id = {}".format(i, event.r0.event_id))

    # Finalize pedestal and write to fits file
    pedestal.finalize_pedestal()

    primaryhdu = fits.PrimaryHDU(ev.lst.tel[tel_id].svc.pixel_ids)
    secondhdu = fits.ImageHDU(np.int16(pedestal.meanped))

    hdulist = fits.HDUList([primaryhdu, secondhdu])
    hdulist.writeto(args.output_file)
def main():
    print("--> Input file: {}".format(args.input_file))
    print("--> Number of events: {}".format(args.max_events))
    reader = event_source(input_url=args.input_file,
                          max_events=args.max_events)
    print("--> Number of files", reader.multi_file.num_inputs())

    config_dic = {}
    if args.config_file is not None:
        try:
            config_dic = read_configuration_file(args.config_file)

        except ("Custom configuration could not be loaded !!!"):
            pass
    # read the configuration file
    config = Config(config_dic)

    # declare the pedestal calibrator
    lst_r0 = LSTR0Corrections(pedestal_path=args.pedestal_file, config=config)

    # declare the time corrector
    timeCorr = TimeCorrectionCalculate(calib_file_path=args.output_file,
                                       config=config)

    tel_id = timeCorr.tel_id

    for i, event in enumerate(reader):
        if event.r0.event_id % 5000 == 0:
            print(event.r0.event_id)

        lst_r0.calibrate(event)

        # Cut in signal to avoid cosmic events
        if event.r1.tel[tel_id].trigger_type == 4 or (np.median(
                np.sum(event.r1.tel[tel_id].waveform[0], axis=1)) > 300):

            timeCorr.calibrate_pulse_time(event)
    # write output
    timeCorr.finalize()
Пример #7
0
def check_interleave_pedestal_cleaning(path_list, calib_time_file, calib_file, max_events=10000):

    signal_place_after_clean = np.zeros(1855)
    sum_ped_ev = 0
    alive_ped_ev = 0

    for path in path_list:
        print(path)
        r0_r1_calibrator = LSTR0Corrections(pedestal_path=None,
                                            r1_sample_start=3,
                                            r1_sample_end=39)

        r1_dl1_calibrator = LSTCameraCalibrator(calibration_path=calib_file,
                                                time_calibration_path=calib_time_file,
                                                extractor_product="LocalPeakWindowSum",
                                                config=charge_config,
                                                allowed_tels=[1])

        reader = LSTEventSource(input_url=path, max_events=max_events)


        for i, ev in enumerate(reader):
            r0_r1_calibrator.calibrate(ev)
            if i%10000 == 0:
                print(ev.r0.event_id)

            if ev.lst.tel[1].evt.tib_masked_trigger == 32:
                sum_ped_ev += 1

                r1_dl1_calibrator(ev)

                img = ev.dl1.tel[1].image

                geom = ev.inst.subarray.tel[1].camera
                clean = tailcuts_clean(
                                    geom,
                                    img,
                                    picture_thresh=6,
                                    boundary_thresh=3,
                                    min_number_picture_neighbors=1,
                                    keep_isolated_pixels=False
                                    )

                cleaned = img.copy()
                cleaned[~clean] = 0.0

                signal_place_after_clean[np.where(clean == True)] += 1

                if np.sum(cleaned>0) > 0:
                    alive_ped_ev += 1

    fig, ax = plt.subplots(figsize=(8, 8))
    geom = ev.inst.subarray.tel[1].camera

    disp0 = CameraDisplay(geom, ax=ax)
    disp0.image = signal_place_after_clean/sum_ped_ev
    disp0.add_colorbar(ax=ax, label="N times signal remain after cleaning")
    disp0.cmap = 'gnuplot2'
    ax.set_title("{} \n {}/{}".format(path.split("/")[-1][8:21], alive_ped_ev, sum_ped_ev))

    print(path.split("/")[-1][8:21])
    print("{}/{}".format(alive_ped_ev, sum_ped_ev))

    ax.set_xlabel(" ")
    ax.set_ylabel(" ")
    plt.tight_layout()
    plt.show()

    return signal_place_after_clean, sum_ped_ev
Пример #8
0
args = parser.parse_args()

if __name__ == '__main__':
    print("input file: {}".format(args.input_file))
    print("max events: {}".format(args.max_events))
    reader = LSTEventSource(input_url=args.input_file,
                            max_events=args.max_events)
    print("---> Number of files", reader.multi_file.num_inputs())

    seeker = EventSeeker(reader)
    ev = seeker[0]
    n_modules = ev.lst.tel[0].svc.num_modules
    telid = ev.r0.tels_with_data[0]

    config = Config({"LSTR0Corrections": {"tel_id": telid}})
    lst_r0 = LSTR0Corrections(config=config)

    ped = DragonPedestal(telid=telid)
    PedList = []
    pedestal_value_array = np.zeros((n_modules, 2, 7, 4096), dtype=np.uint16)

    for i in range(0, n_modules):
        PedList.append(DragonPedestal())

    for i, event in enumerate(reader):
        print("i = {}, ev id = {}".format(i, event.r0.event_id))
        lst_r0.time_lapse_corr(ev)
        for nr_module in range(0, n_modules):
            PedList[nr_module].fill_pedestal_event(event, nr=nr_module)

    # Finalize pedestal and write to fits file
Пример #9
0
def plot_pedestals(data_file,
                   pedestal_file,
                   run=0,
                   plot_file="none",
                   tel_id=1,
                   offset_value=400):
    """
     plot pedestal quantities quantities

     Parameters
     ----------
     data_file:   pedestal run

     pedestal_file:   file with drs4 corrections

     run: run number of data to be corrected

     plot_file:  name of output pdf file

     tel_id: id of the telescope

     offset_value: baseline off_set
     """

    # plot open pdf
    if plot_file != "none":
        pp = PdfPages(plot_file)

    plt.rc('font', size=15)

    # r0 calibrator
    r0_calib = LSTR0Corrections(pedestal_path=pedestal_file,
                                offset=offset_value,
                                tel_id=tel_id)

    # event_reader
    reader = event_source(data_file, max_events=1000)
    t = np.linspace(2, 37, 36)

    # configuration for the charge integrator
    charge_config = Config(
        {"FixedWindowSum": {
            "window_start": 12,
            "window_width": 12,
        }})
    # declare the pedestal component
    pedestal = PedestalIntegrator(tel_id=tel_id,
                                  sample_size=1000,
                                  sample_duration=1000000,
                                  charge_median_cut_outliers=[-10, 10],
                                  charge_std_cut_outliers=[-10, 10],
                                  charge_product="FixedWindowSum",
                                  config=charge_config,
                                  subarray=reader.subarray)

    for i, event in enumerate(reader):
        if tel_id != event.r0.tels_with_data[0]:
            raise Exception(
                f"Given wrong telescope id {tel_id}, files has id {event.r0.tels_with_data[0]}"
            )

        # move from R0 to R1
        r0_calib.calibrate(event)

        ok = pedestal.calculate_pedestals(event)
        if ok:
            ped_data = event.mon.tel[tel_id].pedestal
            break

    camera_geometry = reader.subarray.tels[tel_id].camera.geometry
    camera_geometry = camera_geometry.transform_to(EngineeringCameraFrame())
    # plot open pdf
    if plot_file != "none":
        pp = PdfPages(plot_file)

    plt.rc('font', size=15)

    ### first figure
    fig = plt.figure(1, figsize=(12, 24))
    plt.tight_layout()
    n_samples = charge_config["FixedWindowSum"]['window_width']
    fig.suptitle(f"Run {run}, integration on {n_samples} samples", fontsize=25)
    pad = 420

    image = ped_data.charge_median
    mask = ped_data.charge_median_outliers
    for chan in (np.arange(2)):
        pad += 1
        plt.subplot(pad)
        plt.tight_layout()
        disp = CameraDisplay(camera_geometry)
        mymin = np.median(image[chan]) - 2 * np.std(image[chan])
        mymax = np.median(image[chan]) + 2 * np.std(image[chan])
        disp.set_limits_minmax(mymin, mymax)
        disp.highlight_pixels(mask[chan], linewidth=2)
        disp.image = image[chan]
        disp.cmap = plt.cm.coolwarm
        # disp.axes.text(lposx, 0, f'{channel[chan]} pedestal [ADC]', rotation=90)
        plt.title(f'{channel[chan]} pedestal [ADC]')
        disp.add_colorbar()

    image = ped_data.charge_std
    mask = ped_data.charge_std_outliers
    for chan in (np.arange(2)):
        pad += 1
        plt.subplot(pad)
        plt.tight_layout()
        disp = CameraDisplay(camera_geometry)
        mymin = np.median(image[chan]) - 2 * np.std(image[chan])
        mymax = np.median(image[chan]) + 2 * np.std(image[chan])
        disp.set_limits_minmax(mymin, mymax)
        disp.highlight_pixels(mask[chan], linewidth=2)
        disp.image = image[chan]
        disp.cmap = plt.cm.coolwarm
        # disp.axes.text(lposx, 0, f'{channel[chan]} pedestal std [ADC]', rotation=90)
        plt.title(f'{channel[chan]} pedestal std [ADC]')
        disp.add_colorbar()

    ###  histograms
    for chan in np.arange(2):
        mean_ped = ped_data.charge_mean[chan]
        ped_std = ped_data.charge_std[chan]

        # select good pixels
        select = np.logical_not(mask[chan])

        #fig.suptitle(f"Run {run} channel: {channel[chan]}", fontsize=25)
        pad += 1
        # pedestal charge
        plt.subplot(pad)
        plt.tight_layout()
        plt.ylabel('pixels')
        plt.xlabel(f'{channel[chan]} pedestal')
        median = np.median(mean_ped[select])
        rms = np.std(mean_ped[select])
        label = f"{channel[chan]} Median {median:3.2f}, std {rms:3.2f}"
        plt.hist(mean_ped[select], bins=50, label=label)
        plt.legend()
        pad += 1
        # pedestal std
        plt.subplot(pad)
        plt.ylabel('pixels')
        plt.xlabel(f'{channel[chan]} pedestal std')
        median = np.median(ped_std[select])
        rms = np.std(ped_std[select])
        label = f" Median {median:3.2f}, std {rms:3.2f}"
        plt.hist(ped_std[select], bins=50, label=label)
        plt.legend()

    plt.subplots_adjust(top=0.94)
    if plot_file != "none":

        pp.savefig()

    pix = 0
    pad = 420
    # plot corrected waveforms of first 8 events
    for i, ev in enumerate(reader):
        for chan in np.arange(2):

            if pad == 420:
                # new figure

                fig = plt.figure(ev.index.event_id, figsize=(12, 24))
                fig.suptitle(f"Run {run}, pixel {pix}", fontsize=25)
                plt.tight_layout()
            pad += 1
            plt.subplot(pad)

            plt.subplots_adjust(top=0.92)
            label = f"event {ev.index.event_id}, {channel[chan]}: R0"
            plt.step(t,
                     ev.r0.tel[tel_id].waveform[chan, pix, 2:38],
                     color="blue",
                     label=label)

            r0_calib.subtract_pedestal(ev, tel_id)
            label = "+ pedestal substraction"
            plt.step(t,
                     ev.r1.tel[tel_id].waveform[chan, pix, 2:38],
                     color="red",
                     alpha=0.5,
                     label=label)

            r0_calib.time_lapse_corr(ev, tel_id)
            r0_calib.interpolate_spikes(ev, tel_id)
            label = "+ dt corr + interp. spikes"
            plt.step(t,
                     ev.r1.tel[tel_id].waveform[chan, pix, 2:38],
                     alpha=0.5,
                     color="green",
                     label=label)
            plt.plot([0, 40], [offset_value, offset_value],
                     'k--',
                     label="offset")
            plt.xlabel("time sample [ns]")
            plt.ylabel("counts [ADC]")
            plt.legend()
            plt.ylim([-50, 500])

        if plot_file != "none" and pad == 428:
            pad = 420
            plt.subplots_adjust(top=0.92)
            pp.savefig()

        if i == 8:
            break

    if plot_file != "none":
        pp.close()
Пример #10
0
parser.add_argument("--max_events",
                    help="Maximum numbers of events to read",
                    type=int,
                    default=5000)

args = parser.parse_args()

if __name__ == '__main__':
    print("input file: {}".format(args.input_file))
    print("max events: {}".format(args.max_events))
    reader = LSTEventSource(input_url=args.input_file,
                            max_events=args.max_events)
    print("---> Number of files", reader.multi_file.num_inputs())

    lst_r0 = LSTR0Corrections()

    seeker = EventSeeker(reader)
    ev = seeker[0]
    n_modules = ev.lst.tel[0].svc.num_modules

    ped = DragonPedestal()
    PedList = []
    pedestal_value_array = np.zeros((n_modules, 2, 7, 4096), dtype=np.uint16)

    for i in range(0, n_modules):
        PedList.append(DragonPedestal())

    for i, event in enumerate(reader):
        print("i = {}, ev id = {}".format(i, event.r0.event_id))
        lst_r0.time_lapse_corr(ev)
def main():

    print("input file: {}".format(args.input_file))
    print("output file: {}".format(args.output_file))
    print("pedestal file: {}".format(args.pedestal_file))
    print("calibration file: {}".format(args.calibration_file))
    print("max events: {}".format(args.max_events))

    # Camera geometry
    geom = CameraGeometry.from_name("LSTCam-002")

    # Definition of the output parameters for the table
    output_parameters = {
        'event_id': [],
        'ring_size': [],
        'size_outside': [],
        'ring_radius': [],
        'ring_width': [],
        'good_ring': [],
        'muon_efficiency': [],
        'ring_containment': [],
        'ring_completeness': [],
        'ring_pixel_completeness': [],
        'impact_parameter': [],
        'impact_x_array': [],
        'impact_y_array': [],
    }

    # Calibration related quantities
    r0calib = LSTR0Corrections(pedestal_path=args.pedestal_file,
                               r1_sample_start=2,
                               r1_sample_end=38)

    ff_data = FlatFieldContainer()
    cal_data = WaveformCalibrationContainer()
    ped_data = PedestalContainer()

    dc_to_pe = []
    ped_median = []

    if (args.run_number >
            500):  #  Not sure where did the tel definition change
        with HDF5TableReader(args.calibration_file) as h5_table:
            assert h5_table._h5file.isopen == True
            for cont in h5_table.read('/tel_1/pedestal', ped_data):
                ped_median = cont.charge_median

            for calib in h5_table.read('/tel_1/calibration', cal_data):
                dc_to_pe = calib['dc_to_pe']
        h5_table.close()

    else:
        with HDF5TableReader(args.calibration_file) as h5_table:
            assert h5_table._h5file.isopen == True
            for cont in h5_table.read('/tel_0/pedestal', ped_data):
                ped_median = cont.charge_median

            for calib in h5_table.read('/tel_0/calibration', cal_data):
                dc_to_pe = calib['dc_to_pe']
        h5_table.close()

    # Maximum number of events
    if (args.max_events):
        max_events = args.max_events
    else:
        max_events = None

    # File open
    num_muons = 0
    source = event_source(input_url=args.input_file, max_events=max_events)
    for event in source:
        r0calib.calibrate(event)
        #  Not sure where did the tel definition change
        #  but we moved to tel[0] to tel[1] at some point
        #  of the commissioning period
        if (args.run_number > 500):
            event_id = event.lst.tel[1].evt.event_id
            telescope_description = event.inst.subarray.tel[1]
            pedcorrectedsamples = event.r1.tel[1].waveform
        else:
            event_id = event.lst.tel[0].evt.event_id
            telescope_description = event.inst.subarray.tel[0]
            pedcorrectedsamples = event.r1.tel[0].waveform
        integrator = LocalPeakWindowSum(window_shift=4, window_width=9)
        integration, pulse_time = integrator(pedcorrectedsamples)
        image = (integration - ped_median) * dc_to_pe

        # WARNING!!!
        # The current analysis is not performed using gain selection
        # image[0] is the extracted image from low gain.

        print("Event {}. Number of pixels above 10 phe: {}".format(
            event_id, np.size(image[0][image[0] > 10.])))

        if not tag_pix_thr(
                image[0]):  #default skipps pedestal and calibration events
            continue

        if not muon_filter(image[0]):  #default values apply no filtering
            continue

        equivalent_focal_length = telescope_description.optics.equivalent_focal_length
        mirror_area = telescope_description.optics.mirror_area.to("m2")

        muonintensityparam, size_outside_ring, muonringparam, good_ring = \
            analyze_muon_event(event_id, image[0], geom, equivalent_focal_length,
                               mirror_area, args.plot_rings, args.plots_path)
        #if not (good_ring):
        #    continue
        print("Number of muons found {}, EventID {}".format(
            num_muons, event_id))

        num_muons = num_muons + 1

        output_parameters['event_id'].append(event_id)
        output_parameters['ring_size'].append(muonintensityparam.ring_size)
        output_parameters['size_outside'].append(size_outside_ring)
        output_parameters['ring_radius'].append(
            muonringparam.ring_radius.value)
        output_parameters['ring_width'].append(
            muonintensityparam.ring_width.value)
        output_parameters['good_ring'].append(good_ring)
        output_parameters['muon_efficiency'].append(
            muonintensityparam.optical_efficiency_muon)
        output_parameters['ring_containment'].append(
            muonringparam.ring_containment)
        output_parameters['ring_completeness'].append(
            muonintensityparam.ring_completeness)
        output_parameters['ring_pixel_completeness'].append(
            muonintensityparam.ring_pix_completeness)
        output_parameters['impact_parameter'].append(
            muonintensityparam.impact_parameter.value)
        output_parameters['impact_x_array'].append(
            muonintensityparam.impact_parameter_pos_x.value)
        output_parameters['impact_y_array'].append(
            muonintensityparam.impact_parameter_pos_y.value)

    table = Table(output_parameters)
    if os.path.exists(args.output_file):
        os.remove(args.output_file)
    table.write(args.output_file, format='fits')
def main():

    print("input file: {}".format(args.input_file))
    print("output file: {}".format(args.output_file))
    print("pedestal file: {}".format(args.pedestal_file))
    print("calibration file: {}".format(args.calibration_file))
    print("time calibration file: {}".format(args.time_calibration_file))
    print("max events: {}".format(args.max_events))

    # Camera geometry
    #geom = CameraGeometry.from_name("LSTCam-003")

    # Definition of the output parameters for the table
    output_parameters = {
        'event_id': [],
        'ring_size': [],
        'size_outside': [],
        'ring_radius': [],
        'ring_width': [],
        'good_ring': [],
        'muon_efficiency': [],
        'ring_containment': [],
        'ring_completeness': [],
        'ring_pixel_completeness': [],
        'impact_parameter': [],
        'impact_x_array': [],
        'impact_y_array': [],
    }

    tel_id = args.tel_id

    # Low level calibration
    r0calib = LSTR0Corrections(pedestal_path=args.pedestal_file, tel_id=tel_id)

    # high level calibration and gain selection
    charge_config = Config(
        {"LocalPeakWindowSum": {
            "window_shift": 4,
            "window_width": 8
        }})

    r1_dl1_calibrator = LSTCameraCalibrator(
        calibration_path=args.calibration_file,
        time_calibration_path=args.time_calibration_file,
        image_extractor="LocalPeakWindowSum",
        config=charge_config,
        gain_threshold=args.gain_threshold,
        allowed_tels=[tel_id])

    # Maximum number of events
    if args.max_events:
        max_events = args.max_events
    else:
        max_events = None

    # File open
    num_muons = 0
    source = event_source(input_url=args.input_file, max_events=max_events)

    # geometry
    subarray = source.subarray(tel_id)
    telescope_description = subarray.tel[tel_id]
    equivalent_focal_length = telescope_description.optics.equivalent_focal_length
    mirror_area = telescope_description.optics.mirror_area.to("m2")
    geom = telescope_description.camera

    for event in source:
        event_id = event.lst.tel[tel_id].evt.event_id

        # drs4 calibration
        r0calib.calibrate(event)

        # r1 calibration
        r1_dl1_calibrator(event)
        image = event.dl1.tel[tel_id].image

        if not tag_pix_thr(
                image):  #default skipps pedestal and calibration events
            continue

        if not muon_filter(image, 800,
                           5000):  #default values apply no filtering
            continue

        print("--> Event {}. Number of pixels above 10 phe: {}".format(
            event_id, np.size(image[image > 10.])))


        muonintensityparam, size_outside_ring, muonringparam, good_ring = \
            analyze_muon_event(event_id, image, geom, equivalent_focal_length,
                               mirror_area, args.plot_rings, args.plots_path)
        #if not (good_ring):
        #    continue
        print("Number of muons found {}, EventID {}".format(
            num_muons, event_id))

        num_muons = num_muons + 1

        output_parameters['event_id'].append(event_id)
        output_parameters['ring_size'].append(muonintensityparam.ring_size)
        output_parameters['size_outside'].append(size_outside_ring)
        output_parameters['ring_radius'].append(
            muonringparam.ring_radius.value)
        output_parameters['ring_width'].append(
            muonintensityparam.ring_width.value)
        output_parameters['good_ring'].append(good_ring)
        output_parameters['muon_efficiency'].append(
            muonintensityparam.optical_efficiency_muon)
        output_parameters['ring_containment'].append(
            muonringparam.ring_containment)
        output_parameters['ring_completeness'].append(
            muonintensityparam.ring_completeness)
        output_parameters['ring_pixel_completeness'].append(
            muonintensityparam.ring_pix_completeness)
        output_parameters['impact_parameter'].append(
            muonintensityparam.impact_parameter.value)
        output_parameters['impact_x_array'].append(
            muonintensityparam.impact_parameter_pos_x.value)
        output_parameters['impact_y_array'].append(
            muonintensityparam.impact_parameter_pos_y.value)

    table = Table(output_parameters)
    if os.path.exists(args.output_file):
        os.remove(args.output_file)
    table.write(args.output_file, format='fits')