Ejemplo n.º 1
0
    def test_broken_data(self):
        """
        Test reading of data fails during to a "broken" input file
        """

        # create a "broken" input file (not the spurious "H")
        brokendata = """\
# times       real      imaginary
1000000000.0  -2.3e-25   4.3e-26
1000000060.0   H.2e-26   1.2e-25
1000000120.0  -1.7e-25  -2.8e-25
1000000180.0  -7.6e-26  -8.9e-26
"""
        brokenfile = "brokendata.txt"
        with open(brokenfile, "w") as fp:
            fp.write(brokendata)

        with pytest.raises(IOError):
            HeterodynedData(brokenfile)

        # run through MultiHeterodynedData
        with pytest.raises(IOError):
            MultiHeterodynedData(brokenfile)

        with pytest.raises(IOError):
            MultiHeterodynedData({"H1": brokenfile})

        os.remove(brokenfile)  # clean up file
Ejemplo n.º 2
0
    def test_plot(self):
        """
        Test plotting function (and at the same time test fake noise generation)
        """

        # create an injection parameter file
        parcontent = """\
PSRJ    J0000+0000
RAJ     00:00:00.0
DECJ    00:00:00.0
F0      123.45
F1      1.2e-11
PEPOCH  56789.0
H0      1.5e-22
"""

        parfile = "test.par"
        with open(parfile, "w") as fp:
            fp.write(parcontent)

        # one point per 10 mins
        times = np.linspace(1000000000.0, 1000085800.0, 144)

        with pytest.raises(AttributeError):
            # if no parameter file is given, then generating fake data for a
            # particular detector should fail
            het = HeterodynedData(times=times, fakeasd="H1")

        # set the asd explicitly
        het = HeterodynedData(times=times,
                              fakeasd=1e-24,
                              detector="H1",
                              par=parfile,
                              inject=True)
        mhd = MultiHeterodynedData(het)

        # not allowed argument
        with pytest.raises(ValueError):
            fig = mhd.plot(which="blah")

        # test different plot types
        for which in ["abs", "REAL", "im", "Both"]:
            fig = mhd.plot(which=which)
            assert isinstance(fig[0], Figure)
            del fig

        # remove the par file
        os.remove(parfile)
Ejemplo n.º 3
0
    def test_wrong_inputs(self):
        """
        Test that exceptions are raised for incorrect inputs to the
        TargetedPulsarLikelihood.
        """

        with pytest.raises(TypeError):
            TargetedPulsarLikelihood(None, None)

        # create HeterodynedData object (no par file)
        het = HeterodynedData(self.data,
                              times=self.times,
                              detector=self.detector)

        priors = dict()
        priors["h0"] = Uniform(0.0, 1.0e-23, "h0")

        # error with no par file
        with pytest.raises(ValueError):
            TargetedPulsarLikelihood(het, PriorDict(priors))

        het = HeterodynedData(self.data,
                              times=self.times,
                              detector=self.detector,
                              par=self.parfile)
        mhet = MultiHeterodynedData(het)  # multihet object for testing

        with pytest.raises(TypeError):
            TargetedPulsarLikelihood(het, None)

        with pytest.raises(TypeError):
            TargetedPulsarLikelihood(mhet, None)
