Ejemplo n.º 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__()
Ejemplo n.º 2
0
def test_pha_write_no_bkg():
    with within_directory(__example_dir):

        # custom remove background
        f = fits.open("test.pha")
        f["SPECTRUM"].data["BACKFILE"] = "NONE"
        f.writeto("test_pha_nobkg.pha", overwrite=True)

        ogip = OGIPLike("test_ogip", observation="test_pha_nobkg.pha{1}")

        ogip.write_pha("test_write_nobkg", overwrite=True)

        written_ogip = OGIPLike("write_ogip", observation="test_write_nobkg.pha{1}")

        pha_info = written_ogip.get_pha_files()

        for key in ["pha"]:
            assert isinstance(pha_info[key], PHASpectrum)

        f = fits.open("test_write_nobkg.pha")
        assert f["SPECTRUM"].data["BACKFILE"][0] == "NONE"

        assert pha_info["pha"].background_file is None
        assert pha_info["pha"].ancillary_file is None
        assert pha_info["pha"].instrument == "GBM_NAI_03"
        assert pha_info["pha"].mission == "GLAST"
        assert pha_info["pha"].is_poisson == True
        assert pha_info["pha"].n_channels == len(pha_info["pha"].rates)
Ejemplo n.º 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__()
Ejemplo n.º 4
0
def test_read_gbm_cspec():
    with within_directory(datasets_directory):
        data_dir = os.path.join('gbm', 'bn080916009')

        nai3 = TimeSeriesBuilder.from_gbm_cspec_or_ctime('NAI3',
                                                         os.path.join(data_dir, "glg_cspec_n3_bn080916009_v01.pha"),
                                                         rsp_file=os.path.join(data_dir,
                                                                               "glg_cspec_n3_bn080916009_v00.rsp2"),
                                                         poly_order=-1)
        
        nai3.set_active_time_interval('0-1')
        
        assert not nai3.time_series.poly_fit_exists

        assert nai3.time_series.binned_spectrum_set.n_channels>0

        nai3.set_background_interval('-20--10', '100-200')

        assert nai3.time_series.poly_fit_exists


        speclike = nai3.to_spectrumlike()

        assert isinstance(speclike, DispersionSpectrumLike)

        assert not speclike.background_spectrum.is_poisson

        speclike = nai3.to_spectrumlike(extract_measured_background=True)

        assert isinstance(speclike, DispersionSpectrumLike)

        assert speclike.background_spectrum.is_poisson

        nai3.write_pha_from_binner('test_from_nai3', start=0, stop=2, overwrite=True)
Ejemplo n.º 5
0
def test_read_gbm_cspec():
    with within_directory(datasets_directory):
        data_dir = os.path.join('gbm', 'bn080916009')

        nai3 = TimeSeriesBuilder.from_gbm_cspec_or_ctime('NAI3',
                                                         os.path.join(data_dir, "glg_cspec_n3_bn080916009_v01.pha"),
                                                         rsp_file=os.path.join(data_dir,
                                                                               "glg_cspec_n3_bn080916009_v00.rsp2"),
                                                         poly_order=-1)
        
        nai3.set_active_time_interval('0-1')
        
        assert not nai3.time_series.poly_fit_exists

        assert nai3.time_series.binned_spectrum_set.n_channels>0

        nai3.set_background_interval('-20--10', '100-200')

        assert nai3.time_series.poly_fit_exists


        speclike = nai3.to_spectrumlike()

        assert isinstance(speclike, DispersionSpectrumLike)

        assert not speclike.background_spectrum.is_poisson

        speclike = nai3.to_spectrumlike(extract_measured_background=True)

        assert isinstance(speclike, DispersionSpectrumLike)

        assert speclike.background_spectrum.is_poisson

        nai3.write_pha_from_binner('test_from_nai3', start=0, stop=2, overwrite=True)
Ejemplo n.º 6
0
def test_various_effective_area():
    with within_directory(__example_dir):
        ogip = OGIPLike("test_ogip", observation="test.pha{1}")

        ogip.use_effective_area_correction()

        ogip.fix_effective_area_correction()
Ejemplo n.º 7
0
def test_loading_xrt():

    with within_directory(datasets_dir):

        xrt_dir = 'xrt'
        xrt = SwiftXRTLike("XRT", observation=os.path.join(xrt_dir, "xrt_src.pha"),
                           background=os.path.join(xrt_dir, "xrt_bkg.pha"),
                           response=os.path.join(xrt_dir, "xrt.rmf"),
                           arf_file=os.path.join(xrt_dir, "xrt.arf"))
