def test_lc_keyword_deprecation(self): cs1 = Crossspectrum(self.lc1, self.lc2) with pytest.warns(DeprecationWarning) as record: cs2 = Crossspectrum(lc1=self.lc1, lc2=self.lc2) assert np.any(['lcN keywords' in r.message.args[0] for r in record]) assert np.allclose(cs1.power, cs2.power) assert np.allclose(cs1.freq, cs2.freq)
def setup_class(self): tstart = 0.0 self.tseg = 100000.0 dt = 1 time = np.arange(tstart + 0.5 * dt, self.tseg + 0.5 * dt, dt) np.random.seed(100) counts1 = np.random.poisson(10000, size=time.shape[0]) counts1_norm = counts1 / 13.4 counts1_norm_err = np.std(counts1) / 13.4 self.lc1_norm = \ Lightcurve(time, counts1_norm, gti=[[tstart, self.tseg]], dt=dt, err_dist='gauss', err=np.zeros_like(counts1_norm) + counts1_norm_err) self.lc1 = Lightcurve(time, counts1, gti=[[tstart, self.tseg]], dt=dt) self.rate1 = np.mean( counts1) / dt # mean count rate (counts/sec) of light curve 1 with pytest.warns(UserWarning) as record: self.cs = Crossspectrum(self.lc1, self.lc1, norm="none") with pytest.warns(UserWarning) as record: self.cs_norm = Crossspectrum(self.lc1_norm, self.lc1_norm, norm="none")
def test_classical_significances_with_logbinned_psd(self): with pytest.warns(UserWarning) as record: cs = Crossspectrum(self.lc1, self.lc2, norm='leahy') cs_log = cs.rebin_log() pval = cs_log.classical_significances(threshold=1.1, trial_correction=False) assert len(pval[0]) == len(cs_log.power)
def test_coherence(self): lc1 = Lightcurve([1, 2, 3, 4, 5], [2, 3, 2, 4, 1]) lc2 = Lightcurve([1, 2, 3, 4, 5], [4, 8, 1, 9, 11]) cs = Crossspectrum(lc1, lc2) coh = cs.coherence() assert len(coh) == 2 assert np.abs(np.mean(coh)) < 1
def test_coherence(self): lc1 = Lightcurve([1, 2, 3, 4, 5], [2, 3, 2, 4, 1]) lc2 = Lightcurve([1, 2, 3, 4, 5], [4, 8, 1, 9, 11]) with pytest.warns(UserWarning) as record: cs = Crossspectrum(lc1, lc2) coh = cs.coherence() assert len(coh) == 2 assert np.abs(np.mean(coh)) < 1
def test_normalize_crossspectrum(self): cs1 = Crossspectrum(self.lc1, self.lc2, norm="leahy") cs2 = Crossspectrum(self.lc1, self.lc2, norm="leahy", power_type="all") cs3 = Crossspectrum(self.lc1, self.lc2, norm="leahy", power_type="real") cs4 = Crossspectrum(self.lc1, self.lc2, norm="leahy", power_type="absolute") assert np.all(cs1.power.real == cs3.power) assert np.all(np.isclose(np.abs(cs2.power), cs4.power, atol=0.0001))
def test_classical_significances_trial_correction(self): with pytest.warns(UserWarning) as record: cs = Crossspectrum(self.lc1, self.lc2, norm='leahy') # change the powers so that just one exceeds the threshold cs.power = np.zeros_like(cs.power) + 2.0 index = 1 cs.power[index] = 10.0 threshold = 0.01 pval = cs.classical_significances(threshold=threshold, trial_correction=True) assert np.size(pval) == 0
def ccf_error(ref_counts, ci_counts_0, cs_res_model, rebin_log_factor, meta, ps_rms, filter_type="optimal"): n_seg = meta['N_SEG'] n_seconds = meta['NSECONDS'] dt = meta['DT'] n_bins = meta['N_BINS'] seg_ref_counts = np.array(np.split(ref_counts, n_seg)) seg_ci_counts = np.array(np.split(ci_counts_0, n_seg)) seg_css = np.array([]) seg_ccfs = np.array([]) seg_times = np.arange(0, n_seconds, dt) # light curve time bins for i in range(n_seg): # for each segment # Creating cross spectrum seg_ci_lc = Lightcurve(seg_times, seg_ci_counts[i], dt=dt) # CoI light curve seg_ref_lc = Lightcurve(seg_times, seg_ref_counts[i], dt=dt) # reference band light curve seg_cs = Crossspectrum(lc2=seg_ci_lc, lc1=seg_ref_lc, norm='leahy', power_type="absolute") # cross spectrum seg_cs = seg_cs.rebin_log(rebin_log_factor) # cross spectrum rebinning # applying filter if filter_type == "optimal": cs_filter = Optimal1D(cs_res_model) filter_freq = cs_filter(seg_cs.freq) filtered_seg_cs_power = filter_freq * np.abs(seg_cs.power) else: cs_filter = Window1D(cs_res_model) filter_freq = cs_filter(seg_cs.freq) filtered_seg_cs_power = filter_freq * np.abs(seg_cs.power) # calculating normalized ccf seg_ccf = ifft(filtered_seg_cs_power) # inverse FFT seg_ccf_real = seg_ccf.real # real part of ccf seg_ccf_real_norm = seg_ccf_real * ( 2 / n_bins / ps_rms) # normalisation if i == 0: seg_css = np.hstack((seg_css, np.array(filtered_seg_cs_power))) else: seg_css = np.vstack((seg_css, np.array(filtered_seg_cs_power))) if i == 0: seg_ccfs = np.hstack((seg_ccfs, np.array(seg_ccf_real_norm))) else: seg_ccfs = np.vstack((seg_ccfs, np.array(seg_ccf_real_norm))) # ccf after taking avg avg_seg_css = np.average(seg_css, axis=0) # average of cross spectrum avg_seg_ccf = ccf(avg_seg_css, ps_rms, n_bins) error = standard_error(seg_ccfs, avg_seg_ccf) return error, avg_seg_ccf
def setup_class(self): tstart = 0.0 tend = 1.0 dt = 0.0001 time = np.arange(tstart + 0.5 * dt, tend + 0.5 * dt, dt) counts1 = np.random.poisson(0.01, size=time.shape[0]) counts2 = np.random.negative_binomial(1, 0.09, size=time.shape[0]) self.lc1 = Lightcurve(time, counts1, gti=[[tstart, tend]], dt=dt) self.lc2 = Lightcurve(time, counts2, gti=[[tstart, tend]], dt=dt) self.rate1 = 100. # mean count rate (counts/sec) of light curve 1 self.cs = Crossspectrum(self.lc1, self.lc2)
def setup_class(self): tstart = 0.0 tend = 1.0 dt = 0.0001 time = np.linspace(tstart, tend, int((tend - tstart)/dt)) counts1 = np.random.poisson(0.01, size=time.shape[0]) counts2 = np.random.negative_binomial(1, 0.09, size=time.shape[0]) self.lc1 = Lightcurve(time, counts1) self.lc2 = Lightcurve(time, counts2) self.cs = Crossspectrum(self.lc1, self.lc2)
def calculate_lag(self, lc, h, delay): """ Class method to calculate lag between two light curves. """ s = lc.counts output = self.simulator.simulate(s, h, 'same')[delay:] s = s[delay:] time = lc.time[delay:] lc1 = Lightcurve(time, s) lc2 = Lightcurve(time, output) cross = Crossspectrum(lc1, lc2) cross = cross.rebin(0.0075) return np.angle(cross.power) / (2 * np.pi * cross.freq)
def test_pvals_is_numpy_array(self): cs = Crossspectrum(self.lc1, self.lc2, norm='leahy') # change the powers so that just one exceeds the threshold cs.power = np.zeros_like(cs.power) + 2.0 index = 1 cs.power[index] = 10.0 threshold = 1.0 pval = cs.classical_significances(threshold=threshold, trial_correction=True) assert isinstance(pval, np.ndarray) assert pval.shape[0] == 2
def test_norm_abs(self): # Testing for a power spectrum of lc1 cs = Crossspectrum(self.lc1, self.lc1, norm='abs') assert len(cs.power) == 4999 assert cs.norm == 'abs' abs_noise = 2. * self.rate1 # expected Poisson noise level assert np.isclose(np.mean(cs.power[1:]), abs_noise)
def test_norm_leahy(self): with pytest.warns(UserWarning) as record: cs = Crossspectrum(self.lc1, self.lc1, norm='leahy') assert len(cs.power) == 4999 assert cs.norm == 'leahy' leahy_noise = 2.0 # expected Poisson noise level assert np.isclose(np.mean(cs.power[1:]), leahy_noise, rtol=0.02)
def test_norm_frac(self): with pytest.warns(UserWarning) as record: cs = Crossspectrum(self.lc1, self.lc1, norm='frac') assert len(cs.power) == 4999 assert cs.norm == 'frac' norm = 2. / self.rate1 assert np.isclose(np.mean(cs.power[1:]), norm, rtol=0.2)
def test_intensity_varying_channels(self): """ Tests lags for multiple energy channels with each channel having same position and varying intensity. """ lc = sampledata.sample_data() s = lc.counts h = [] h.append(self.simulator.simple_ir(start=4, width=1, intensity=10)) h.append(self.simulator.simple_ir(start=4, width=1, intensity=20)) delay = int(5 / lc.dt) outputs = [] for i in h: lc2 = self.simulator.simulate(s, i) lc2 = lc2.shift(-lc2.time[0] + lc.time[0]) outputs.append(lc2) cross = [Crossspectrum(lc, lc2).rebin(0.0075) for lc2 in outputs] lags = [np.angle(c.power) / (2 * np.pi * c.freq) for c in cross] v_cutoff = 1.0 / (2.0 * 5) h_cutoffs = [ lag[int((v_cutoff - 0.0075) * 1 / 0.0075)] for lag in lags ] assert np.abs(5 - h_cutoffs[0]) < np.sqrt(5) assert np.abs(5 - h_cutoffs[1]) < np.sqrt(5)
def setup_class(cls): np.random.seed(150) cls.nlor = 3 cls.x_0_0 = 0.5 cls.x_0_1 = 2.0 cls.x_0_2 = 7.5 cls.amplitude_0 = 200.0 cls.amplitude_1 = 100.0 cls.amplitude_2 = 50.0 cls.fwhm_0 = 0.1 cls.fwhm_1 = 1.0 cls.fwhm_2 = 0.5 cls.whitenoise = 2.0 cls.priors = { 'x_0_0': cls.x_0_0, 'x_0_1': cls.x_0_1, 'x_0_2': cls.x_0_2, 'amplitude_0': cls.amplitude_0, 'amplitude_1': cls.amplitude_1, 'amplitude_2': cls.amplitude_2, 'fwhm_0': cls.fwhm_0, 'fwhm_1': cls.fwhm_1, 'fwhm_2': cls.fwhm_2, 'whitenoise': cls.whitenoise } cls.model = models.Lorentz1D(cls.amplitude_0, cls.x_0_0, cls.fwhm_0) +\ models.Lorentz1D(cls.amplitude_1, cls.x_0_1, cls.fwhm_1) + \ models.Lorentz1D(cls.amplitude_2, cls.x_0_2, cls.fwhm_2) + \ models.Const1D(cls.whitenoise) freq = np.linspace(0.01, 10.0, 1000) p = cls.model(freq) noise = np.random.exponential(size=len(freq)) power = p * noise cls.ps = Powerspectrum() cls.ps.freq = freq cls.ps.power = power cls.ps.power_err = np.array([0.] * len(power)) cls.ps.df = cls.ps.freq[1] - cls.ps.freq[0] cls.ps.m = 1 cls.cs = Crossspectrum() cls.cs.freq = freq cls.cs.power = power cls.cs.power_err = np.array([0.] * len(power)) cls.cs.df = cls.cs.freq[1] - cls.cs.freq[0] cls.cs.m = 1 cls.t0 = np.asarray( [200.0, 0.5, 0.1, 100.0, 2.0, 1.0, 50.0, 7.5, 0.5, 2.0]) cls.parest, cls.res = fit_lorentzians(cls.ps, cls.nlor, cls.t0)
def test_norm_frac(self): # Testing for a power spectrum of lc1 cs = Crossspectrum(lc1=self.lc1, lc2=self.lc1, norm='frac') assert len(cs.power) == 4999 assert cs.norm == 'frac' frac_noise = 2. / self.rate1 # expected Poisson noise level print(np.mean(cs.power), frac_noise) assert np.isclose(np.mean(cs.power[1:]), frac_noise, atol=0.005)
def test_norm_leahy(self): # Testing for a power spectrum of lc1 cs = Crossspectrum(lc1=self.lc1, lc2=self.lc1, norm='leahy') assert len(cs.power) == 4999 assert cs.norm == 'leahy' leahy_noise = 2.0 # expected Poisson noise level print(np.mean(cs.power), leahy_noise) assert np.isclose(np.mean(cs.power[1:]), leahy_noise, atol=0.2)
def test_make_crossspectrum_diff_lc_stat(self): lc_ = copy.copy(self.lc1) lc_.err_dist = 'gauss' with pytest.warns(UserWarning) as record: cs = Crossspectrum(self.lc1, lc_) assert np.any(["different statistics" in r.message.args[0] for r in record])
def test_get_new_df(): np.random.seed(150) amplitude_0 = 200.0 amplitude_1 = 100.0 amplitude_2 = 50.0 x_0_0 = 0.5 x_0_1 = 2.0 x_0_2 = 7.5 fwhm_0 = 0.1 fwhm_1 = 1.0 fwhm_2 = 0.5 whitenoise = 100.0 model = models.Lorentz1D(amplitude_0, x_0_0, fwhm_0) + \ models.Lorentz1D(amplitude_1, x_0_1, fwhm_1) + \ models.Lorentz1D(amplitude_2, x_0_2, fwhm_2) + \ models.Const1D(whitenoise) freq = np.linspace(0.01, 10.0, 1000) p = model(freq) noise = np.random.exponential(size=len(freq)) power = p * noise cs = Crossspectrum() cs.freq = freq cs.power = power cs.df = cs.freq[1] - cs.freq[0] cs.n = len(freq) cs.m = 1 assert np.isclose(cs.df, spec.get_new_df(cs, cs.n), rtol=0.001)
def test_make_crossspectrum_bad_lc_stat(self): lc1 = copy.copy(self.lc1) lc1.err_dist = 'gauss' lc2 = copy.copy(self.lc1) lc2.err_dist = 'gauss' with pytest.warns(UserWarning) as record: cs = Crossspectrum(lc1, lc2) assert np.any(["is not poisson" in r.message.args[0] for r in record])
def test_make_empty_crossspectrum(self): cs = Crossspectrum() assert cs.freq is None assert cs.power is None assert cs.df is None assert cs.nphots1 is None assert cs.nphots2 is None assert cs.m == 1 assert cs.n is None
def test_norm_abs(self, power_type): # Testing for a power spectrum of lc1 self.cs.norm = 'abs' # New lc with the same absolute variance, but mean-subtracted norm_lc_sub = copy.deepcopy(self.lc1) norm_lc_sub.counts = norm_lc_sub.counts - np.mean(norm_lc_sub.counts) norm_lc_sub.err_dist = 'gauss' cs = Crossspectrum(norm_lc_sub, norm_lc_sub, norm="none") cs.norm = 'abs' cs.power_type = power_type self.cs.power_type = power_type power = self.cs._normalize_crossspectrum(self.cs.unnorm_power, self.tseg) power_norm = cs._normalize_crossspectrum(cs.unnorm_power, self.tseg) abs_noise = 2. * self.rate1 # expected Poisson noise level assert np.isclose(np.mean(power[1:]), abs_noise, rtol=0.01) assert np.allclose(power[1:], power_norm[1:], atol=0.5)
def test_fullspec(self): csT = Crossspectrum(self.lc1, self.lc2, fullspec=True) assert csT.fullspec == True assert self.cs.fullspec == False assert csT.n == self.cs.n assert csT.n == len(csT.power) assert self.cs.n != len(self.cs.power) assert len(csT.power) >= len(self.cs.power) assert len(csT.power) == len(self.lc1) assert csT.freq[csT.n // 2] <= 0.
def CspecMain(bench_msg): func_dict = { 'Crossspectrum': [ 'Time_Init', 'Mem_Init', 'Time_Rebin_Linear', 'Mem_Rebin_Linear', 'Time_Coherence', 'Mem_Coherence', 'Time_Tlag', 'Mem_Tlag' ] } wall_time = [[ f'{datetime.utcfromtimestamp(int(time.time())).strftime("%Y-%m-%d %H:%M:%S")}', f'{bench_msg}', ] for i in range(int(sum([len(x) for x in func_dict.values()]) / 2))] mem_use = [[ f'{datetime.utcfromtimestamp(int(time.time())).strftime("%Y-%m-%d %H:%M:%S")}', f'{bench_msg}', ] for i in range(int(sum([len(x) for x in func_dict.values()]) / 2))] for size in [10**i for i in range(5, 9)]: num_func = 0 times = np.arange(size) counts = np.random.rand(size) * 100 lc = Lightcurve(times, counts, dt=1.0, skip_checks=True) lc_other = Lightcurve(times, counts * np.random.rand(size), dt=1.0, skip_checks=True) time1, mem1 = benchCode(createCspec, lc, lc_other) wall_time[num_func].append(time1) mem_use[num_func].append(mem1) num_func += 1 cspec = Crossspectrum(lc, lc_other, dt=1.0) time1, mem1 = benchCode(rebinCspec, cspec) wall_time[num_func].append(time1) mem_use[num_func].append(mem1) num_func += 1 time1, mem1 = benchCode(coherCspec, cspec) wall_time[num_func].append(time1) mem_use[num_func].append(mem1) num_func += 1 time1, mem1 = benchCode(TlagCspec, cspec) wall_time[num_func].append(time1) mem_use[num_func].append(mem1) num_func += 1 del times, counts, lc, lc_other, cspec, time1, mem1 CSVWriter(f'{os.path.abspath(os.path.join(os.getcwd(), os.pardir))}/data', func_dict, wall_time, mem_use) del func_dict, wall_time, mem_use
def test_get_new_df(): np.random.seed(150) amplitude_0 = 200.0 amplitude_1 = 100.0 amplitude_2 = 50.0 x_0_0 = 0.5 x_0_1 = 2.0 x_0_2 = 7.5 fwhm_0 = 0.1 fwhm_1 = 1.0 fwhm_2 = 0.5 whitenoise = 100.0 model = models.Lorentz1D(amplitude_0, x_0_0, fwhm_0) + \ models.Lorentz1D(amplitude_1, x_0_1, fwhm_1) + \ models.Lorentz1D(amplitude_2, x_0_2, fwhm_2) + \ models.Const1D(whitenoise) freq = np.linspace(0.01, 10.0, 10.0 / 0.01) p = model(freq) noise = np.random.exponential(size=len(freq)) power = p * noise cs = Crossspectrum() cs.freq = freq cs.power = power cs.df = cs.freq[1] - cs.freq[0] cs.n = len(freq) cs.m = 1 assert np.isclose(cs.df, spec.get_new_df(cs, cs.n), rtol=0.001)
def setup_class(self): tstart = 0.0 tend = 1.0 dt = 0.0001 time = np.arange(tstart + 0.5*dt, tend + 0.5*dt, dt) counts1 = np.random.poisson(0.01, size=time.shape[0]) counts2 = np.random.negative_binomial(1, 0.09, size=time.shape[0]) self.lc1 = Lightcurve(time, counts1, gti=[[tstart, tend]], dt=dt) self.lc2 = Lightcurve(time, counts2, gti=[[tstart, tend]], dt=dt) self.cs = Crossspectrum(self.lc1, self.lc2)
def setup_class(self): tstart = 0.0 self.tseg = 10.0 dt = 0.0001 time = np.arange(tstart + 0.5 * dt, self.tseg + 0.5 * dt, dt) np.random.seed(100) counts1 = np.random.poisson(0.01, size=time.shape[0]) self.lc1 = Lightcurve(time, counts1, gti=[[tstart, self.tseg]], dt=dt) self.rate1 = 100. # mean count rate (counts/sec) of light curve 1 with pytest.warns(UserWarning) as record: self.cs = Crossspectrum(self.lc1, self.lc1, norm="none")
def test_compute_rms(): np.random.seed(150) amplitude_0 = 200.0 amplitude_1 = 100.0 amplitude_2 = 50.0 x_0_0 = 0.5 x_0_1 = 2.0 x_0_2 = 7.5 fwhm_0 = 0.1 fwhm_1 = 1.0 fwhm_2 = 0.5 whitenoise = 100.0 model = models.Lorentz1D(amplitude_0, x_0_0, fwhm_0) + \ models.Lorentz1D(amplitude_1, x_0_1, fwhm_1) + \ models.Lorentz1D(amplitude_2, x_0_2, fwhm_2) + \ models.Const1D(whitenoise) freq = np.linspace(-10.0, 10.0, 1000) p = model(freq) noise = np.random.exponential(size=len(freq)) power = p * noise cs = Crossspectrum() cs.freq = freq cs.power = power cs.df = cs.freq[1] - cs.freq[0] cs.n = len(freq) cs.m = 1 rms = np.sqrt(np.sum(model(cs.freq) * cs.df)).mean() assert rms == spec.compute_rms(cs, model, criteria="all") rms_pos = np.sqrt(np.sum(model(cs.freq[cs.freq > 0]) * cs.df)).mean() assert rms_pos == spec.compute_rms(cs, model, criteria="posfreq") optimal_filter = Window1D(model) optimal_filter_freq = optimal_filter(cs.freq) filtered_cs_power = optimal_filter_freq * np.abs(model(cs.freq)) rms = np.sqrt(np.sum(filtered_cs_power * cs.df)).mean() assert rms == spec.compute_rms(cs, model, criteria="window") with pytest.raises(ValueError): spec.compute_rms(cs, model, criteria="filter")
def test_crossparam_input(self): # need to create new results to check against spec = Crossspectrum(self.lc1, self.lc2, fullspec=True) ifft = abs(scipy.fft.ifft(spec.power).real) time = scipy.fft.fftfreq(len(ifft), spec.df) time, resultifft = (list(t) for t in zip(*sorted(zip(time, ifft)))) cr2 = CrossCorrelation(cross=spec) lags_result = np.array([-2, -1, 0, 1, 2]) assert np.allclose(cr2.cross.power, spec.power) assert np.allclose(cr2.cross.freq, spec.freq) assert np.allclose(cr2.corr, resultifft) assert np.isclose(cr2.dt, self.lc1.dt) assert cr2.n == 5 assert np.allclose(cr2.time_lags, lags_result) assert cr2.mode == 'same' assert cr2.auto is False
def test_compute_rms(): np.random.seed(150) amplitude_0 = 200.0 amplitude_1 = 100.0 amplitude_2 = 50.0 x_0_0 = 0.5 x_0_1 = 2.0 x_0_2 = 7.5 fwhm_0 = 0.1 fwhm_1 = 1.0 fwhm_2 = 0.5 whitenoise = 100.0 model = models.Lorentz1D(amplitude_0, x_0_0, fwhm_0) + \ models.Lorentz1D(amplitude_1, x_0_1, fwhm_1) + \ models.Lorentz1D(amplitude_2, x_0_2, fwhm_2) + \ models.Const1D(whitenoise) freq = np.linspace(-10.0, 10.0, 10.0 / 0.01) p = model(freq) noise = np.random.exponential(size=len(freq)) power = p * noise cs = Crossspectrum() cs.freq = freq cs.power = power cs.df = cs.freq[1] - cs.freq[0] cs.n = len(freq) cs.m = 1 rms = np.sqrt(np.sum(model(cs.freq) * cs.df)).mean() assert rms == spec.compute_rms(cs, model, criteria="all") rms_pos = np.sqrt(np.sum(model(cs.freq[cs.freq > 0]) * cs.df)).mean() assert rms_pos == spec.compute_rms(cs, model, criteria="posfreq") optimal_filter = Window1D(model) optimal_filter_freq = optimal_filter(cs.freq) filtered_cs_power = optimal_filter_freq * np.abs(model(cs.freq)) rms = np.sqrt(np.sum(filtered_cs_power * cs.df)).mean() assert rms == spec.compute_rms(cs, model, criteria="window") with pytest.raises(ValueError): spec.compute_rms(cs, model, criteria="filter")
def setup_class(self): tstart = 0.0 tend = 1.0 self.dt = np.longdouble(0.0001) times1 = np.sort(np.random.uniform(tstart, tend, 1000)) times2 = np.sort(np.random.uniform(tstart, tend, 1000)) gti = np.array([[tstart, tend]]) self.events1 = EventList(times1, gti=gti) self.events2 = EventList(times2, gti=gti) self.cs = Crossspectrum(self.events1, self.events2, dt=self.dt) self.acs = AveragedCrossspectrum(self.events1, self.events2, segment_size=1, dt=self.dt) self.lc1, self.lc2 = self.events1, self.events2
class TestCrossspectrum(object): def setup_class(self): tstart = 0.0 tend = 1.0 dt = 0.0001 time = np.arange(tstart + 0.5*dt, tend + 0.5*dt, dt) counts1 = np.random.poisson(0.01, size=time.shape[0]) counts2 = np.random.negative_binomial(1, 0.09, size=time.shape[0]) self.lc1 = Lightcurve(time, counts1, gti=[[tstart, tend]], dt=dt) self.lc2 = Lightcurve(time, counts2, gti=[[tstart, tend]], dt=dt) self.cs = Crossspectrum(self.lc1, self.lc2) def test_make_empty_crossspectrum(self): cs = Crossspectrum() assert cs.freq is None assert cs.power is None assert cs.df is None assert cs.nphots1 is None assert cs.nphots2 is None assert cs.m == 1 assert cs.n is None assert cs.power_err is None def test_init_with_one_lc_none(self): with pytest.raises(TypeError): cs = Crossspectrum(self.lc1) def test_init_with_multiple_gti(self): gti = np.array([[0.0, 0.2], [0.6, 1.0]]) with pytest.raises(TypeError): cs = Crossspectrum(self.lc1, self.lc2, gti=gti) def test_init_with_norm_not_str(self): with pytest.raises(TypeError): cs = Crossspectrum(norm=1) def test_init_with_invalid_norm(self): with pytest.raises(ValueError): cs = Crossspectrum(norm='frabs') def test_init_with_wrong_lc1_instance(self): lc_ = Crossspectrum() with pytest.raises(TypeError): cs = Crossspectrum(lc_, self.lc2) def test_init_with_wrong_lc2_instance(self): lc_ = Crossspectrum() with pytest.raises(TypeError): cs = Crossspectrum(self.lc1, lc_) def test_make_crossspectrum_diff_lc_counts_shape(self): counts = np.array([1]*10001) time = np.linspace(0.0, 1.0001, 10001) lc_ = Lightcurve(time, counts) with pytest.raises(StingrayError): cs = Crossspectrum(self.lc1, lc_) def test_make_crossspectrum_diff_lc_stat(self): lc_ = copy.copy(self.lc1) lc_.err_dist = 'gauss' with pytest.warns(UserWarning) as record: cs = Crossspectrum(self.lc1, lc_) assert np.any(["different statistics" in r.message.args[0] for r in record]) def test_make_crossspectrum_bad_lc_stat(self): lc1 = copy.copy(self.lc1) lc1.err_dist = 'gauss' lc2 = copy.copy(self.lc1) lc2.err_dist = 'gauss' with pytest.warns(UserWarning) as record: cs = Crossspectrum(lc1, lc2) assert np.any(["is not poisson" in r.message.args[0] for r in record]) def test_make_crossspectrum_diff_dt(self): counts = np.array([1]*10000) time = np.linspace(0.0, 2.0, 10000) lc_ = Lightcurve(time, counts) with pytest.raises(StingrayError): cs = Crossspectrum(self.lc1, lc_) def test_rebin_smaller_resolution(self): # Original df is between 0.9 and 1.0 with pytest.raises(ValueError): new_cs = self.cs.rebin(df=0.1) def test_rebin(self): new_cs = self.cs.rebin(df=1.5) assert new_cs.df == 1.5 new_cs.time_lag() def test_rebin_factor(self): new_cs = self.cs.rebin(f=1.5) assert new_cs.df == self.cs.df * 1.5 new_cs.time_lag() def test_rebin_log(self): # For now, just verify that it doesn't crash new_cs = self.cs.rebin_log(f=0.1) assert type(new_cs) == type(self.cs) new_cs.time_lag() def test_norm_leahy(self): cs = Crossspectrum(self.lc1, self.lc2, norm='leahy') assert len(cs.power) == 4999 assert cs.norm == 'leahy' def test_norm_frac(self): cs = Crossspectrum(self.lc1, self.lc2, norm='frac') assert len(cs.power) == 4999 assert cs.norm == 'frac' def test_norm_abs(self): cs = Crossspectrum(self.lc1, self.lc2, norm='abs') assert len(cs.power) == 4999 assert cs.norm == 'abs' def test_failure_when_normalization_not_recognized(self): with pytest.raises(ValueError): cs = Crossspectrum(self.lc1, self.lc2, norm='wrong') def test_coherence(self): coh = self.cs.coherence() assert len(coh) == 4999 assert np.abs(coh[0]) < 1 def test_timelag(self): time_lag = self.cs.time_lag() assert max(time_lag) <= np.pi assert min(time_lag) >= -np.pi def test_nonzero_err(self): assert np.all(self.cs.power_err > 0) def test_timelag_error(self): class Child(Crossspectrum): def __init__(self): pass obj = Child() with pytest.raises(AttributeError): lag = obj.time_lag()
class TestCrossspectrum(object): def setup_class(self): tstart = 0.0 tend = 1.0 dt = 0.0001 time = np.linspace(tstart, tend, int((tend - tstart)/dt)) counts1 = np.random.poisson(0.01, size=time.shape[0]) counts2 = np.random.negative_binomial(1, 0.09, size=time.shape[0]) self.lc1 = Lightcurve(time, counts1) self.lc2 = Lightcurve(time, counts2) self.cs = Crossspectrum(self.lc1, self.lc2) def test_make_empty_crossspectrum(self): cs = Crossspectrum() assert cs.freq is None assert cs.power is None assert cs.df is None assert cs.nphots1 is None assert cs.nphots2 is None assert cs.m == 1 assert cs.n is None def test_init_with_one_lc_none(self): with pytest.raises(TypeError): cs = Crossspectrum(self.lc1) def test_init_with_norm_not_str(self): with pytest.raises(TypeError): cs = Crossspectrum(norm=1) def test_init_with_invalid_norm(self): with pytest.raises(ValueError): cs = Crossspectrum(norm='frabs') def test_init_with_wrong_lc1_instance(self): lc_ = Crossspectrum() with pytest.raises(AssertionError): cs = Crossspectrum(lc_, self.lc2) def test_init_with_wrong_lc2_instance(self): lc_ = Crossspectrum() with pytest.raises(AssertionError): cs = Crossspectrum(self.lc1, lc_) def test_make_crossspectrum_diff_lc_counts_shape(self): counts = np.array([1]*10001) time = np.linspace(0.0, 1.0001, 10001) lc_ = Lightcurve(time, counts) with pytest.raises(AssertionError): cs = Crossspectrum(self.lc1, lc_) def test_make_crossspectrum_diff_dt(self): counts = np.array([1]*10000) time = np.linspace(0.0, 2.0, 10000) lc_ = Lightcurve(time, counts) with pytest.raises(AssertionError): cs = Crossspectrum(self.lc1, lc_) def test_rebin_smaller_resolution(self): # Original df is between 0.9 and 1.0 with pytest.raises(AssertionError): new_cs = self.cs.rebin(df=0.1) def test_rebin(self): new_cs = self.cs.rebin(df=1.5) assert new_cs.df == 1.5 def test_norm_leahy(self): cs = Crossspectrum(self.lc1, self.lc2, norm='leahy') assert len(cs.power) == 4999 assert cs.norm == 'leahy' def test_norm_frac(self): cs = Crossspectrum(self.lc1, self.lc2, norm='frac') assert len(cs.power) == 4999 assert cs.norm == 'frac' def test_norm_abs(self): cs = Crossspectrum(self.lc1, self.lc2, norm='abs') assert len(cs.power) == 4999 assert cs.norm == 'abs' def test_failure_when_normalization_not_recognized(self): with pytest.raises(ValueError): cs = Crossspectrum(self.lc1, self.lc2, norm='wrong') def test_coherence(self): coh = self.cs.coherence() assert len(coh) == 4999 assert np.abs(coh[0]) < 1 def test_timelag(self): time_lag = self.cs.time_lag() assert max(time_lag) <= np.pi assert min(time_lag) >= -np.pi def test_timelag_error(self): class Child(Crossspectrum): def __init__(self): pass obj = Child() with pytest.raises(AttributeError): lag = obj.time_lag()