Ejemplo n.º 4
0
    def test_multi_data(self):
        """
        Test various ways of generating data for multiple detectors.
        """

        # create four datasets
        times1 = np.linspace(1000000000.0, 1000086340.0, 1440)
        data1 = np.random.normal(0.0, 1e-25, size=(1440, 2)).tolist()
        detector1 = "H1"

        times2 = np.linspace(1000000000.0, 1000086340.0, 1440)
        data2 = np.random.normal(0.0, 1e-25, size=(1440, 2))
        detector2 = "L1"

        times3 = np.linspace(1000000000.0, 1000086340.0, 1440)
        data3 = np.random.normal(0.0, 1e-25, size=(1440, 2))
        detector3 = "G1"

        times4 = np.linspace(1000000000.0, 1000086340.0, 1440)
        data4 = np.random.normal(0.0, 1e-25, size=(1440, 2))
        detector4 = "K1"

        # add first dataset as precreated HeterodynedData object
        het1 = HeterodynedData(data1, times=times1, detector=detector1)

        mhet = MultiHeterodynedData(het1)

        # add second dataset as a dictionary
        ddic = {detector2: data2}
        tdic = {"XX": times2}  # set to fail

        # add second dataset
        with pytest.raises(KeyError):
            mhet.add_data(ddic, tdic, detector2)

        # fix tdic
        tdic = {detector2: times2}
        mhet.add_data(ddic, tdic, detector2)

        # add third data set as a dictionary of HeterodynedData
        het3 = HeterodynedData(data3, times=times3, detector=detector3)
        ddic = {detector3: het3}
        mhet.add_data(ddic)

        # add fourth data set by just passing the data
        tdic = {detector4: times4}  # fail with dictionary of times

        with pytest.raises(TypeError):
            mhet.add_data(data4, tdic, detector4)

        # just add with times
        mhet.add_data(data4, times4, detector4)

        assert len(mhet) == 4
        assert len(mhet.detectors) == 4
        assert len(mhet.to_list) == 4

        # test looping over MultiHeterodynedData
        dets = [detector1, detector2, detector3, detector4]
        for data, det in zip(mhet, dets):
            assert det == data.detector
Ejemplo n.º 5
0
    def test_spectrum_plots(self):
        """
        Test the spectrogram, periodogram and power spectrum plots.
        """

        times1 = np.linspace(1000000000.0, 1000172740.0, 2 * 1440)
        data1 = np.random.normal(
            0.0, 1.0,
            size=2 * 1440) + 1j * np.random.normal(0.0, 1.0, size=2 * 1440)
        detector1 = "H1"

        times2 = np.linspace(1000000000.0, 1000172740.0, 2 * 1440)
        data2 = np.random.normal(
            0.0, 1.0,
            size=2 * 1440) + 1j * np.random.normal(0.0, 1.0, size=2 * 1440)
        detector2 = "L1"

        data = {
            detector1: HeterodynedData(data1, times=times1),
            detector2: HeterodynedData(data2, times=times2),
        }

        mhd = MultiHeterodynedData(data)

        # test errors
        with pytest.raises(ValueError):
            _ = mhd.spectrogram(dt="a")

        with pytest.raises(ValueError):
            _ = mhd.spectrogram(dt=200000)

        # with pytest.raises(TypeError):
        #    _ = mhd.spectrogram(overlap='a')

        with pytest.raises(ValueError):
            _ = mhd.spectrogram(overlap=-1)

        with pytest.raises(ValueError):
            _ = mhd.power_spectrum(average="a")

        # create a spectrogram
        freqs, power, stimes, fig = data[detector1].spectrogram(dt=3600)

        assert isinstance(fig, Figure)
        assert freqs.shape[0] == 60
        assert power.shape[0] == 60 and power.shape[1] == 95
        assert stimes.shape[0] == power.shape[1]

        # create a power spectrum
        freqs, power, fig = data[detector1].power_spectrum(dt=86400)

        assert isinstance(fig, Figure)
        assert power.shape[0] == len(data1) // 2
        assert freqs.shape[0] == power.shape[0]

        # create a periodogram
        freqs, power, fig = data[detector1].periodogram()

        assert isinstance(fig, Figure)
        assert power.shape[0] == len(data1)
        assert freqs.shape[0] == power.shape[0]

        # do the same, but with some data removed to test zero padding
        newdata = np.delete(data1, [10, 51, 780])
        newtimes = np.delete(times1, [10, 51, 780])

        newhet = HeterodynedData(newdata, times=newtimes, detector="H1")

        # create a power spectrum
        freqs, power, fig = newhet.power_spectrum(dt=86400)

        assert isinstance(fig, Figure)
        assert power.shape[0] == len(data1) // 2
        assert freqs.shape[0] == power.shape[0]

        # add a DCC signal and check it's at 0 Hz
        datadc = np.random.normal(
            5.0, 1.0,
            size=2 * 1440) + 1j * np.random.normal(5.0, 1.0, size=2 * 1440)

        newhet2 = HeterodynedData(datadc, times=times1, detector="H1")

        # create a power spectrum
        freqs, power, fig = newhet2.power_spectrum(dt=86400)

        assert freqs[np.argmax(power)] == 0.0