Ejemplo n.º 8
0
def test_simulating_data_sets():
    with within_directory(__example_dir):

        ogip = OGIPLike('test_ogip', observation='test.pha{1}')

        with pytest.raises(AssertionError):
            _ = ogip.simulated_parameters

        n_data_points = 128
        ogip.set_active_measurements("all")

        assert ogip._n_synthetic_datasets == 0

        ab = AnalysisBuilder(ogip)
        _ = ab.get_jl('normal')

        new_ogip = ogip.get_simulated_dataset('sim')

        assert new_ogip.name == 'sim'
        assert ogip._n_synthetic_datasets == 1
        assert new_ogip.n_data_points == n_data_points

        assert new_ogip.n_data_points == sum(new_ogip._mask)
        assert sum(new_ogip._mask) == new_ogip.n_data_points
        assert new_ogip.tstart == 0.

        assert 'cons_sim' in new_ogip.nuisance_parameters
        assert new_ogip.nuisance_parameters['cons_sim'].fix == True
        assert new_ogip.nuisance_parameters['cons_sim'].free == False

        pha_info = new_ogip.get_pha_files()

        assert 'pha' in pha_info
        assert 'bak' in pha_info
        assert 'rsp' in pha_info

        del ogip
        del new_ogip

        ogip = OGIPLike('test_ogip', observation='test.pha{1}')

        ab = AnalysisBuilder(ogip)
        _ = ab.get_jl('normal')

        # Now check that generationing a lot of data sets works

        sim_data_sets = [
            ogip.get_simulated_dataset('sim%d' % i) for i in range(100)
        ]

        assert len(sim_data_sets) == ogip._n_synthetic_datasets

        for i, ds in enumerate(sim_data_sets):

            assert ds.name == "sim%d" % i
            assert sum(ds._mask) == sum(ogip._mask)
            assert ds._rebinner is None
Ejemplo n.º 9
0
def test_loading_xrt():

    with within_directory(datasets_dir):

        xrt_dir = 'xrt'
        xrt = SwiftXRTLike("XRT",
                           observation=os.path.join(xrt_dir, "xrt_src.pha"),
                           background=os.path.join(xrt_dir, "xrt_bkg.pha"),
                           response=os.path.join(xrt_dir, "xrt.rmf"),
                           arf_file=os.path.join(xrt_dir, "xrt.arf"))
Ejemplo n.º 10
0
def test_loading_bad_keywords_file():

    with within_directory(__example_dir):
        pha_fn = "example_integral_spi.pha"
        rsp_fn = "example_integral_spi.rsp"

        pha_spectrum = PHASpectrum(pha_fn, rsp_file=rsp_fn)

        assert type(pha_spectrum.is_poisson) == bool

        ogip = OGIPLike("test_ogip", observation=pha_fn, response=rsp_fn)
        ogip.__repr__()
Ejemplo n.º 11
0
def test_swift_gbm():
    with within_directory(__example_dir):
        gbm_dir = "gbm"
        bat_dir = "bat"

        bat = OGIPLike(
            "BAT",
            observation=os.path.join(bat_dir, "gbm_bat_joint_BAT.pha"),
            response=os.path.join(bat_dir, "gbm_bat_joint_BAT.rsp"),
        )

        bat.set_active_measurements("15-150")
        bat.view_count_spectrum()

        nai6 = OGIPLike(
            "n6",
            os.path.join(gbm_dir, "gbm_bat_joint_NAI_06.pha"),
            os.path.join(gbm_dir, "gbm_bat_joint_NAI_06.bak"),
            os.path.join(gbm_dir, "gbm_bat_joint_NAI_06.rsp"),
            spectrum_number=1,
        )

        nai6.set_active_measurements("8-900")
        nai6.view_count_spectrum()

        bgo0 = OGIPLike(
            "b0",
            os.path.join(gbm_dir, "gbm_bat_joint_BGO_00.pha"),
            os.path.join(gbm_dir, "gbm_bat_joint_BGO_00.bak"),
            os.path.join(gbm_dir, "gbm_bat_joint_BGO_00.rsp"),
            spectrum_number=1,
        )

        bgo0.set_active_measurements("250-10000")
        bgo0.view_count_spectrum()

        bat.use_effective_area_correction(0.2, 1.5)
        bat.fix_effective_area_correction(0.6)
        bat.use_effective_area_correction(0.2, 1.5)

        band = Band()
        model = Model(PointSource("joint_fit", 0, 0, spectral_shape=band))

        band.K = 0.04
        band.xp = 300.0

        data_list = DataList(bat, nai6, bgo0)

        jl = JointLikelihood(model, data_list)

        _ = jl.fit()

        _ = display_spectrum_model_counts(jl, step=False)
Ejemplo n.º 12
0
def test_reading_of_written_pha():
    with within_directory(datasets_directory):
        # check the number of items written

        with fits.open('test_from_nai3.rsp') as f:
            # 2 ext + 5 rsp ext
            assert len(f) == 7

        # make sure we can read spectrum number

        _ = OGIPLike('test', observation='test_from_nai3.pha', spectrum_number=1)
        _ = OGIPLike('test', observation='test_from_nai3.pha', spectrum_number=2)

        os.remove('test_from_nai3.pha')
Ejemplo n.º 13
0
def test_reading_of_written_pha():
    with within_directory(datasets_directory):
        # check the number of items written

        with fits.open('test_from_nai3.rsp') as f:
            # 2 ext + 5 rsp ext
            assert len(f) == 7

        # make sure we can read spectrum number

        _ = OGIPLike('test', observation='test_from_nai3.pha', spectrum_number=1)
        _ = OGIPLike('test', observation='test_from_nai3.pha', spectrum_number=2)

        os.remove('test_from_nai3.pha')
