Exemplo n.º 1
0
    def test_plot_wrong_label_type(self):
        lc = Lightcurve(self.times, self.counts)

        with pytest.raises(TypeError):
            with warnings.catch_warnings(record=True) as w:
                lc.plot(labels=123)
                assert "must be either a list or tuple" in str(w[0].message)
Exemplo n.º 2
0
 def test_io_with_pickle(self):
     lc = Lightcurve(self.times, self.counts)
     lc.write('lc.pickle', format_='pickle')
     lc.read('lc.pickle',format_='pickle')
     assert np.all(lc.time == self.times)
     assert np.all(lc.counts == self.counts)
     os.remove('lc.pickle')
Exemplo n.º 3
0
 def test_lightcurve_from_toa(self):
     lc = Lightcurve.make_lightcurve(self.times, self.dt, use_hist=True,
                                     tstart=0.5)
     lc2 = Lightcurve.make_lightcurve(self.times, self.dt, use_hist=False,
                                     tstart=0.5)
     assert np.allclose(lc.time, lc2.time)
     assert np.all(lc.counts == lc2.counts)
Exemplo n.º 4
0
 def test_io_with_pickle(self):
     lc = Lightcurve(self.times, self.counts)
     lc.write("lc.pickle", format_="pickle")
     lc.read("lc.pickle", format_="pickle")
     assert np.all(lc.time == self.times)
     assert np.all(lc.counts == self.counts)
     assert np.all(lc.gti == self.gti)
     os.remove("lc.pickle")
Exemplo n.º 5
0
 def test_lightcurve_from_toa_random_nums(self):
     times = np.random.uniform(0, 10, 1000)
     lc = Lightcurve.make_lightcurve(times, self.dt, use_hist=True,
                                     tstart=0.5)
     lc2 = Lightcurve.make_lightcurve(times, self.dt, use_hist=False,
                                     tstart=0.5)
     assert np.allclose(lc.time, lc2.time)
     assert np.all(lc.counts == lc2.counts)
Exemplo n.º 6
0
    def test_analyze_lc_chunks(self):
        lc = Lightcurve(self.times, self.counts, gti=self.gti)

        def func(lc):
            return lc.time[0]
        start, stop, res = lc.analyze_lc_chunks(2, func)
        assert start[0] == 0.5
        assert np.all(start + lc.dt / 2 == res)
Exemplo n.º 7
0
    def test_truncate_by_index(self):
        lc = Lightcurve(self.times, self.counts)

        lc1 = lc.truncate(start=1)
        assert np.all(lc1.time == np.array([2, 3, 4]))
        assert np.all(lc1.counts == np.array([2, 2, 2]))

        lc2 = lc.truncate(stop=2)
        assert np.all(lc2.time == np.array([1, 2]))
        assert np.all(lc2.counts == np.array([2, 2]))
Exemplo n.º 8
0
    def test_join_with_different_dt(self):
        _times = [5, 5.5, 6]
        _counts = [2, 2, 2]

        lc1 = Lightcurve(self.times, self.counts)
        lc2 = Lightcurve(_times, _counts)

        with warnings.catch_warnings(record=True) as w:
            lc1.join(lc2)
            assert "different bin widths" in str(w[0].message)
Exemplo n.º 9
0
 def test_lc_baseline(self):
     times = np.arange(0, 100, 0.01)
     counts = np.random.normal(100, 0.1, len(times)) + \
         0.001 * times
     gti = [[-0.005, 50.005], [59.005, 100.005]]
     good = create_gti_mask(times, gti)
     counts[np.logical_not(good)] = 0
     lc = Lightcurve(times, counts, gti=gti)
     baseline = lc.baseline(10000, 0.01)
     assert np.all(lc.counts - baseline < 1)
Exemplo n.º 10
0
    def test_truncate_by_time(self):
        lc = Lightcurve(self.times, self.counts)

        lc1 = lc.truncate(start=1, method='time')
        assert np.all(lc1.time == np.array([1, 2, 3, 4]))
        assert np.all(lc1.counts == np.array([2, 2, 2, 2]))

        lc2 = lc.truncate(stop=3, method='time')
        assert np.all(lc2.time == np.array([1, 2]))
        assert np.all(lc2.counts == np.array([2, 2]))
