def test_adev_average(noisegen, b, tau, qd, nr=pow(2, 16), N_averages=30, rtol=1e-1): """ check that time-series has the ADEV that we expect generate many time-series (N_averages) compute average adev from the multiple time-series """ noisegen.set_input(nr=nr, qd=qd, b=b) adevs = [] for n in range(N_averages): noisegen.generateNoise() (taus, devs, errs, ns) = at.adev(noisegen.time_series, taus=[tau], rate=1.0) adev_calculated = devs[0] adevs.append(adev_calculated) adev_mu = np.mean(adevs) adev_predicted = noisegen.adev(tau0=1.0, tau=tau) print(b, tau, qd, adev_predicted, adev_mu, adev_mu / adev_predicted) # NOTE relative tolerance here! assert np.isclose(adev_predicted, adev_mu, rtol=rtol, atol=0)
def run(): """ <Description> Args: param1: This is the first param. Returns: This is a description of what is returned. """ file_name = "defl.ibw" defl_volts_wave = PxpLoader.read_ibw_as_wave(file_name) defl_volts = defl_volts_wave.DataY invols_nm_per_volt = 154.8 spring_pN_per_nM = 5.70 force_pN = defl_volts * invols_nm_per_volt * spring_pN_per_nM # zero out to the maximum force_pN -= np.mean(force_pN) data_interval_in_s = 1/500e3 rate = 1/float(data_interval_in_s) # data rate in Hz taus = np.logspace(-5,2,num=50,base=10) # tau-values in seconds # fractional frequency data (taus_used, adev, adeverror, adev_n) = \ allantools.adev(force_pN, data_type='freq', rate=rate, taus=taus) fig = PlotUtilities.figure() plt.errorbar(x=taus_used,y=adev,yerr=2*adeverror,label="95% C.I.") plt.xscale('log') plt.yscale('log') plt.axhline(1,color='r',linestyle='--',label="1 pN") PlotUtilities.lazyLabel("Averaging time (s)","Force (pN)","") PlotUtilities.savefig(fig,"out.png")
def test_phasedat_adev(self): #(s32_taus, s32_devs, s32_devs_lo, s32_devs_hi, s32_ns) = read_stable32( 'phase_dat_adev_octave.txt' , 1.0 ) s32_rows = testutils.read_stable32( 'phase_dat_adev_octave.txt' , 1.0 ) phase = testutils.read_datafile('PHASE.DAT') (taus,devs,errs,ns) = allan.adev(phase, taus=[s32['tau'] for s32 in s32_rows]) # CI computation los=[] his=[] for (d,t, n) in zip(devs, taus, ns): #edf = greenhall_simple_edf( alpha=0, d=2, m=t, S=1, F=t, N=len(phase) ) edf2 = allan.edf_greenhall( alpha=0, d=2, m=t, N=len(phase), overlapping = False, modified=False ) (lo,hi) = allan.confidence_intervals( dev=d, ci=0.68268949213708585, edf=edf2 ) # 0.68268949213708585 #(lo2,hi2) = allan.confidence_intervals( dev=d, ci=0.68268949213708585, edf=edf2, use_scipy_chi2_ppf=False ) #testutils.check_approx_equal(lo, lo2, tolerance=1e-4) #testutils.check_approx_equal(hi, hi2, tolerance=1e-4) #allan.uncertainty_estimate(len(phase), t, d,ci=0.683,noisetype='wf') los.append(lo) his.append(hi) for (s32, t2, d2, lo2, hi2, n2) in zip(s32_rows, taus, devs, los, his, ns): print("s32 %03d %03f %1.6f %1.6f %1.6f" % (s32['n'], s32['tau'], s32['dev_min'], s32['dev'], s32['dev_max'])) print("at %03d %03f %1.6f %1.6f %1.6f" % (n2, t2, round(lo2,5), round(d2,5), round(hi2,5) )) testutils.check_approx_equal(s32['dev_min'], lo2,tolerance=1e-3) testutils.check_approx_equal(s32['dev'], d2,tolerance=1e-4) testutils.check_approx_equal(s32['dev_max'], hi2,tolerance=1e-3) print("----")
def test_adev_ci_and_noiseID(self): """ ADEV with confidence intervals, including noise-ID """ change_to_test_dir() s32rows = testutils.read_stable32(resultfile='adev_octave.txt', datarate=1.0) for row in s32rows: data = testutils.read_datafile(data_file) data = allan.frequency2fractional(data, mean_frequency=1.0e7) (taus, devs, errs, ns) = allan.adev(data, rate=rate, data_type="freq", taus=[row['tau']]) dev = devs[0] try: # CI including noise-ID (lo2, hi2) = allan.confidence_interval_noiseID(data, dev, af=int(row['m']), dev_type="adev", data_type="freq") assert np.isclose(lo2, row['dev_min'], rtol=1e-2) assert np.isclose(hi2, row['dev_max'], rtol=1e-2) print(" CI OK! tau= %f lo/s32_lo = %f hi/s32_hi = %f " % (row['tau'], lo2 / row['dev_min'], hi2 / row['dev_max'])) except NotImplementedError: print("can't do CI for tau= %f" % row['tau']) pass
def test_phasedat_adev(self): s32_rows = testutils.read_stable32('phase_dat_adev_octave.txt', 1.0) phase = testutils.read_datafile('PHASE.DAT') (taus, devs, errs, ns) = allan.adev(phase, taus=[s32['tau'] for s32 in s32_rows]) # separate CI computation los = [] his = [] for (d, t, n) in zip(devs, taus, ns): edf2 = allan.edf_greenhall(alpha=0, d=2, m=t, N=len(phase), overlapping=False, modified=False) (lo, hi) = allan.confidence_interval(dev=d, edf=edf2) los.append(lo) his.append(hi) # compare to Stable32 print("adev()") for (s32, t2, d2, lo2, hi2, n2) in zip(s32_rows, taus, devs, los, his, ns): print("S32 %03d %03.1f %1.6f %1.6f %1.6f" % (s32['n'], s32['tau'], s32['dev_min'], s32['dev'], s32['dev_max'])) print("AT %03d %03.1f %1.6f %1.6f %1.6f" % (n2, t2, round(lo2, 5), round(d2, 5), round(hi2, 5))) testutils.check_approx_equal(s32['n'], n2, tolerance=1e-3) testutils.check_approx_equal(s32['dev_min'], lo2, tolerance=1e-3) testutils.check_approx_equal(s32['dev'], d2, tolerance=1e-4) testutils.check_approx_equal(s32['dev_max'], hi2, tolerance=1e-3) print("----")
def b1(x, af, rate): """ B1 ratio for noise identification (and bias correction?) ratio of Standard Variace to AVAR Howe, Beard, Greenhall, Riley, A TOTAL ESTIMATOR OF THE HADAMARD FUNCTION USED FOR GPS OPERATIONS 32nd PTTI, 2000 https://apps.dtic.mil/dtic/tr/fulltext/u2/a484835.pdf Barnes, 1974 https://tf.nist.gov/general/pdf/11.pdf """ (taus, devs, errs, ns) = at.adev(x, taus=[af * rate], data_type="phase", rate=rate) oadev_x = devs[0] avar = pow(oadev_x, 2.0) # variance of y, at given af y = np.diff(x) y_cut = np.array(y[:len(y) - (len(y) % af)]) # cut to length assert len(y_cut) % af == 0 y_shaped = y_cut.reshape((int(len(y_cut) / af), af)) y_averaged = np.average(y_shaped, axis=1) # average var = np.var(y_averaged, ddof=1) return var / avar
def test_adev_ci(self): s32rows = testutils.read_stable32(resultfile='adev_decade.txt', datarate=1.0) for row in s32rows: data = testutils.read_datafile(data_file) (taus, devs, errs, ns) = allan.adev(data, rate=rate, taus=[row['tau']]) edf = allan.edf_greenhall(alpha=row['alpha'], d=2, m=row['m'], N=len(data), overlapping=False, modified=False, verbose=True) (lo, hi) = allan.confidence_intervals(devs[0], ci=0.68268949213708585, edf=edf) print("n check: ", testutils.check_equal(ns[0], row['n'])) print("dev check: ", testutils.check_approx_equal(devs[0], row['dev'])) print( "min dev check: ", lo, row['dev_min'], testutils.check_approx_equal(lo, row['dev_min'], tolerance=1e-3)) print( "max dev check: ", hi, row['dev_max'], testutils.check_approx_equal(hi, row['dev_max'], tolerance=1e-3))
def test_adev_ci_and_noiseID(self): """ ADEV with confidence intervals, including noise-ID """ change_to_test_dir() s32rows = testutils.read_stable32( resultfile='stable32_ADEV_decade.txt', datarate=1.0) for row in s32rows: phase = testutils.read_datafile('gps_1pps_phase_data.txt.gz') (taus, devs, errs, ns) = allan.adev(phase, rate=rate, data_type="phase", taus=[row['tau']]) dev = devs[0] try: # CI including noise-ID (lo2, hi2) = allan.confidence_interval_noiseID(phase, dev, af=int(row['m']), dev_type="adev", data_type="phase") assert np.isclose(lo2, row['dev_min'], rtol=1e-2, atol=0) assert np.isclose(hi2, row['dev_max'], rtol=1e-2, atol=0) print(" CI OK! tau= %f lo/s32_lo = %f hi/s32_hi = %f " % (row['tau'], lo2 / row['dev_min'], hi2 / row['dev_max'])) except NotImplementedError: print("can't do CI for tau= %f" % row['tau']) pass
def plotallan_adev(plt, y, rate, taus, style): (t2, ad, ade, adn) = allantools.adev(y, rate=rate, data_type="freq", taus=taus) plt.loglog(t2, ad, style) return t2, ad, ade, adn
def test_adev_ci(self): change_to_test_dir() s32rows = testutils.read_stable32(resultfile='adev_octave.txt', datarate=1.0) for row in s32rows: data = testutils.read_datafile(data_file) data = allan.frequency2fractional(data, mean_frequency=1.0e7) (taus, devs, errs, ns) = allan.adev(data, rate=rate, data_type="freq", taus=[row['tau']]) # NOTE! Here we use alhpa from Stable32-results for the allantools edf computation! edf = allan.edf_greenhall(alpha=row['alpha'], d=2, m=row['m'], N=len(data), overlapping=False, modified=False, verbose=True) print("alpha=", row['alpha']) (lo, hi) = allan.confidence_interval(devs[0], edf=edf) print(" n check: %d" % testutils.check_equal(ns[0], row['n'])) print(" dev check: %d" % testutils.check_approx_equal( devs[0], row['dev'], tolerance=2e-4)) print("min dev check: %.4g %.4g %d" % (lo, row['dev_min'], testutils.check_approx_equal( lo, row['dev_min'], tolerance=1e-3))) print("max dev check: %.4g %.4g %d" % (hi, row['dev_max'], testutils.check_approx_equal( hi, row['dev_max'], tolerance=1e-3)))
def test_phasedat_adev(self): s32_rows = testutils.read_stable32( 'phase_dat_adev_octave.txt' , 1.0 ) phase = np.array( testutils.read_datafile('PHASE.DAT') ) (taus,devs,errs,ns) = allan.adev(phase, taus=[s32['tau'] for s32 in s32_rows]) # separate CI computation los=[] his=[] for (d,t, n, s32) in zip(devs, taus, ns,s32_rows): # Note FIXED alpha here edf2 = allan.edf_greenhall( alpha=0, d=2, m=t, N=len(phase), overlapping = False, modified=False ) (lo,hi) = allan.confidence_interval( dev=d, edf=edf2 ) los.append(lo) his.append(hi) try: (lo2,hi2) = allan.confidence_interval_noiseID(phase, d, af=int(t), dev_type="adev", data_type="phase") assert np.isclose( lo2, s32['dev_min'] , rtol=1e-2) assert np.isclose( hi2, s32['dev_max'] , rtol=1e-2) print(" CI OK! tau= ",t) except NotImplementedError: print("can't do CI for tau= ",t) pass # compare to Stable32 print("adev()") print(" n tau dev_min dev dev_max ") for (s32, t2, d2, lo2, hi2, n2) in zip(s32_rows, taus, devs, los, his, ns): print("S32 %03d %03.1f %1.6f %1.6f %1.6f" % (s32['n'], s32['tau'], s32['dev_min'], s32['dev'], s32['dev_max'])) print("AT %03d %03.1f %1.6f %1.6f %1.6f" % (n2, t2, round(lo2,5), round(d2,5), round(hi2,5) )) testutils.check_approx_equal(s32['n'], n2, tolerance=1e-9) testutils.check_approx_equal(s32['dev_min'], lo2, tolerance=1e-3) testutils.check_approx_equal(s32['dev'], d2, tolerance=1e-4) testutils.check_approx_equal(s32['dev_max'], hi2, tolerance=1e-3) print("----")
def plot_adev(self) -> None: """Opens a Pyplot showing the non-overlappint Allan variance.""" taus, adev, _, _ = allantools.adev(self.frequencies, data_type='freq', rate=self.gate_time) plt.plot(taus, adev) plt.xlabel('Integration Time in s') plt.ylabel('Non-Overlapping Allan Variance') plt.xscale('log') plt.yscale('log') plt.show()
def rn_noise_id(x, af, rate): """ R(n) ratio for noise identification """ #print "len(x) ", len(x), "oadev",af*rate (taus,devs,errs,ns) = at.adev(x,taus=[af*rate], data_type='phase', rate=rate) #print devs oadev_x = devs[0] (mtaus,mdevs,errs,ns) = at.mdev(x,taus=[af*rate], data_type='phase', rate=rate) mdev_x = mdevs[0] rn = pow(mdev_x/oadev_x,2) return rn
def test_phasedat_adev(self): s32_rows = testutils.read_stable32('phase_dat_adev_octave.txt', 1.0) phase = np.array(testutils.read_datafile('PHASE.DAT')) (taus, devs, errs, ns) = allan.adev(phase, taus=[s32['tau'] for s32 in s32_rows]) # separate CI computation los = [] his = [] for (d, t, n, s32) in zip(devs, taus, ns, s32_rows): # Note FIXED alpha here edf2 = allan.edf_greenhall(alpha=0, d=2, m=t, N=len(phase), overlapping=False, modified=False) (lo, hi) = allan.confidence_interval(dev=d, edf=edf2) assert np.isclose(lo, s32['dev_min'], rtol=1e-2) assert np.isclose(hi, s32['dev_max'], rtol=1e-2) print(" alpha=0 FIXED, CI OK! tau = %f" % t) los.append(lo) his.append(hi) try: (lo2, hi2) = allan.confidence_interval_noiseID(phase, d, af=int(t), dev_type="adev", data_type="phase") assert np.isclose(lo2, s32['dev_min'], rtol=1e-2) assert np.isclose(hi2, s32['dev_max'], rtol=1e-2) print(" ACF_NID CI OK! tau = %f" % t) except NotImplementedError: print("can't do CI for tau = %f" % t) pass # compare to Stable32 print("adev()") print(" n tau dev_min dev dev_max ") for (s32, t2, d2, lo2, hi2, n2) in zip(s32_rows, taus, devs, los, his, ns): print("S32 %03d %03.1f %1.6f %1.6f %1.6f" % (s32['n'], s32['tau'], s32['dev_min'], s32['dev'], s32['dev_max'])) print("AT %03d %03.1f %1.6f %1.6f %1.6f" % (n2, t2, round(lo2, 5), round(d2, 5), round(hi2, 5))) testutils.check_approx_equal(s32['n'], n2, tolerance=1e-9) testutils.check_approx_equal(s32['dev_min'], lo2, tolerance=1e-3) testutils.check_approx_equal(s32['dev'], d2, tolerance=1e-4) testutils.check_approx_equal(s32['dev_max'], hi2, tolerance=1e-3) print("----")
def test_adev_ci(self): s32rows = testutils.read_stable32(resultfile='adev_decade.txt', datarate=1.0) for row in s32rows: data = testutils.read_datafile(data_file) (taus, devs, errs, ns) = allan.adev(data, rate=rate, taus=[ row['tau'] ]) edf = allan.edf_greenhall(alpha=row['alpha'],d=2,m=row['m'],N=len(data),overlapping=False, modified = False, verbose=True) (lo,hi) =allan.confidence_intervals(devs[0],ci=0.68268949213708585, edf=edf) print("n check: ", testutils.check_equal( ns[0], row['n'] ) ) print("dev check: ", testutils.check_approx_equal( devs[0], row['dev'] ) ) print("min dev check: ", lo, row['dev_min'], testutils.check_approx_equal( lo, row['dev_min'], tolerance=1e-3 ) ) print("max dev check: ", hi, row['dev_max'], testutils.check_approx_equal( hi, row['dev_max'], tolerance=1e-3 ) )
def test_adev(noisegen, b, tau, qd): """ check that time-series has the ADEV that we expect """ noisegen.set_input(nr=pow(2,16), qd=qd , b=b) noisegen.generateNoise() (taus,devs,errs,ns)=at.adev( noisegen.time_series, taus=[tau], rate=1.0 ) adev_calculated = devs[0] adev_predicted = noisegen.adev(tau0=1.0, tau=tau) #print( taus,devs ) print( b, tau, qd, adev_calculated, adev_predicted, adev_calculated/adev_predicted ) assert np.isclose( adev_calculated, adev_predicted, rtol=3e-1, atol=0)
def b1_noise_id(x, af, rate): """ B1 ratio for noise identification ratio of Standard Variace to AVAR """ (taus,devs,errs,ns) = at.adev(x,taus=[af*rate],data_type="phase", rate=rate) oadev_x = devs[0] y = np.diff(x) y_cut = np.array( y[:len(y)-(len(y)%af)] ) # cut to length assert len(y_cut)%af == 0 y_shaped = y_cut.reshape( ( int(len(y_cut)/af), af) ) y_averaged = np.average(y_shaped,axis=1) # average var = np.var(y_averaged, ddof=1) return var/pow(oadev_x,2.0)
def test_adev(noisegen, b, tau, qd): """ check that time-series has the ADEV that we expect """ noisegen.set_input(nr=pow(2, 16), qd=qd, b=b) noisegen.generateNoise() (taus, devs, errs, ns) = at.adev(noisegen.time_series, taus=[tau], rate=1.0) adev_calculated = devs[0] adev_predicted = noisegen.adev(tau0=1.0, tau=tau) #print( taus,devs ) print(b, tau, qd, adev_calculated, adev_predicted, adev_calculated / adev_predicted) assert np.isclose(adev_calculated, adev_predicted, rtol=3e-1, atol=0)
def rn(x, af, rate): """ R(n) ratio for noise identification ratio of MVAR to AVAR """ (taus, devs, errs, ns) = at.adev(x, taus=[af * rate], data_type='phase', rate=rate) oadev_x = devs[0] (mtaus, mdevs, errs, ns) = at.mdev(x, taus=[af * rate], data_type='phase', rate=rate) mdev_x = mdevs[0] return pow(mdev_x / oadev_x, 2)
def test_adev_ci(self): """ ADEV with confidence intervals, fixed alpha (no noise-ID) """ change_to_test_dir() s32rows = testutils.read_stable32(resultfile='adev_octave.txt', datarate=1.0) for row in s32rows: data = testutils.read_datafile(data_file) data = allan.frequency2fractional(data, mean_frequency=1.0e7) (taus, devs, errs, ns) = allan.adev(data, rate=rate, data_type="freq", taus=[ row['tau'] ]) # NOTE! Here we use alhpa from Stable32-results for the allantools edf computation! edf = allan.edf_greenhall(alpha=row['alpha'],d=2,m=row['m'],N=len(data),overlapping=False, modified = False, verbose=True) print("alpha=",row['alpha']) (lo, hi) =allan.confidence_interval(devs[0], edf=edf) print(" n check: %d" % testutils.check_equal( ns[0], row['n'] ) ) print(" dev check: %d" % testutils.check_approx_equal( devs[0], row['dev'], tolerance=2e-4 ) ) print("min dev check: %.4g %.4g %d" % ( lo, row['dev_min'], testutils.check_approx_equal( lo, row['dev_min'], tolerance=1e-3 ) ) ) print("max dev check: %.4g %.4g %d" % ( hi, row['dev_max'], testutils.check_approx_equal( hi, row['dev_max'], tolerance=1e-3 ) ) )
def test_adev_ci_and_noiseID(self): """ ADEV with confidence intervals, including noise-ID """ change_to_test_dir() s32rows = testutils.read_stable32(resultfile='stable32_ADEV_decade.txt', datarate=1.0) for row in s32rows: phase = testutils.read_datafile('gps_1pps_phase_data.txt.gz') (taus, devs, errs, ns) = allan.adev(phase, rate=rate, data_type="phase", taus=[row['tau']]) dev = devs[0] try: # CI including noise-ID (lo2, hi2) = allan.confidence_interval_noiseID(phase, dev, af=int(row['m']), dev_type="adev", data_type="phase") assert np.isclose(lo2, row['dev_min'], rtol=1e-2, atol=0) assert np.isclose(hi2, row['dev_max'], rtol=1e-2, atol=0) print(" CI OK! tau= %f lo/s32_lo = %f hi/s32_hi = %f "% (row['tau'], lo2/row['dev_min'], hi2/row['dev_max'])) except NotImplementedError: print("can't do CI for tau= %f"%row['tau']) pass
def b1_noise_id(x, af, rate): """ B1 ratio for noise identification ratio of Standard Variace to AVAR """ (taus, devs, errs, ns) = at.adev(x, taus=[af * rate], data_type="phase", rate=rate) oadev_x = devs[0] y = np.diff(x) y_cut = np.array(y[:len(y) - (len(y) % af)]) # cut to length assert len(y_cut) % af == 0 y_shaped = y_cut.reshape((int(len(y_cut) / af), af)) y_averaged = np.average(y_shaped, axis=1) # average var = np.var(y_averaged, ddof=1) return var / pow(oadev_x, 2.0)
def test_adev_average(noisegen, b, tau, qd, nr=pow(2, 16), N_averages=30, rtol=1e-1): """ check that time-series has the ADEV that we expect generate many time-series (N_averages) compute average adev from the multiple time-series """ noisegen.set_input(nr=nr, qd=qd, b=b) adevs = [] for n in range(N_averages): noisegen.generateNoise() (taus,devs,errs,ns)=at.adev( noisegen.time_series, taus=[tau], rate=1.0 ) adev_calculated = devs[0] adevs.append( adev_calculated ) adev_mu = np.mean( adevs ) adev_predicted = noisegen.adev(tau0=1.0, tau=tau) print( b, tau, qd, adev_predicted, adev_mu, adev_mu/adev_predicted ) # NOTE relative tolerance here! assert np.isclose( adev_predicted, adev_mu, rtol=rtol, atol=0)
def test_adev_ci_and_noiseID(self): """ ADEV with confidence intervals, including noise-ID """ change_to_test_dir() s32rows = testutils.read_stable32(resultfile='adev_octave.txt', datarate=1.0) for row in s32rows: data = testutils.read_datafile(data_file) data = allan.frequency2fractional(data, mean_frequency=1.0e7) (taus, devs, errs, ns) = allan.adev(data, rate=rate, data_type="freq", taus=[ row['tau'] ]) dev=devs[0] try: # CI including noise-ID (lo2,hi2) = allan.confidence_interval_noiseID(data, dev, af=int(row['m']), dev_type="adev", data_type="freq") assert np.isclose( lo2, row['dev_min'] , rtol=1e-2) assert np.isclose( hi2, row['dev_max'] , rtol=1e-2) print(" CI OK! tau= %.0f lo/s32_lo = %f hi/s32_hi = %f "% (row['tau'], lo2/row['dev_min'], hi2/row['dev_max']) ) except NotImplementedError: print("can't do CI for tau= %f"%row['tau']) pass
def test_adev_ci(self): s32rows = testutils.read_stable32(resultfile='adev_decade.txt', datarate=1.0) edfs = [] err_lo = [] err_hi = [] err_dev = [] for row in s32rows: data = testutils.read_datafile(data_file) (taus, devs, errs, ns) = allan.adev(data, rate=rate, taus=[row['tau']]) # here allantools does not identify the noise type # instead the noise type alpha from Stable 32 is used edf = allan.edf_greenhall(alpha=row['alpha'], d=2, m=row['m'], N=len(data), overlapping=False, modified=False, verbose=True) (lo, hi) = allan.confidence_interval(devs[0], edf) print("n check: ", testutils.check_equal(ns[0], row['n'])) print("dev check: ", testutils.check_approx_equal(devs[0], row['dev'])) print( "min dev check: ", lo, row['dev_min'], testutils.check_approx_equal(lo, row['dev_min'], tolerance=1e-3)) print( "max dev check: ", hi, row['dev_max'], testutils.check_approx_equal(hi, row['dev_max'], tolerance=1e-3)) # store relative errors for later printout edfs.append(edf) err_dev.append(row['dev'] / devs[0] - 1.0) err_hi.append(row['dev_max'] / hi - 1.0) err_lo.append(row['dev_min'] / lo - 1.0) # print table with relative errors for (e, lo, err, hi) in zip(edfs, err_lo, err_dev, err_hi): print('%d %.6f %.6f %.6f' % (e, lo, err, hi))
def test_adev_ci(self): s32rows = testutils.read_stable32(resultfile="adev_octave.txt", datarate=1.0) for row in s32rows: data = testutils.read_datafile(data_file) data = allan.frequency2fractional(data, mean_frequency=1.0e7) (taus, devs, errs, ns) = allan.adev(data, rate=rate, data_type="freq", taus=[row["tau"]]) edf = allan.edf_greenhall( alpha=row["alpha"], d=2, m=row["m"], N=len(data), overlapping=False, modified=False, verbose=True ) print("alpha=", row["alpha"]) (lo, hi) = allan.confidence_intervals(devs[0], ci=0.68268949213708585, edf=edf) print("n check: ", testutils.check_equal(ns[0], row["n"])) print("dev check: ", testutils.check_approx_equal(devs[0], row["dev"], tolerance=2e-4)) print( "min dev check: ", lo, row["dev_min"], testutils.check_approx_equal(lo, row["dev_min"], tolerance=1e-3) ) print( "max dev check: ", hi, row["dev_max"], testutils.check_approx_equal(hi, row["dev_max"], tolerance=1e-3) )
def calculate_adev(self, sample_rate=1): # x = allantools.noise.white(10000) # (t2, ad, ade, adn) = allantools.adev( # x, rate=sample_rate, data_type="freq", taus=self.tau) (t2, ad, ade, adn) = allantools.adev(self.y, rate=sample_rate, data_type="freq", taus=self.tau) self.tau_result = t2 # tau values self.alan_dev_result = ad # Alan deviations per tau self.error = ade # errors of alan adeviations self.data_points = adn # values of N for t # Determine a tau value tau_index = 40 self.avg_adev = ad[tau_index] # print('[TAU {}] = {}'.format(tau_index, round(self.avg_adev,2))) return ad
def test_phasedat_adev(self): (s32_taus, s32_devs, s32_devs_lo, s32_devs_hi, s32_ns) = read_stable32('phase_dat_adev_octave.txt', 1.0) phase = read_datafile('PHASE.DAT') (taus, devs, errs, ns) = allan.adev(phase, taus=s32_taus) # CI computation los = [] his = [] for (d, t, n) in zip(devs, taus, ns): #edf = greenhall_simple_edf( alpha=0, d=2, m=t, S=1, F=t, N=len(phase) ) edf2 = allan.edf_greenhall(alpha=0, d=2, m=t, N=len(phase), overlapping=False, modified=False) #print(edf,edf2,edf2/edf) (lo, hi) = allan.confidence_intervals(dev=d, ci=0.68268949213708585, edf=edf2) # 0.68268949213708585 #allan.uncertainty_estimate(len(phase), t, d,ci=0.683,noisetype='wf') los.append(lo) his.append(hi) #print greenhall_simple_edf( alpha=0, d=2, m=1, S=1, F=1, N=len(phase) ) #print confidence_intervals( dev # tau N edf chi2_l # 1 999 782.030 821.358 , 742.689 # 2.851498, 2.922319 2.998720 for (t1, d1, lo1, hi1, n1, t2, d2, lo2, hi2, n2) in zip(s32_taus, s32_devs, s32_devs_lo, s32_devs_hi, s32_ns, taus, devs, los, his, ns): print("s32 %03d %03f %1.6f %1.6f %1.6f" % (n1, t1, lo1, d1, hi1)) print("at %03d %03f %1.6f %1.6f %1.6f" % (n2, t2, round(lo2, 5), round(d2, 5), round(hi2, 5))) approx_equal(lo1, lo2, tolerance=1e-3) approx_equal(hi1, hi2, tolerance=1e-3) print("----")
def test_phasedat_adev(self): #(s32_taus, s32_devs, s32_devs_lo, s32_devs_hi, s32_ns) = read_stable32( 'phase_dat_adev_octave.txt' , 1.0 ) s32_rows = testutils.read_stable32('phase_dat_adev_octave.txt', 1.0) phase = testutils.read_datafile('PHASE.DAT') (taus, devs, errs, ns) = allan.adev(phase, taus=[s32['tau'] for s32 in s32_rows]) # CI computation los = [] his = [] for (d, t, n) in zip(devs, taus, ns): #edf = greenhall_simple_edf( alpha=0, d=2, m=t, S=1, F=t, N=len(phase) ) edf2 = allan.edf_greenhall(alpha=0, d=2, m=t, N=len(phase), overlapping=False, modified=False) (lo, hi) = allan.confidence_intervals(dev=d, ci=0.68268949213708585, edf=edf2) # 0.68268949213708585 #(lo2,hi2) = allan.confidence_intervals( dev=d, ci=0.68268949213708585, edf=edf2, use_scipy_chi2_ppf=False ) #testutils.check_approx_equal(lo, lo2, tolerance=1e-4) #testutils.check_approx_equal(hi, hi2, tolerance=1e-4) #allan.uncertainty_estimate(len(phase), t, d,ci=0.683,noisetype='wf') los.append(lo) his.append(hi) for (s32, t2, d2, lo2, hi2, n2) in zip(s32_rows, taus, devs, los, his, ns): print("s32 %03d %03f %1.6f %1.6f %1.6f" % (s32['n'], s32['tau'], s32['dev_min'], s32['dev'], s32['dev_max'])) print("at %03d %03f %1.6f %1.6f %1.6f" % (n2, t2, round(lo2, 5), round(d2, 5), round(hi2, 5))) testutils.check_approx_equal(s32['dev_min'], lo2, tolerance=1e-3) testutils.check_approx_equal(s32['dev'], d2, tolerance=1e-4) testutils.check_approx_equal(s32['dev_max'], hi2, tolerance=1e-3) print("----")
def updateAllan(self): # Get the selected column column = self.allan_var_param.value() data = column.data times = column.parent.timeColumnData.data # Check if DAQ must be used daq_times = None for sisterCol in column.parent.children: if "DAQ time" in sisterCol.header: sisterCol.data = column.parent.np_array[:,sisterCol.index] daq_times = sisterCol.data minTime, maxTime = column.plot.getViewBox().viewRange()[0] indexes = np.argwhere(np.logical_and(times >= minTime,times <= maxTime)) if daq_times is not None: rate = 1./(daq_times[1] - daq_times[0]) else: rate = len(times)/(max(times)-min(times)) if self.fractional_var_param.value(): data_freq = data[indexes]/data[indexes[0]] else: data_freq = data[indexes] taus = np.logspace(0.0,4.0,num=50) sys.stdout.write("Computing Allan deviation ") (tau_used, ad , ade, adn) = allantools.adev(data_freq, rate, taus) sys.stdout.write("Done\n") x = tau_used y = ad top_error = np.log10(ad + ade/2) - np.log10(ad) bot_error = np.log10(ad) - np.log10(ad - ade/2) self.err_bara.setData(x=np.log10(x), y=np.log10(y), top=top_error, bottom=bot_error) self.curvea.setData(x=x,y=y) if self.fractional_var_param.value(): self.pa.setTitle("Fractional - "+column.header) else: self.pa.setTitle(column.header)
def to_fractional(flist,f0): out=[] for f in flist: out.append( f/float(f0) - 1.0 ) return out fname = "gps_1pps_phase_data.txt.gz" phase = read_datafile(fname,column=0) print len(phase), " values read: ", len(phase)/3600.0 , " hours" #f = to_fractional(f10MHz, 10e6 ) # convert to fractional frequency my_taus = numpy.logspace(1,6,60) # log-spaced tau values from 10s and upwards rate = 1/float(1.0) (adev_taus,adev_devs,adev_errs,ns) = allan.adev(phase=phase, rate=rate, taus=my_taus) (oadev_taus,oadev_devs,oadev_errs,ns) = allan.oadev(phase=phase, rate=rate, taus=my_taus) (hdev_taus,hdev_devs,hdev_errs,ns) = allan.hdev(phase=phase, rate=rate, taus=my_taus) (ohdev_taus,ohdev_devs,ohdev_errs,ns) = allan.ohdev(phase=phase, rate=rate, taus=my_taus) (mdev_taus,mdev_devs,mdev_errs,ns) = allan.mdev(phase=phase, rate=rate, taus=my_taus) (totdev_taus,totdev_devs,totdev_errs,ns) = allan.totdev(phase=phase, rate=rate, taus=my_taus) (tie_taus,tie_devs,tie_errs,ns) = allan.tierms(phase=phase, rate=rate, taus=my_taus) #(mtie_taus,mtie_devs,mtie_errs,ns) = allan.mtie(phase=phase, rate=rate, taus=my_taus) (tdev_taus,tdev_devs,tdev_errs,ns) = allan.tdev(phase=phase, rate=rate, taus=my_taus) (tdev2_taus,tdev2_devs,tdev2_errs,ns2) = allan.tdev(frequency=allan.phase2frequency(phase,1.0), rate=rate, taus=my_taus)
serial_port.write(initBytes) print(initBytes) time.sleep(1) serial_port.write(setsBytes) print(setsBytes) time.sleep(1) if __name__ == '__main__': serial_port = serial.Serial('COM9', 230400, timeout=0.5) if serial_port.isOpen(): print("open success!\n") else: raise RuntimeError("open failed") # send(serial_port) receive(serial_port) adevAccX = allantools.adev(accX, rate=100, data_type='freq') adevAccY = allantools.adev(accY, rate=100, data_type='freq') adevAccZ = allantools.adev(accZ, rate=100, data_type='freq') print(adevAccX) plt.loglog(adevAccX[0], adevAccX[1]) plt.loglog(adevAccY[0], adevAccY[1]) plt.loglog(adevAccZ[0], adevAccZ[1]) plt.grid(axis='both', linestyle='-', color='b') plt.xlabel('tao') plt.ylabel('Allan dev of acc') plt.show()
def test_tau_generator_numpy1234(): wanted_taus = np.array([1, 2, 3, 4]) (taus_used, adev, adeverror, adev_n) = at.adev(d, rate=r, taus=wanted_taus) np.testing.assert_allclose(taus_used, wanted_taus)
def test_tau_generator_decade(): (taus_used, adev, adeverror, adev_n) = at.adev(d, rate=r, taus="decade") np.testing.assert_array_equal(taus_used, expected_decade)
# this demonstrates how to calculate confidence intervals for ADEV # using the algorithms from Greenhall2004 data_file = '../tests/phasedat/PHASE.DAT' def read_datafile(filename): p = [] with open(filename) as f: for line in f: if not line.startswith("#"): # skip comments p.append(float(line)) return p # read input data from file phase = read_datafile(data_file) # normal ADEV computation, giving naive 1/sqrt(N) errors (taus,devs,errs,ns) = at.adev(phase, taus='octave') # Confidence-intervals for each (tau,adev) pair separately. cis=[] for (t,dev) in zip(taus,devs): # Greenhalls EDF (Equivalent Degrees of Freedom) # alpha +2,...,-4 noise type, either estimated or known # d 1 first-difference variance, 2 allan variance, 3 hadamard variance # we require: alpha+2*d >1 (is this ever false?) # m tau/tau0 averaging factor # N number of phase observations edf = at.edf_greenhall( alpha=0, d=2, m=t, N=len(phase), overlapping = False, modified=False ) # with the known EDF we get CIs # for 1-sigma confidence we set # ci = scipy.special.erf(1/math.sqrt(2)) = 0.68268949213708585 (lo,hi) = at.confidence_intervals( dev=dev, ci=0.68268949213708585, edf=edf )
""" ########################## # test stable32plot.py # ########################## """ import allantools from pylab import figure, show, plot from stable32plot import sigmaplot, dataplot #import 2 functions: sigmaplot,dataplot """#------------generate random data and cal adev-----------------""" x1 = allantools.noise.white(1000) (taus, adevs, errors, ns) = allantools.adev(x1) (taust, adevst, errorst, nst) = allantools.tdev(x1) (tauso, adevso, errorso, nso) = allantools.oadev(x1) x2 = allantools.noise.white(1000, 0.6) (taus2, adevs2, errors2, ns2) = allantools.oadev(x2) x3 = allantools.noise.white(1000, 0.5) (taus3, adevs3, errors3, ns3) = allantools.oadev(x3) x4 = allantools.noise.white(1000, 0.4) (taus4, adevs4, errors4, ns4) = allantools.oadev(x4) x5 = allantools.noise.white(1000, 0.3) (taus5, adevs5, errors5, ns5) = allantools.oadev(x5) x6 = allantools.noise.white(1000, 0.2) (taus6, adevs6, errors6, ns6) = allantools.oadev(x6)
for f in flist: out.append(f / float(f0) - 1.0) return out fname = "gps_1pps_phase_data.txt.gz" phase = read_datafile(fname, column=0) print len(phase), " values read: ", len(phase) / 3600.0, " hours" #f = to_fractional(f10MHz, 10e6 ) # convert to fractional frequency my_taus = numpy.logspace(1, 6, 60) # log-spaced tau values from 10s and upwards rate = 1 / float(1.0) (adev_taus, adev_devs, adev_errs, ns) = allan.adev(phase=phase, rate=rate, taus=my_taus) (oadev_taus, oadev_devs, oadev_errs, ns) = allan.oadev(phase=phase, rate=rate, taus=my_taus) (hdev_taus, hdev_devs, hdev_errs, ns) = allan.hdev(phase=phase, rate=rate, taus=my_taus) (ohdev_taus, ohdev_devs, ohdev_errs, ns) = allan.ohdev(phase=phase, rate=rate, taus=my_taus) (mdev_taus, mdev_devs, mdev_errs, ns) = allan.mdev(phase=phase, rate=rate,
def plot_clock_lock(data_filename, center_freq, units='Hz', allan_cuts=[(0, None)]): data = Data(most_recent(data_filename), cuts=allan_cuts) fig, ax = plt.subplots(3, 2) fig.set_size_inches(14, 15) ax[0, 0].get_shared_x_axes().join(ax[0, 0], ax[1, 0]) for i, (frac, tot, lock) in enumerate( zip(data['andor']['frac'][2:], data['andor']['tot'][2:], data['clock_servo']['dither_lock'][:-2])): if lock['dither'][0] == '-9/2': ax[0, 0].plot(i, frac, 'bo') ax[1, 0].plot(i, tot, 'bo') else: ax[0, 0].plot(i, frac, 'ro') ax[1, 0].plot(i, tot, 'ro') for i, (frac, tot, lock) in enumerate( zip(data['andor']['frac'][2:], data['andor']['tot'][2:], data['clock_servo']['dither_lock'][:-2])): if (lock['dither'][0] == '-9/2') and (lock['dither'][1] == 'right'): f = data['andor']['frac'] ax[0, 0].plot([i, i - 2], [f[i + 2], f[i]], 'b') if (lock['dither'][0] == '+9/2') and (lock['dither'][1] == 'right'): f = data['andor']['frac'] ax[0, 0].plot([i, i - 2], [f[i + 2], f[i]], 'r') ax[0, 0].set_ylim([0, 1]) ax[0, 0].set_xlabel('Experiment index') ax[0, 0].set_ylabel('Excitation fraction') # else: # ax[0,0].plot(i, frac, 'ro') zeeman_shifts = (data['-9/2']['frequency'][4::4] - data['+9/2']['frequency'][4::4]) / 2. zeeman_shift = np.mean(zeeman_shifts) mean_freqs = (data['+9/2']['frequency'][4::4] + data['-9/2']['frequency'][4::4]) / 2. ax[0, 1].plot(center_freq - mean_freqs, 'k') ax[0, 1].plot(center_freq - data['-9/2']['frequency'][4::4] + zeeman_shift, 'b') ax[0, 1].plot(center_freq - data['+9/2']['frequency'][4::4] - zeeman_shift, 'r') ax[0, 1].set_ylabel('frequency [Hz]') ax[0, 1].set_xlabel('Cycle index') freqs = mean_freqs # freqs = zeeman_shifts # freqs = np.concatenate([freqs[i:f] for i,f in allan_cuts]) (taus, devs, errs, n) = allantools.adev(signal.detrend(freqs) / 429e12, rate=1. / (4 * 14.58), data_type='freq', taus='all') devs_ctrl = devs for tau, dev, err in zip(taus, devs, errs): ax[1, 1].plot(tau, dev, 'ko') ax[1, 1].plot([tau, tau], [dev - err, dev + err], 'k-') ax[1, 1].set_yscale('log') ax[1, 1].set_xscale('log') ax[1, 1].set_ylabel('Instability') ax[1, 1].set_xlabel('Averaging time') errp = [] errm = [] for i, (frac, lock) in enumerate( zip(data['andor']['frac'][2:], data['clock_servo']['dither_lock'][:-2])): if lock['dither'] == ['-9/2', 'right']: error = data['andor']['frac'][i - 2 + 2] - frac ax[2, 0].plot(i, error, 'bo') errm.append(error) elif lock['dither'] == ['+9/2', 'right']: error = data['andor']['frac'][i - 2 + 2] - frac ax[2, 0].plot(i, error, 'ro') errp.append(error) ax[2, 0].set_ylim([-1, 1]) contrast = .9 if 'ramsey_clock' in data['sequencer']['sequence'][0]: print 'detected Ramsey sequence' err_correction_factor = contrast * .32 * .5 / np.mean( data['sequencer']['*Tramsey']) else: print 'detected Rabi sequence' err_correction_factor = contrast * .35 * .8 / np.mean( data['sequencer']['*Trabi']) fm_err = np.array(errm) * err_correction_factor (taus, devs, errs, n) = allantools.adev(signal.detrend(fm_err) / 429e12, rate=1. / (4 * 14.58), data_type='freq', taus='all') devs_m = devs for tau, dev, err in zip(taus, devs, errs): ax[1, 1].plot(tau, dev, 'bo') ax[1, 1].plot([tau, tau], [dev - err, dev + err], 'b-') fm_uncorrected = data['-9/2']['frequency'][4::4] fm_corrected = fm_err[:len(fm_uncorrected )][1:] + fm_uncorrected[:len(fm_err)][:-1] ax[0, 1].plot(range(1, len(fm_corrected) + 1), center_freq - fm_corrected + zeeman_shift, 'b--') (taus, devs, errs, n) = allantools.adev(signal.detrend(fm_corrected) / 429e12, rate=1. / (4 * 14.58), data_type='freq', taus='all') devs_m = devs # for tau, dev, err in zip(taus, devs, errs): # ax[1,1].plot(tau, dev, 'bo') # ax[1,1].plot([tau, tau], [dev - err, dev + err], 'b-') fp_err = np.array(errp) * err_correction_factor (taus, devs, errs, n) = allantools.adev(signal.detrend(fp_err) / 429e12, rate=1. / (4 * 14.58), data_type='freq', taus='all') devs_p = devs for tau, dev, err in zip(taus, devs, errs): ax[1, 1].plot(tau, dev, 'ro') ax[1, 1].plot([tau, tau], [dev - err, dev + err], 'r-') fp_uncorrected = data['+9/2']['frequency'][4::4] fp_corrected = fp_err[:len(fp_uncorrected )][1:] + fp_uncorrected[:len(fp_err)][:-1] ax[0, 1].plot(range(1, len(fp_corrected) + 1), center_freq - fp_corrected - zeeman_shift, 'r--') (taus, devs, errs, n) = allantools.adev(signal.detrend(fp_corrected) / 429e12, rate=1. / (4 * 14.58), data_type='freq', taus='all') # for tau, dev, err in zip(taus, devs, errs): # ax[1,1].plot(tau, dev, 'ro') # ax[1,1].plot([tau, tau], [dev - err, dev + err], 'r-') for tau, dc, dp, dm in zip(taus, devs_ctrl, devs_p, devs_m): d_tot = np.sqrt(dc**2 + (dp + dm)**2 / 4) ax[1, 1].plot(tau, d_tot, 'o', color='magenta') # ax[1,1].plot([tau, tau], [dev - err, dev + err], 'r-') # ax[2,1].plot(autocorrelate(signal.detrend(fm_uncorrected)), 'bo') # ax[2,1].plot(autocorrelate(signal.detrend(fm_corrected)), 'bo--') # ax[2,1].plot(autocorrelate(signal.detrend(fp_uncorrected)), 'ro') # ax[2,1].plot(autocorrelate(signal.detrend(fp_corrected)), 'ro--') ax[2, 1].plot(autocorrelate(errm), 'bo-') ax[2, 1].plot(autocorrelate(errp), 'ro-') # ax[2,1].plot(zeeman_shifts - zeeman_shift, 'k') # ax[2,1].set_title('zeeman shift: {}'.format(zeeman_shift)) # ax[2,1].set_xlabel('Cycle index') # ax[2,1].set_ylabel('frequency (Hz)') return fig, ax
def test_tau_generator_empty_list(): (taus_used, adev, adeverror, adev_n) = at.adev(d, taus=[]) np.testing.assert_allclose(taus_used, expected_octave)
def test_zero_rate(): with pytest.raises(RuntimeError): at.adev(d, rate=0.0)
def makeplots(self): """ """ col = ['b', 'r', 'g', 'c'] t_sky = array(self.time[0]) t_load = array(self.time[1]) G = self.G G2 = self.G2 Trx = self.Trx Tcold = self.Tcold wvr_state = self.wvr_state nchan = self.nchan Trx_m = self.Trx_m rTsys_sky = self.rTsys_sky difTsys_sky = self.difTsys_sky Tsky = self.Tsky Tsys_sky = self.Tsys_sky Tsys_load = self.Tsys_load q = self.q if '/' in self.txtfile: filename = self.txtfile.split('/')[1].split('.')[0] else: filename = self.txtfile.split('.')[0] q = self.get_index() m = [] ##### plotting the time series ##### figure(1, figsize=(14, 10)) clf() suptitle('Raw Data of ' + self.txtfile) subplot(3, 3, 1) for i in range(nchan): plot(t_sky, Tsys_sky[i, :]) xlabel('time [s]') ylabel('Tsys_sky [K]') xlim([-10, max(t_load) + 10]) grid() subplot(3, 3, 2) for i in range(nchan): plot(t_sky, Tsys_sky[i, :] - mean(Tsys_sky[i, :]) + i * 5) xlabel('time [s]') ylabel('mean subtracted Tsys_sky [K]') xlim([-10, max(t_load) + 10]) grid() ylim([-5, 20]) subplot(3, 3, 3) for i in range(nchan): plot(t_sky, Tsys_sky[i, :] - Trx_m[0, i]) xlabel('time [s]') ylabel('Tsky [K]') xlim([-10, max(t_load) + 10]) grid() subplot(3, 3, 4) for i in range(nchan): plot(t_load, Tsys_load[i, :]) xlabel('time [s]') ylabel('Tsys_load [K]') xlim([-10, max(t_load) + 10]) grid() subplot(3, 3, 5) for i in range(nchan): plot(t_load, Tsys_load[i, :] - median(Tsys_load[i, :]) + i * 5) xlabel('time [s]') ylabel('mean subtracted Tsys_load [K]') ylim([-5, 20]) xlim([-10, max(t_load) + 10]) grid() subplot(3, 3, 6) for i in range(nchan): plot(t_load, Tsys_load[i, :] - Trx_m[0, i]) xlabel('time [s]') ylabel('Tload [K]') legend(['Chan 0', 'Chan 1', 'Chan 2', 'Chan 3'], bbox_to_anchor=(1.3, 1.1)) ylim([140 - 5, 140 + 20]) xlim([-10, max(t_load) + 10]) grid() subplot(3, 3, 7) plot(t_load, self.Tamb) xlabel('time [s]') ylabel('Ambient Load Temp [K]') ylim([mean(self.Tamb) - 2, mean(self.Tamb) + 2]) subplots_adjust(wspace=.35) xlim([-10, max(t_load) + 10]) grid() subplot(3, 3, 8) plot(t_load, self.Tcold) xlabel('time [s]') ylabel('Cold Load Temp [K]') ylim([mean(self.Tcold) - 2, mean(self.Tcold) + 2]) subplots_adjust(wspace=.35) xlim([-10, max(t_load) + 10]) grid() subplot(3, 3, 9) plot(t_load, self.Tif) if self.Thtr0 != []: plot(t_load, self.Thtr0, 'g+') plot(t_load, median(self.Thtr0) + (self.Thtr0 - median(self.Thtr0)) * 20, 'g-') xlabel('time [s]') ylabel('IF Amplifier Temp [K]') ylim([mean(self.Tif) - 2, mean(self.Tif) + 2]) subplots_adjust(wspace=.35) xlim([-10, max(t_load) + 10]) legend(['$T_{IF}$', '$T_{Htr0}$ ', '$T_{Htr0}$ x20'], bbox_to_anchor=(1.4, 1.0), prop={'size': 10}) grid() savefig('plots/' + filename + "_raw_tod.png") ############################### #plots the gain fluctuations and receiver noise temperature figure(2, figsize=(12, 9)) clf() suptitle('Gain and Trx for ' + self.txtfile) ngains = shape(G)[2] for i in range(nchan): ax = subplot(2 * nchan, 1, i + 1) errorbar(arange(ngains), G[0, i, :], G[1, i, :], fmt='.-') errorbar(arange(ngains), G2[0, i, :], G2[1, i, :], fmt='.-') m = mean(G[0, i]) axhline(m, linestyle='--') ylim([m - 50, m + 50]) xlim([-1, ngains]) locator_params(axis='y', nbins=4) subplots_adjust(hspace=.01) if i != nchan - 1: ax.set_xticklabels([]) if i != 0: ax.yaxis.set_major_locator(MaxNLocator(nbins=4, prune='upper')) grid() subplots_adjust(hspace=1) ylabel('Gain [K/AD]') for i in range(nchan): subplot(8, 1, nchan + i + 1) errorbar(arange(ngains), Trx[0, i, :], Trx[1, i, :], fmt='.-') m = mean(Trx[0, i]) axhline(m, linestyle='--') ylim([m - 15, m + 15]) xlim([-1, ngains]) locator_params(axis='y', nbins=4) subplots_adjust(hspace=.01) if i != nchan - 1: ax.set_xticklabels([]) if i != 0: ax.yaxis.set_major_locator(MaxNLocator(nbins=4, prune='upper')) grid() xlabel('index') ylabel('Trx [K]') legend(['Chan 0', 'Chan 1', 'Chan 2', 'Chan 3'], bbox_to_anchor=(1.3, 1.1)) savefig('plots/' + filename + "_gain_trx.png") ############################ #plots the allan deviation of Tsky for specifications listed below figure(3, figsize=(14, 9)) clf() suptitle('Allan Deviation of Tsys_sky for ' + self.txtfile) interval = math.log10(t_sky[-1] / 2) + 1 dt = arange(50) / 50. * interval - 1 taux = 10**dt BW = [0.16e9, 0.75e9, 1.25e9, 2.5e9] col = ['r', 'b', 'g', 'c'] # standard allan variance subplot(2, 2, 1) for i in range(nchan): [tau_out, adev, adeverr, n] = at.adev(rTsys_sky[i], 10.4, taux) errorbar(tau_out, array(adev), array(adeverr), fmt=col[i] + '+-') plot(tau_out, sqrt(2 / (BW[i] * array(tau_out))), col[i] + '--') xscale('log') yscale('log') xlabel('Delta t [s]') ylabel('Allan deviation [rms]') grid() ylim([1e-6, 1e-3]) xlim([t_sky[1] - t_sky[0], t_sky[-1]]) title('Raw Tsys_sky') # subtracting channel 3 subplot(2, 2, 2) for i in range(nchan - 1): [tau_out, adev, adeverr, n] = at.adev(rTsys_sky[i] - rTsys_sky[3], 10.4, taux) errorbar(tau_out, array(adev), array(adeverr), fmt=col[i] + '+-') plot(tau_out, sqrt(2 / (BW[i] * array(tau_out))), col[i] + '--') xscale('log') yscale('log') xlabel('Delta t [s]') ylabel('Allan deviation [rms]') grid() ylim([1e-6, 1e-3]) xlim([t_sky[1] - t_sky[0], t_sky[-1]]) title('frequency differencing (subtract channel 3)') # subtracting Tload and frequency differencing subplot(2, 2, 3) for i in range(nchan - 1): [tau_out, adev, adeverr, n] = at.adev(difTsys_sky[i] - difTsys_sky[3], 10.4, taux) errorbar(tau_out, array(adev), array(adeverr), fmt=col[i] + '+-') plot(tau_out, sqrt(2 / (BW[i] * array(tau_out))), col[i] + '--') xscale('log') yscale('log') xlabel('Delta t [s]') ylabel('Allan deviation [rms]') grid() ylim([1e-6, 1e-3]) xlim([t_sky[1] - t_sky[0], t_sky[-1]]) title('Dicke switching AND frequency differencing') # subtracting Tload (ie, doing the proper Dicke-switching) subplot(2, 2, 4) for i in range(nchan): [tau_out, adev, adeverr, n] = at.adev(array(difTsys_sky[i]), 10.4, taux) errorbar(tau_out, array(adev), array(adeverr), fmt=col[i] + '+-') for i in range(nchan): plot(tau_out, sqrt(2 / (BW[i] * array(tau_out))), col[i] + '--') xscale('log') yscale('log') xlabel('Delta t [s]') ylabel('Allan deviation [rms]') grid() legend(['Chan 0', 'Chan 1', 'Chan 2', 'Chan 3'], bbox_to_anchor=(1.2, 1.1)) ylim([1e-6, 1e-3]) xlim([t_sky[1] - t_sky[0], t_sky[-1]]) title('only Dicke-switching') savefig('plots/' + filename + "_allan_variance.png") ############################### #### plotting the time series of the fractional fluctuations figure(4, figsize=(14, 9)) clf() suptitle('time series of fractional Tsky for ' + self.txtfile) ys = [-.25, .25] ax = subplot(2, 2, 1) for i in range(nchan): plot(t_sky, (rTsys_sky[i] - 1) * 100, col[i]) # -1 and *100 to get it in % grid() ylim(ys) xlim([-10, max(t_load) + 10]) title('Raw Tsys_sky') xlabel('time [s]') ylabel('Tsys_sky [% fluctuations from mean]') ax = subplot(2, 2, 2) for i in range(nchan): if i == 3: continue plot(t_sky, (rTsys_sky[i] - rTsys_sky[3]) * 100, col[i]) # -1 and *100 to get it in % grid() ylim(ys) xlim([-10, max(t_load) + 10]) title('Frequency-differenced Tsys_sky ') xlabel('time [s]') ylabel('Tsys_sky [% fluctuations from mean]') ax = subplot(2, 2, 4) for i in range(nchan): plot(t_sky[q[0]], (difTsys_sky[i] - 1) * 100, col[i]) # -1 and *100 to get it in % grid() ylim(ys) xlim([-10, max(t_load) + 10]) title('Dicke-switched Tsys_sky ') xlabel('time [s]') ylabel('Tsys_sky [% fluctuations from mean]') legend(['Chan 0', 'Chan 1', 'Chan 2', 'Chan 3'], bbox_to_anchor=(1.2, 1.1)) ax = subplot(2, 2, 3) for i in range(nchan): if i == 3: continue plot(t_sky[q[0]], (difTsys_sky[i] - difTsys_sky[3]) * 100, col[i]) # -1 and *100 to get it in % grid() ylim(ys) xlim([-10, max(t_load) + 10]) title('Dicke-switched AND frequency-differenced Tsys_sky') xlabel('time [s]') ylabel('Tsys_sky [% fluctuations from mean ]') savefig('plots/' + filename + "_processed_fractional_tod.png") show() ############################### #### plotting the time series of Tsky figure(5, figsize=(14, 9)) clf() suptitle('time series Tsky for ' + self.txtfile) chanlist = self.chanlist ax = subplot(2, 2, 1) for i in chanlist: plot(t_sky[q[0]], Tsky[0, i], col[i]) grid() #ylim() xlim([-10, max(t_load) + 10]) title('Raw Tsky') xlabel('time [s]') ylabel('Tsky [K]') ax = subplot(2, 2, 2) for i in chanlist: if i == 3: continue plot(t_sky[q[0]], Tsky[1, i], col[i]) grid() #ylim(ys) xlim([-10, max(t_load) + 10]) title('Frequency-differenced Tsky ') xlabel('time [s]') ylabel('Tsky [K]') ax = subplot(2, 2, 4) for i in chanlist: plot(t_sky[q[0]], (Tsky[2, i]), col[i]) grid() # ylim(ys) xlim([-10, max(t_load) + 10]) title('Dicke-switched Tsky ') xlabel('time [s]') ylabel('Tsky [K]') legend(['Chan 0', 'Chan 1', 'Chan 2', 'Chan 3'], bbox_to_anchor=(1.2, 1.1)) ax = subplot(2, 2, 3) for i in chanlist: if i == 3: continue plot(t_sky[q[0]], Tsky[3, i], col[i]) grid() #ylim(ys) xlim([-10, max(t_load) + 10]) title('Dicke-switched AND frequency-differenced Tsky') xlabel('time [s]') ylabel('Tsky [K]') savefig('plots/' + filename + "_processed_tod.png") show() return t_sky, q, Tsys_sky, Tsys_load
""" ########################## # test stable32plot.py # ########################## """ import allantools from pylab import figure,show,plot from stable32plot import sigmaplot,dataplot#import 2 functions: sigmaplot,dataplot """#------------generate random data and cal adev-----------------""" x1 = allantools.noise.white(1000) (taus, adevs, errors, ns) = allantools.adev(x1) (taust, adevst, errorst, nst) = allantools.tdev(x1) (tauso, adevso, errorso, nso) = allantools.oadev(x1) x2=allantools.noise.white(1000,0.6) (taus2,adevs2,errors2,ns2)=allantools.oadev(x2) x3=allantools.noise.white(1000,0.5) (taus3,adevs3,errors3,ns3)=allantools.oadev(x3) x4=allantools.noise.white(1000,0.4) (taus4,adevs4,errors4,ns4)=allantools.oadev(x4) x5=allantools.noise.white(1000,0.3) (taus5,adevs5,errors5,ns5)=allantools.oadev(x5) x6=allantools.noise.white(1000,0.2)
def main(argv): vartypes = ['avar', 'oavar'] tau_axis = None for arg in argv: key = arg.split('=')[0] value = arg.split('=')[1] if key == 'taus': tau_axis = value elif key == 'var': toKeep = value toRemove = [] for i in range(0, len(vartypes)): if vartypes[i] != toKeep: toRemove.append(i) for idx in toRemove[::-1]: del vartypes[idx] # allantools options if not (tau_axis in [None, 'all', 'octave', 'decade']): print('./plot.py taus=[all,octave,decade]') return 0 # read input x = readcsv("input.csv") #x = allantools.noise.brown(16384, b2=1.0) #x = allantools.noise.white(16384*100) # b2=1.0) # gui fig = plt.figure() ax1 = plt.subplot(111) plt.grid(True) for vartype in vartypes: print("VAR: {:s}".format(vartype)) for dtype in ['phase', 'freq']: # generate model if vartype == 'avar': if tau_axis == 'all': (taus, ym, errors, ns) = allantools.adev(x, data_type=dtype, taus='all') elif tau_axis == 'decade': (taus, ym, errors, ns) = allantools.adev(x, data_type=dtype, taus='decade') elif tau_axis == 'octave': (taus, ym, errors, ns) = allantools.adev(x, data_type=dtype, taus='octave') else: (taus, ym, errors, ns) = allantools.adev(x, data_type=dtype) elif vartype == 'oavar': if tau_axis == 'all': (taus, ym, errors, ns) = allantools.oadev(x, data_type=dtype, taus='all') elif tau_axis == 'decade': (taus, ym, errors, ns) = allantools.oadev(x, data_type=dtype, taus='decade') elif tau_axis == 'octave': (taus, ym, errors, ns) = allantools.oadev(x, data_type=dtype, taus='octave') else: (taus, ym, errors, ns) = allantools.oadev(x, data_type=dtype) ym = np.power(ym, 2) # adev compared to avar ym = 20 * np.log10(ym) ax1.semilogx(taus, ym, '+-', label="{:s} '{:s}' model".format(vartype, dtype)) # output y = readcsv("{:s}-{:s}.csv".format(vartype, dtype)) y = 20 * np.log10(y) if tau_axis == None: taus = powers_of_two_axis(len(y)) elif tau_axis == 'decade': taus = powers_of_ten_axis(len(y)) else: taus = np.linspace(0, len(y), len(y), dtype='int') ax1.semilogx(taus, y, '+', label="{:s} '{:s}'".format(vartype, dtype)) ax1.legend(loc='best') # tb error = 0 max_tol = 0.01 print("-------- {:s} test -------".format(dtype)) for i in range(0, min(len(ym), len(y))): e = abs(y[i] - ym[i]) if e > max_tol: error += 1 print("tau: {:d} error: {:.3e} dB".format(taus[i], e)) if error > 0: print("failed") else: print("passed") print("---------------------") plt.show()
# ad = [] # for tau in range(1,10000): # a = np.square((randWalk[0] - 2*randWalk[tau] + randWalk[2*tau]))/(2*tau*tau) # ad.append(a) # b = np.arange(0,250-0.025,0.025) # # print(np.shape(b)) # plt.plot(b,np.array(ad)) x = allan.noise.white(100000) # print(x+np.array(randWalk)) plt.plot(x + np.array(randWalk)) plt.show() for i in range(0, np.size(gyroOut)): gyroOutInte = np.sum(gyroOut[0:i]) (taus2, ad, ade, ns) = allan.adev(x + np.array(randWalk), rate=415.0, data_type="phase", taus="all") print(np.shape(taus2)) plt.plot(ad) plt.yscale('log') plt.xscale('log') plt.show()
def test_tau_generator_empty_list(): (taus_used, adev, adeverror, adev_n) = at.adev(d, taus=[]) np.testing.assert_array_equal(taus_used, expected_octave)
def nbs14_test(): taus = [1, 2] devs = [] tol = 1e-4 # first tests that call the _phase functions print "nbs14 tests for phase data:" (taus2,adevs2,aerrs2,ns2) = allan.adev_phase( nbs14_phase, 1.0, taus) adevs = nbs14_devs[0] assert( check_devs( adevs2[0], adevs[0] ) ) assert( check_devs( adevs2[1], adevs[1] ) ) print "nbs14 adev OK" (taus2,adevs2,aerrs2,ns2) = allan.oadev_phase( nbs14_phase, 1.0, taus) oadevs = nbs14_devs[1] assert( check_devs( adevs2[0], oadevs[0] ) ) assert( check_devs( adevs2[1], oadevs[1] ) ) print "nbs14 oadev OK" (taus2,adevs2,aerrs2,ns2) = allan.mdev_phase( nbs14_phase, 1.0, taus) mdevs = nbs14_devs[2] assert( check_devs( adevs2[0], mdevs[0] ) ) assert( check_devs( adevs2[1], mdevs[1] ) ) print "nbs14 mdev OK" (taus2,adevs2,aerrs2,ns2) = allan.totdev_phase( nbs14_phase, 1.0, taus) totdevs = nbs14_devs[3] assert( check_devs( adevs2[0], totdevs[0] ) ) assert( check_devs( adevs2[1], totdevs[1] ) ) print "nbs14 totdev OK" (taus2,adevs2,aerrs2,ns2) = allan.hdev_phase( nbs14_phase, 1.0, taus) hdevs = nbs14_devs[4] assert( check_devs( adevs2[0], hdevs[0] ) ) assert( check_devs( adevs2[1], hdevs[1] ) ) print "nbs14 hdev OK" (taus2,adevs2,aerrs2,ns2) = allan.tdev_phase( nbs14_phase, 1.0, taus) tdevs = nbs14_devs[5] assert( check_devs( adevs2[0], tdevs[0] ) ) assert( check_devs( adevs2[1], tdevs[1] ) ) print "nbs14 tdev OK" (taus2,adevs2,aerrs2,ns2) = allan.ohdev_phase( nbs14_phase, 1.0, taus) ohdevs = nbs14_devs[6] assert( check_devs( adevs2[0], ohdevs[0] ) ) assert( check_devs( adevs2[1], ohdevs[1] ) ) print "nbs14 ohdev OK" # then the same tests for frequency data print "nbs14 tests for frequency data:" f_fract = [ float(f) for f in nbs14_f] (taus2,adevs2,aerrs2,ns2) = allan.adev( f_fract, 1.0, taus) adevs = nbs14_devs[0] assert( check_devs( adevs2[0], adevs[0] ) ) assert( check_devs( adevs2[1], adevs[1] ) ) print "nbs14 freqdata adev OK" (taus2,adevs2,aerrs2,ns2) = allan.oadev( f_fract, 1.0, taus) oadevs = nbs14_devs[1] assert( check_devs( adevs2[0], oadevs[0] ) ) assert( check_devs( adevs2[1], oadevs[1] ) ) print "nbs14 freqdata oadev OK" (taus2,adevs2,aerrs2,ns2) = allan.mdev( f_fract, 1.0, taus) mdevs = nbs14_devs[2] assert( check_devs( adevs2[0], mdevs[0] ) ) assert( check_devs( adevs2[1], mdevs[1] ) ) print "nbs14 freqdata mdev OK" (taus2,adevs2,aerrs2,ns2) = allan.totdev( f_fract, 1.0, taus) totdevs = nbs14_devs[3] assert( check_devs( adevs2[0], totdevs[0] ) ) assert( check_devs( adevs2[1], totdevs[1] ) ) print "nbs14 freqdata totdev OK" (taus2,adevs2,aerrs2,ns2) = allan.hdev( f_fract, 1.0, taus) hdevs = nbs14_devs[4] assert( check_devs( adevs2[0], hdevs[0] ) ) assert( check_devs( adevs2[1], hdevs[1] ) ) print "nbs14 freqdata hdev OK" (taus2,adevs2,aerrs2,ns2) = allan.tdev( f_fract, 1.0, taus) tdevs = nbs14_devs[5] assert( check_devs( adevs2[0], tdevs[0] ) ) assert( check_devs( adevs2[1], tdevs[1] ) ) print "nbs14 freqdata tdev OK" (taus2,adevs2,aerrs2,ns2) = allan.ohdev( f_fract, 1.0, taus) ohdevs = nbs14_devs[6] assert( check_devs( adevs2[0], ohdevs[0] ) ) assert( check_devs( adevs2[1], ohdevs[1] ) ) print "nbs14 freqdata ohdev OK" print "nbs14 all test OK"
def test_tau_generator_numpy1234(): wanted_taus = np.array([1, 2, 3, 4]) (taus_used, adev, adeverror, adev_n) = at.adev(d, rate=r, taus=wanted_taus) np.testing.assert_array_equal(taus_used, wanted_taus)
def test_tau_generator_decade(): (taus_used, adev, adeverror, adev_n) = at.adev(d, rate=r, taus="decade") np.testing.assert_allclose(taus_used, expected_decade)