Ejemplo n.º 14
0
def test_ogip_energy_selection():
    with within_directory(__example_dir):
        ogip = OGIPLike("test_ogip", observation="test.pha{1}")

        assert sum(ogip._mask) == sum(ogip.quality.good)

        # Test that  selecting a subset reduces the number of data points
        ogip.set_active_measurements("10-30")

        assert sum(ogip._mask) == ogip.n_data_points
        assert sum(ogip._mask) < 128

        # Test selecting all channels
        ogip.set_active_measurements("all")

        assert sum(ogip._mask) == ogip.n_data_points
        assert sum(ogip._mask) == 128

        # Test channel setting
        ogip.set_active_measurements(exclude=["c0-c1"])

        assert sum(ogip._mask) == ogip.n_data_points
        assert sum(ogip._mask) == 126

        # Test mixed ene/chan setting
        ogip.set_active_measurements(exclude=["0-c1"], verbose=True)

        assert sum(ogip._mask) == ogip.n_data_points
        assert sum(ogip._mask) == 126

        # Test that energies cannot be input backwards
        with pytest.raises(AssertionError):
            ogip.set_active_measurements("50-30")

        with pytest.raises(AssertionError):
            ogip.set_active_measurements("c20-c10")

        with pytest.raises(AssertionError):
            ogip.set_active_measurements("c100-0")

        with pytest.raises(AssertionError):
            ogip.set_active_measurements("c1-c200")

        with pytest.raises(AssertionError):
            ogip.set_active_measurements("10-c200")

        ogip.set_active_measurements("reset")

        assert sum(ogip._mask) == sum(ogip.quality.good)
Ejemplo n.º 15
0
def test_swift_gbm():
    with within_directory(__example_dir):
        gbm_dir = "gbm"
        bat_dir = "bat"

        bat = OGIPLike('BAT',
                       observation=os.path.join(bat_dir,
                                                'gbm_bat_joint_BAT.pha'),
                       response=os.path.join(bat_dir, 'gbm_bat_joint_BAT.rsp'))

        bat.set_active_measurements('15-150')
        bat.view_count_spectrum()

        nai6 = OGIPLike('n6',
                        os.path.join(gbm_dir, 'gbm_bat_joint_NAI_06.pha'),
                        os.path.join(gbm_dir, 'gbm_bat_joint_NAI_06.bak'),
                        os.path.join(gbm_dir, 'gbm_bat_joint_NAI_06.rsp'),
                        spectrum_number=1)

        nai6.set_active_measurements('8-900')
        nai6.view_count_spectrum()

        bgo0 = OGIPLike('b0',
                        os.path.join(gbm_dir, 'gbm_bat_joint_BGO_00.pha'),
                        os.path.join(gbm_dir, 'gbm_bat_joint_BGO_00.bak'),
                        os.path.join(gbm_dir, 'gbm_bat_joint_BGO_00.rsp'),
                        spectrum_number=1)

        bgo0.set_active_measurements('250-10000')
        bgo0.view_count_spectrum()

        bat.use_effective_area_correction(.2, 1.5)
        bat.fix_effective_area_correction(.6)
        bat.use_effective_area_correction(.2, 1.5)

        band = Band()
        model = Model(PointSource('joint_fit', 0, 0, spectral_shape=band))

        band.K = .04
        band.xp = 300.

        data_list = DataList(bat, nai6, bgo0)

        jl = JointLikelihood(model, data_list)

        _ = jl.fit()

        _ = display_spectrum_model_counts(jl, step=False)
Ejemplo n.º 16
0
def test_read_lle():
    with within_directory(datasets_directory):
        data_dir = "lat"

        lle = TimeSeriesBuilder.from_lat_lle(
            "lle",
            os.path.join(data_dir, "gll_lle_bn080916009_v10.fit"),
            os.path.join(data_dir, "gll_pt_bn080916009_v10.fit"),
            rsp_file=os.path.join(data_dir, "gll_cspec_bn080916009_v10.rsp"),
            poly_order=-1,
        )

        lle.view_lightcurve()

        lle.set_active_time_interval("0-10")

        lle.set_background_interval("-150-0", "100-250", unbinned=False)

        speclike = lle.to_spectrumlike()

        assert isinstance(speclike, DispersionSpectrumLike)

        # will test background with lle data

        old_coefficients, old_errors = lle.get_background_parameters()

        old_tmin_list = lle._time_series.poly_intervals

        lle.save_background("temp_lle", overwrite=True)

        lle = TimeSeriesBuilder.from_lat_lle(
            "lle",
            os.path.join(data_dir, "gll_lle_bn080916009_v10.fit"),
            os.path.join(data_dir, "gll_pt_bn080916009_v10.fit"),
            rsp_file=os.path.join(data_dir, "gll_cspec_bn080916009_v10.rsp"),
            restore_background="temp_lle.h5",
        )

        new_coefficients, new_errors = lle.get_background_parameters()

        new_tmin_list = lle._time_series.poly_intervals

        assert new_coefficients == old_coefficients

        assert new_errors == old_errors

        assert old_tmin_list == new_tmin_list