Exemplo n.º 11
0
    def test_join_different_err_dist_disjoint_times(self):
        _times = [5 , 6, 7, 8]
        _counts =[2, 2, 2, 2]

        lc1 = Lightcurve(self.times, self.counts, err_dist = "poisson")
        lc2 = Lightcurve(_times, _counts, err_dist = "gauss")

        lc3 = lc1.join(lc2)

        assert np.all(lc3.counts_err[:len(self.times)] == lc1.counts_err)
        assert np.all(lc3.counts_err[len(self.times):] == np.zeros_like(lc2.counts))
Exemplo n.º 12
0
    def test_join_different_err_dist_overlapping_times(self):
        _times = [3, 4, 5, 6]
        _counts = [4, 4, 4, 4]

        lc1 = Lightcurve(self.times, self.counts, err_dist = "poisson")
        lc2 = Lightcurve(_times, _counts, err_dist = "gauss")

        with warnings.catch_warnings(record=True) as w:
            lc3 = lc1.join(lc2)
            assert "We are setting the errors to zero." in str(w[1].message)
            assert np.all(lc3.counts_err == np.zeros_like(lc3.time))
Exemplo n.º 13
0
    def test_join_disjoint_time_arrays(self):
        _times = [5, 6, 7, 8]
        _counts = [2, 2, 2, 2]

        lc1 = Lightcurve(self.times, self.counts)
        lc2 = Lightcurve(_times, _counts)

        lc = lc1.join(lc2)

        assert len(lc.counts) == len(lc.time) == 8
        assert np.all(lc.counts == 2)
Exemplo n.º 14
0
    def test_plot_matplotlib_not_installed(self):
        try:
            import matplotlib.pyplot as plt
        except Exception as e:

            lc = Lightcurve(self.times, self.counts)
            try:
                lc.plot()
            except Exception as e:
                assert type(e) is ImportError
                assert str(e) == "Matplotlib required for plot()"
Exemplo n.º 15
0
 def test_lc_baseline_offset(self):
     times = np.arange(0, 100, 0.01)
     input_stdev = 0.1
     counts = np.random.normal(100, input_stdev, len(times)) + \
         0.001 * times
     gti = [[-0.005, 50.005], [59.005, 100.005]]
     good = create_gti_mask(times, gti)
     counts[np.logical_not(good)] = 0
     lc = Lightcurve(times, counts, gti=gti)
     baseline = lc.baseline(10000, 0.01, offset_correction=True)
     assert np.isclose(np.std(lc.counts - baseline), input_stdev, rtol=0.1)
Exemplo n.º 16
0
    def test_truncate_by_time(self):
        lc = Lightcurve(self.times, self.counts, gti=self.gti)

        lc1 = lc.truncate(start=1, method='time')
        assert np.all(lc1.time == np.array([1, 2, 3, 4]))
        assert np.all(lc1.counts == np.array([2, 2, 2, 2]))
        np.testing.assert_almost_equal(lc1.gti[0][0], 0.5)

        lc2 = lc.truncate(stop=3, method='time')
        assert np.all(lc2.time == np.array([1, 2]))
        assert np.all(lc2.counts == np.array([2, 2]))
        np.testing.assert_almost_equal(lc2.gti[-1][-1], 2.5)
Exemplo n.º 17
0
    def test_lc_baseline_offset_fewbins(self):
        times = np.arange(0, 4, 1)
        input_stdev = 0.1
        counts = np.random.normal(100, input_stdev, len(times)) + \
            0.001 * times
        gti = [[-0.005, 4.005]]
        lc = Lightcurve(times, counts, gti=gti)
        with pytest.warns(UserWarning) as record:
            lc.baseline(10000, 0.01, offset_correction=True)

        assert np.any(["Too few bins to perform baseline offset correction"
                       in r.message.args[0] for r in record])
Exemplo n.º 18
0
    def test_join_overlapping_time_arrays(self):
        _times = [3, 4, 5, 6]
        _counts = [4, 4, 4, 4]

        lc1 = Lightcurve(self.times, self.counts)
        lc2 = Lightcurve(_times, _counts)

        with warnings.catch_warnings(record=True) as w:
            lc = lc1.join(lc2)
            assert "overlapping time ranges" in str(w[0].message)

        assert len(lc.counts) == len(lc.time) == 6
        assert np.all(lc.counts == np.array([2, 2, 3, 3, 4, 4]))
