Esempio n. 1
0
 def test_rebin_data_should_raise_error_when_method_is_different_than_allowed(self):
     dx_new = 2.0
     try:
         utils.rebin_data(self.x, self.y, dx_new, method='not_allowed_method')
     except utils.UnrecognizedMethod:
         pass
     else:
         raise AssertionError("Expected exception does not occurred")
Esempio n. 2
0
 def test_rebin_data_should_raise_error_when_method_is_not_allowed(self):
     dx_new = 2.0
     with pytest.raises(ValueError):
         utils.rebin_data(self.x,
                          self.y,
                          dx_new,
                          self.yerr,
                          method='not_allowed_method')
Esempio n. 3
0
 def test_rebin_data_should_raise_error_when_method_is_different_than_allowed(
         self):
     dx_new = 2.0
     try:
         utils.rebin_data(self.x,
                          self.y,
                          dx_new,
                          method='not_allowed_method')
     except utils.UnrecognizedMethod:
         pass
     else:
         raise AssertionError("Expected exception does not occurred")
Esempio n. 4
0
    def rebin(self, dt_new, method='sum'):
        """
        Rebin the light curve to a new time resolution. While the new
        resolution need not be an integer multiple of the previous time
        resolution, be aware that if it is not, the last bin will be cut
        off by the fraction left over by the integer division.

        Parameters
        ----------
        dt_new: float
            The new time resolution of the light curve. Must be larger than
            the time resolution of the old light curve!

        method: {"sum" | "mean" | "average"}, optional, default "sum"
            This keyword argument sets whether the counts in the new bins
            should be summed or averaged.


        Returns
        -------
        lc_new: :class:`Lightcurve` object
            The :class:`Lightcurve` object with the new, binned light curve.
        """

        if dt_new < self.dt:
            raise ValueError("New time resolution must be larger than "
                             "old time resolution!")

        bin_time, bin_counts, _ = utils.rebin_data(self.time,
                                                   self.counts,
                                                   dt_new, method)

        lc_new = Lightcurve(bin_time, bin_counts)
        return lc_new
Esempio n. 5
0
    def rebin_frequency(self, df_new, method="sum"):
        """
        Rebin the Dynamic Power Spectrum to a new frequency resolution.
        While the new resolution need not be an integer multiple of the
        previous frequency resolution, be aware that if it is not, the last
        bin will be cut off by the fraction left over by the integer division.

        Parameters
        ----------
        df_new: float
            The new frequency resolution of the Dynamica Power Spectrum.
            Must be larger than the frequency resolution of the old Dynamical
            Power Spectrum!

        method: {"sum" | "mean" | "average"}, optional, default "sum"
            This keyword argument sets whether the counts in the new bins
            should be summed or averaged.
        """
        dynspec_new = []
        for data in self.dyn_ps.T:
            freq_new, bin_counts, bin_err, _ = \
                utils.rebin_data(self.freq, data, dx_new=df_new,
                                 method=method)
            dynspec_new.append(bin_counts)

        self.freq = freq_new
        self.dyn_ps = np.array(dynspec_new).T
        self.df = df_new
Esempio n. 6
0
    def rebin(self, df, method="mean"):
        """
        Rebin the cross spectrum to a new frequency resolution df.

        Parameters
        ----------
        df: float
            The new frequency resolution

        Returns
        -------
        bin_cs = Crossspectrum object
            The newly binned cross spectrum
        """

        # rebin cross spectrum to new resolution
        binfreq, bincs, step_size = utils.rebin_data(self.freq[1:],
                                                     self.power[1:], df,
                                                     method=method)

        # make an empty cross spectrum object
        # note: syntax deliberate to work with subclass Powerspectrum
        bin_cs = self.__class__()

        # store the binned periodogram in the new object
        bin_cs.freq = np.hstack([binfreq[0]-self.df, binfreq])
        bin_cs.power = np.hstack([self.power[0], bincs])
        bin_cs.df = df
        bin_cs.n = self.n
        bin_cs.norm = self.norm
        bin_cs.nphots1 = self.nphots1
        bin_cs.nphots2 = self.nphots2
        bin_cs.m = int(step_size)

        return bin_cs