Ejemplo n.º 17
0
def test_read_gbm_cspec():
    with within_directory(datasets_directory):
        data_dir = os.path.join('gbm', 'bn080916009')

        nai3 = TimeSeriesBuilder.from_gbm_cspec_or_ctime('NAI3',
                                                         os.path.join(data_dir, "glg_cspec_n3_bn080916009_v01.pha"),
                                                         rsp_file=os.path.join(data_dir,
                                                                               "glg_cspec_n3_bn080916009_v00.rsp2"),
                                                         poly_order=-1)

        nai3.set_active_time_interval('0-1')
        nai3.set_background_interval('-200--10', '100-200')

        speclike = nai3.to_spectrumlike()

        assert isinstance(speclike, DispersionSpectrumLike)

        nai3.write_pha_from_binner('test_from_nai3', start=0, stop=2, overwrite=True)
Ejemplo n.º 18
0
def test_likelihood_ratio_test():
    with within_directory(__example_dir):
        ogip = OGIPLike('test_ogip', observation='test.pha{1}')

        ogip.set_active_measurements("all")

        ab = AnalysisBuilder(ogip)

        jl1 = ab.get_jl('normal')

        res1, _ = jl1.fit(compute_covariance=True)

        jl2 = ab.get_jl('cpl')
        res2, _ = jl2.fit(compute_covariance=True)

    lrt = LikelihoodRatioTest(jl1, jl2)

    null_hyp_prob, TS, data_frame, like_data_frame = lrt.by_mc(
        n_iterations=50, continue_on_failure=True)
Ejemplo n.º 19
0
def test_read_lle():
    with within_directory(datasets_directory):
        data_dir = 'lat'

        lle = TimeSeriesBuilder.from_lat_lle('lle', os.path.join(data_dir, "gll_lle_bn080916009_v10.fit"),
                                             os.path.join(data_dir, "gll_pt_bn080916009_v10.fit"),
                                             rsp_file=os.path.join(data_dir, "gll_cspec_bn080916009_v10.rsp"),
                                             poly_order=-1)

        lle.view_lightcurve()

        lle.set_active_time_interval("0-10")

        lle.set_background_interval("-150-0", "100-250")

        speclike = lle.to_spectrumlike()

        assert isinstance(speclike, DispersionSpectrumLike)

        # will test background with lle data


        old_coefficients, old_errors = lle.get_background_parameters()

        old_tmin_list = lle._time_series.poly_intervals

        lle.save_background('temp_lle', overwrite=True)

        lle = TimeSeriesBuilder.from_lat_lle('lle', os.path.join(data_dir, "gll_lle_bn080916009_v10.fit"),
                                             os.path.join(data_dir, "gll_pt_bn080916009_v10.fit"),
                                             rsp_file=os.path.join(data_dir, "gll_cspec_bn080916009_v10.rsp"),
                                             restore_background='temp_lle.h5')

        new_coefficients, new_errors = lle.get_background_parameters()

        new_tmin_list = lle._time_series.poly_intervals

        assert new_coefficients == old_coefficients

        assert new_errors == old_errors

        assert old_tmin_list == new_tmin_list
Ejemplo n.º 20
0
def test_xrt():
    with within_directory(__example_dir):
        trigger = "GRB110731A"
        dec = -28.546
        ra = 280.52
        xrt_dir = 'xrt'
        xrt = SwiftXRTLike("XRT",
                           observation=os.path.join(xrt_dir, "xrt_src.pha"),
                           background=os.path.join(xrt_dir, "xrt_bkg.pha"),
                           response=os.path.join(xrt_dir, "xrt.rmf"),
                           arf_file=os.path.join(xrt_dir, "xrt.arf"))

        spectral_model = Powerlaw()

        ptsrc = PointSource(trigger, ra, dec, spectral_shape=spectral_model)
        model = Model(ptsrc)

        data = DataList(xrt)

        jl = JointLikelihood(model, data, verbose=False)
Ejemplo n.º 21
0
def test_loading_a_generic_pha_file():

    with within_directory(__example_dir):
        ogip = OGIPLike('test_ogip', observation='test.pha{1}')

        pha_info = ogip.get_pha_files()

        assert ogip.name == 'test_ogip'
        assert ogip.n_data_points == sum(ogip._mask)
        assert sum(ogip._mask) == ogip.n_data_points
        assert ogip.tstart == 0.
        assert ogip.tstop == 9.95012
        assert 'cons_test_ogip' in ogip.nuisance_parameters
        assert ogip.nuisance_parameters['cons_test_ogip'].fix == True
        assert ogip.nuisance_parameters['cons_test_ogip'].free == False

        assert 'pha' in pha_info
        assert 'bak' in pha_info
        assert 'rsp' in pha_info

        ogip.__repr__()
Ejemplo n.º 22
0
def test_pha_write():
    with within_directory(__example_dir):

        ogip = OGIPLike('test_ogip', observation='test.pha{1}')

        ogip.write_pha('test_write', overwrite=True)

        written_ogip = OGIPLike('write_ogip', observation='test_write.pha{1}')

        pha_info = written_ogip.get_pha_files()

        for key in ['pha', 'bak']:

            assert isinstance(pha_info[key], PHASpectrum)

        assert pha_info['pha'].background_file == 'test_bak.pha{1}'
        assert pha_info['pha'].ancillary_file is None
        assert pha_info['pha'].instrument == 'GBM_NAI_03'
        assert pha_info['pha'].mission == 'GLAST'
        assert pha_info['pha'].is_poisson == True
        assert pha_info['pha'].n_channels == len(pha_info['pha'].rates)