Exemplo n.º 19
0
    def test_sort(self):
        _times = [1, 2, 3, 4]
        _counts = [40, 10, 20, 5]
        lc = Lightcurve(_times, _counts)

        lc.sort()

        assert np.all(lc.counts == np.array([ 5, 10, 20, 40]))
        assert np.all(lc.time == np.array([4, 2, 3, 1]))

        lc.sort(reverse=True)

        assert np.all(lc.counts == np.array([40, 20, 10,  5]))
        assert np.all(lc.time == np.array([1, 3, 2, 4]))
Exemplo n.º 20
0
 def test_shift(self):
     times = [1, 2, 3, 4, 5, 6, 7, 8]
     counts = [1, 1, 1, 1, 2, 3, 3, 2]
     lc = Lightcurve(times, counts, input_counts=True)
     lc2 = lc.shift(1)
     assert np.all(lc2.time - 1 == times)
     lc2 = lc.shift(-1)
     assert np.all(lc2.time + 1 == times)
     assert np.all(lc2.counts == lc.counts)
     assert np.all(lc2.countrate == lc.countrate)
     lc = Lightcurve(times, counts, input_counts=False)
     lc2 = lc.shift(1)
     assert np.all(lc2.counts == lc.counts)
     assert np.all(lc2.countrate == lc.countrate)
Exemplo n.º 21
0
    def test_truncate_by_index(self):
        lc = Lightcurve(self.times, self.counts, gti=self.gti)

        lc1 = lc.truncate(start=1)
        assert np.all(lc1.time == np.array([2, 3, 4]))
        assert np.all(lc1.counts == np.array([2, 2, 2]))
        np.testing.assert_almost_equal(lc1.gti[0][0], 1.5)
        assert lc1.mjdref == lc.mjdref

        lc2 = lc.truncate(stop=2)
        assert np.all(lc2.time == np.array([1, 2]))
        assert np.all(lc2.counts == np.array([2, 2]))
        np.testing.assert_almost_equal(lc2.gti[-1][-1], 2.5)
        assert lc2.mjdref == lc.mjdref
Exemplo n.º 22
0
    def test_rebin_with_gtis(self):
        times = np.arange(0, 100, 0.1)

        counts = np.random.normal(100, 0.1, size=times.shape[0])
        gti = [[0, 40], [60, 100]]

        good = create_gti_mask(times, gti)

        counts[np.logical_not(good)] = 0
        lc = Lightcurve(times, counts, gti=gti)

        lc_rebin = lc.rebin(1.0)

        assert (lc_rebin.time[39] - lc_rebin.time[38]) > 1.0
Exemplo n.º 23
0
    def test_split_lc_by_gtis(self):
        times = [1, 2, 3, 4, 5, 6, 7, 8]
        counts = [1, 1, 1, 1, 2, 3, 3, 2]
        gti = [[0.5, 4.5], [5.5, 7.5]]

        lc = Lightcurve(times, counts, gti=gti)
        list_of_lcs = lc.split_by_gti()
        lc0 = list_of_lcs[0]
        lc1 = list_of_lcs[1]
        assert np.all(lc0.time == [1, 2, 3, 4])
        assert np.all(lc1.time == [6, 7])
        assert np.all(lc0.counts == [1, 1, 1, 1])
        assert np.all(lc1.counts == [3, 3])
        assert np.all(lc0.gti == [[0.5, 4.5]])
        assert np.all(lc1.gti == [[5.5, 7.5]])
Exemplo n.º 24
0
    def test_tseg(self):
        tstart = 0.0
        tseg = 5.0
        lc = Lightcurve.make_lightcurve(self.times, self.dt, tseg=tseg, tstart=tstart)

        assert lc.tseg == tseg
        assert lc.time[-1] - lc.time[0] == tseg - self.dt
Exemplo n.º 25
0
    def test_sort_counts(self):
        _times = [1, 2, 3, 4]
        _counts = [40, 10, 20, 5]
        lc = Lightcurve(_times, _counts, mjdref=57000)
        mjdref = lc.mjdref

        lc_new = lc.sort_counts()

        assert np.all(lc_new.counts == np.array([5, 10, 20, 40]))
        assert np.all(lc_new.time == np.array([4, 2, 3, 1]))
        assert lc_new.mjdref == mjdref

        lc_new = lc.sort_counts(reverse=True)

        assert np.all(lc_new.counts == np.array([40, 20, 10,  5]))
        assert np.all(lc_new.time == np.array([1, 3, 2, 4]))
        assert lc_new.mjdref == mjdref