Esempio n. 7
0
    def rebin_frequency(self, df_new, method="sum"):
        """
        Rebin the Dynamic Power Spectrum to a new frequency resolution. Rebinning is
        an in-place operation, i.e. will replace the existing ``dyn_ps`` attribute.

        While the new resolution need not be an integer multiple of the
        previous frequency resolution, be aware that if it is not, the last
        bin will be cut off by the fraction left over by the integer division.

        Parameters
        ----------
        df_new: float
            The new frequency resolution of the Dynamical Power Spectrum.
            Must be larger than the frequency resolution of the old Dynamical
            Power Spectrum!

        method: {``sum`` | ``mean`` | ``average``}, optional, default ``sum``
            This keyword argument sets whether the counts in the new bins
            should be summed or averaged.
        """
        new_dynspec_object = copy.deepcopy(self)
        dynspec_new = []
        for data in self.dyn_ps.T:
            freq_new, bin_counts, bin_err, _ = \
                utils.rebin_data(self.freq, data, dx_new=df_new,
                                 method=method)
            dynspec_new.append(bin_counts)

        new_dynspec_object.freq = freq_new
        new_dynspec_object.dyn_ps = np.array(dynspec_new).T
        new_dynspec_object.df = df_new
        return new_dynspec_object
Esempio n. 8
0
    def rebin_frequency(self, df_new, method="sum"):
        """
        Rebin the Dynamic Power Spectrum to a new frequency resolution.
        While the new resolution need not be an integer multiple of the
        previous frequency resolution, be aware that if it is not, the last
        bin will be cut off by the fraction left over by the integer division.

        Parameters
        ----------
        df_new: float
            The new frequency resolution of the Dynamica Power Spectrum.
            Must be larger than the frequency resolution of the old Dynamical
            Power Spectrum!

        method: {"sum" | "mean" | "average"}, optional, default "sum"
            This keyword argument sets whether the counts in the new bins
            should be summed or averaged.
        """
        dynspec_new = []
        for data in self.dyn_ps.T:
            freq_new, bin_counts, bin_err, _ = \
                utils.rebin_data(self.freq, data, dx_new=df_new,
                                 method=method)
            dynspec_new.append(bin_counts)

        self.freq = freq_new
        self.dyn_ps = np.array(dynspec_new).T
        self.df = df_new
Esempio n. 9
0
    def rebin(self, df, method="mean"):
        """
        Rebin the periodogram to a new frequency resolution df.

        Parameters
        ----------
        df: float
            The new frequency resolution

        Returns
        -------
        bin_ps = Periodogram object
            The newly binned periodogram
        """

        ## rebin power spectrum to new resolution
        binfreq, binps, step_size = utils.rebin_data(self.freq[1:],
                                                     self.ps[1:], df,
                                                     method=method)

        ## make an empty periodogram object
        bin_ps = Powerspectrum()

        ## store the binned periodogram in the new object
        bin_ps.norm = self.norm
        bin_ps.freq = np.hstack([binfreq[0]-self.df, binfreq])
        bin_ps.ps = np.hstack([self.ps[0], binps])
        bin_ps.df = df
        bin_ps.n = self.n
        bin_ps.nphots = self.nphots
        bin_ps.m = int(step_size)

        return bin_ps
Esempio n. 10
0
    def rebin(self, df, method="mean"):
        """
        Rebin the periodogram to a new frequency resolution df.

        Parameters
        ----------
        df: float
            The new frequency resolution

        Returns
        -------
        bin_ps = Periodogram object
            The newly binned periodogram
        """

        ## rebin power spectrum to new resolution
        binfreq, binps, step_size = utils.rebin_data(self.freq[1:],
                                                     self.ps[1:],
                                                     df,
                                                     method=method)

        ## make an empty periodogram object
        bin_ps = Powerspectrum()

        ## store the binned periodogram in the new object
        bin_ps.norm = self.norm
        bin_ps.freq = np.hstack([binfreq[0] - self.df, binfreq])
        bin_ps.ps = np.hstack([self.ps[0], binps])
        bin_ps.df = df
        bin_ps.n = self.n
        bin_ps.nphots = self.nphots
        bin_ps.m = int(step_size)

        return bin_ps