Ejemplo n.º 23
0
def test_loading_a_loose_ogip_pha_file():

    with within_directory(__example_dir):
        ogip = OGIPLike("test_ogip", observation="example_integral.pha")

        pha_info = ogip.get_pha_files()

        assert ogip.name == "test_ogip"
        assert ogip.n_data_points == sum(ogip._mask)
        assert sum(ogip._mask) == ogip.n_data_points
        # assert ogip.tstart is None
        # assert ogip.tstop is None
        assert "cons_test_ogip" in ogip.nuisance_parameters
        assert ogip.nuisance_parameters["cons_test_ogip"].fix == True
        assert ogip.nuisance_parameters["cons_test_ogip"].free == False

        assert "pha" in pha_info
        # assert 'bak' in pha_info
        assert "rsp" in pha_info

        ogip.__repr__()
Ejemplo n.º 24
0
def test_pha_write():
    with within_directory(__example_dir):

        ogip = OGIPLike("test_ogip", observation="test.pha{1}")

        ogip.write_pha("test_write", overwrite=True)

        written_ogip = OGIPLike("write_ogip", observation="test_write.pha{1}")

        pha_info = written_ogip.get_pha_files()

        for key in ["pha", "bak"]:

            assert isinstance(pha_info[key], PHASpectrum)

        assert pha_info["pha"].background_file == "test_bak.pha{1}"
        assert pha_info["pha"].ancillary_file is None
        assert pha_info["pha"].instrument == "GBM_NAI_03"
        assert pha_info["pha"].mission == "GLAST"
        assert pha_info["pha"].is_poisson == True
        assert pha_info["pha"].n_channels == len(pha_info["pha"].rates)
Ejemplo n.º 25
0
def test_loading_a_generic_pha_file():

    with within_directory(__example_dir):
        ogip = OGIPLike("test_ogip", observation="test.pha{1}")

        pha_info = ogip.get_pha_files()

        assert ogip.name == "test_ogip"
        assert ogip.n_data_points == sum(ogip._mask)
        assert sum(ogip._mask) == ogip.n_data_points
        assert ogip.tstart == 0.0
        assert ogip.tstop == 9.95012
        assert "cons_test_ogip" in ogip.nuisance_parameters
        assert ogip.nuisance_parameters["cons_test_ogip"].fix == True
        assert ogip.nuisance_parameters["cons_test_ogip"].free == False

        assert "pha" in pha_info
        assert "bak" in pha_info
        assert "rsp" in pha_info

        ogip.__repr__()
Ejemplo n.º 26
0
def test_ogip_rebinner():
    with within_directory(__example_dir):
        ogip = OGIPLike("test_ogip", observation="test.pha{1}")

        n_data_points = 128
        ogip.set_active_measurements("all")

        assert ogip.n_data_points == n_data_points

        ogip.rebin_on_background(min_number_of_counts=100)

        assert ogip.n_data_points < 128

        with pytest.raises(AssertionError):
            ogip.set_active_measurements("all")

        ogip.remove_rebinning()

        assert ogip._rebinner is None

        assert ogip.n_data_points == n_data_points

        ogip.view_count_spectrum()
Ejemplo n.º 27
0
def test_hist_constructor():

    with within_directory(__this_dir__):

        bins=[-3,-2,-1,0,1,2,3]

        bounds = IntervalSet.from_list_of_edges(bins)

        contents = np.ones(len(bins) - 1)

        hh1 = Histogram(bounds, contents, is_poisson=True)

        assert hh1.is_poisson == True

        assert len(hh1) == len(bins)-1

        hh1.display()

        # rnum = np.loadtxt('test_hist_data.txt')
        #
        #
        # #rnum = np.random.randn(1000)
        # hrnum = np.histogram(rnum, bins=bins, normed=False)
        # hh2 = Histogram.from_numpy_histogram(hrnum, is_poisson=True)

        # hh3 = Histogram.from_entries(bounds,rnum)
        #
        # assert hh2==hh3

        hh4 = Histogram(bounds, contents, errors=contents)

        assert hh4.is_poisson == False


        with pytest.raises(AssertionError):

            hh4 = Histogram(bounds, contents, errors=contents,is_poisson=True)
Ejemplo n.º 28
0
def test_hist_constructor():

    with within_directory(__this_dir__):

        bins = [-3, -2, -1, 0, 1, 2, 3]

        bounds = IntervalSet.from_list_of_edges(bins)

        contents = np.ones(len(bins) - 1)

        hh1 = Histogram(bounds, contents, is_poisson=True)

        assert hh1.is_poisson == True

        assert len(hh1) == len(bins) - 1

        hh1.display()

        # rnum = np.loadtxt('test_hist_data.txt')
        #
        #
        # #rnum = np.random.randn(1000)
        # hrnum = np.histogram(rnum, bins=bins, normed=False)
        # hh2 = Histogram.from_numpy_histogram(hrnum, is_poisson=True)

        # hh3 = Histogram.from_entries(bounds,rnum)
        #
        # assert hh2==hh3

        hh4 = Histogram(bounds, contents, errors=contents)

        assert hh4.is_poisson == False

        with pytest.raises(AssertionError):

            hh4 = Histogram(bounds, contents, errors=contents, is_poisson=True)