Exemplo n.º 26
0
    def setup_class(cls):
        photon_arrivals = np.sort(np.random.uniform(0,1000, size=10000))
        cls.lc = Lightcurve.make_lightcurve(photon_arrivals, dt=1.0)
        cls.ps = Powerspectrum(cls.lc, norm="frac")
        pl = models.PowerLaw1D()
        pl.x_0.fixed = True

        cls.lpost = PSDPosterior(cls.ps.freq, cls.ps.power, pl, m=cls.ps.m)
Exemplo n.º 27
0
 def test_nondivisble_tseg(self):
     """
     If the light curve length input is not divisible by the time
     resolution, the last (fractional) time bin will be dropped.
     """
     tstart = 0.0
     tseg = 5.5
     lc = Lightcurve.make_lightcurve(self.times, self.dt, tseg=tseg, tstart=tstart)
     assert lc.tseg == int(tseg / self.dt)
Exemplo n.º 28
0
 def setUp(self):
     #dt = 1.0
     #n = 10
     dt = 0.0001220703125
     n = 1384132
     mean_counts = 2.0
     times = np.arange(dt/2, dt/2+n*dt, dt)
     counts= np.zeros_like(times)+mean_counts
     self.lc = Lightcurve(times, counts)
Exemplo n.º 29
0
class TestLightcurveRebin(object):

    def setUp(self):
        #dt = 1.0
        #n = 10
        dt = 0.0001220703125
        n = 1384132
        mean_counts = 2.0
        times = np.arange(dt/2, dt/2+n*dt, dt)
        counts= np.zeros_like(times)+mean_counts
        self.lc = Lightcurve(times, counts)

    def test_rebin_even(self):
        dt_new = 2.0
        lc_binned = self.lc.rebin_lightcurve(dt_new)
        assert np.isclose(lc_binned.dt, dt_new)
        counts_test = np.zeros_like(lc_binned.time) + \
                      self.lc.counts[0]*dt_new/self.lc.dt
        assert np.allclose(lc_binned.counts, counts_test)


    def test_rebin_odd(self):
        dt_new = 1.5
        lc_binned = self.lc.rebin_lightcurve(dt_new)
        assert np.isclose(lc_binned.dt, dt_new)

        counts_test = np.zeros_like(lc_binned.time) + \
                      self.lc.counts[0]*dt_new/self.lc.dt
        assert np.allclose(lc_binned.counts, counts_test)


    def rebin_several(self, dt):
        """
        TODO: Not sure how to write tests for the rebin method!
        """
        lc_binned = self.lc.rebin_lightcurve(dt)
        assert len(lc_binned.time) == len(lc_binned.counts)

    def test_rebin_equal_numbers(self):
        dt_all = [2, 3, np.pi, 5]
        for dt in dt_all:
            yield self.rebin_several, dt
Exemplo n.º 30
0
    def test_bin_correctly(self):
        ncounts = np.array([2, 1, 0, 3])
        tstart = 0.0
        tseg = 4.0

        toa = np.hstack([np.random.uniform(i, i + 1, size=n) for i, n in enumerate(ncounts)])

        dt = 1.0
        lc = Lightcurve.make_lightcurve(toa, dt, tseg=tseg, tstart=tstart)

        assert np.allclose(lc.counts, ncounts)