Esempio n. 11
0
    def rebin(self, dt_new, method='sum'):
        """
        Rebin the light curve to a new time resolution. While the new
        resolution need not be an integer multiple of the previous time
        resolution, be aware that if it is not, the last bin will be cut
        off by the fraction left over by the integer division.

        Parameters
        ----------
        dt_new: float
            The new time resolution of the light curve. Must be larger than
            the time resolution of the old light curve!

        method: {"sum" | "mean" | "average"}, optional, default "sum"
            This keyword argument sets whether the counts in the new bins
            should be summed or averaged.


        Returns
        -------
        lc_new: :class:`Lightcurve` object
            The :class:`Lightcurve` object with the new, binned light curve.
        """

        if dt_new < self.dt:
            raise ValueError("New time resolution must be larger than "
                             "old time resolution!")

        bin_time, bin_counts, _ = utils.rebin_data(self.time, self.counts,
                                                   dt_new, method)

        lc_new = Lightcurve(bin_time, bin_counts)
        return lc_new
Esempio n. 12
0
    def test_binned_counts(self):
        dx_new = 2.0

        xbin, ybin, step_size = utils.rebin_data(self.x, self.y, dx_new)

        ybin_test = np.zeros_like(xbin) + self.counts*dx_new/self.dx
        assert np.allclose(ybin, ybin_test)
Esempio n. 13
0
 def test_uneven_binned_counts(self):
     dx_new = 1.5
     xbin, ybin, step_size = utils.rebin_data(self.x, self.y, dx_new)
     print(xbin)
     print(ybin)
     ybin_test = np.zeros_like(xbin) + self.counts*dx_new/self.dx
     assert np.allclose(ybin_test, ybin)
Esempio n. 14
0
 def test_uneven_binned_counts(self):
     dx_new = 1.5
     xbin, ybin, step_size = utils.rebin_data(self.x, self.y, dx_new)
     print(xbin)
     print(ybin)
     ybin_test = np.zeros_like(xbin) + self.counts * dx_new / self.dx
     assert np.allclose(ybin_test, ybin)
Esempio n. 15
0
    def test_binned_counts(self):
        dx_new = 2.0

        xbin, ybin, step_size = utils.rebin_data(self.x, self.y, dx_new)

        ybin_test = np.zeros_like(xbin) + self.counts * dx_new / self.dx
        assert np.allclose(ybin, ybin_test)
Esempio n. 16
0
    def rebin(self, dt_new=None, f=None, method='sum'):
        """
        Rebin the light curve to a new time resolution. While the new
        resolution need not be an integer multiple of the previous time
        resolution, be aware that if it is not, the last bin will be cut
        off by the fraction left over by the integer division.

        Parameters
        ----------
        dt_new: float
            The new time resolution of the light curve. Must be larger than
            the time resolution of the old light curve!

        method: {"sum" | "mean" | "average"}, optional, default "sum"
            This keyword argument sets whether the counts in the new bins
            should be summed or averaged.

        Other Parameters
        ----------------
        f: float
            the rebin factor. If specified, it substitutes dt_new with
            f*self.dt

        Returns
        -------
        lc_new: :class:`Lightcurve` object
            The :class:`Lightcurve` object with the new, binned light curve.
        """

        if f is None and dt_new is None:
            raise ValueError('You need to specify at least one between f and '
                             'dt_new')
        elif f is not None:
            dt_new = f * self.dt

        if dt_new < self.dt:
            raise ValueError("New time resolution must be larger than "
                             "old time resolution!")

        bin_time, bin_counts, bin_err, _ = \
            utils.rebin_data(self.time, self.counts, dt_new,
                             yerr=self.counts_err, method=method)

        lc_new = Lightcurve(bin_time,
                            bin_counts,
                            err=bin_err,
                            mjdref=self.mjdref,
                            dt=dt_new)
        return lc_new