Ejemplo n.º 29
0
def test_spectrum_like_with_background_model():
    energies = np.logspace(1, 3, 51)

    low_edge = energies[:-1]
    high_edge = energies[1:]

    sim_K = 1e-1
    sim_kT = 20.0

    # get a blackbody source function
    source_function = Blackbody(K=sim_K, kT=sim_kT)

    # power law background function
    background_function = Powerlaw(K=5, index=-1.5, piv=100.0)

    spectrum_generator = SpectrumLike.from_function(
        "fake",
        source_function=source_function,
        background_function=background_function,
        energy_min=low_edge,
        energy_max=high_edge,
    )

    background_plugin = SpectrumLike.from_background("background",
                                                     spectrum_generator)

    bb = Blackbody()

    pl = Powerlaw()
    pl.piv = 100

    bkg_ps = PointSource("bkg", 0, 0, spectral_shape=pl)

    bkg_model = Model(bkg_ps)

    jl_bkg = JointLikelihood(bkg_model, DataList(background_plugin))

    _ = jl_bkg.fit()

    plugin_bkg_model = SpectrumLike("full",
                                    spectrum_generator.observed_spectrum,
                                    background=background_plugin)

    pts = PointSource("mysource", 0, 0, spectral_shape=bb)

    model = Model(pts)

    # MLE fitting

    jl = JointLikelihood(model, DataList(plugin_bkg_model))

    result = jl.fit()

    K_variates = jl.results.get_variates("mysource.spectrum.main.Blackbody.K")

    kT_variates = jl.results.get_variates(
        "mysource.spectrum.main.Blackbody.kT")

    assert np.all(
        np.isclose([K_variates.average, kT_variates.average], [sim_K, sim_kT],
                   rtol=0.5))

    ## test with ogiplike
    with within_directory(__example_dir):
        ogip = OGIPLike("test_ogip",
                        observation="test.pha{1}",
                        background=background_plugin)
Ejemplo n.º 30
0
def test_read_gbm_tte():
    with within_directory(datasets_directory):
        data_dir = os.path.join('gbm', 'bn080916009')

        nai3 = TimeSeriesBuilder.from_gbm_tte('NAI3',
                                              os.path.join(data_dir, "glg_tte_n3_bn080916009_v01.fit.gz"),
                                              rsp_file=os.path.join(data_dir, "glg_cspec_n3_bn080916009_v00.rsp2"),
                                              poly_order=-1)

        nai3.set_active_time_interval('0-1')
        nai3.set_background_interval('-20--10', '100-200')




        speclike = nai3.to_spectrumlike()

        assert isinstance(speclike, DispersionSpectrumLike)


        assert not speclike.background_spectrum.is_poisson

        speclike = nai3.to_spectrumlike(extract_measured_background=True)

        assert isinstance(speclike, DispersionSpectrumLike)

        assert speclike.background_spectrum.is_poisson



        # test binning


        # should not have bins yet



        with pytest.raises(RuntimeError):
            nai3.bins

        # First catch the errors


        # This is without specifying the correct options name





        with pytest.raises(RuntimeError):
            nai3.create_time_bins(start=0, stop=10, method='constant')

        with pytest.raises(RuntimeError):
            nai3.create_time_bins(start=0, stop=10, method='significance')

        with pytest.raises(RuntimeError):
            nai3.create_time_bins(start=0, stop=10, method='constant', p0=.1)

        with pytest.raises(RuntimeError):
            nai3.create_time_bins(start=0, stop=10, method='significance', dt=1)

        # now incorrect options

        with pytest.raises(RuntimeError):
            nai3.create_time_bins(start=0, stop=10, method='not_a_method')

        # Now test values



        nai3.create_time_bins(start=0, stop=10, method='constant', dt=1)

        assert len(nai3.bins) == 10

        assert nai3.bins.argsort() == range(len(nai3.bins))

        nai3.create_time_bins(start=0, stop=10, method='bayesblocks', p0=.1)

        assert nai3.bins.argsort() == range(len(nai3.bins))

        assert len(nai3.bins) == 5

        nai3.create_time_bins(start=0, stop=10, method='significance', sigma=40)

        assert nai3.bins.argsort() == range(len(nai3.bins))

        assert len(nai3.bins) == 5

        nai3.view_lightcurve(use_binner=True)

        nai3.write_pha_from_binner('test_from_nai3', overwrite=True)