Exemplo n.º 31
0
    def _simulate_model_string(self, model_str, params):
        """
        For generating a light curve from a pre-defined model

        Parameters
        ----------
        model_str: string
            name of the pre-defined model
        params: list or dictionary
            parameters of the pre-defined model

        Returns
        -------
        lightCurve: `LightCurve` object
        """

        # Frequencies at which the PSD is to be computed
        # (only positive frequencies, since the signal is real)
        nbins = self.red_noise*self.N
        simfreq = np.fft.rfftfreq(nbins, d=self.dt)[1:]

        if model_str in dir(models):
            if isinstance(params, dict):
                model = eval('models.' + model_str + '(**params)')
                # Compute PSD from model
                simpsd = model(simfreq)
            elif isinstance(params, list):
                simpsd = eval('models.' + model_str + '(simfreq, params)')
            else:
                raise ValueError('Params should be list or dictionary!')

            fac = np.sqrt(simpsd/2.)
            pos_real   = self.random_state.normal(size=nbins//2)*fac
            pos_imag   = self.random_state.normal(size=nbins//2)*fac

            long_lc = self._find_inverse(pos_real, pos_imag)

            lc = Lightcurve(self.time, self._extract_and_scale(long_lc),
                            err_dist='gauss', dt=self.dt)
            return lc
        else:
            raise ValueError('Model is not defined!')
Exemplo n.º 32
0
    def test_fractional_rms_in_frac_norm_is_consistent_averaged(self):
        time = np.arange(0, 400, 1) + 0.5

        poisson_counts = np.random.poisson(100.0, size=time.shape[0])

        lc = Lightcurve(time, counts=poisson_counts, dt=1, gti=[[0, 400]])
        ps = AveragedPowerspectrum(lc,
                                   norm="leahy",
                                   segment_size=100,
                                   silent=True)
        rms_ps_l, rms_err_l = ps.compute_rms(min_freq=ps.freq[1],
                                             max_freq=ps.freq[-1],
                                             white_noise_offset=0)

        ps = AveragedPowerspectrum(lc, norm="frac", segment_size=100)
        rms_ps, rms_err = ps.compute_rms(min_freq=ps.freq[1],
                                         max_freq=ps.freq[-1],
                                         white_noise_offset=0)
        assert np.allclose(rms_ps, rms_ps_l, atol=0.01)
        assert np.allclose(rms_err, rms_err_l, atol=0.01)
Exemplo n.º 33
0
    def _simulate_power_spectrum(self, s):
        """
        Generate a light curve from user-provided spectrum.

        Parameters
        ----------
        s : array-like
            power spectrum

        Returns
        -------
        lightCurve : `LightCurve` object
        """
        # Cast spectrum as numpy array
        s = np.array(s)

        if self.nphot == 0:
            nphot = 1.0
        else:
            nphot = self.nphot
        self.std = np.sqrt(
            (nphot / (self.N**2.)) * (np.sum(s[:-1]) + 0.5 * s[-1]))

        self.red_noise = 1

        # Draw two set of 'N' guassian distributed numbers
        a1 = self.random_state.normal(size=len(s))
        a2 = self.random_state.normal(size=len(s))

        real = a1 * nphot * np.sqrt(s) / 4.0
        imaginary = a2 * nphot * np.sqrt(s) / 4.0

        lc = self._find_inverse(real, imaginary)
        lc = Lightcurve(self.time,
                        self._extract_and_scale(lc),
                        err=np.zeros_like(self.time) + np.sqrt(self.mean),
                        err_dist='gauss',
                        dt=self.dt,
                        skip_checks=True)

        return lc
Exemplo n.º 34
0
    def _simulate_impulse_response(self, s, h, mode='same'):
        """
        Generate LightCurve from impulse response. To get
        accurate results, binning intervals (dt) of variability
        signal 's' and impulse response 'h' must be equal.

        Parameters
        ----------
        s : array-like
            Underlying variability signal
        h : array-like
            Impulse response
        mode : str
            mode can be 'same', 'filtered, or 'full'.
            'same' indicates that the length of output light
            curve is same as that of input signal.
            'filtered' means that length of output light curve
            is len(s) - lag_delay
            'full' indicates that the length of output light
            curve is len(s) + len(h) -1

        Returns
        -------
        lightCurve : :class:`stingray.lightcurve.LightCurve` object
        """
        lc = signal.fftconvolve(s, h)

        if mode == 'same':
            lc = lc[:-(len(h) - 1)]

        elif mode == 'filtered':
            lc = lc[(len(h) - 1):-(len(h) - 1)]

        time = self.dt * np.arange(0.5, len(lc)) + self.tstart
        err = np.zeros_like(time)
        return Lightcurve(time,
                          lc,
                          err_dist='gauss',
                          dt=self.dt,
                          err=err,
                          skip_checks=True)
Exemplo n.º 35
0
    def test_leahy_correct_for_multiple(self, legacy, use_common_mean):

        n = 10
        lc_all = []
        for i in range(n):
            time = np.arange(0.0, 10.0, 10. / 10000)
            counts = np.random.poisson(1000, size=time.shape[0])
            lc = Lightcurve(time, counts)
            lc_all.append(lc)

        ps = AveragedPowerspectrum(lc_all,
                                   1.0,
                                   norm="leahy",
                                   legacy=legacy,
                                   use_common_mean=use_common_mean)

        assert np.isclose(np.mean(ps.power), 2.0, atol=1e-2, rtol=1e-2)
        assert np.isclose(np.std(ps.power),
                          2.0 / np.sqrt(n * 10),
                          atol=0.1,
                          rtol=0.1)
Exemplo n.º 36
0
    def test_list_of_light_curves(self):
        n_lcs = 10

        tstart = 0.0
        tend = 1.0
        dt = 0.0001

        time = np.linspace(tstart, tend, int((tend - tstart) / dt))

        mean_count_rate = 1000.0
        mean_counts = mean_count_rate * dt

        lc_all = []
        for n in range(n_lcs):
            poisson_counts = np.random.poisson(mean_counts, size=len(time))

            lc = Lightcurve(time, counts=poisson_counts)
            lc_all.append(lc)

        segment_size = 0.5
        assert AveragedPowerspectrum(lc_all, segment_size)
Exemplo n.º 37
0
    def _simulate_model(self, model):
        """
        For generating a light curve from a pre-defined model

        Parameters
        ----------
        model: astropy.modeling.Model derived function
            the pre-defined model
            (library-based, available in astropy.modeling.models or custom-defined)

        Returns
        -------
        lightCurve: `LightCurve` object
        """

        # Frequencies at which the PSD is to be computed
        # (only positive frequencies, since the signal is real)
        nbins = self.red_noise * self.N
        simfreq = np.fft.rfftfreq(nbins, d=self.dt)[1:]

        # Compute PSD from model
        simpsd = model(simfreq)

        fac = np.sqrt(simpsd / 2.)
        pos_real = self.random_state.normal(size=nbins // 2) * fac
        pos_imag = self.random_state.normal(size=nbins // 2) * fac

        pos_freq_transform = pos_real + 1j * pos_imag

        # Simulate light curve from its Fourier transform
        arg = np.concatenate(([self.mean], pos_freq_transform))

        # Inverse Fourier transform
        long_lc = np.fft.irfft(arg)

        lc = Lightcurve(self.time,
                        self._extract_and_scale(long_lc),
                        err_dist='gauss',
                        dt=self.dt)
        return lc
Exemplo n.º 38
0
    def _make_lightcurves(self, data):

        self.tstart = np.min(data[:, 0])
        self.tend = np.max(data[:, 0])

        self.tseg = self.tend - self.tstart

        lc_all = []

        for i, b in enumerate(self.band_interest):
            elow = b[0]
            ehigh = b[1]

            toa = data[np.logical_and(data[:, 1] >= elow, data[:, 1] <= ehigh)]

            lc = Lightcurve.make_lightcurve(toa,
                                            self.dt,
                                            tstart=self.tstart,
                                            tseg=self.tseg)
            lc_all.append(lc)

        return lc_all
Exemplo n.º 39
0
    def test_fractional_rms_in_frac_norm_is_consistent(self):
        """
        Copied from test_powerspectrum.py
        """
        time = np.arange(0, 100, 1) + 0.5

        poisson_counts = np.random.poisson(100.0,
                                           size=time.shape[0])

        lc = Lightcurve(time, counts=poisson_counts, dt=1,
                        gti=[[0, 100]])
        mtp = Multitaper(lc, norm="leahy")
        rms_mtp_l, rms_err_l = mtp.compute_rms(min_freq=mtp.freq[1],
                                               max_freq=mtp.freq[-1],
                                               white_noise_offset=0)

        mtp = Multitaper(lc, norm="frac")
        rms_mtp, rms_err = mtp.compute_rms(min_freq=mtp.freq[1],
                                           max_freq=mtp.freq[-1],
                                           white_noise_offset=0)
        assert np.allclose(rms_mtp, rms_mtp_l, atol=0.01)
        assert np.allclose(rms_err, rms_err_l, atol=0.01)
Exemplo n.º 40
0
    def test_sort(self):
        _times = [1, 2, 3, 4]
        _counts = [40, 10, 20, 5]
        lc = Lightcurve(_times, _counts, mjdref=57000)
        mjdref = lc.mjdref

        lc.sort()

        assert np.all(lc.counts == np.array([5, 10, 20, 40]))
        assert np.all(lc.time == np.array([4, 2, 3, 1]))
        assert lc.mjdref == mjdref

        lc.sort(reverse=True)

        assert np.all(lc.counts == np.array([40, 20, 10, 5]))
        assert np.all(lc.time == np.array([1, 3, 2, 4]))
        assert lc.mjdref == mjdref
Exemplo n.º 41
0
    def _make_lightcurves(self, data):
        """
        Create light curves for all bands of interest from ``data``. Takes the information the
        ``band_interest`` attribute and event data in ``data``, and produces a list of
        :class:`stingray.Lightcurve` objects.

        Parameters
        ----------
        data : numpy.ndarray
            Array of shape ``(N, 2)``, where ``N`` is the number of photons. First column contains the
            times of arrivals, second column the corresponding photon energies.

        Returns
        -------
        lc_all : iterable of :class:`stingray.Lightcurve` objects
            A list of :class:`stingray.Lightcurve` objects of all bands of interest.
        """

        self.tstart = np.min(data[:, 0])
        self.tend = np.max(data[:, 0])

        self.tseg = self.tend - self.tstart

        lc_all = []

        for i, b in enumerate(self.band_interest):
            elow = b[0]
            ehigh = b[1]

            toa = data[np.logical_and(data[:, 1] >= elow, data[:, 1] <= ehigh)]

            lc = Lightcurve.make_lightcurve(toa,
                                            self.dt,
                                            tstart=self.tstart,
                                            tseg=self.tseg)
            lc_all.append(lc)

        return lc_all
Exemplo n.º 42
0
    def _simulate_model(self, mod, p):
        """
        For generating a light curve from pre-defined model

        Parameters
        ----------
        mod: str
            name of the pre-defined model

        p: list iterable
            model parameters. For details, see model definitions
            in model.py

        Returns
        -------
        lightCurve: `LightCurve` object
        """

        # Define frequencies at which to compute PSD
        w = np.fft.rfftfreq(self.red_noise * self.N, d=self.dt)[1:]

        if mod in dir(models):
            mod = 'models.' + mod
            s = eval(mod + '(w, p)')

            # Draw two set of 'N' guassian distributed numbers
            a1 = np.random.normal(size=len(s))
            a2 = np.random.normal(size=len(s))

            long_lc = self._find_inverse(a1 * s, a2 * s)
            lc = Lightcurve(self.time, self._extract_and_scale(long_lc))

            return lc

        else:
            raise ValueError('Model is not defined!')
Exemplo n.º 43
0
    def test_multitaper_lombscargle(self):
        rng = np.random.default_rng()
        N = 1000

        white_noise_irregular = rng.normal(loc=0.0, scale=7, size=N)
        start = 0.0
        end = 9.0

        # Generating uneven sampling times by adding white noise. Do tell a better way
        time_irregular = np.linspace(start, end, N) + rng.normal(loc=0.0,
                                                                 scale=(end-start)/(3*N), size=N)
        time_irregular = np.sort(time_irregular)

        with pytest.warns(UserWarning) as record:
            lc_nonuni = Lightcurve(time=time_irregular,
                                   counts=white_noise_irregular, err_dist="gauss",
                                   err=np.ones_like(time_irregular) + np.sqrt(0.))  # Zero mean
        assert np.any(["aren't equal" in r.message.args[0]
                       for r in record])

        mtls_white = Multitaper(lc_nonuni, lombscargle=True, low_bias=True, NW=4)
        assert mtls_white.norm == "frac"
        assert mtls_white.fullspec is False
        assert mtls_white.meancounts == lc_nonuni.meancounts
        assert mtls_white.nphots == np.float64(np.sum(lc_nonuni.counts))
        assert mtls_white.err_dist == lc_nonuni.err_dist
        assert mtls_white.dt == lc_nonuni.dt
        assert mtls_white.n == lc_nonuni.time.shape[0]
        assert mtls_white.df == 1.0 / lc_nonuni.tseg
        assert mtls_white.m == 1
        assert mtls_white.freq is not None
        assert mtls_white.multitaper_norm_power is not None
        assert mtls_white.power is not None
        assert mtls_white.power_err is not None
        assert mtls_white.jk_var_deg_freedom is None  # Not supported yet
        assert len(mtls_white.eigvals) > 0
Exemplo n.º 44
0
    def test_list_with_nonsense_component(self):
        n_lcs = 10

        tstart = 0.0
        tend = 1.0
        dt = 0.0001

        time = np.linspace(tstart, tend, int((tend - tstart) / dt))

        mean_count_rate = 1000.0
        mean_counts = mean_count_rate * dt

        lc_all = []
        for n in range(n_lcs):
            poisson_counts = np.random.poisson(mean_counts, size=len(time))

            lc = Lightcurve(time, counts=poisson_counts)
            lc_all.append(lc)

        lc_all.append(1.0)
        segment_size = 0.5

        with pytest.raises(TypeError):
            assert AveragedPowerspectrum(lc_all, segment_size)
Exemplo n.º 45
0
    def test_indexing(self):
        lc = Lightcurve(self.times, self.counts)

        assert lc[0] == lc[1] == lc[2] == lc[3] == 2
Exemplo n.º 46
0
 def test_tstart(self):
     tstart = 0.0
     lc = Lightcurve.make_lightcurve(self.times, self.dt, tstart=0.0)
     assert lc.tstart == tstart
     assert lc.time[0] == tstart + 0.5 * self.dt
Exemplo n.º 47
0
 def test_correct_timeresolution(self):
     lc = Lightcurve.make_lightcurve(self.times, self.dt)
     assert np.isclose(lc.dt, self.dt)
Exemplo n.º 48
0
 def test_n(self):
     lc = Lightcurve(self.times, self.counts)
     assert lc.n == 4
Exemplo n.º 49
0
 def test_lightcurve_from_toa(self):
     lc = Lightcurve.make_lightcurve(self.times, self.dt)
Exemplo n.º 50
0
 def test_plot_title(self):
     lc = Lightcurve(self.times, self.counts)
     lc.plot(title="Test Lightcurve")
     assert plt.fignum_exists(1)
Exemplo n.º 51
0
 def test_io_with_ascii(self):
     lc = Lightcurve(self.times, self.counts)
     lc.write('ascii_lc.txt', format_='ascii')
     lc.read('ascii_lc.txt', format_='ascii')
     os.remove('ascii_lc.txt')
Exemplo n.º 52
0
 def test_plot_custom_filename(self):
     lc = Lightcurve(self.times, self.counts)
     lc.plot(save=True, filename='lc.png')
     assert os.path.isfile('lc.png')
     os.unlink('lc.png')
Exemplo n.º 53
0
 def test_plot_axis(self):
     lc = Lightcurve(self.times, self.counts)
     lc.plot(axis=[0, 1, 0, 100])
     assert plt.fignum_exists(1)
Exemplo n.º 54
0
 def test_plot_labels_index_error(self):
     lc = Lightcurve(self.times, self.counts)
     with warnings.catch_warnings(record=True) as w:
         lc.plot(labels=('x'))
         assert "must have two labels" in str(w[0].message)
Exemplo n.º 55
0
 def test_plot_default_filename(self):
     lc = Lightcurve(self.times, self.counts)
     lc.plot(save=True)
     assert os.path.isfile('out.png')
     os.unlink('out.png')
Exemplo n.º 56
0
 def test_plot_simple(self):
     lc = Lightcurve(self.times, self.counts)
     lc.plot()
     assert plt.fignum_exists(1)
Exemplo n.º 57
0
 def test_truncate_fails_with_incorrect_method(self):
     lc = Lightcurve(self.times, self.counts)
     with pytest.raises(ValueError):
         lc1 = lc.truncate(start=1, method="wrong")
Exemplo n.º 58
0
    def test_truncate_by_time_stop_less_than_start(self):
        lc = Lightcurve(self.times, self.counts)

        with pytest.raises(ValueError):
            lc1 = lc.truncate(start=2, stop=1, method='time')
Exemplo n.º 59
0
 def test_create(self):
     """
     Demonstrate that we can create a trivial Lightcurve object.
     """
     lc = Lightcurve(self.times, self.counts)
Exemplo n.º 60
0
    def test_slicing_index_error(self):
        lc = Lightcurve(self.times, self.counts)

        with pytest.raises(StingrayError):
            lc_new = lc[1:2]