Esempio n. 17
0
    def test_rebin_variable_input_sampling(self):
        x1 = np.linspace(0, 10, 11)
        x2 = np.linspace(10.33, 20.0, 30)
        x3 = np.linspace(21, 30, 10)
        x = np.hstack([x1, x2, x3])

        counts = 2.0
        y = np.zeros_like(x) + counts

        yerr = np.sqrt(y)
        dx_new = 1.5
        xbin, ybin, yerr_bin, step_size = utils.rebin_data(x, y, dx_new, yerr)

        assert np.allclose(ybin, counts * step_size)
        assert len(xbin) == 20
Esempio n. 18
0
    def rebin(self, dt_new=None, f=None, method='sum'):
        """
        Rebin the light curve to a new time resolution. While the new
        resolution need not be an integer multiple of the previous time
        resolution, be aware that if it is not, the last bin will be cut
        off by the fraction left over by the integer division.

        Parameters
        ----------
        dt_new: float
            The new time resolution of the light curve. Must be larger than
            the time resolution of the old light curve!

        method: {"sum" | "mean" | "average"}, optional, default "sum"
            This keyword argument sets whether the counts in the new bins
            should be summed or averaged.

        Other Parameters
        ----------------
        f: float
            the rebin factor. If specified, it substitutes dt_new with
            f*self.dt

        Returns
        -------
        lc_new: :class:`Lightcurve` object
            The :class:`Lightcurve` object with the new, binned light curve.
        """

        if f is None and dt_new is None:
            raise ValueError('You need to specify at least one between f and '
                             'dt_new')
        elif f is not None:
            dt_new = f * self.dt

        if dt_new < self.dt:
            raise ValueError("New time resolution must be larger than "
                             "old time resolution!")

        bin_time, bin_counts, bin_err, _ = \
            utils.rebin_data(self.time, self.counts, dt_new,
                             yerr=self.counts_err, method=method)

        lc_new = Lightcurve(bin_time, bin_counts, err=bin_err,
                            mjdref=self.mjdref, dt=dt_new)
        return lc_new
Esempio n. 19
0
    def rebin(self, df, method="mean"):
        """
        Rebin the cross spectrum to a new frequency resolution df.

        Parameters
        ----------
        df: float
            The new frequency resolution

        Returns
        -------
        bin_cs = Crossspectrum object
            The newly binned cross spectrum
        """

        # rebin cross spectrum to new resolution
        binfreq, bincs, binerr, step_size = \
            rebin_data(self.freq, self.power, df, self.power_err,
                       method=method)

        # make an empty cross spectrum object
        # note: syntax deliberate to work with subclass Powerspectrum
        bin_cs = self.__class__()

        # store the binned periodogram in the new object
        bin_cs.freq = binfreq
        bin_cs.power = bincs
        bin_cs.df = df
        bin_cs.n = self.n
        bin_cs.norm = self.norm
        bin_cs.nphots1 = self.nphots1
        bin_cs.power_err = binerr

        try:
            bin_cs.nphots2 = self.nphots2
        except AttributeError:
            if self.type == 'powerspectrum':
                pass
            else:
                raise AttributeError(
                    'Spectrum has no attribute named nphots2.')

        bin_cs.m = int(step_size) * self.m

        return bin_cs
