Exemple #1
0
def test_binned_fit():
    with within_directory(datasets_dir):
        start, stop = 0, 50

        poly = [1]

        arrival_times = np.loadtxt('test_event_data.txt')

        evt_list = EventListWithDeadTime(
            arrival_times=arrival_times,
            measurement=np.zeros_like(arrival_times),
            n_channels=1,
            start_time=arrival_times[0],
            stop_time=arrival_times[-1],
            dead_time=np.zeros_like(arrival_times))

        evt_list.set_polynomial_fit_interval("%f-%f" % (start + 1, stop - 1),
                                             unbinned=False)

        evt_list.set_active_time_intervals("0-1")

        results = evt_list.get_poly_info()['coefficients']

        assert evt_list.time_intervals == TimeIntervalSet.from_list_of_edges(
            [0, 1])

        assert evt_list._poly_counts.sum() > 0

        evt_list.__repr__()
Exemple #2
0
def test_unbinned_fit(event_time_series):

    start, stop = 0, 50

    poly = [1]

    arrival_times = event_time_series

    evt_list = EventListWithDeadTime(
        arrival_times=arrival_times,
        measurement=np.zeros_like(arrival_times),
        n_channels=1,
        start_time=arrival_times[0],
        stop_time=arrival_times[-1],
        dead_time=np.zeros_like(arrival_times),
    )

    evt_list.set_polynomial_fit_interval("%f-%f" % (start + 1, stop - 1),
                                         unbinned=True)

    results = evt_list.get_poly_info()["coefficients"]

    evt_list.set_active_time_intervals("0-1")

    assert evt_list.time_intervals == TimeIntervalSet.from_list_of_edges(
        [0, 1])

    assert evt_list._poly_counts.sum() > 0

    evt_list.__repr__()
Exemple #3
0
def test_binned_fit():
    with within_directory(datasets_dir):
        start, stop = 0, 50

        poly = [1]

        arrival_times = np.loadtxt('test_event_data.txt')

        evt_list = EventListWithDeadTime(arrival_times=arrival_times,
                                         measurement=np.zeros_like(arrival_times),
                                         n_channels=1,
                                         start_time=arrival_times[0],
                                         stop_time=arrival_times[-1],
                                         dead_time=np.zeros_like(arrival_times)
                                         )

        evt_list.set_polynomial_fit_interval("%f-%f" % (start + 1, stop - 1), unbinned=False)

        evt_list.set_active_time_intervals("0-1")

        results = evt_list.get_poly_info()['coefficients']

        assert evt_list.time_intervals == TimeIntervalSet.from_list_of_edges([0,1])


        assert evt_list._poly_counts.sum() > 0

        evt_list.__repr__()