Ejemplo n.º 6
0
    def test_optimal_snr(self):
        with pytest.raises(TypeError):
            # invalid input type for results directory
            optimal_snr(9.8, self.hetdir)

        with pytest.raises(TypeError):
            # invalid input type for heterodyned data directory
            optimal_snr(self.resdir, 1.6)

        with pytest.raises(ValueError):
            # invalid "which" value
            optimal_snr(self.resdir, self.hetdir, which="blah")

        resfiles = find_results_files(self.resdir)
        hetfiles = find_heterodyned_files(self.hetdir)

        # get single detector, single source SNR
        snr = optimal_snr(resfiles[self.pnames[0]]["H1"],
                          hetfiles[self.pnames[0]]["H1"])
        assert isinstance(snr, float)

        # use a dictionary instead
        snr = optimal_snr(resfiles[self.pnames[0]]["H1"],
                          {"H1": hetfiles[self.pnames[0]]["H1"]})
        assert isinstance(snr, float)

        # check using likelihood gives same value as posterior (a flat prior was used to produce the files)
        snrl = optimal_snr(
            resfiles[self.pnames[0]]["H1"],
            hetfiles[self.pnames[0]]["H1"],
            which="likelihood",
        )
        assert snr == snrl

        # pass remove outliers flag
        snr = optimal_snr(
            resfiles[self.pnames[0]]["H1"],
            {"H1": hetfiles[self.pnames[0]]["H1"]},
            remove_outliers=True,
        )
        assert isinstance(snr, float)

        # pass result as Result object
        snr = optimal_snr(
            read_in_result(resfiles[self.pnames[0]]["H1"]),
            hetfiles[self.pnames[0]]["H1"],
        )
        assert isinstance(snr, float) and snr == snrl

        # pass heterodyned data as HeterodynedData object
        snr = optimal_snr(
            resfiles[self.pnames[0]]["H1"],
            HeterodynedData.read(hetfiles[self.pnames[0]]["H1"]),
        )
        assert isinstance(snr, float)

        # get single joint multi-detector result
        snr = optimal_snr(resfiles[self.pnames[0]]["H1L1"],
                          hetfiles[self.pnames[0]])
        assert isinstance(snr, float)

        # do the same, but with MultiHeterodynedData object
        snr = optimal_snr(
            resfiles[self.pnames[0]]["H1L1"],
            MultiHeterodynedData(hetfiles[self.pnames[0]]),
        )
        assert isinstance(snr, float)

        # get results for all pulsars and all detectors combination
        snr = optimal_snr(self.resdir, self.hetdir)
        assert isinstance(snr, dict)
        assert sorted(snr.keys()) == sorted(self.pnames)
        for k in snr:
            assert sorted(snr[k].keys()) == sorted(self.dets)
            assert all([isinstance(v, float) for v in snr[k].values()])

        # pass in par files directory
        snr = optimal_snr(self.resdir, self.hetdir, par=self.pardir)
        assert isinstance(snr, dict)
        assert sorted(snr.keys()) == sorted(self.pnames)
        for k in snr:
            assert sorted(snr[k].keys()) == sorted(self.dets)
            assert all([isinstance(v, float) for v in snr[k].values()])

        # get results for a single detector
        snr = optimal_snr(self.resdir, self.hetdir, det="H1")
        assert isinstance(snr, dict)
        assert sorted(snr.keys()) == sorted(self.pnames)
        assert all([isinstance(v, float) for v in snr.values()])