Esempio n. 20
0
    def rebin_time(self, dt_new, method='sum'):

        """
        Rebin the Dynamic Power Spectrum to a new time resolution.
        While the new resolution need not be an integer multiple of the
        previous time resolution, be aware that if it is not, the last bin
        will be cut off by the fraction left over by the integer division.

        Parameters
        ----------
        dt_new: float
            The new time resolution of the Dynamical Power Spectrum.
            Must be larger than the time resolution of the old Dynamical Power
            Spectrum!

        method: {"sum" | "mean" | "average"}, optional, default "sum"
            This keyword argument sets whether the counts in the new bins
            should be summed or averaged.


        Returns
        -------
        time_new: numpy.ndarray
            Time axis with new rebinned time resolution.

        dynspec_new: numpy.ndarray
            New rebinned Dynamical Power Spectrum.
        """
        if dt_new < self.dt:
            raise ValueError("New time resolution must be larger than "
                             "old time resolution!")

        new_dynspec_object = copy.deepcopy(self)

        dynspec_new = []
        for data in self.dyn_ps:
            time_new, bin_counts, bin_err, _ = \
                utils.rebin_data(self.time, data, dt_new,
                                 method=method)
            dynspec_new.append(bin_counts)

        new_dynspec_object.time = time_new
        new_dynspec_object.dyn_ps = np.array(dynspec_new)
        new_dynspec_object.dt = dt_new
        return new_dynspec_object
Esempio n. 21
0
    def rebin(self, df, method="mean"):
        """
        Rebin the cross spectrum to a new frequency resolution df.

        Parameters
        ----------
        df: float
            The new frequency resolution

        Returns
        -------
        bin_cs = Crossspectrum object
            The newly binned cross spectrum
        """

        # rebin cross spectrum to new resolution
        binfreq, bincs, step_size = utils.rebin_data(self.freq,
                                                     self.power, df,
                                                     method=method)

        # make an empty cross spectrum object
        # note: syntax deliberate to work with subclass Powerspectrum
        bin_cs = self.__class__()

        # store the binned periodogram in the new object
        bin_cs.freq = binfreq
        bin_cs.power = bincs
        bin_cs.df = df
        bin_cs.n = self.n
        bin_cs.norm = self.norm
        bin_cs.nphots1 = self.nphots1

        try:
            bin_cs.nphots2 = self.nphots2
        except AttributeError:
            if self.type == 'powerspectrum':
                pass
            else:
                raise AttributeError('Spectrum has no attribute named nphots2.')

        bin_cs.m = int(step_size)*self.m

        return bin_cs
Esempio n. 22
0
    def rebin_time(self, dt_new, method='sum'):

        """
        Rebin the Dynamic Power Spectrum to a new time resolution.
        While the new resolution need not be an integer multiple of the
        previous time resolution, be aware that if it is not, the last bin
        will be cut off by the fraction left over by the integer division.

        Parameters
        ----------
        dt_new: float
            The new time resolution of the Dynamica Power Spectrum.
            Must be larger than the time resolution of the old Dynamical Power
            Spectrum!

        method: {"sum" | "mean" | "average"}, optional, default "sum"
            This keyword argument sets whether the counts in the new bins
            should be summed or averaged.


        Returns
        -------
        time_new: numpy.ndarray
            Time axis with new rebinned time resolution.

        dynspec_new: numpy.ndarray
            New rebinned Dynamical Power Spectrum.
        """

        if dt_new < self.dt:
            raise ValueError("New time resolution must be larger than "
                             "old time resolution!")

        dynspec_new = []
        for data in self.dyn_ps:
            time_new, bin_counts, bin_err, _ = \
                utils.rebin_data(self.time, data, dt_new,
                                 method=method)
            dynspec_new.append(bin_counts)

        self.time = time_new
        self.dyn_ps = np.array(dynspec_new)
        self.dt = dt_new
Esempio n. 23
0
    def rebin(self, df, method="mean"):
        """
        Rebin the cross spectrum to a new frequency resolution df.

        Parameters
        ----------
        df: float
            The new frequency resolution

        Returns
        -------
        bin_cs = Crossspectrum object
            The newly binned cross spectrum
        """

        # rebin cross spectrum to new resolution
        binfreq, bincs, step_size = utils.rebin_data(self.freq,
                                                     self.power,
                                                     df,
                                                     method=method)

        # make an empty cross spectrum object
        # note: syntax deliberate to work with subclass Powerspectrum
        bin_cs = self.__class__()

        # store the binned periodogram in the new object
        bin_cs.freq = binfreq
        bin_cs.power = bincs
        bin_cs.df = df
        bin_cs.n = self.n
        bin_cs.norm = self.norm
        bin_cs.nphots1 = self.nphots1
        bin_cs.nphots2 = self.nphots2
        bin_cs.m = int(step_size) * self.m

        return bin_cs