Exemple #4
0
    def _set_plugins(self):
        """
        Set the plugins using the saved background hdf5 files
        :return:
        """

        det_ts = []
        det_rsp = []

        for det in self._use_dets:

            # set up responses
            tte_file = f"{base_dir}/{self._grb_name}/tte/data/glg_tte_{det}_bn{self._grb_name[3:]}_{self._version}.fit"
            cspec_file = f"{base_dir}/{self._grb_name}/tte/data/glg_cspec_{det}_bn{self._grb_name[3:]}_{self._version}.pha"

            rsp = drm.DRMGenTTE(tte_file=tte_file,
                                trigdat=self._trigdat_file,
                                mat_type=2,
                                cspecfile=cspec_file,
                                occult=True)

            det_rsp.append(rsp)

            # Time Series
            gbm_tte_file = GBMTTEFile(tte_file)

            event_list = EventListWithDeadTime(
                arrival_times=gbm_tte_file.arrival_times -
                gbm_tte_file.trigger_time,
                measurement=gbm_tte_file.energies,
                n_channels=gbm_tte_file.n_channels,
                start_time=gbm_tte_file.tstart - gbm_tte_file.trigger_time,
                stop_time=gbm_tte_file.tstop - gbm_tte_file.trigger_time,
                dead_time=gbm_tte_file.deadtime,
                first_channel=0,
                instrument=gbm_tte_file.det_name,
                mission=gbm_tte_file.mission,
                verbose=True,
            )

            success_restore = False
            i = 0
            while not success_restore:
                try:
                    ts = TimeSeriesBuilder(
                        det,
                        event_list,
                        response=BALROG_DRM(rsp, 0.0, 0.0),
                        unbinned=False,
                        verbose=True,
                        container_type=BinnedSpectrumWithDispersion,
                        restore_poly_fit=self._bkg_fit_files[det],
                    )

                    success_restore = True
                    i = 0
                except:
                    time.sleep(1)
                i += 1
                if i == 50:
                    raise AssertionError("Can not restore background fit...")

            ts.set_active_time_interval(
                f"{self._active_time_start}-{self._active_time_stop}")
            det_ts.append(ts)

        # Mean of active time
        rsp_time = (float(self._active_time_start) +
                    float(self._active_time_stop)) / 2

        # Spectrum Like
        det_sl = []
        # set up energy range
        for series in det_ts:
            if series._name != "b0" and series._name != "b1":
                sl = series.to_spectrumlike()
                sl.set_active_measurements("8.1-700")
                det_sl.append(sl)
            else:
                sl = series.to_spectrumlike()
                sl.set_active_measurements("350-25000")
                det_sl.append(sl)

        # Make Balrog Like
        det_bl = []
        for i, det in enumerate(self._use_dets):
            det_bl.append(
                drm.BALROGLike.from_spectrumlike(det_sl[i],
                                                 rsp_time,
                                                 det_rsp[i],
                                                 free_position=True))

        self._data_list = DataList(*det_bl)
    def from_gbm_tte(cls,
                     name,
                     tte_file,
                     rsp_file,
                     restore_background=None,
                     trigger_time=None,
                     poly_order=-1,
                     unbinned=True,
                     verbose=True):
        """
           A plugin to natively bin, view, and handle Fermi GBM TTE data.
           A TTE event file are required as well as the associated response



           Background selections are specified as
           a comma separated string e.g. "-10-0,10-20"

           Initial source selection is input as a string e.g. "0-5"

           One can choose a background polynomial order by hand (up to 4th order)
           or leave it as the default polyorder=-1 to decide by LRT test

           :param name: name for your choosing
           :param tte_file: GBM tte event file
           :param rsp_file: Associated TTE CSPEC response file
           :param trigger_time: trigger time if needed
           :param poly_order: 0-4 or -1 for auto
           :param unbinned: unbinned likelihood fit (bool)
           :param verbose: verbose (bool)



               """

        # self._default_unbinned = unbinned

        # Load the relevant information from the TTE file

        gbm_tte_file = GBMTTEFile(tte_file)

        # Set a trigger time if one has not been set

        if trigger_time is not None:
            gbm_tte_file.trigger_time = trigger_time

        # Create the the event list

        event_list = EventListWithDeadTime(
            arrival_times=gbm_tte_file.arrival_times -
            gbm_tte_file.trigger_time,
            measurement=gbm_tte_file.energies,
            n_channels=gbm_tte_file.n_channels,
            start_time=gbm_tte_file.tstart - gbm_tte_file.trigger_time,
            stop_time=gbm_tte_file.tstop - gbm_tte_file.trigger_time,
            dead_time=gbm_tte_file.deadtime,
            first_channel=0,
            instrument=gbm_tte_file.det_name,
            mission=gbm_tte_file.mission,
            verbose=verbose,
        )

        if isinstance(rsp_file, str) or isinstance(rsp_file, unicode):

            # we need to see if this is an RSP2

            test = re.match('^.*\.rsp2$', rsp_file)

            # some GBM RSPs that are not marked RSP2 are in fact RSP2s
            # we need to check

            if test is None:

                with fits.open(rsp_file) as f:

                    # there should only be a header, ebounds and one spec rsp extension

                    if len(f) > 3:

                        # make test a dummy value to trigger the nest loop

                        test = -1

                        custom_warnings.warn(
                            'The RSP file is marked as a single response but in fact has multiple matrices. We will treat it as an RSP2'
                        )

            if test is not None:

                rsp = InstrumentResponseSet.from_rsp2_file(
                    rsp2_file=rsp_file,
                    counts_getter=event_list.counts_over_interval,
                    exposure_getter=event_list.exposure_over_interval,
                    reference_time=gbm_tte_file.trigger_time)

            else:

                rsp = OGIPResponse(rsp_file)

        else:

            assert isinstance(
                rsp_file, InstrumentResponse
            ), 'The provided response is not a 3ML InstrumentResponse'
            rsp = rsp_file

        # pass to the super class

        return cls(name,
                   event_list,
                   response=rsp,
                   poly_order=poly_order,
                   unbinned=unbinned,
                   verbose=verbose,
                   restore_poly_fit=restore_background,
                   container_type=BinnedSpectrumWithDispersion)
Exemple #6
0
    def _build_bkg_plugins(self):
        """
        Build the background plugins for all dets
        :return:
        """
        # Time selection from yaml file
        with open(self._time_selection_file_path, "r") as f:
            data = yaml.safe_load(f)

            active_time = (
                f"{data['active_time']['start']}-{data['active_time']['stop']}"
            )
            background_time_neg = f"{data['background_time']['before']['start']}-{data['background_time']['before']['stop']}"
            background_time_pos = f"{data['background_time']['after']['start']}-{data['background_time']['after']['stop']}"
            poly_order = data["poly_order"]

        det_ts = []

        for det in _gbm_detectors:
            # Response Setup

            rsp = BALROG_DRM(
                drm.DRMGenTTE(
                    tte_file=self._tte_files[det],
                    trigdat=self._trigdat_file,
                    mat_type=2,
                    cspecfile=self._cspec_files[det],
                ),
                0.0,
                0.0,
            )

            # Time Series
            gbm_tte_file = GBMTTEFile(self._tte_files[det])
            event_list = EventListWithDeadTime(
                arrival_times=gbm_tte_file.arrival_times -
                gbm_tte_file.trigger_time,
                measurement=gbm_tte_file.energies,
                n_channels=gbm_tte_file.n_channels,
                start_time=gbm_tte_file.tstart - gbm_tte_file.trigger_time,
                stop_time=gbm_tte_file.tstop - gbm_tte_file.trigger_time,
                dead_time=gbm_tte_file.deadtime,
                first_channel=0,
                instrument=gbm_tte_file.det_name,
                mission=gbm_tte_file.mission,
                verbose=True,
            )

            ts = TimeSeriesBuilder(
                det,
                event_list,
                response=rsp,
                poly_order=poly_order,
                unbinned=False,
                verbose=True,
                container_type=BinnedSpectrumWithDispersion,
            )

            ts.set_background_interval(background_time_neg,
                                       background_time_pos)
            ts.set_active_time_interval(active_time)
            det_ts.append(ts)

        self._ts = det_ts