Ejemplo n.º 31
0
def test_read_gbm_tte():
    with within_directory(datasets_directory):
        data_dir = os.path.join('gbm', 'bn080916009')

        nai3 = TimeSeriesBuilder.from_gbm_tte(
            'NAI3',
            os.path.join(data_dir, "glg_tte_n3_bn080916009_v01.fit.gz"),
            rsp_file=os.path.join(data_dir,
                                  "glg_cspec_n3_bn080916009_v00.rsp2"),
            poly_order=-1)

        nai3.set_active_time_interval('0-1')
        nai3.set_background_interval('-20--10', '100-200')

        speclike = nai3.to_spectrumlike()

        assert isinstance(speclike, DispersionSpectrumLike)

        assert not speclike.background_spectrum.is_poisson

        speclike = nai3.to_spectrumlike(extract_measured_background=True)

        assert isinstance(speclike, DispersionSpectrumLike)

        assert speclike.background_spectrum.is_poisson

        # test binning

        # should not have bins yet

        with pytest.raises(RuntimeError):
            nai3.bins

        # First catch the errors

        # This is without specifying the correct options name

        with pytest.raises(RuntimeError):
            nai3.create_time_bins(start=0, stop=10, method='constant')

        with pytest.raises(RuntimeError):
            nai3.create_time_bins(start=0, stop=10, method='significance')

        with pytest.raises(RuntimeError):
            nai3.create_time_bins(start=0, stop=10, method='constant', p0=.1)

        with pytest.raises(RuntimeError):
            nai3.create_time_bins(start=0,
                                  stop=10,
                                  method='significance',
                                  dt=1)

        # now incorrect options

        with pytest.raises(RuntimeError):
            nai3.create_time_bins(start=0, stop=10, method='not_a_method')

        # Now test values

        nai3.create_time_bins(start=0, stop=10, method='constant', dt=1)

        assert len(nai3.bins) == 10

        assert nai3.bins.argsort() == range(len(nai3.bins))

        nai3.create_time_bins(start=0, stop=10, method='bayesblocks', p0=.1)

        assert nai3.bins.argsort() == range(len(nai3.bins))

        assert len(nai3.bins) == 5

        nai3.create_time_bins(start=0,
                              stop=10,
                              method='significance',
                              sigma=40)

        assert nai3.bins.argsort() == range(len(nai3.bins))

        assert len(nai3.bins) == 5

        nai3.view_lightcurve(use_binner=True)

        nai3.write_pha_from_binner('test_from_nai3', overwrite=True)
Ejemplo n.º 32
0
def test_read_gbm_tte():
    with within_directory(datasets_directory):
        data_dir = os.path.join("gbm", "bn080916009")

        nai3 = TimeSeriesBuilder.from_gbm_tte(
            "NAI3",
            os.path.join(data_dir, "glg_tte_n3_bn080916009_v01.fit.gz"),
            rsp_file=os.path.join(data_dir,
                                  "glg_cspec_n3_bn080916009_v00.rsp2"),
            poly_order=-1,
        )

        nai3.set_active_time_interval("0-1")
        nai3.set_background_interval("-20--10", "100-200", unbinned=False)

        speclike = nai3.to_spectrumlike()

        assert isinstance(speclike, DispersionSpectrumLike)

        assert not speclike.background_spectrum.is_poisson

        speclike = nai3.to_spectrumlike(extract_measured_background=True)

        assert isinstance(speclike, DispersionSpectrumLike)

        assert speclike.background_spectrum.is_poisson

        # test binning

        # should not have bins yet

        with pytest.raises(RuntimeError):
            nai3.bins

        # First catch the errors

        # This is without specifying the correct options name

        with pytest.raises(RuntimeError):
            nai3.create_time_bins(start=0, stop=10, method="constant")

        with pytest.raises(RuntimeError):
            nai3.create_time_bins(start=0, stop=10, method="significance")

        with pytest.raises(RuntimeError):
            nai3.create_time_bins(start=0, stop=10, method="constant", p0=0.1)

        with pytest.raises(RuntimeError):
            nai3.create_time_bins(start=0,
                                  stop=10,
                                  method="significance",
                                  dt=1)

        # now incorrect options

        with pytest.raises(RuntimeError):
            nai3.create_time_bins(start=0, stop=10, method="not_a_method")

        # Now test values

        nai3.create_time_bins(start=0, stop=10, method="constant", dt=1)

        assert len(nai3.bins) == 10

        assert nai3.bins.argsort() == list(range(len(nai3.bins)))

        nai3.create_time_bins(start=0, stop=10, method="bayesblocks", p0=0.1)

        assert nai3.bins.argsort() == list(range(len(nai3.bins)))

        assert len(nai3.bins) == 5

        nai3.create_time_bins(start=0,
                              stop=10,
                              method="significance",
                              sigma=40)

        assert nai3.bins.argsort() == list(range(len(nai3.bins)))

        assert len(nai3.bins) == 5

        nai3.view_lightcurve(use_binner=True)

        nai3.write_pha_from_binner("test_from_nai3",
                                   overwrite=True,
                                   force_rsp_write=True)
Ejemplo n.º 33
0
def test_loading_ogip():

    with within_directory(datasets_dir):

        _ = OGIPLike('test_ogip', observation='test.pha{1}')
Ejemplo n.º 34
0
def test_loading_ogip():

    with within_directory(datasets_dir):

        _ = OGIPLike("test_ogip", observation="test.pha{1}")