Esempio n. 24
0
 def test_length_matches(self):
     dx_new = 2.0
     xbin, ybin, step_size = utils.rebin_data(self.x, self.y, dx_new)
     assert xbin.shape[0] == ybin.shape[0]
Esempio n. 25
0
 def test_arrays(self):
     dx_new = 2.0
     xbin, ybin, step_size = utils.rebin_data(self.x, self.y, dx_new)
     assert isinstance(xbin, np.ndarray)
     assert isinstance(ybin, np.ndarray)
Esempio n. 26
0
 def test_new_stepsize(self):
     dx_new = 2.0
     xbin, ybin, step_size = utils.rebin_data(self.x, self.y, dx_new)
     assert step_size == dx_new/self.dx
Esempio n. 27
0
    def rebin(self, dt_new=None, f=None, method='sum'):
        """
        Rebin the light curve to a new time resolution. While the new
        resolution need not be an integer multiple of the previous time
        resolution, be aware that if it is not, the last bin will be cut
        off by the fraction left over by the integer division.

        Parameters
        ----------
        dt_new: float
            The new time resolution of the light curve. Must be larger than
            the time resolution of the old light curve!

        method: {``sum`` | ``mean`` | ``average``}, optional, default ``sum``
            This keyword argument sets whether the counts in the new bins
            should be summed or averaged.

        Other Parameters
        ----------------
        f: float
            the rebin factor. If specified, it substitutes ``dt_new`` with
            ``f*self.dt``

        Returns
        -------
        lc_new: :class:`Lightcurve` object
            The :class:`Lightcurve` object with the new, binned light curve.
        """

        if f is None and dt_new is None:
            raise ValueError('You need to specify at least one between f and '
                             'dt_new')
        elif f is not None:
            dt_new = f * self.dt

        if dt_new < self.dt:
            raise ValueError("New time resolution must be larger than "
                             "old time resolution!")

        if self.gti is None:

            bin_time, bin_counts, bin_err, _ = \
                utils.rebin_data(self.time, self.counts, dt_new,
                                 yerr=self.counts_err, method=method)

        else:
            bin_time, bin_counts, bin_err = [], [], []
            gti_new = []
            for g in self.gti:
                if g[1] - g[0] < dt_new:
                    continue
                else:
                    # find start and end of GTI segment in data
                    start_ind = self.time.searchsorted(g[0])
                    end_ind = self.time.searchsorted(g[1])

                    t_temp = self.time[start_ind:end_ind]
                    c_temp = self.counts[start_ind:end_ind]
                    e_temp = self.counts_err[start_ind:end_ind]

                    bin_t, bin_c, bin_e, _ = \
                        utils.rebin_data(t_temp, c_temp, dt_new,
                                         yerr=e_temp, method=method)

                    bin_time.extend(bin_t)
                    bin_counts.extend(bin_c)
                    bin_err.extend(bin_e)
                    gti_new.append(g)

        lc_new = Lightcurve(bin_time, bin_counts, err=bin_err,
                            mjdref=self.mjdref, dt=dt_new, gti=gti_new)
        return lc_new
Esempio n. 28
0
 def test_uneven_bins(self):
     dx_new = 1.5
     xbin, ybin, yerr, step_size = utils.rebin_data(self.x, self.y, dx_new,
                                                    self.yerr)
     assert np.isclose(xbin[1]-xbin[0], dx_new)
Esempio n. 29
0
 def test_length_matches(self):
     dx_new = 2.0
     xbin, ybin, yerr, step_size = utils.rebin_data(self.x, self.y, dx_new,
                                                    self.yerr)
     assert xbin.shape[0] == ybin.shape[0]
Esempio n. 30
0
 def test_arrays(self):
     dx_new = 2.0
     xbin, ybin, yerr, step_size = utils.rebin_data(self.x, self.y, dx_new,
                                                    self.yerr)
     assert isinstance(xbin, np.ndarray)
     assert isinstance(ybin, np.ndarray)
Esempio n. 31
0
 def test_new_stepsize(self):
     dx_new = 2.0
     xbin, ybin, yerr, step_size = utils.rebin_data(self.x, self.y, dx_new,
                                                    self.yerr)
     assert step_size == dx_new/self.dx
Esempio n. 32
0
 def test_uneven_bins(self):
     dx_new = 1.5
     xbin, ybin, step_size = utils.rebin_data(self.x, self.y, dx_new)
     assert np.isclose(xbin[1]-xbin[0], dx_new)
Esempio n. 33
0
    def rebin(self, df=None, f=None, method="mean"):
        """
        Rebin the cross spectrum to a new frequency resolution df.

        Parameters
        ----------
        df: float
            The new frequency resolution

        Other Parameters
        ----------------
        f: float
            the rebin factor. If specified, it substitutes df with f*self.df

        Returns
        -------
        bin_cs = Crossspectrum (or one of its subclasses) object
            The newly binned cross spectrum or power spectrum.
            Note: this object will be of the same type as the object
            that called this method. For example, if this method is called
            from `AveragedPowerspectrum`, it will return an object of class
            `AveragedPowerspectrum`, too.
        """

        if f is None and df is None:
            raise ValueError('You need to specify at least one between f and '
                             'df')
        elif f is not None:
            df = f * self.df

        # rebin cross spectrum to new resolution
        binfreq, bincs, binerr, step_size = \
            rebin_data(self.freq, self.power, df, self.power_err,
                       method=method, dx=self.df)

        # make an empty cross spectrum object
        # note: syntax deliberate to work with subclass Powerspectrum
        bin_cs = copy.copy(self)

        # store the binned periodogram in the new object
        bin_cs.freq = binfreq
        bin_cs.power = bincs
        bin_cs.df = df
        bin_cs.n = self.n
        bin_cs.norm = self.norm
        bin_cs.nphots1 = self.nphots1
        bin_cs.power_err = binerr

        if hasattr(self, 'unnorm_power'):
            _, binpower_unnorm, _, _ = \
                rebin_data(self.freq, self.unnorm_power, df,
                           method=method, dx=self.df)

            bin_cs.unnorm_power = binpower_unnorm

        if hasattr(self, 'cs_all'):
            cs_all = []
            for c in self.cs_all:
                cs_all.append(c.rebin(df=df, f=f, method=method))
            bin_cs.cs_all = cs_all
        if hasattr(self, 'pds1'):
            bin_cs.pds1 = self.pds1.rebin(df=df, f=f, method=method)
        if hasattr(self, 'pds2'):
            bin_cs.pds2 = self.pds2.rebin(df=df, f=f, method=method)

        try:
            bin_cs.nphots2 = self.nphots2
        except AttributeError:
            if self.type == 'powerspectrum':
                pass
            else:
                raise AttributeError('Spectrum has no attribute named nphots2.')

        bin_cs.m = np.rint(step_size * self.m)

        return bin_cs