Ejemplo n.º 35
0
def test_pha_files_in_generic_ogip_constructor_spec_number_in_file_name():
    with within_directory(__example_dir):

        ogip = OGIPLike('test_ogip', observation='test.pha{1}')
        ogip.set_active_measurements('all')
        pha_info = ogip.get_pha_files()

        for key in ['pha', 'bak']:

            assert isinstance(pha_info[key], PHASpectrum)

        assert pha_info['pha'].background_file == 'test_bak.pha{1}'
        assert pha_info['pha'].ancillary_file is None
        assert pha_info['pha'].instrument == 'GBM_NAI_03'
        assert pha_info['pha'].mission == 'GLAST'
        assert pha_info['pha'].is_poisson == True
        assert pha_info['pha'].n_channels == ogip.n_data_points
        assert pha_info['pha'].n_channels == len(pha_info['pha'].rates)

        # Test that Poisson rates cannot call rate error
        assert pha_info['pha'].rate_errors is None

        assert sum(pha_info['pha'].sys_errors == np.zeros_like(
            pha_info['pha'].rates)) == pha_info['bak'].n_channels

        assert pha_info['pha'].response_file.split(
            '/')[-1] == 'glg_cspec_n3_bn080916009_v07.rsp'
        assert pha_info['pha'].scale_factor == 1.0

        assert pha_info['bak'].background_file is None

        # Test that we cannot get a bak file
        #
        #
        # with pytest.raises(KeyError):
        #
        #     _ = pha_info['bak'].background_file

        # Test that we cannot get a anc file
        # with pytest.raises(KeyError):
        #
        #     _ = pha_info['bak'].ancillary_file

        # Test that we cannot get a RSP file

        assert pha_info['bak'].response_file is None

        assert pha_info['bak'].ancillary_file is None

        # with pytest.raises(AttributeError):
        #      _ = pha_info['bak'].response_file

        assert pha_info['bak'].instrument == 'GBM_NAI_03'
        assert pha_info['bak'].mission == 'GLAST'

        assert pha_info['bak'].is_poisson == False

        assert pha_info['bak'].n_channels == ogip.n_data_points
        assert pha_info['bak'].n_channels == len(pha_info['pha'].rates)

        assert len(pha_info['bak'].rate_errors) == pha_info['bak'].n_channels

        assert sum(pha_info['bak'].sys_errors == np.zeros_like(
            pha_info['pha'].rates)) == pha_info['bak'].n_channels

        assert pha_info['bak'].scale_factor == 1.0

        assert isinstance(pha_info['rsp'], OGIPResponse)
Ejemplo n.º 36
0
def test_pha_files_in_generic_ogip_constructor_spec_number_in_arguments():
    with within_directory(__example_dir):
        ogip = OGIPLike("test_ogip", observation="test.pha", spectrum_number=1)
        ogip.set_active_measurements("all")

        pha_info = ogip.get_pha_files()

        for key in ["pha", "bak"]:

            assert isinstance(pha_info[key], PHASpectrum)

        assert pha_info["pha"].background_file == "test_bak.pha{1}"
        assert pha_info["pha"].ancillary_file is None
        assert pha_info["pha"].instrument == "GBM_NAI_03"
        assert pha_info["pha"].mission == "GLAST"
        assert pha_info["pha"].is_poisson == True
        assert pha_info["pha"].n_channels == ogip.n_data_points
        assert pha_info["pha"].n_channels == len(pha_info["pha"].rates)

        # Test that Poisson rates cannot call rate error
        assert pha_info["pha"].rate_errors is None

        assert (
            sum(pha_info["pha"].sys_errors == np.zeros_like(pha_info["pha"].rates))
            == pha_info["bak"].n_channels
        )
        assert (
            pha_info["pha"].response_file.split("/")[-1]
            == "glg_cspec_n3_bn080916009_v07.rsp"
        )
        assert pha_info["pha"].scale_factor == 1.0

        assert pha_info["bak"].background_file is None

        # Test that we cannot get a bak file
        #
        # with pytest.raises(KeyError):
        #
        #     _ = pha_info['bak'].background_file
        #
        # Test that we cannot get a anc file
        # with pytest.raises(KeyError):
        #
        #     _ = pha_info['bak'].ancillary_file

        assert pha_info["bak"].response_file is None

        assert pha_info["bak"].ancillary_file is None

        # # Test that we cannot get a RSP file
        # with pytest.raises(AttributeError):
        #      _ = pha_info['bak'].response_file

        assert pha_info["bak"].instrument == "GBM_NAI_03"
        assert pha_info["bak"].mission == "GLAST"

        assert pha_info["bak"].is_poisson == False

        assert pha_info["bak"].n_channels == ogip.n_data_points
        assert pha_info["bak"].n_channels == len(pha_info["pha"].rates)

        assert len(pha_info["bak"].rate_errors) == pha_info["bak"].n_channels

        assert (
            sum(pha_info["bak"].sys_errors == np.zeros_like(pha_info["pha"].rates))
            == pha_info["bak"].n_channels
        )

        assert pha_info["bak"].scale_factor == 1.0

        assert isinstance(pha_info["rsp"], OGIPResponse)