Esempio n. 34
0
    def rebin(self, df=None, f=None, method="mean"):
        """
        Rebin the cross spectrum to a new frequency resolution ``df``.

        Parameters
        ----------
        df: float
            The new frequency resolution

        Other Parameters
        ----------------
        f: float
            the rebin factor. If specified, it substitutes df with ``f*self.df``

        Returns
        -------
        bin_cs = :class:`Crossspectrum` (or one of its subclasses) object
            The newly binned cross spectrum or power spectrum.
            Note: this object will be of the same type as the object
            that called this method. For example, if this method is called
            from :class:`AveragedPowerspectrum`, it will return an object of class
            :class:`AveragedPowerspectrum`, too.
        """

        if f is None and df is None:
            raise ValueError('You need to specify at least one between f and '
                             'df')
        elif f is not None:
            df = f * self.df

        # rebin cross spectrum to new resolution
        binfreq, bincs, binerr, step_size = \
            rebin_data(self.freq, self.power, df, self.power_err,
                       method=method, dx=self.df)

        # make an empty cross spectrum object
        # note: syntax deliberate to work with subclass Powerspectrum
        bin_cs = copy.copy(self)

        # store the binned periodogram in the new object
        bin_cs.freq = binfreq
        bin_cs.power = bincs
        bin_cs.df = df
        bin_cs.n = self.n
        bin_cs.norm = self.norm
        bin_cs.nphots1 = self.nphots1
        bin_cs.power_err = binerr

        if hasattr(self, 'unnorm_power'):
            _, binpower_unnorm, _, _ = \
                rebin_data(self.freq, self.unnorm_power, df,
                           method=method, dx=self.df)

            bin_cs.unnorm_power = binpower_unnorm

        if hasattr(self, 'cs_all'):
            cs_all = []
            for c in self.cs_all:
                cs_all.append(c.rebin(df=df, f=f, method=method))
            bin_cs.cs_all = cs_all
        if hasattr(self, 'pds1'):
            bin_cs.pds1 = self.pds1.rebin(df=df, f=f, method=method)
        if hasattr(self, 'pds2'):
            bin_cs.pds2 = self.pds2.rebin(df=df, f=f, method=method)

        try:
            bin_cs.nphots2 = self.nphots2
        except AttributeError:
            if self.type == 'powerspectrum':
                pass
            else:
                raise AttributeError(
                    'Spectrum has no attribute named nphots2.')

        bin_cs.m = np.rint(step_size * self.m)

        return bin_cs
Esempio n. 35
0
    def rebin(self, dt_new=None, f=None, method='sum'):
        """
        Rebin the light curve to a new time resolution. While the new
        resolution need not be an integer multiple of the previous time
        resolution, be aware that if it is not, the last bin will be cut
        off by the fraction left over by the integer division.

        Parameters
        ----------
        dt_new: float
            The new time resolution of the light curve. Must be larger than
            the time resolution of the old light curve!

        method: {``sum`` | ``mean`` | ``average``}, optional, default ``sum``
            This keyword argument sets whether the counts in the new bins
            should be summed or averaged.

        Other Parameters
        ----------------
        f: float
            the rebin factor. If specified, it substitutes ``dt_new`` with
            ``f*self.dt``

        Returns
        -------
        lc_new: :class:`Lightcurve` object
            The :class:`Lightcurve` object with the new, binned light curve.
        """

        if f is None and dt_new is None:
            raise ValueError('You need to specify at least one between f and '
                             'dt_new')
        elif f is not None:
            dt_new = f * self.dt

        if dt_new < self.dt:
            raise ValueError("New time resolution must be larger than "
                             "old time resolution!")

        if self.gti is None:

            bin_time, bin_counts, bin_err, _ = \
                utils.rebin_data(self.time, self.counts, dt_new,
                                 yerr=self.counts_err, method=method)

        else:
            bin_time, bin_counts, bin_err = [], [], []
            gti_new = []
            for g in self.gti:
                if g[1] - g[0] < dt_new:
                    continue
                else:
                    # find start and end of GTI segment in data
                    start_ind = self.time.searchsorted(g[0])
                    end_ind = self.time.searchsorted(g[1])

                    t_temp = self.time[start_ind:end_ind]
                    c_temp = self.counts[start_ind:end_ind]
                    e_temp = self.counts_err[start_ind:end_ind]

                    bin_t, bin_c, bin_e, _ = \
                        utils.rebin_data(t_temp, c_temp, dt_new,
                                         yerr=e_temp, method=method)

                    bin_time.extend(bin_t)
                    bin_counts.extend(bin_c)
                    bin_err.extend(bin_e)
                    gti_new.append(g)

        lc_new = Lightcurve(bin_time, bin_counts, err=bin_err,
                            mjdref=self.mjdref, dt=dt_new, gti=gti_new)
        return lc_new
Esempio n. 36
0
 def test_rebin_data_should_raise_error_when_method_is_different_than_allowed(self):
     dx_new = 2.0
     with pytest.raises(ValueError):
         utils.rebin_data(self.x, self.y, dx_new, method='not_allowed_method')