Пример #1
0
def three_in_one(wanted='X', save='yes'):
    path1 = r"C:\Users\Lenovo\Desktop\Internship\NoisyData" + "\\" + str(
        wanted) + str(205) + ".npy"
    path2 = r"C:\Users\Lenovo\Desktop\Internship\NoisyData" + "\\" + str(
        wanted) + str(305) + ".npy"
    path3 = r"C:\Users\Lenovo\Desktop\Internship\NoisyData" + "\\" + str(
        wanted) + str(405) + ".npy"

    data1 = np.load(path1)
    data2 = np.load(path2)
    data3 = np.load(path3)

    tau1 = np.logspace(0, 4, 1000)
    rate = [0.01, 1, 10, 20, 30, 40, 50, 60, 70, 80, 90, 100]

    fig = plt.figure(figsize=(12, 7))  #width , height
    fig.suptitle(
        "Allan Deviation for " + wanted +
        " for different rates \n BLUE - 400 \n GREEN - 650 \n RED - 900")
    fig.subplots_adjust(hspace=0.9, wspace=0.8)  #height , width

    for i, r in enumerate(rate):
        (tau21, ad1, ade, adn) = allantools.oadev(data1,
                                                  rate=r,
                                                  data_type="freq",
                                                  taus=tau1)
        (tau22, ad2, ade, adn) = allantools.oadev(data2,
                                                  rate=r,
                                                  data_type="freq",
                                                  taus=tau1)
        (tau23, ad3, ade, adn) = allantools.oadev(data3,
                                                  rate=r,
                                                  data_type="freq",
                                                  taus=tau1)

        plt.subplot(3, 4, i + 1)
        plt.loglog(tau21, ad1, 'b')
        plt.loglog(tau22, ad2, 'g')
        plt.loglog(tau23, ad3, 'r')
        plt.title("Rate " + str(r))
        plt.xlabel('tau')
        plt.ylabel('ADEV [V]')
        plt.grid()

    plt.show()

    save_path = r"C:\Users\Lenovo\Desktop\Internship\NoisyData\\AllanAll" + wanted
    if save == 'yes':
        plot_path = save_path + ".png"
        fig.savefig(plot_path)
Пример #2
0
 def test_phasedat_oadev(self):
     s32_rows = testutils.read_stable32( 'phase_dat_oadev_octave.txt' , 1.0 )
     phase = testutils.read_datafile('PHASE.DAT')
     (taus,devs,errs,ns) = allan.oadev(phase, taus=[s32['tau'] for s32 in s32_rows])
     
     # CI computation
     # alhpa     +2,...,-4   noise power
     # d         1 first-difference variance, 2 allan variance, 3 hadamard variance
     #           alpha+2*d >1
     # m         tau/tau0 averaging factor
     # F         filter factor, 1 modified variance, m unmodified variance
     # S         stride factor, 1 nonoverlapped estimator, m overlapped estimator (estimator stride = tau/S )
     # N         number of phase observations
     los=[]
     his=[]
     for (d,t, n) in zip(devs, taus, ns):
         edf2 = allan.edf_greenhall( alpha=0, d=2, m=int(t), N=len(phase), overlapping = True, modified=False  )
         (lo,hi) = allan.confidence_interval( dev=d, edf=edf2 )
         los.append(lo)
         his.append(hi)
     # compare to Stable32
     print("oadev()")
     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("----")
Пример #3
0
 def test_oadev_ci_and_noiseID(self):
     """ ADEV with confidence intervals, including noise-ID """
     change_to_test_dir()
     s32rows = testutils.read_stable32(
         resultfile='stable32_OADEV_octave.txt', datarate=1.0)
     for row in s32rows:
         phase = testutils.read_datafile('gps_1pps_phase_data.txt.gz')
         (taus, devs, errs, ns) = allan.oadev(phase,
                                              rate=rate,
                                              data_type="phase",
                                              taus=[row['tau']])
         dev = devs[0]
         #print(dev/row['dev'])
         assert np.isclose(dev, row['dev'], rtol=1e-2, atol=0)
         try:
             # CI including noise-ID
             (lo2,
              hi2) = allan.confidence_interval_noiseID(phase,
                                                       dev,
                                                       af=int(row['m']),
                                                       dev_type="oadev",
                                                       data_type="phase")
             print(" tau= %f  lo/s32_lo = %f hi/s32_hi = %f " %
                   (row['tau'], lo2 / row['dev_min'], hi2 / row['dev_max']))
             assert np.isclose(lo2, row['dev_min'], rtol=1e-2, atol=0)
             assert np.isclose(hi2, row['dev_max'], rtol=1e-2, atol=0)
         except NotImplementedError:
             print("can't do CI for tau= %f" % row['tau'])
             pass
Пример #4
0
def allan_deviation(data, rate):
    """Returns the Allan deviation. Makes use of `oadev` from the `allantools` 
    repository

    Parameters
    ----------

    data: array_like(float)
        The data to be processed

    rate: float
        The sampling rate in Hz

    Returns
    -------

    tau: list of float
        The taus used in the Allan deviation
    dev: list of float
        The  Allan deviations.

    Examples
    --------

        >>>foo()
    """

    tau, dev, dev_error, N = oadev(data, rate=rate, data_type='freq')

    return tau, dev
Пример #5
0
 def test_oadev_ci(self):
     s32rows = testutils.read_stable32(resultfile='oadev_decade.txt',
                                       datarate=1.0)
     for row in s32rows:
         data = testutils.read_datafile(data_file)
         (taus, devs, errs, ns) = allan.oadev(data,
                                              rate=rate,
                                              taus=[row['tau']])
         edf = allan.edf_greenhall(alpha=row['alpha'],
                                   d=2,
                                   m=row['m'],
                                   N=len(data),
                                   overlapping=True,
                                   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))
Пример #6
0
def allan_deviation(data, rate):
    tau1 = np.logspace(0, 4, 1000)  # tau values from 1 to 10000
    (tau2, ad, ade, adn) = allantools.oadev(data,
                                            rate=rate,
                                            data_type="freq",
                                            taus=tau1)
    return tau2, ad
Пример #7
0
 def test_oadev_ci(self):
     s32rows = testutils.read_stable32(resultfile='oadev_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.oadev(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=True,
                                   modified=False,
                                   verbose=True)
         (lo, hi) = allan.confidence_interval(devs[0], edf=edf)
         print("n check: ", testutils.check_equal(ns[0], row['n']))
         print(
             "dev check: ", devs[0], row['dev'],
             testutils.check_approx_equal(devs[0],
                                          row['dev'],
                                          tolerance=2e-3))
         print(
             "min dev check: ", lo, row['dev_min'],
             testutils.check_approx_equal(lo,
                                          row['dev_min'],
                                          tolerance=2e-3))
         print(
             "max dev check: ", hi, row['dev_max'],
             testutils.check_approx_equal(hi,
                                          row['dev_max'],
                                          tolerance=2e-3))
 def AllanDeviation(self,id=29850,spacing=1.0):
     self.curve = cs.CurveDB.objects.get(id=id)
     dat = self.curve.data
     l=len(dat)
     rate = 1/float(spacing) # data rate in Hz
     taus = np.logspace(np.log10(spacing),np.log10(spacing*l),5000)
     # fractional frequency data
     #(taus_used, adev, adeverror, adev_n) = allantools.adev(dat.values, rate, taus)
     (taus_used, adev, adeverror, adev_n) = allantools.oadev(dat.values, rate, taus)
     self.adev = cs.CurveDB.create(taus_used,adev,name="Allan deviation")
     self.curve.add_child(self.adev)
def main_use_allantools() :
    f_0 = 3e8 / 730e-9 # the frequency of 730nm light
    timet, fract_data = read_data(r'./Ca_clock_transition_data.xls')
    timet.pop()
    fract_data.pop()

    for i, elem in enumerate(fract_data) :
        fract_data[i] = elem / f_0
    (t2, ad, ade, adn) = allantools.oadev(fract_data, rate=11.2,
            data_type="freq", taus = [i for i in range(1, len(timet) + 1)])
    plt.loglog(t2, ad)
    plt.savefig('ad.png', dpi=400)
Пример #10
0
def plotallan_phase(plt, y, rate, taus, style, label):
    (t2, ad, ade, adn) = allantools.oadev(y,
                                          data_type='phase',
                                          rate=rate,
                                          taus=taus)
    plt.loglog(
        t2,
        ad,
        style,
        fillstyle='none',
        label=label,
    )
Пример #11
0
 def test_oadev_ci(self):
     s32rows = testutils.read_stable32(resultfile='oadev_decade.txt', datarate=1.0)
     for row in s32rows:
         data = testutils.read_datafile(data_file)
         (taus, devs, errs, ns) = allan.oadev(data, rate=rate,
                                               taus=[ row['tau'] ])
         edf = allan.edf_greenhall(alpha=row['alpha'],d=2,m=row['m'],N=len(data),overlapping=True, 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 ) )
Пример #12
0
def oadev(data, taus, scale=1 / 429228004229873, alpha=0):
    """Calculate overlapping Allan deviation with non-naive errors, from frequency data file.

    Args:
        data (array):          array of fractional frequency data file whose first column is a timestamp in (s)
        taus (list of float):       list of tau-values for OADEV computation
        scale (float, optional):    scaling factor for fractional frequency. Defaults to 1/Sr87_BIPM_frequency
        alpha (int, optional):      +2,...,-4   noise type, either estimated or known. Defaults to 0 to match Stable 32

    Returns:
        t2 (list of floats):                            list of tau_values for which deviations were computed
        ad_ff (list of floats):                         list of oadev deviations in fractional frequency units
        err_lo_ff (list of floats):                     list of non-naive lower 1-sigma errors for each point over which
                                                        deviations were computed
        err_hi_ff (list of floats):                     list of non-naive higher 1-sigma errors for each point over
                                                        which deviations were computed
        adn (list):                                     list of number of pairs in overlapping allan computation

    """

    x = data[:, 0]  # Get timestamps
    y = data[:, 1]  # Get fractional frequency data

    avg_interval = (x[-1] - x[0]) / len(
        x)  # average interval between measurements
    r = 1 / avg_interval  # average sample rate in Hz of the input data

    t = np.array(taus) * avg_interval  # tau values on which to evaluate metric
    (t2, ad, ade, adn) = allantools.oadev(
        y, rate=r, data_type="freq",
        taus=t)  # normal ODEV computation, giving naive 1/sqrt(N) errors

    # correct for deadtime ad/np.sqrt(B2*B3)
    # https://nvlpubs.nist.gov/nistpubs/Legacy/SP/nistspecialpublication1065.pdf | 5.15 Dead Time
    # TODO

    # Get correct (Stable32) errors
    err_lo, err_hi = get_better_ade(t2,
                                    ad,
                                    avg_interval,
                                    len(x),
                                    alpha=alpha,
                                    d=2,
                                    overlapping=True,
                                    modified=False)

    ad_ff = ad * scale
    err_lo_ff = err_lo * scale
    err_hi_ff = err_hi * scale

    return t2, ad_ff, err_lo_ff, err_hi_ff, adn
Пример #13
0
def allandeviation(wanted="X", number=0):
    if wanted == "X":
        path_allan = SavingAndReadingData.path + "\X" + str(number) + ".npy"
    if wanted == "Y":
        path_allan = SavingAndReadingData.path + "\Y" + str(number) + ".npy"
    values = np.load(path_allan)
    tau = []
    for i in range(1, (len(values) + 1)):
        tau.append(i)

    tau1 = np.logspace(0, 4, 1000)  # tau values from 1 to 1000

    # values = np.random.randn(10000)
    r = 20  # sampling rate
    (tau2, ad, ade, adn) = allantools.oadev(values,
                                            rate=20,
                                            data_type="freq",
                                            taus=tau1)
    (tau22, ad2, ade2, adn2) = allantools.oadev(values,
                                                rate=1,
                                                data_type="freq",
                                                taus=tau1)

    fig = plt.figure(figsize=(8, 6))
    # fig.subplots_adjust(hspace=0.5, wspace=0.3)
    plt.subplot(1, 2, 1)
    plt.loglog(tau2, ad, 'b')
    plt.plot([10000], [10000])
    plt.xlabel('tau')
    plt.ylabel('ADEV [V]')
    plt.grid()
    plt.subplot(1, 2, 2)
    plt.plot([10000], [10000])
    plt.loglog(tau22, ad2, 'b')
    plt.xlabel('tau')
    plt.ylabel('ADEV [V]')
    plt.grid()
    plt.show()
Пример #14
0
 def test_oadev_ci(self):
     """ Overlapping ADEV with confidence intervals """
     s32rows = testutils.read_stable32(resultfile='oadev_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.oadev(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=True, modified = False, verbose=True)
         (lo, hi) =allan.confidence_interval(devs[0], edf=edf)
         print("n check: ", testutils.check_equal( ns[0], row['n'] ) )
         print("dev check: ", devs[0], row['dev'], testutils.check_approx_equal( devs[0], row['dev'], tolerance=2e-3 ) )
         print("min dev check: ",  lo, row['dev_min'], testutils.check_approx_equal( lo, row['dev_min'], tolerance=2e-3 ) )
         print("max dev check: ", hi, row['dev_max'], testutils.check_approx_equal( hi, row['dev_max'], tolerance=2e-3 ) )
Пример #15
0
    def test_phasedat_oadev(self):
        (s32_taus, s32_devs, s32_devs_lo, s32_devs_hi,
         s32_ns) = read_stable32('phase_dat_oadev_octave.txt', 1.0)
        phase = read_datafile('PHASE.DAT')
        (taus, devs, errs, ns) = allan.oadev(phase, taus=s32_taus)

        # CI computation
        # alhpa= +2,...,-4   noise power
        # d= 1 first-difference variance, 2 allan variance, 3 hadamard variance
        # alpha+2*d >1
        # m = tau/tau0 averaging factor
        # F filter factor, 1 modified variance, m unmodified variance
        # S stride factor, 1 nonoverlapped estimator, m overlapped estimator (estimator stride = tau/S )
        # N number of phase obs
        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=int(t),
                                       N=len(phase),
                                       overlapping=True,
                                       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    chi2    dev_lo      dev         dev_hi
        #   1   999     782.030     821.358 742.689 2.8515e-01  2.9223e-01  2.9987e-01
        #   2   997     540.681     573.374 507.975 1.9520e-01  2.0102e-01  2.0738e-01

        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("----")
Пример #16
0
def oallan_plot(y,
                plotaxis,
                rate,
                taus,
                style,
                marker,
                x_lab,
                yl_lab,
                label,
                title,
                legends=True):
    y, label = ratio_builder_allan(y, plotaxis, label)
    colors = colormap_generator(plotaxis)
    if np.size(y) != 0:
        y_size = np.shape(y)[0]
    else:
        y_size = 0

    plt.figure()
    ax = plt.subplot(111,
                     xscale="log",
                     yscale="log",
                     xlabel=x_lab,
                     ylabel=yl_lab,
                     title=title)
    for i in range(y_size):
        yy = check_mask(y[i])
        col = next(colors)
        (t2, ad, ade, adn) = at.oadev(yy,
                                      rate=rate,
                                      data_type="freq",
                                      taus='all')
        mini = np.argmin(ad[:int(np.size(ad) / 2)])
        allan_minimum = '{:1.1e}'.format(ad[mini])
        time_minimum = '{:1.1e}'.format(t2[mini])
        label[i] = label[i].replace(
            "Amplitude", "") + " [" + allan_minimum + "; " + time_minimum + "]"

        ax.loglog(t2,
                  ad,
                  "g.",
                  c=col,
                  ls=style[i % np.size(style)],
                  marker=marker[i % np.size(marker)],
                  label=label[i])  #label[i])
    if legends == True:
        ax.legend(loc='best')
    plt.show()
Пример #17
0
def plotallan_oadev(plt, y, rate, taus, style):
    (t2, ad, ade, adn) = allantools.oadev(y,
                                          rate=rate,
                                          data_type="freq",
                                          taus=taus)
    plt.loglog(t2, ad, style)
    ad_min_y = round(ad.min(), 4)  #save Allan minimum
    ad_min_x = round(t2[np.argmin(ad)])  #save corresponding averaging time/tau
    string = "Allan Minimum " + str(ad_min_y) + "\nIntegration time " + str(
        ad_min_x)
    plt.text(ad_min_x, ad_min_y + (ad.max() - ad_min_y) / 2, string)
    plt.ylabel('Allan Deviation [per mil]')
    plt.xlabel('Time [sec]')
    ttext = plt.title('Allan Deviation')
    plt.setp(ttext, size='large', color='r', weight='bold')
    return t2, ad, ade, adn
Пример #18
0
 def test_oadev_ci(self):
     s32rows = testutils.read_stable32(resultfile="oadev_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.oadev(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=True, 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: ", devs[0], row["dev"], testutils.check_approx_equal(devs[0], row["dev"], tolerance=2e-3))
         print(
             "min dev check: ", lo, row["dev_min"], testutils.check_approx_equal(lo, row["dev_min"], tolerance=2e-3)
         )
         print(
             "max dev check: ", hi, row["dev_max"], testutils.check_approx_equal(hi, row["dev_max"], tolerance=2e-3)
         )
Пример #19
0
    def test_phasedat_oadev(self):
        s32_rows = testutils.read_stable32('phase_dat_oadev_octave.txt', 1.0)
        phase = testutils.read_datafile('PHASE.DAT')
        (taus, devs, errs,
         ns) = allan.oadev(phase, taus=[s32['tau'] for s32 in s32_rows])

        # CI computation
        # alhpa     +2,...,-4   noise power
        # d         1 first-difference variance, 2 allan variance, 3 hadamard variance
        #           alpha+2*d >1
        # m         tau/tau0 averaging factor
        # F         filter factor, 1 modified variance, m unmodified variance
        # S         stride factor, 1 nonoverlapped estimator, m overlapped estimator (estimator stride = tau/S )
        # N         number of phase observations
        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=int(t),
                                       N=len(phase),
                                       overlapping=True,
                                       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)

        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_max'], hi2, tolerance=1e-3)
            print("----")
Пример #20
0
 def test_oadev_ci_and_noiseID(self):
     """ ADEV with confidence intervals, including noise-ID """
     change_to_test_dir()
     s32rows = testutils.read_stable32(resultfile='stable32_OADEV_octave.txt', datarate=1.0)
     for row in s32rows:
         phase = testutils.read_datafile('gps_1pps_phase_data.txt.gz')
         (taus, devs, errs, ns) = allan.oadev(phase, rate=rate, data_type="phase",
                                              taus=[row['tau']])
         dev = devs[0]
         #print(dev/row['dev'])
         assert np.isclose(dev, row['dev'], rtol=1e-2, atol=0)
         try:
             # CI including noise-ID
             (lo2, hi2) = allan.confidence_interval_noiseID(phase, dev, af=int(row['m']), dev_type="oadev", data_type="phase")
             print(" tau= %f  lo/s32_lo = %f hi/s32_hi = %f "% (row['tau'], lo2/row['dev_min'], hi2/row['dev_max']))
             assert np.isclose(lo2, row['dev_min'], rtol=1e-2, atol=0)
             assert np.isclose(hi2, row['dev_max'], rtol=1e-2, atol=0)
         except NotImplementedError:
             print("can't do CI for tau= %f"%row['tau'])
             pass
Пример #21
0
def plot_allan(samples):
    taus = np.logspace(-3, 3, 100)
    (t2, ad, ade, adn) = allantools.oadev(samples,
                                          rate=100,
                                          data_type='freq',
                                          taus=taus)

    (tau_n, n, line_n) = estimate_random_walk(t2, ad)
    (tau_k, k, line_k) = estimate_rate_random_walk(t2, ad)
    (tau_b, b, line_b) = estimate_bias_instability(t2, ad)

    plt.subplot(111, xscale='log', yscale='log')
    plt.loglog(t2, ad)
    plt.grid(True)

    plt.text(tau_n, n, 'N: ' + str(n))
    plt.plot(t2, line_n)
    plt.text(tau_k, k, 'K: ' + str(k))
    plt.plot(t2, line_k)
    plt.text(tau_b, b, 'B: ' + str(b))
    plt.plot(t2, line_b)
    plt.legend(['sigma', 'sigma_N', 'sigma_K', 'sigma_B'])
Пример #22
0
    def get_arw(self,
                seconds=60,
                autophase=False,
                autohome=True,
                scale_factor=None,
                rate=None):
        """
        Performs a tombstone test of the gyro, but rather than returning a
        :class:`pyfog.tombstone.Tombstone` object, it returns the ARW in units
        of deg/√h. If this is not set, the gyro will run the
        :func:`hardware.gyros.get_scale_factor` routine.

        Args:
            seconds (float): The number of seconds
            minutes (float): The number of minutes
            hours (float): The number of hours
            rate (float): The sample rate
            autophse (bool): If true, the gyro will return to the home position
                before running the tombstone test.
            scale_factor (float): The scale factor to use in order to convert
            between lock-in amplifier voltage and rotation rate in units of
            °/h/Volt. If this is not set, the gyro will run the

        Returns:
            float: The angular random walk in units of °/√h
        """
        if not scale_factor:
            scale_factor = self.get_scale_factor()

        data = daq.read(seconds, rate=rate)
        if not rate:
            # duration isn't defined in this method, even in the original code
            rate = len(data / duration)
        _, dev, _, _ = oadev(data * scale_factor,
                             rate=rate,
                             data_type='freq',
                             taus=[1])
        return dev[0] / 60
Пример #23
0
"""

##########################
#  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)
Пример #24
0
plt.loglog(f_fi[1:],[h0*v0*v0/(ff*ff) for ff in f_fi[1:]],label='h_0 * v0^2 * f^-2'  )
plt.legend(framealpha=0.5)
plt.title('PSD of phase (radians)')
plt.xlabel('Frequeny / Hz')
plt.ylabel('one-sided PSD / S_fi(f)')

plt.figure()
plt.loglog(f_x,psd_x,label='numpy.fft()')
plt.loglog(f_x2,psd_x2,label='scipy.signal.welch()')
plt.loglog(f_x[1:],[h0/(2*math.pi*ff)**2 for ff in f_x[1:]],label='h0/(2*pi*f)**2'  )
plt.legend(framealpha=0.5)
plt.title('PSD of phase (time)')
plt.xlabel('Frequeny / Hz')
plt.ylabel('one-sided PSD / S_x(f)')

plt.figure()
taus=np.logspace(-2.2,4,100)
(taus_y, devs_y, errs_y, ns_y) = allantools.oadev(frequency=y, rate=fs, taus=taus)
(taus_x, devs_x, errs_x, ns_x) = allantools.oadev(phase=x, rate=fs, taus=taus)
plt.loglog(taus_y,devs_y,'o',label='ADEV from y')
plt.loglog(taus_x,devs_x,'*',label='ADEV from x')

adev_y = [math.sqrt( 0.5*h0*(1.0/tt) ) for tt in taus]
plt.loglog(taus,adev_y,label='sqrt( 0.5*h0*tau^-1 )')
plt.xlim((8e-3,1e3))
plt.legend(framealpha=0.6)
plt.title('Allan deviation')
plt.xlabel('Tau / s')
plt.ylabel('Allan deviation')
plt.show()
Пример #25
0
def moving_allan(y, x, length, size, rate, plotaxis, yl_lab, title, label):
    y_new, label = ratio_builder_allan(y, plotaxis, label)

    if np.shape(y_new)[1] != 0:
        y_size = np.shape(y_new)[0]
    else:
        y_size = 0

    k = int((np.shape(y_new)[1] - length) / size) + 1
    x_allan = (length / 2.0 + np.arange(0, k) * size) / rate + x[0]
    minimas = np.zeros((2, y_size, k))
    for i in range(y_size):
        yy = check_mask(y_new[i])
        for j in range(k):
            (t2, ad, ade, adn) = at.oadev(yy[j * size:length + j * size],
                                          rate=rate,
                                          data_type="freq",
                                          taus='all')
            minimas[0][i][j] = (t2[np.argmin(ad[:int(length / 2)])])
            minimas[1][i][j] = (np.min(ad[:int(length / 2)]))
        H, xedges, yedges = (np.histogram2d(minimas[1][i],
                                            minimas[0][i],
                                            bins=10))
        H /= k
        fig = plt.figure()
        ax = fig.add_subplot(111, projection='3d')
        X, Y = np.meshgrid(xedges[:-1] + 0.1 * xedges[0],
                           yedges[:-1] + 0.1 * yedges[0])
        X = X.flatten('F')
        Y = Y.flatten('F')
        H = H.flatten()
        Z = np.zeros_like(X)
        dx = 0.8 * abs(xedges[1] - xedges[0])
        dy = 0.8 * abs(yedges[1] - yedges[0])
        ax.bar3d(X, Y, Z, dx, dy, H, zsort='average')
        ax.set_xlabel('Allan minimum')
        ax.set_ylabel('Integration time (sec)')
        ax.set_zlabel('normalized frequency')
        fig.show()
        plt.figure()
        ax1 = plt.subplot(211)
        ax2 = plt.subplot(212, sharex=ax1)
        ax3 = ax2.twinx()
        x = np.linspace(0, np.size(yy) / rate, num=np.size(yy))
        ax1.plot(x, yy)
        #        ax1.set_xlim
        ax2.set_yscale('log')
        ax2.errorbar(x_allan,
                     minimas[1][0],
                     xerr=length / (2 * rate),
                     c='r',
                     ls='',
                     label='Allan minima')
        #        ax2.set_xlim([min(x),max(x)])
        ax3.plot(x_allan,
                 minimas[0][0],
                 c='b',
                 ls='',
                 marker='o',
                 label="Integration time")
        ax1.set_ylabel(yl_lab)
        ax3.set_ylabel("Time (sec)")
        ax2.set_ylabel("Allan minimum")
        lines2, labels2 = ax2.get_legend_handles_labels()
        lines3, labels3 = ax3.get_legend_handles_labels()
        ax3.legend(lines2 + lines3, labels2 + labels3, loc=4)
        plt.title(title)
        plt.show()
Пример #26
0
def main():

    nr = 2**14  # number of datapoints in time-series
    adev0 = 1.0e-11

    #
    # for each noise type generated with cn.noiseGen()
    # compute
    #   - phase PSD and coefficient g_b
    #   - frequency PSD and coefficient h_a
    #   - ADEV
    #   - MDEV
    #
    tau0 = 0.1  # sample interval for simulated time-series
    sample_rate = 1.0 / tau0

    qd0 = qd1 = qd2 = qd3 = qd4 = pow(adev0,
                                      2)  # discrete variance for noiseGen()
    # This scaling makes all g_i coefficients equal
    # -> PSDs cross at 1 Hz.
    qd1 = qd0 * 2 * np.pi / sample_rate
    qd2 = qd1 * 2 * np.pi / sample_rate
    qd3 = qd2 * 2 * np.pi / sample_rate
    qd4 = qd3 * 2 * np.pi / sample_rate

    print("generating timeseries..."),
    x0 = cn.noiseGen(nr, qd0, 0)  # white phase noise (WPM)
    x1 = cn.noiseGen(nr, qd1, -1)  # flicker phase noise (FPM)
    x2 = cn.noiseGen(nr, qd2, -2)  # white frequency noise (WFM)
    x3 = cn.noiseGen(nr, qd3, -3)  # flicker frequency noise (FFM)
    x4 = cn.noiseGen(nr, qd4, -4)  # random walk frequency noise (RWFM)

    # compute frequency time-series
    y0 = at.phase2frequency(x0, sample_rate)
    y1 = at.phase2frequency(x1, sample_rate)
    y2 = at.phase2frequency(x2, sample_rate)
    y3 = at.phase2frequency(x3, sample_rate)
    y4 = at.phase2frequency(x4, sample_rate)
    print("done.")

    print("computing PSDs..."),
    # compute phase PSD
    (f0, psd0) = at.noise.scipy_psd(x0, f_sample=sample_rate, nr_segments=4)
    (f1, psd1) = at.noise.scipy_psd(x1, f_sample=sample_rate, nr_segments=4)
    (f2, psd2) = at.noise.scipy_psd(x2, f_sample=sample_rate, nr_segments=4)
    (f3, psd3) = at.noise.scipy_psd(x3, f_sample=sample_rate, nr_segments=4)
    (f4, psd4) = at.noise.scipy_psd(x4, f_sample=sample_rate, nr_segments=4)
    # compute phase PSD prefactor g_b
    g0 = cn.phase_psd_from_qd(qd0, 0, tau0)
    g1 = cn.phase_psd_from_qd(qd1, -1, tau0)
    g2 = cn.phase_psd_from_qd(qd2, -2, tau0)
    g3 = cn.phase_psd_from_qd(qd3, -3, tau0)
    g4 = cn.phase_psd_from_qd(qd4, -4, tau0)
    print g0
    print g1
    print g2
    print g3
    print g4

    # compute frequency PSD
    (ff0, fpsd0) = at.noise.scipy_psd(y0, f_sample=sample_rate, nr_segments=4)
    (ff1, fpsd1) = at.noise.scipy_psd(y1, f_sample=sample_rate, nr_segments=4)
    (ff2, fpsd2) = at.noise.scipy_psd(y2, f_sample=sample_rate, nr_segments=4)
    (ff3, fpsd3) = at.noise.scipy_psd(y3, f_sample=sample_rate, nr_segments=4)
    (ff4, fpsd4) = at.noise.scipy_psd(y4, f_sample=sample_rate, nr_segments=4)
    # compute frequency PSD prefactor h_a
    a0 = cn.frequency_psd_from_qd(qd0, 0, tau0)
    a1 = cn.frequency_psd_from_qd(qd1, -1, tau0)
    a2 = cn.frequency_psd_from_qd(qd2, -2, tau0)
    a3 = cn.frequency_psd_from_qd(qd3, -3, tau0)
    a4 = cn.frequency_psd_from_qd(qd4, -4, tau0)
    print "a_i == g_i*(4pi^2)"
    print a0, g0 * pow(2 * np.pi, 2)
    print a1, g1 * pow(2 * np.pi, 2)
    print a2, g2 * pow(2 * np.pi, 2)
    print a3, g3 * pow(2 * np.pi, 2)
    print a4, g4 * pow(2 * np.pi, 2)

    print("done.")

    print("computing ADEV/MDEV..."),
    # compute ADEV
    (t0, d0, e, n) = at.oadev(x0, rate=sample_rate)
    (t1, d1, e, n) = at.oadev(x1, rate=sample_rate)
    (t2, d2, e, n) = at.oadev(x2, rate=sample_rate)
    (t3, d3, e, n) = at.oadev(x3, rate=sample_rate)
    (t4, d4, e, n) = at.oadev(x4, rate=sample_rate)

    # compute MDEV
    (mt0, md0, e, n) = at.mdev(x0, rate=sample_rate)
    (mt1, md1, e, n) = at.mdev(x1, rate=sample_rate)
    (mt2, md2, e, n) = at.mdev(x2, rate=sample_rate)
    (mt3, md3, e, n) = at.mdev(x3, rate=sample_rate)
    (mt4, md4, e, n) = at.mdev(x4, rate=sample_rate)
    print("done.")

    plt.figure()
    # Phase PSD figure
    plt.subplot(2, 2, 1)
    plt.loglog(f0, [g0 * pow(xx, 0.0) for xx in f0],
               '--',
               label=r'$g_0f^0 = {h_2\over4\pi^2}f^0$',
               color='black')
    plt.loglog(f0, psd0, '.', color='black')

    plt.loglog(f1[1:], [g1 * pow(xx, -1.0) for xx in f1[1:]],
               '--',
               label=r'$g_{-1}f^{-1}  = {h_1\over4\pi^2}f^{-1} $',
               color='red')
    plt.loglog(f1, psd1, '.', color='red')

    plt.loglog(f2[1:], [g2 * pow(xx, -2.0) for xx in f2[1:]],
               '--',
               label=r'$g_{-2}f^{-2}   = {h_0\over4\pi^2}f^{-2} $',
               color='green')
    plt.loglog(f2, psd2, '.', color='green')

    plt.loglog(f3[1:], [g3 * pow(xx, -3.0) for xx in f3[1:]],
               '--',
               label=r'$g_{-3}f^{-3}   = {h_{-1}\over4\pi^2}f^{-3} $',
               color='pink')
    plt.loglog(f3, psd3, '.', color='pink')

    plt.loglog(f4[1:], [g4 * pow(xx, -4.0) for xx in f4[1:]],
               '--',
               label=r'$g_{-4}f^{-4}   = {h_{-2}\over4\pi^2}f^{-4}$',
               color='blue')
    plt.loglog(f4, psd4, '.', color='blue')
    plt.grid()
    plt.legend(framealpha=0.9, fontsize=22)
    plt.title(r'Phase Power Spectral Density')
    plt.xlabel(r'Frequency (Hz)')
    plt.ylabel(r' $S_x(f)$ $(s^2/Hz)$')

    # frequency PSD figure
    plt.subplot(2, 2, 2)
    plt.loglog(ff0[1:], [a0 * pow(xx, 2) for xx in ff0[1:]],
               '--',
               label=r'$h_{2}f^{2}$',
               color='black')
    plt.loglog(ff0, fpsd0, '.', color='black')

    plt.loglog(ff1[1:], [a1 * pow(xx, 1) for xx in ff1[1:]],
               '--',
               label=r'$h_{1}f^{1}$',
               color='red')
    plt.loglog(ff1, fpsd1, '.', color='red')

    plt.loglog(ff2[1:], [a2 * pow(xx, 0) for xx in ff2[1:]],
               '--',
               label=r'$h_{0}f^{0}$',
               color='green')
    plt.loglog(ff2, fpsd2, '.', color='green')

    plt.loglog(ff3[1:], [a3 * pow(xx, -1) for xx in ff3[1:]],
               '--',
               label=r'$h_{-1}f^{-1}$',
               color='pink')
    plt.loglog(ff3, fpsd3, '.', color='pink')

    plt.loglog(ff4[1:], [a4 * pow(xx, -2) for xx in ff4[1:]],
               '--',
               label=r'$h_{-2}f^{-2}$',
               color='blue')
    plt.loglog(ff4, fpsd4, '.', color='blue')
    plt.grid()
    plt.legend(framealpha=0.9, fontsize=22)
    plt.title(r'Frequency Power Spectral Density')
    plt.xlabel(r'Frequency (Hz)')
    plt.ylabel(r' $S_y(f)$ $(1/Hz)$')

    # ADEV figure
    plt.subplot(2, 2, 3)
    f_h = 0.5 / tau0
    K0 = 3.0 * f_h / (4.0 * pow(np.pi, 2))
    plt.loglog(t0, [np.sqrt(K0 * a0) / xx for xx in t0],
               '--',
               label=r'$\sqrt{3f_H\over4\pi^2} \sqrt{h_{2}}\tau^{-3/2}$',
               color='black')
    plt.loglog(t0, d0, 'o', color='black')

    # IEEE 1139-2008, table B.2
    def K1(f_H, tau):
        gamma = 1.038 / 2
        return ((3.0 / 2.0) * np.log(2.0 * np.pi * f_h * tau) +
                gamma) / (2.0 * pow(np.pi, 2))

    plt.loglog(
        t1, [np.sqrt(K1(f_h, xx) * a1) / xx for xx in t1],
        '--',
        label=
        r'$\sqrt{ 3\ln{(2 \pi f_H \tau)} + \gamma \over 4\pi^2 }\sqrt{h_{1}}\tau^{-1}$',
        color='red')
    plt.loglog(t1, d1, 'o', color='red')

    K2 = 0.5
    plt.loglog(t2, [np.sqrt(K2 * a2) / math.sqrt(xx) for xx in t2],
               '--',
               label=r'$\sqrt{1\over2} \sqrt{h_{0}}\tau^{-1/2}$',
               color='green')
    plt.loglog(t2, d2, 'o', color='green')

    K3 = 2 * np.log(2)
    plt.loglog(t3, [np.sqrt(K3 * a3) for xx in t3],
               '--',
               label=r'$ \sqrt{2\ln{2}}\sqrt{h_{-1}}\tau^0$',
               color='pink')
    plt.loglog(t3, d3, 'o', color='pink')

    K4 = (2 * np.pi**2.0) / 3.0
    plt.loglog(t4, [np.sqrt(K4 * a4) * math.sqrt(xx) for xx in t4],
               '--',
               label=r'$\sqrt{2\pi^2\over3}\sqrt{h_{-2}}\tau^{+1/2}$',
               color='blue')
    plt.loglog(t4, d4, 'o', color='blue')

    plt.legend(framealpha=0.9, loc='lower left', fontsize=22)
    plt.grid()
    plt.title(r'Allan Deviation')
    plt.xlabel(r'$\tau$ (s)')
    plt.ylabel(r'ADEV')

    # MDEV
    plt.subplot(2, 2, 4)
    M0 = 3.0 / (8.0 * pow(np.pi, 2))
    plt.loglog(t0, [np.sqrt(M0 * a0) / pow(xx, 3.0 / 2.0) for xx in t0],
               '--',
               label=r'$\sqrt{ 3\over 8\pi^2 } \sqrt{h_{2}}\tau^{-3/2}$',
               color='black')
    plt.loglog(mt0, md0, 'o', color='black')

    M1 = (24.0 * np.log(2) - 9.0 * np.log(3)) / (8.0 * pow(np.pi, 2))

    plt.loglog(
        t1, [np.sqrt(M1 * a1) / xx for xx in t1],
        '--',
        label=r'$\sqrt{ 24\ln(2)-9\ln(3) \over 8\pi^2 } \sqrt{h_{1}}\tau^{-1}$',
        color='red')
    plt.loglog(mt1, md1, 'o', color='red')

    M2 = 0.25
    plt.loglog(t2, [np.sqrt(M2 * a2) / math.sqrt(xx) for xx in t2],
               '--',
               label=r'$ \sqrt{1\over4}\sqrt{h_{0}}\tau^{-1/2}$',
               color='green')
    plt.loglog(mt2, md2, 'o', color='green')

    M3 = 27.0 / 20.0 * np.log(2)
    plt.loglog(t3, [np.sqrt(M3 * a3) for xx in t3],
               '--',
               label=r'$\sqrt{ {27\over20}\ln(2) } \sqrt{h_{-1}}\tau^0$',
               color='pink')
    plt.loglog(mt3, md3, 'o', color='pink')

    M4 = 11.0 / 20.0 * pow(np.pi, 2)
    plt.loglog(t4, [np.sqrt(M4 * a4) * math.sqrt(xx) for xx in t4],
               '--',
               label=r'$ \sqrt{ {11\over20}\pi^2  } \sqrt{h_{-2}}\tau^{+1/2}$',
               color='blue')
    plt.loglog(mt4, md4, 'o', color='blue')

    plt.legend(framealpha=0.9, loc='lower left', fontsize=22)
    plt.grid()
    plt.title(r'Modified Allan Deviation')
    plt.xlabel(r'$\tau$ (s)')
    plt.ylabel(r'MDEV')
    plt.show()
Пример #27
0
##########################
#  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)
Пример #28
0
# S_x
plt.figure()
plt.loglog(f_x, psd_x, label='numpy.fft()')
plt.loglog(f_x2, psd_x2, label='scipy.signal.welch()')
plt.loglog(f_x, [h2 / (2 * math.pi)**2] * len(f_x), label='h2/(4*pi^2)')
plt.legend(framealpha=0.5)
plt.title('PSD of phase (time)')
plt.xlabel('Frequeny / Hz')
plt.ylabel('one-sided PSD / S_x(f)')
plt.grid()

# ADEV figure
plt.figure()
taus = [tt for tt in np.logspace(-7, 4, 100)]
(taus_y, devs_y, errs_y, ns_y) = allantools.oadev(y,
                                                  data_type='freq',
                                                  rate=fs,
                                                  taus=taus)
(taus_x, devs_x, errs_x, ns_x) = allantools.oadev(x,
                                                  data_type='phase',
                                                  rate=fs,
                                                  taus=taus)
plt.loglog(taus_y, devs_y, 'o', label='ADEV from y')
plt.loglog(taus_x, devs_x, '*', label='ADEV from x')

print(devs_y)
print(devs_x)
fh = 0.5 * fs  # this restricts the noise power to below fh
adev_y = [
    math.sqrt(3 * fh / (4 * math.pi**2) * h2 * (1.0 / tt**2)) for tt in taus
]
plt.loglog(taus, adev_y, label='sqrt( 3*fh/(4*pi^2) * h2*tau^-2 )')
Пример #29
0
mpu_sample_rate = len(data_mpu) / last_mpu_timestamp
adis_sample_rate = len(data_adis) / last_adis_timestamp

print("Last MPU Timestamp: " + str(last_mpu_timestamp))
print("Last ADIS Timestamp: " + str(last_adis_timestamp))

print("MPU Sample Rate: " + str(mpu_sample_rate))
print("ADIS Sample Rate: " + str(adis_sample_rate))

taus = [tt for tt in np.logspace(-1, 4, 100)]

if (allan):

    if sensor == 'gyro':
        (taus, devs_x, _, _) = allantools.oadev(data_adis[:, 0],
                                                rate=adis_sample_rate,
                                                data_type='freq',
                                                taus=taus)
        (taus, devs_y, _, _) = allantools.oadev(data_adis[:, 1],
                                                rate=adis_sample_rate,
                                                data_type='freq',
                                                taus=taus)
        (taus, devs_z, _, _) = allantools.oadev(data_adis[:, 2],
                                                rate=adis_sample_rate,
                                                data_type='freq',
                                                taus=taus)

        plt.loglog(taus, devs_x, label='ADIS Gyro X')
        plt.loglog(taus, devs_y, label='ADIS Gyro Y')
        plt.loglog(taus, devs_z, label='ADIS Gyro Z')

        for (t, x, y, z) in zip(taus, devs_x, devs_y, devs_z):
Пример #30
0
def allandeviation(density='low', wanted="X", number=0, save='yes'):
    if density == 'low':
        if wanted == "X":
            path_allan = r"C:\Users\Lenovo\Desktop\Internship\Data\LessDense" + "\X" + str(
                number) + ".npy"
            save_path = r"C:\Users\Lenovo\Desktop\Internship\Data\LessDense" + "\Xallan" + str(
                number)
        if wanted == "Y":
            path_allan = r"C:\Users\Lenovo\Desktop\Internship\Data\LessDense" + "\Y" + str(
                number) + ".npy"
            save_path = r"C:\Users\Lenovo\Desktop\Internship\Data\LessDense" + "\Yallan" + str(
                number)
    if density == 'high':
        if wanted == "X":
            path_allan = r"C:\Users\Lenovo\Desktop\Internship\Data\MoreDense" + "\X" + str(
                number) + ".npy"
            save_path = r"C:\Users\Lenovo\Desktop\Internship\Data\MoreDense" + "\Xallan" + str(
                number)
        if wanted == "Y":
            path_allan = r"C:\Users\Lenovo\Desktop\Internship\Data\MoreDense" + "\Y" + str(
                number) + ".npy"
            save_path = r"C:\Users\Lenovo\Desktop\Internship\Data\MoreDense" + "\Yallan" + str(
                number)
    if density == 'random':
        wanted = "Random"
        save_path = r"C:\Users\Lenovo\Desktop\Internship\Data\allanRandom" + str(
            number)

    values = np.load(path_allan)
    # tau = []
    # for i in range(1,(len(values)+1)):
    #     tau.append(i)

    tau1 = np.logspace(0, 4, 1000)  # tau values from 1 to 10000

    # values = np.random.randn(10000)

    rate = [0.01, 1, 10, 20, 30, 40, 50, 60, 70, 80, 90, 100]

    fig = plt.figure(figsize=(12, 6))  #width , height
    # Global title
    fig.suptitle("Allan Deviation for " + wanted + " for different rates")
    for i, r in enumerate(rate):
        (tau2, ad, ade, adn) = allantools.oadev(values,
                                                rate=r,
                                                data_type="freq",
                                                taus=tau1)
        fig.subplots_adjust(hspace=0.8, wspace=0.8)  #height , width
        plt.subplot(3, 4, i + 1)
        plt.loglog(tau2, ad, 'b')
        plt.title("Rate " + str(r))
        plt.xlabel('tau')
        plt.ylabel('ADEV [V]')
        plt.grid()

        # Calculating the characteristics
        characteristics_calculation(tau2, ad, ade, adn, r)
    plt.show()

    if save == 'yes':
        plot_path = save_path + ".png"
        fig.savefig(plot_path)
Пример #31
0
plt.loglog(f_fi[1:], [h0 * v0 * v0 / (ff * ff) for ff in f_fi[1:]], label="h_0 * v0^2 * f^-2")
plt.legend(framealpha=0.5)
plt.title("PSD of phase (radians)")
plt.xlabel("Frequeny / Hz")
plt.ylabel("one-sided PSD / S_fi(f)")

plt.figure()
plt.loglog(f_x, psd_x, label="numpy.fft()")
plt.loglog(f_x2, psd_x2, label="scipy.signal.welch()")
plt.loglog(f_x[1:], [h0 / (2 * math.pi * ff) ** 2 for ff in f_x[1:]], label="h0/(2*pi*f)**2")
plt.legend(framealpha=0.5)
plt.title("PSD of phase (time)")
plt.xlabel("Frequeny / Hz")
plt.ylabel("one-sided PSD / S_x(f)")

plt.figure()
taus = [tt for tt in np.logspace(-2.2, 4, 100)]
(taus_y, devs_y, errs_y, ns_y) = allantools.oadev(y, data_type="freq", rate=fs, taus=taus)
(taus_x, devs_x, errs_x, ns_x) = allantools.oadev(x, data_type="phase", rate=fs, taus=taus)
plt.loglog(taus_y, devs_y, "o", label="ADEV from y")
plt.loglog(taus_x, devs_x, "*", label="ADEV from x")

adev_y = [math.sqrt(0.5 * h0 * (1.0 / tt)) for tt in taus]
plt.loglog(taus, adev_y, label="sqrt( 0.5*h0*tau^-1 )")
plt.xlim((8e-3, 1e3))
plt.legend(framealpha=0.6)
plt.title("Allan deviation")
plt.xlabel("Tau / s")
plt.ylabel("Allan deviation")
plt.show()
Пример #32
0
    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)

plt.subplot(111, xscale="log", yscale="log") 
Пример #33
0
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"
Пример #34
0
def to_fractional(flist, f0):
    out = []
    for f in flist:
        out.append(f/float(f0) - 1.0)
    return out


fname = "ocxo_frequency.txt"
f10MHz = read_datafile(fname, column=0)

f = to_fractional(f10MHz, 10e6)  # convert to fractional frequency
# log-spaced tau values from 10s and upwards
my_taus = numpy.logspace(1, 5, 40)
rate = 1/float(10)  # data collected with 10s gate time

(oadev_taus, oadev_devs, oadev_errs, ns) = allan.oadev(
    f, data_type='freq', rate=rate, taus=my_taus)
(mdev_taus, mdev_devs, mdev_errs, ns) = allan.mdev(
    f, data_type='freq', rate=rate, taus=my_taus)
(hdev_taus, hdev_devs, hdev_errs, ns) = allan.hdev(
    f, data_type='freq', rate=rate, taus=my_taus)
(ohdev_taus, ohdev_devs, ohdev_errs, ns) = allan.ohdev(
    f, data_type='freq', rate=rate, taus=my_taus)

plt.subplot(111, xscale="log", yscale="log")

plt.errorbar(oadev_taus, oadev_devs, yerr=oadev_errs, label='OADEV')
plt.errorbar(mdev_taus, mdev_devs, yerr=mdev_errs, label='MDEV')
plt.errorbar(hdev_taus, hdev_devs, yerr=hdev_errs, label='HDEV')
plt.errorbar(ohdev_taus, ohdev_devs, yerr=ohdev_errs, label='OHDEV')

plt.xlabel('Taus (s)')
Пример #35
0
 def adev(self):
     tau, dev, _, _ = oadev(self.rotation, rate=self.rate, data_type='freq')
     return tau, dev
Пример #36
0
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()
Пример #37
0
 def drift(self):
     tau, dev, _, _ = oadev(self.rotation, rate=self.rate, data_type='freq')
     return min(dev)
Пример #38
0
def vank(objname, weightthresh=10.0,chithresh=0.0, sigmaithresh=0.0):

    c = 299792458.0

    if socket.gethostname() == 'Main':
        filenames = glob.glob('/Data/kiwispec-proc/n20160[5,6]*/*' + objname + '*.chrec' + exten + '.npy')
    else:
        filenames = glob.glob('/n/home12/jeastman/minerva/data/n2016051[4-9]/*' + objname + '*.chrec' + exten + '.npy') +\
            glob.glob('/n/home12/jeastman/minerva/data/n201605[2-3]?/*' + objname + '*.chrec' + exten + '.npy') +\
            glob.glob('/n/home12/jeastman/minerva/data/n2016060?/*' + objname + '*.chrec' + exten + '.npy') +\
            glob.glob('/n/home12/jeastman/minerva/data/n2016061[0-2]/*' + objname + '*.chrec' + exten + '.npy')

    ntel = 4
    nobs = len(filenames)*ntel
    if nobs <= 3: return

    vji = []
    wji = []
    chiji = []
    ctsji = []
    alphaji = []
    ipsigmaji = []
    slopeji = []
    jdutcs = np.array([])
    telescope = np.array([])

    for filename in filenames:

        st = os.stat(filename)
#        if (st.st_size != 121120): continue
        if (st.st_size == 0.0): 
            nobs -= 4
            continue
 
        chrec = np.load(filename)
        fitsname = os.path.splitext(os.path.splitext(filename)[0])[0] + '.fits'
        h = pyfits.open(fitsname,mode='update')
        
#        # reject chunks with bad DSST (Step 1)
#        bad = np.where(chrec['wt' + str(i)] == 0)
#        chrec['z' + str(i)][bad] = np.nan

        # reject chunks where fitter failed to converge (rchi2 == 0 or 100)
        # (Step 2)
        for i in range(1,ntel+1):

            if h[0].header['FLUXMID' + str(i)] == 'UNKNOWN':
                t = Time(h[0].header['DATE-OBS'], format='isot',scale='utc')
                midflux = t.jd+h[0].header['EXPTIME']/2.0/86400.0
                h[0].header['FLUXMID' + str(i)] = midflux
            else:
                midflux = h[0].header['FLUXMID' + str(i)]

            # very noisy data can find great fits
            bad = np.where(chrec['chi' + str(i)] <= 0.3)
            chrec['z' + str(i)][bad] = np.nan

            # bad fits will have bad chi^2
            bad = np.where(chrec['chi' + str(i)] >= 5)
            chrec['z' + str(i)][bad] = np.nan

            # very noisy data can find great fits
            bad = np.where((chrec['alpha' + str(i)] <= -0.95) | (chrec['alpha' + str(i)] >= 0.95))
            chrec['z' + str(i)][bad] = np.nan

            # very noisy data can find great fits
            bad = np.where((chrec['sigma' + str(i)] <= 0.25) | (chrec['sigma' + str(i)] >= 1.25))
            chrec['z' + str(i)][bad] = np.nan

            # reject chunks with the lowest DSST weight (Step 3) or bad weights (Step 1)
            lowweight = np.nanpercentile(chrec['wt' + str(i)],weightthresh)
            bad = np.where((chrec['wt' + str(i)] <= lowweight) | (chrec['wt' + str(i)] == 0))
            chrec['z' + str(i)][bad] = np.nan

            if 'BARYCOR' + str(i) not in h[0].header.keys():
                # do the barycentric correction
                ra = h[0].header['TARGRA' + str(i)]
                dec = h[0].header['TARGDEC' + str(i)]
                try: pmra = h[0].header['PMRA' + str(i)]
                except: pmra = 0.0
                try: pmdec = h[0].header['PMDEC' + str(i)]
                except: pmdec = 0.0
                try: parallax = h[0].header['PARLAX' + str(i)]
                except: parallax = 0.0
                try: rv = h[0].header['RV' + str(i)]
                except: rv = 0.0
            
                result = utils.barycorr(midflux, ra, dec, pmra=pmra, pmdec=pmdec, parallax=parallax, rv=rv, zmeas=0.0)
                zb = result/c
                h[0].header['BARYCOR' + str(i)] = zb
            elif h[0].header['BARYCOR' + str(i)] == 'UNKNOWN':
                # do the barycentric correction
                ra = h[0].header['TARGRA' + str(i)]
                dec = h[0].header['TARGDEC' + str(i)]
                try: pmra = h[0].header['PMRA' + str(i)]
                except: pmra = 0.0
                try: pmdec = h[0].header['PMDEC' + str(i)]
                except: pmdec = 0.0
                try: parallax = h[0].header['PARLAX' + str(i)]
                except: parallax = 0.0
                try: rv = h[0].header['RV' + str(i)]
                except: rv = 0.0
            
                result = utils.barycorr(midflux, ra, dec, pmra=pmra, pmdec=pmdec, parallax=parallax, rv=rv, zmeas=0.0)
                zb = result/c
                h[0].header['BARYCOR' + str(i)] = zb
            else:
                zb = h[0].header['BARYCOR' + str(i)]

#            active = np.append(active ,h[0].header['FAUSTAT' + str(i)] == 'GUIDING')
            if h[0].header['FAUSTAT' + str(i)] == 'GUIDING' or 'daytimeSky' in h[0].header['OBJECT' + str(i)]:

                rvs = c*((1.0+chrec['z' + str(i)])*(1.0+zb)-1.0)

                # if all chunks are bad, skip it
                if len(np.where(np.isnan(rvs))[0]) == len(rvs): 
                    nobs-=1
                    continue

                jdutcs = np.append(jdutcs,midflux)
                telescope = np.append(telescope,i)

                if len(vji) == 0: vji = rvs
                else: vji = np.vstack((vji,rvs))

                if len(wji) == 0: wji = chrec['wt' + str(i)]
                else: wji = np.vstack((wji,chrec['wt' + str(i)]))
            
                if len(chiji) == 0: chiji = chrec['chi' + str(i)]
                else: chiji = np.vstack((chiji,chrec['chi' + str(i)]))

                if len(ctsji) == 0: ctsji = chrec['cts' + str(i)]
                else: ctsji = np.vstack((ctsji,chrec['cts' + str(i)]))

                if len(alphaji) == 0: alphaji = chrec['alpha' + str(i)]
                else: alphaji = np.vstack((alphaji,chrec['alpha' + str(i)]))

                if len(ipsigmaji) == 0: ipsigmaji = chrec['sigma' + str(i)]
                else: ipsigmaji = np.vstack((ipsigmaji,chrec['sigma' + str(i)]))

                if len(slopeji) == 0: slopeji = chrec['slope' + str(i)]
                else: slopeji = np.vstack((slopeji,chrec['slope' + str(i)]))
            else: nobs-=1

        h.flush()
        h.close()

    nchunks = len(chrec)
    vij = np.transpose(vji)
    wij = np.transpose(wji)
    chiij = np.transpose(chiji)
    ctsij = np.transpose(ctsji)
    alphaij = np.transpose(alphaji)
    ipsigmaij = np.transpose(ipsigmaji)
    slopeij = np.transpose(slopeji)
    
    snr = np.sqrt(np.nansum(ctsij,axis=0))

    # reject chunks with the worst fits (step 4)
    chimed = np.nanmedian(chiij,axis=1)
    hichi = np.nanpercentile(chimed,100.0-chithresh)
    bad = np.where(chimed >= hichi)
    vij[bad,:] = np.nan  

    # adjust all chunks to have the same RV zero points (step 5)
    # subtract the mean velocity of all observations from each chunk
    vij -= np.transpose(np.tile(np.nanmean(vij,axis=1),(nobs,1)))

    # compute chunk weights (step 6):
    # median velocities for each observation
    vjmed = np.nanmedian(vij,axis=0) # eq 2.9

    # compute the matrix of velocity differences 
    Deltaij = vij - np.tile(vjmed,(nchunks,1)) # eq 2.8
    sigmai = np.nanstd(Deltaij,axis=1) # eq 2.6

    # reject the highest sigmai (step 7)
    bad = np.where(sigmai == 0.0)
    sigmai[bad] = np.inf
    hisigma = np.nanpercentile(sigmai,100.0-sigmaithresh)
    bad = np.where(sigmai >= hisigma)
    sigmai[bad] = np.inf

    # compute rj (eq 2.7)
    rj = np.nanmedian(np.abs(Deltaij)*np.transpose(np.tile(sigmai,(nobs,1))),axis=0) # eq 2.7
    sigmaij = np.transpose(np.tile(sigmai,(nobs,1)))*np.tile(rj,(nchunks,1)) # eq 2.5

    # prevent nans
    bad = np.where(sigmaij == 0.0)
    sigmaij[bad] = np.inf

    wij = 1.0/sigmaij**2

    vj = np.nansum(vij*wij,axis=0)/np.nansum(wij,axis=0) # eq 2.10
    sigmavj = 1.0/np.sqrt(np.nansum(wij,axis=0)) # eq 2.12
    
    print objname + " RMS: " + str(np.nanstd(vj))
    
    # plot scatter vs time
    colors = ['','r','g','b','orange']
    for i in range(1,ntel+1):
        match = np.where(telescope == i)
        plt.plot(jdutcs[match]-2457389,vj[match],'o',color=colors[i])

    plt.title(objname)
    plt.xlabel('Days since UT 2016-01-01')
    plt.ylabel('RV (m/s)')
    plt.savefig(objname + '.' + exten + '.png')
    plt.close()
    
    nightlyrvs = {'all':np.array([]),
                  'T1':np.array([]),
                  'T2':np.array([]),
                  'T3':np.array([]),
                  'T4':np.array([])}

    # bin per telescope per night
    for jd in range(2457480,2457571):
        for i in range(1,ntel+1):
            match = np.where((jdutcs >= jd) & (jdutcs < (jd+1)) & np.isfinite(vj) & (telescope==i))
            night = np.mean(jdutcs[match])-2457389
            nightlyrv = np.sum(vj[match]/sigmavj[match]**2)/np.sum(1.0/sigmavj[match]**2)
            plt.plot([night],[nightlyrv],'o',color=colors[i])
            nightlyrvs['T' + str(i)] = np.append(nightlyrvs['T' + str(i)],nightlyrv)
            
        match = np.where((jdutcs >= jd) & (jdutcs < (jd+1)) & np.isfinite(vj))
        night = np.mean(jdutcs[match])-2457389
        nightlyrv = np.sum(vj[match]/sigmavj[match]**2)/np.sum(1.0/sigmavj[match]**2)
        plt.plot([night],[nightlyrv],'ko')
        nightlyrvs['all'] = np.append(nightlyrvs['all'],nightlyrv)

    plt.title(objname)
    plt.xlabel('Days since UT 2016-01-01')
    plt.ylabel('Nightly binned RV (m/s)')
    plt.savefig(objname + '.' + exten + '.binned.png')
    plt.close()
    print objname + ' nightly binned RMS:'
    print "All: " + str(np.nanstd(nightlyrvs['all']))
    print "T1: " + str(np.nanstd(nightlyrvs['T1']))
    print "T2: " + str(np.nanstd(nightlyrvs['T2']))
    print "T3: " + str(np.nanstd(nightlyrvs['T3']))
    print "T4: " + str(np.nanstd(nightlyrvs['T4']))
        
    # create a histogram of scatter within a night
    mindate = int(math.floor(min(jdutcs)))
    maxdate = int(math.ceil(max(jdutcs)))

    jdbin = []
    rvbin = []
    errbin = []
    sigmabin = []
    for i in range(mindate,maxdate):
        match = np.where((jdutcs >= i) & (jdutcs < (i+1)) & (np.isfinite(vj)))
        if len(match[0]) > 1:
            jdbin.append(mindate)
            rvbin.append(np.mean(vj[match]))
            errbin.append(np.std(vj[match]))
            sigmabin.append(np.mean(sigmavj[match]))

#    print jdbin, rvbin, errbin, sigmabin
    hist, bins = np.histogram(errbin, bins=20)
    width = 0.7 * (bins[1] - bins[0])
    center = (bins[:-1] + bins[1:]) / 2
    
    plt.bar(center, hist, align='center', width=width)
    plt.xlabel('Intranight RMS (m/s)')
    plt.ylabel('# of Nights')
    plt.savefig(objname + '.' + exten + '.hist.png')
    plt.close()


    # plot median sigma as a function of chunk number
    for tel in range(1,ntel+1):
        match = np.where(telescope == tel)
        for chunk in range(np.shape(ipsigmaij)[0]):
            plt.plot(chunk,np.nanmedian(ipsigmaij[chunk,match]),'o',color=colors[tel])
            sigmawav.append()
            sigmaall.append(np.nanmedian(ipsigmaij[chunk,match]))
            sigmatel.append(tel)
            
    plt.title(objname)
    plt.xlabel('Chunk number')
    plt.ylabel('sigma')
    plt.savefig(objname + '.' + exten + '.sigmavchunk.png')
    plt.close()

    # plot median alpha as a function of chunk number
    for tel in range(1,ntel+1):
        match = np.where(telescope == tel)
        for chunk in range(np.shape(alphaij)[0]):
                         plt.plot(chunk,np.nanmedian(alphaij[chunk,match]),'o',color=colors[tel])
    plt.title(objname)
    plt.xlabel('Chunk number')
    plt.ylabel('alpha')
    plt.savefig(objname + '.' + exten + '.alphavchunk.png')
    plt.close()

    # plot median slope as a function of chunk number
    for tel in range(1,ntel+1):
        match = np.where(telescope == tel)
        for chunk in range(np.shape(slopeij)[0]):
            plt.plot(chunk,np.nanmedian(slopeij[chunk,match]),'o',color=colors[tel])
    plt.title(objname)
    plt.xlabel('Chunk number')
    plt.ylabel('slope')
    plt.savefig(objname + '.' + exten + '.slopevchunk.png')
    plt.close()


    # plot sigma for chunk 150 over time
    chunk = 150
    for t in jdutcs:
        for tel in range(1,ntel+1):
            match = np.where((telescope == tel) & (jdutcs == t))
            plt.plot(t-2457389,np.nanmedian(ipsigmaij[chunk,match]),'o',color=colors[tel])
    plt.title(objname)
    plt.xlabel('Days since UT 2016-01-01')
    plt.ylabel('sigma')
    plt.savefig(objname + '.' + exten + '.sigma150vtime.png')
    plt.close()



    # plot scatter within a night vs SNR
    plt.plot(sigmabin, errbin,'bo')
    plt.title(objname)
    plt.xlabel('Sigma_v_j')
    plt.ylabel('Intranight RMS (m/s)')
    plt.savefig(objname + '.' + exten + '.SNR.png')
    plt.close()

    # subtract a linear trend from vj
    good = np.where(np.isfinite(vj))
    t0 = np.nanmedian(jdutcs[good])
    coeffs = np.polyfit(jdutcs[good]-t0,vj[good],1)
    vjtrend = coeffs[1] + (jdutcs[good]-t0)*coeffs[0] 

    # output text files of JD, rv, rverr
    f = open(objname + '.dat','w')
    for i in range(len(vj)):
        if np.isfinite(vj[i]):
            f.write('{0:f} {1:f} {2:f} T{3:d} {4:s}'.format(jdutcs[i],vj[i],sigmavj[i],int(telescope[i]),'\n'))
    f.close()

    # plot scatter minus trend vs time
    plt.plot(jdutcs[good]-2457389,vj[good]-vjtrend,'bo')
    plt.title(objname)
    plt.xlabel('Days since UT 2016-01-01')
    plt.ylabel('RV (m/s)')
    plt.savefig(objname + '.' + exten + '.detrended.png')
    plt.close()
    print objname + " Detrended RMS: " + str(np.nanstd(vj[good]-vjtrend))

    for i in range(1,ntel+1):
        match = np.where((telescope == i) & np.isfinite(vj))
#        rate = 1.0/(jdutcs[match]-np.roll(jdutcs[match],1))
#        taus = np.logspace(0, 3, 50)
        taus = np.arange(1,len(vj[match])/3)
        (t2, ad, ade, adn) = allantools.oadev(vj[match], rate=1, data_type="freq", taus=taus)
        plt.loglog(t2,ad,'o',color=colors[i])

        # overplot the line
        y = np.asarray([pow(tt,-0.5) for tt in taus])*ad[0]
        plt.loglog(taus,y,'-',color=colors[i])
        

    match = np.where(np.isfinite(vj))
    taus = np.arange(1,len(vj[match])/3)
    (t2, ad, ade, adn) = allantools.oadev(vj[match], rate=1, data_type="freq", taus=taus)
    plt.loglog(t2,ad,'ko')
    # overplot the line
    y = np.asarray([pow(tt,-0.5) for tt in taus])*ad[0]
    plt.loglog(taus,y,'k-')

    plt.xlabel('N bin')
    plt.ylabel('Precision (m/s)')
        

    plt.savefig(objname + '.' + exten + '.allan.png')
    plt.close()
Пример #39
0
def main():

    nr = 2**14 # number of datapoints in time-series
    tau0=1.0 # sampling interval, sets nyquist frequency to 0.5/tau0
    adev0 = 1.0e-11
    
    #
    # for each noise type generated with cn.noiseGen()
    # compute 
    #   - phase PSD and coefficient g_b
    #   - frequency PSD and coefficient h_a
    #   - ADEV
    #   - MDEV
    #
    qd0 = qd1 = qd2 = qd3 = qd4 = pow(adev0, 2) # discrete variance for noiseGen()
    tau0 = 1.0 # sample interval
    sample_rate = 1/tau0
    
    x0 = cn.noiseGen(nr, qd0, 0)   # white phase noise (WPM)
    x1 = cn.noiseGen(nr, qd1, -1)  # flicker phase noise (FPM)
    x2 = cn.noiseGen(nr, qd2, -2)  # white frequency noise (WFM)
    x3 = cn.noiseGen(nr, qd3 , -3) # flicker frequency noise (FFM)
    x4 = cn.noiseGen(nr, qd4 , -4) # random walk frequency noise (RWFM)
    
    # compute frequency time-series
    y0 = at.phase2frequency(x0, sample_rate)
    y1 = at.phase2frequency(x1, sample_rate)
    y2 = at.phase2frequency(x2, sample_rate)
    y3 = at.phase2frequency(x3, sample_rate)
    y4 = at.phase2frequency(x4, sample_rate)
    
    # compute phase PSD
    (f0, psd0) = at.noise.scipy_psd(x0, fs=sample_rate, nr_segments=4)
    (f1, psd1) = at.noise.scipy_psd(x1, fs=sample_rate, nr_segments=4)
    (f2, psd2) = at.noise.scipy_psd(x2, fs=sample_rate, nr_segments=4)
    (f3, psd3) = at.noise.scipy_psd(x3, fs=sample_rate, nr_segments=4)
    (f4, psd4) = at.noise.scipy_psd(x4, fs=sample_rate, nr_segments=4)
    # compute phase PSD prefactor g_b
    g0 = cn.phase_psd_from_qd( qd0, 0, tau0 )
    g1 = cn.phase_psd_from_qd( qd0, -1, tau0 )
    g2 = cn.phase_psd_from_qd( qd0, -2, tau0 )
    g3 = cn.phase_psd_from_qd( qd0, -3, tau0 )
    g4 = cn.phase_psd_from_qd( qd0, -4, tau0 )

    # compute frequency PSD
    (ff0, fpsd0) = at.noise.scipy_psd(y0, fs=sample_rate, nr_segments=4)
    (ff1, fpsd1) = at.noise.scipy_psd(y1, fs=sample_rate, nr_segments=4)
    (ff2, fpsd2) = at.noise.scipy_psd(y2, fs=sample_rate, nr_segments=4)
    (ff3, fpsd3) = at.noise.scipy_psd(y3, fs=sample_rate, nr_segments=4)
    (ff4, fpsd4) = at.noise.scipy_psd(y4, fs=sample_rate, nr_segments=4)
    # compute frequency PSD prefactor h_a
    a0 = cn.frequency_psd_from_qd( qd0, 0, tau0 )
    a1 = cn.frequency_psd_from_qd( qd1, -1, tau0 )
    a2 = cn.frequency_psd_from_qd( qd2, -2, tau0 )
    a3 = cn.frequency_psd_from_qd( qd3, -3, tau0 )
    a4 = cn.frequency_psd_from_qd( qd4, -4, tau0 )

    # compute ADEV
    (t0,d0,e,n) = at.oadev(x0, rate=sample_rate)
    (t1,d1,e,n) = at.oadev(x1, rate=sample_rate)
    (t2,d2,e,n) = at.oadev(x2, rate=sample_rate)
    (t3,d3,e,n) = at.oadev(x3, rate=sample_rate)
    (t4,d4,e,n) = at.oadev(x4, rate=sample_rate)
    
    # compute MDEV
    (mt0,md0,e,n) = at.mdev(x0, rate=sample_rate)
    (mt1,md1,e,n) = at.mdev(x1, rate=sample_rate)
    (mt2,md2,e,n) = at.mdev(x2, rate=sample_rate)
    (mt3,md3,e,n) = at.mdev(x3, rate=sample_rate)
    (mt4,md4,e,n) = at.mdev(x4, rate=sample_rate)
    

    plt.figure()
    # Phase PSD figure
    plt.subplot(2,2,1)
    plt.loglog(f0,[ g0*pow(xx, 0.0) for xx in f0],'--',label=r'$g_0f^0$', color='black')
    plt.loglog(f0,psd0,'.', color='black')
    
    plt.loglog(f1[1:],[ g1*pow(xx, -1.0) for xx in f1[1:]],'--',label=r'$g_{-1}f^{-1}$', color='red')
    plt.loglog(f1,psd1,'.' ,color='red')
    
    plt.loglog(f2[1:],[ g2*pow(xx,-2.0) for xx in f2[1:]],'--',label=r'$g_{-2}f^{-2}$', color='green')
    plt.loglog(f2,psd2,'.',  color='green')
    
    plt.loglog(f3[1:], [ g3*pow(xx,-3.0) for xx in f3[1:]],'--',label=r'$g_{-3}f^{-3}$', color='pink')
    plt.loglog(f3, psd3, '.', color='pink')
    
    plt.loglog(f4[1:], [ g4*pow(xx,-4.0) for xx in f4[1:]],'--',label=r'$g_{-4}f^{-4}$', color='blue')
    plt.loglog(f4, psd4, '.', color='blue')
    plt.grid()
    plt.legend(framealpha=0.9)
    plt.title(r'Phase Power Spectral Density')
    plt.xlabel(r'Frequency (Hz)')
    plt.ylabel(r' $S_x(f)$ $(s^2/Hz)$')
    
    # frequency PSD figure
    plt.subplot(2,2,2)
    plt.loglog(ff0[1:], [ a0*pow(xx,2) for xx in ff0[1:]],'--',label=r'$h_{2}f^{2}$', color='black')
    plt.loglog(ff0,fpsd0,'.',  color='black')
    
    plt.loglog(ff1[1:], [ a1*pow(xx,1) for xx in ff1[1:]],'--',label=r'$h_{1}f^{1}$', color='red')
    plt.loglog(ff1,fpsd1,'.',  color='red')

    plt.loglog(ff2[1:], [ a2*pow(xx,0) for xx in ff2[1:]],'--',label=r'$h_{0}f^{0}$', color='green')
    plt.loglog(ff2,fpsd2,'.', color='green')
    
    plt.loglog(ff3[1:], [ a3*pow(xx,-1) for xx in ff3[1:]],'--',label=r'$h_{-1}f^{-1}$', color='pink')
    plt.loglog(ff3,fpsd3,'.', color='pink')

    plt.loglog(ff4[1:], [ a4*pow(xx,-2) for xx in ff4[1:]],'--',label=r'$h_{-2}f^{-2}$', color='blue')
    plt.loglog(ff4,fpsd4,'.', color='blue')
    plt.grid()
    plt.legend(framealpha=0.9)
    plt.title(r'Frequency Power Spectral Density')
    plt.xlabel(r'Frequency (Hz)')
    plt.ylabel(r' $S_y(f)$ $(1/Hz)$')
    
    # ADEV figure
    plt.subplot(2,2,3)

    plt.loglog(t0, [ cn.adev_from_qd(qd0, 0, tau0)/xx for xx in t0],'--', label=r'$\sqrt{Eh_{2}}\tau^{-1}$', color='black')
    plt.loglog(t0,d0,'o', color='black')

    plt.loglog(t1, [ cn.adev_from_qd(qd1, -1, tau0)/xx for xx in t1],'--', label=r'$\sqrt{Dh_{1}}\tau^{-1}$', color='red')
    plt.loglog(t1,d1,'o', color='red')

    plt.loglog(t2, [ cn.adev_from_qd(qd2, -2, tau0)/math.sqrt(xx) for xx in t2],'--', label=r'$\sqrt{Ch_{0}}\tau^{-1/2}$', color='green')
    plt.loglog(t2,d2,'o', color='green')

    plt.loglog(t3, [ cn.adev_from_qd(qd3, -3, tau0)*1 for xx in t3],'--', label=r'$\sqrt{Bh_{-1}}\tau^0$', color='pink')
    plt.loglog(t3,d3,'o', color='pink')

    plt.loglog(t4, [ cn.adev_from_qd(qd4, -4, tau0)*math.sqrt(xx) for xx in t4],'--', label=r'$\sqrt{Ah_{-2}}\tau^{+1/2}$', color='blue')
    plt.loglog(t4,d4,'o', color='blue')

    plt.legend(framealpha=0.9, loc='lower left')
    plt.grid()
    plt.title(r'Allan Deviation')
    plt.xlabel(r'$\tau$ (s)')
    plt.ylabel(r'ADEV')
    
    # MDEV
    plt.subplot(2, 2, 4)

    plt.loglog(t0, [ cn.adev_from_qd(qd0, 0, tau0)/pow(xx,3.0/2.0) for xx in t0],'--', label=r'$\sqrt{Eh_{2}}\tau^{-3/2}$', color='black')
    plt.loglog(mt0,md0,'o', color='black')

    plt.loglog(t1, [ cn.adev_from_qd(qd1, -1, tau0)/xx for xx in t1],'--', label=r'$\sqrt{Dh_{1}}\tau^{-1}$', color='red')
    plt.loglog(mt1,md1,'o', color='red')

    plt.loglog(t2, [ cn.adev_from_qd(qd2, -2, tau0)/math.sqrt(xx) for xx in t2],'--', label=r'$\sqrt{Ch_{0}}\tau^{-1/2}$', color='green')
    plt.loglog(mt2,md2,'o', color='green')

    plt.loglog(t3, [ cn.adev_from_qd(qd3, -3, tau0)**1 for xx in t3],'--', label=r'$\sqrt{Bh_{-1}}\tau^0$', color='pink')
    plt.loglog(mt3,md3,'o', color='pink')

    plt.loglog(t4, [ cn.adev_from_qd(qd4, -4, tau0)*math.sqrt(xx) for xx in t4],'--', label=r'$\sqrt{Ah_{-2}}\tau^{+1/2}$', color='blue')
    plt.loglog(mt4,md4,'o', color='blue')

    plt.legend(framealpha=0.9, loc='lower left')
    plt.grid()
    plt.title(r'Modified Allan Deviation')
    plt.xlabel(r'$\tau$ (s)')
    plt.ylabel(r'MDEV')
    plt.show()
Пример #40
0
 def noise(self):
     _, dev, _, _ = oadev(self.rotation, rate=self.rate, data_type='freq')
     return dev[0] / 60
Пример #41
0
def main():

    nr = 2**14  # number of datapoints in time-series
    adev0 = 1.0e-11

    #
    # for each noise type generated Noise class
    # compute
    #   - phase PSD and coefficient g_b
    #   - frequency PSD and coefficient h_a
    #   - ADEV
    #   - MDEV
    #
    # discrete variance for noiseGen()
    qd0 = qd1 = qd2 = qd3 = qd4 = pow(adev0, 2)
    tau0 = 1.0  # sample interval
    sample_rate = 1.0 / tau0

    x0 = at.Noise(nr, qd0, 0)  # white phase noise (WPM)
    x0.generateNoise()
    x1 = at.Noise(nr, qd1, -1)  # flicker phase noise (FPM)
    x1.generateNoise()
    x2 = at.Noise(nr, qd2, -2)  # white frequency noise (WFM)
    x2.generateNoise()
    x3 = at.Noise(nr, qd3, -3)  # flicker frequency noise (FFM)
    x3.generateNoise()
    x4 = at.Noise(nr, qd4, -4)  # random walk frequency noise (RWFM)
    x4.generateNoise()

    # compute frequency time-series
    y0 = at.phase2frequency(x0.time_series, sample_rate)
    y1 = at.phase2frequency(x1.time_series, sample_rate)
    y2 = at.phase2frequency(x2.time_series, sample_rate)
    y3 = at.phase2frequency(x3.time_series, sample_rate)
    y4 = at.phase2frequency(x4.time_series, sample_rate)

    # compute phase PSD
    (f0, psd0) = at.noise.scipy_psd(x0.time_series,
                                    f_sample=sample_rate,
                                    nr_segments=4)
    (f1, psd1) = at.noise.scipy_psd(x1.time_series,
                                    f_sample=sample_rate,
                                    nr_segments=4)
    (f2, psd2) = at.noise.scipy_psd(x2.time_series,
                                    f_sample=sample_rate,
                                    nr_segments=4)
    (f3, psd3) = at.noise.scipy_psd(x3.time_series,
                                    f_sample=sample_rate,
                                    nr_segments=4)
    (f4, psd4) = at.noise.scipy_psd(x4.time_series,
                                    f_sample=sample_rate,
                                    nr_segments=4)

    # compute phase PSD prefactor g_b
    g0 = x0.phase_psd_from_qd(tau0)
    g1 = x1.phase_psd_from_qd(tau0)
    g2 = x2.phase_psd_from_qd(tau0)
    g3 = x3.phase_psd_from_qd(tau0)
    g4 = x4.phase_psd_from_qd(tau0)

    # compute frequency PSD
    (ff0, fpsd0) = at.noise.scipy_psd(y0, f_sample=sample_rate, nr_segments=4)
    (ff1, fpsd1) = at.noise.scipy_psd(y1, f_sample=sample_rate, nr_segments=4)
    (ff2, fpsd2) = at.noise.scipy_psd(y2, f_sample=sample_rate, nr_segments=4)
    (ff3, fpsd3) = at.noise.scipy_psd(y3, f_sample=sample_rate, nr_segments=4)
    (ff4, fpsd4) = at.noise.scipy_psd(y4, f_sample=sample_rate, nr_segments=4)

    # compute frequency PSD prefactor h_a
    a0 = x0.frequency_psd_from_qd(tau0)
    a1 = x1.frequency_psd_from_qd(tau0)
    a2 = x2.frequency_psd_from_qd(tau0)
    a3 = x3.frequency_psd_from_qd(tau0)
    a4 = x4.frequency_psd_from_qd(tau0)

    # compute ADEV
    (t0, d0, e, n) = at.oadev(x0.time_series, rate=sample_rate)
    (t1, d1, e, n) = at.oadev(x1.time_series, rate=sample_rate)
    (t2, d2, e, n) = at.oadev(x2.time_series, rate=sample_rate)
    (t3, d3, e, n) = at.oadev(x3.time_series, rate=sample_rate)
    (t4, d4, e, n) = at.oadev(x4.time_series, rate=sample_rate)

    # compute MDEV
    (mt0, md0, e, n) = at.mdev(x0.time_series, rate=sample_rate)
    (mt1, md1, e, n) = at.mdev(x1.time_series, rate=sample_rate)
    (mt2, md2, e, n) = at.mdev(x2.time_series, rate=sample_rate)
    (mt3, md3, e, n) = at.mdev(x3.time_series, rate=sample_rate)
    (mt4, md4, e, n) = at.mdev(x4.time_series, rate=sample_rate)

    plt.figure()
    # Phase PSD figure
    plt.subplot(2, 2, 1)
    plt.loglog(f0, [g0 * pow(xx, 0.0) for xx in f0],
               '--',
               label=r'$g_0f^0$',
               color='black')
    plt.loglog(f0, psd0, '.', color='black')

    plt.loglog(f1[1:], [g1 * pow(xx, -1.0) for xx in f1[1:]],
               '--',
               label=r'$g_{-1}f^{-1}$',
               color='red')
    plt.loglog(f1, psd1, '.', color='red')

    plt.loglog(f2[1:], [g2 * pow(xx, -2.0) for xx in f2[1:]],
               '--',
               label=r'$g_{-2}f^{-2}$',
               color='green')
    plt.loglog(f2, psd2, '.', color='green')

    plt.loglog(f3[1:], [g3 * pow(xx, -3.0) for xx in f3[1:]],
               '--',
               label=r'$g_{-3}f^{-3}$',
               color='pink')
    plt.loglog(f3, psd3, '.', color='pink')

    plt.loglog(f4[1:], [g4 * pow(xx, -4.0) for xx in f4[1:]],
               '--',
               label=r'$g_{-4}f^{-4}$',
               color='blue')
    plt.loglog(f4, psd4, '.', color='blue')
    plt.grid()
    plt.legend(framealpha=0.9)
    plt.title(r'Phase Power Spectral Density')
    plt.xlabel(r'Frequency (Hz)')
    plt.ylabel(r' $S_x(f)$ $(s^2/Hz)$')

    # frequency PSD figure
    plt.subplot(2, 2, 2)
    plt.loglog(ff0[1:], [a0 * pow(xx, 2) for xx in ff0[1:]],
               '--',
               label=r'$h_{2}f^{2}$',
               color='black')
    plt.loglog(ff0, fpsd0, '.', color='black')

    plt.loglog(ff1[1:], [a1 * pow(xx, 1) for xx in ff1[1:]],
               '--',
               label=r'$h_{1}f^{1}$',
               color='red')
    plt.loglog(ff1, fpsd1, '.', color='red')

    plt.loglog(ff2[1:], [a2 * pow(xx, 0) for xx in ff2[1:]],
               '--',
               label=r'$h_{0}f^{0}$',
               color='green')
    plt.loglog(ff2, fpsd2, '.', color='green')

    plt.loglog(ff3[1:], [a3 * pow(xx, -1) for xx in ff3[1:]],
               '--',
               label=r'$h_{-1}f^{-1}$',
               color='pink')
    plt.loglog(ff3, fpsd3, '.', color='pink')

    plt.loglog(ff4[1:], [a4 * pow(xx, -2) for xx in ff4[1:]],
               '--',
               label=r'$h_{-2}f^{-2}$',
               color='blue')
    plt.loglog(ff4, fpsd4, '.', color='blue')
    plt.grid()
    plt.legend(framealpha=0.9)
    plt.title(r'Frequency Power Spectral Density')
    plt.xlabel(r'Frequency (Hz)')
    plt.ylabel(r' $S_y(f)$ $(1/Hz)$')

    # ADEV figure
    plt.subplot(2, 2, 3)

    plt.loglog(t0, [x0.adev_from_qd(tau0, xx) / xx for xx in t0],
               '--',
               label=r'$\propto\sqrt{h_{2}}\tau^{-1}$',
               color='black')
    plt.loglog(t0, d0, 'o', color='black')

    plt.loglog(t1, [x1.adev_from_qd(tau0, xx) / xx for xx in t1],
               '--',
               label=r'$\propto\sqrt{h_{1}}\tau^{-1}$',
               color='red')
    plt.loglog(t1, d1, 'o', color='red')

    plt.loglog(t2, [x2.adev_from_qd(tau0, xx) / math.sqrt(xx) for xx in t2],
               '--',
               label=r'$\propto\sqrt{h_{0}}\tau^{-1/2}$',
               color='green')
    plt.loglog(t2, d2, 'o', color='green')

    plt.loglog(t3, [x3.adev_from_qd(tau0, xx) * 1 for xx in t3],
               '--',
               label=r'$\propto\sqrt{h_{-1}}\tau^0$',
               color='pink')
    plt.loglog(t3, d3, 'o', color='pink')

    plt.loglog(t4, [x4.adev_from_qd(tau0, xx) * math.sqrt(xx) for xx in t4],
               '--',
               label=r'$\propto\sqrt{h_{-2}}\tau^{+1/2}$',
               color='blue')
    plt.loglog(t4, d4, 'o', color='blue')

    plt.legend(framealpha=0.9, loc='lower left')
    plt.grid()
    plt.title(r'Allan Deviation')
    plt.xlabel(r'$\tau$ (s)')
    plt.ylabel(r'ADEV')

    # MDEV
    plt.subplot(2, 2, 4)

    plt.loglog(t0,
               [x0.mdev_from_qd(tau0, xx) / pow(xx, 3.0 / 2.0) for xx in t0],
               '--',
               label=r'$\propto\sqrt{h_{2}}\tau^{-3/2}$',
               color='black')
    plt.loglog(mt0, md0, 'o', color='black')

    plt.loglog(t1, [x1.mdev_from_qd(tau0, xx) / xx for xx in t1],
               '--',
               label=r'$\propto\sqrt{h_{1}}\tau^{-1}$',
               color='red')
    plt.loglog(mt1, md1, 'o', color='red')

    plt.loglog(t2, [x2.mdev_from_qd(tau0, xx) / math.sqrt(xx) for xx in t2],
               '--',
               label=r'$\propto\sqrt{h_{0}}\tau^{-1/2}$',
               color='green')
    plt.loglog(mt2, md2, 'o', color='green')

    plt.loglog(t3, [x3.mdev_from_qd(tau0, xx)**1 for xx in t3],
               '--',
               label=r'$\propto\sqrt{h_{-1}}\tau^0$',
               color='pink')
    plt.loglog(mt3, md3, 'o', color='pink')

    plt.loglog(t4, [x4.mdev_from_qd(tau0, xx) * math.sqrt(xx) for xx in t4],
               '--',
               label=r'$\propto\sqrt{h_{-2}}\tau^{+1/2}$',
               color='blue')
    plt.loglog(mt4, md4, 'o', color='blue')

    plt.legend(framealpha=0.9, loc='lower left')
    plt.grid()
    plt.title(r'Modified Allan Deviation')
    plt.xlabel(r'$\tau$ (s)')
    plt.ylabel(r'MDEV')
    plt.show()
Пример #42
0
    return p

def to_fractional(flist,f0):
    out=[]
    for f in flist:
        out.append( f/float(f0) - 1.0 )
    return out

fname = "ocxo_frequency.txt"
f10MHz = read_datafile(fname,column=0)

f = to_fractional(f10MHz, 10e6 ) # convert to fractional frequency
my_taus = numpy.logspace(1,5,40) # log-spaced tau values from 10s and upwards
rate = 1/float(10) # data collected with 10s gate time

(oadev_taus,oadev_devs,oadev_errs,ns)  = allan.oadev(frequency=f, rate=rate, taus=my_taus)
(mdev_taus,mdev_devs,mdev_errs,ns)  = allan.mdev(frequency=f, rate=rate, taus=my_taus)
(hdev_taus,hdev_devs,hdev_errs,ns)  = allan.hdev(frequency=f, rate=rate, taus=my_taus)
(ohdev_taus,ohdev_devs,ohdev_errs,ns)  = allan.ohdev(frequency=f, rate=rate, taus=my_taus)

plt.subplot(111, xscale="log", yscale="log") 

plt.errorbar(oadev_taus, oadev_devs, yerr=oadev_errs, label='OADEV') 
plt.errorbar(mdev_taus, mdev_devs, yerr=mdev_errs, label='MDEV') 
plt.errorbar(hdev_taus, hdev_devs, yerr=hdev_errs, label='HDEV') 
plt.errorbar(ohdev_taus, ohdev_devs, yerr=ohdev_errs, label='OHDEV') 

plt.xlabel('Taus (s)')
plt.ylabel('ADEV')

Пример #43
0
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,
Пример #44
0
def main(args):

    rospy.init_node('allan_variance_node')

    t0 = rospy.get_time()
    """""" """""" ""
    " Parameters "
    """""" """""" ""
    bagfile = rospy.get_param('~bagfile_path', '~/data/static.bag')
    topic = rospy.get_param('~imu_topic_name', '/imu')
    axis = rospy.get_param('~axis', 0)
    sampleRate = rospy.get_param('~sample_rate', 100)
    isDeltaType = rospy.get_param('~delta_measurement', False)
    numTau = rospy.get_param('~number_of_lags', 1000)
    resultsPath = rospy.get_param('~results_directory_path', None)
    """""" """""" """""" """""" ""
    " Results Directory Path "
    """""" """""" """""" """""" ""
    if resultsPath is None:
        paths = rospkg.get_ros_paths()
        path = paths[1]  # path to workspace's devel
        idx = path.find("ws/")
        workspacePath = path[0:(idx + 3)]
        resultsPath = workspacePath + 'av_results/'

        if not os.path.isdir(resultsPath):
            os.mkdir(resultsPath)

    print "\nResults will be save in the following directory: \n\n\t %s\n" % resultsPath
    """""" """""" """"""
    " Form Tau Array "
    """""" """""" """"""
    taus = [None] * numTau

    cnt = 0
    for i in np.linspace(
            -2.0, 5.0,
            num=numTau):  # lags will span from 10^-2 to 10^5, log spaced
        taus[cnt] = pow(10, i)
        cnt = cnt + 1
    """""" """""" """""
    " Parse Bagfile "
    """ """""" """""" ""
    bag = rosbag.Bag(bagfile)

    N = bag.get_message_count(topic)  # number of measurement samples

    data = np.zeros((6, N))  # preallocate vector of measurements

    if isDeltaType:
        scale = sampleRate
    else:
        scale = 1.0

    cnt = 0
    for topic, msg, t in bag.read_messages(topics=[topic]):
        data[0, cnt] = msg.linear_acceleration.x * scale
        data[1, cnt] = msg.linear_acceleration.y * scale
        data[2, cnt] = msg.linear_acceleration.z * scale
        data[3, cnt] = msg.angular_velocity.x * scale
        data[4, cnt] = msg.angular_velocity.y * scale
        data[5, cnt] = msg.angular_velocity.z * scale
        cnt = cnt + 1

    bag.close()

    print "[%0.2f seconds] Bagfile parsed\n" % (rospy.get_time() - t0)
    """""" """""" """"""
    " Allan Variance "
    """""" """""" """"""
    if axis is 0:
        currentAxis = 1  # loop through all axes 1-6
    else:
        currentAxis = axis  # just loop one time and break

    while (currentAxis <= 6):
        (taus_used, adev, adev_err,
         adev_n) = allantools.oadev(data[currentAxis - 1],
                                    data_type='freq',
                                    rate=float(sampleRate),
                                    taus=np.array(taus))

        randomWalkSegment = getRandomWalkSegment(taus_used, adev)
        biasInstabilityPoint = getBiasInstabilityPoint(taus_used, adev)

        randomWalk = randomWalkSegment[3]
        biasInstability = biasInstabilityPoint[1]
        """""" """""" """
        " Save as CSV "
        """ """""" """"""
        if (currentAxis == 1):
            fname = 'allan_accel_x'
            title = 'Allan Deviation: Accelerometer X'
        elif (currentAxis == 2):
            fname = 'allan_accel_y'
            title = 'Allan Deviation: Accelerometer Y'
        elif (currentAxis == 3):
            fname = 'allan_accel_z'
            title = 'Allan Deviation: Accelerometer Z'
        elif (currentAxis == 4):
            fname = 'allan_gyro_x'
            title = 'Allan Deviation: Gyroscope X'
        elif (currentAxis == 5):
            fname = 'allan_gyro_y'
            title = 'Allan Deviation: Gyroscope Y'
        elif (currentAxis == 6):
            fname = 'allan_gyro_z'
            title = 'Allan Deviation: Gyroscope Z'

        print "[%0.2f seconds] Finished calculating allan variance - writing results to %s" % (
            rospy.get_time() - t0, fname)

        f = open(resultsPath + fname + '.csv', 'wt')

        try:
            writer = csv.writer(f)
            writer.writerow(('Random Walk', 'Bias Instability'))
            writer.writerow((randomWalk, biasInstability))
            writer.writerow(('Tau', 'AllanDev', 'AllanDevError', 'AllanDevN'))
            for i in range(taus_used.size):
                writer.writerow(
                    (taus_used[i], adev[i], adev_err[i], adev_n[i]))
        finally:
            f.close()
        """""" """""" """
        " Plot Result "
        """ """""" """"""
        plt.figure(figsize=(12, 8))
        ax = plt.gca()
        ax.set_yscale('log')
        ax.set_xscale('log')

        plt.plot(taus_used, adev)
        plt.plot([randomWalkSegment[0], randomWalkSegment[2]],
                 [randomWalkSegment[1], randomWalkSegment[3]], 'k--')
        plt.plot(1, randomWalk, 'rx', markeredgewidth=2.5, markersize=14.0)
        plt.plot(biasInstabilityPoint[0], biasInstabilityPoint[1], 'ro')

        plt.grid(True, which="both")
        plt.title(title)
        plt.xlabel('Tau (s)')
        plt.ylabel('ADEV')

        for item in ([ax.title, ax.xaxis.label, ax.yaxis.label] +
                     ax.get_xticklabels() + ax.get_yticklabels()):
            item.set_fontsize(20)

        plt.show(block=False)

        plt.savefig(resultsPath + fname)

        currentAxis = currentAxis + 1 + axis * 6  # increment currentAxis also break if axis is not =0

    inp = raw_input("Press Enter key to close figures and end program\n")
Пример #45
0
# S_x
plt.figure()
plt.loglog(f_x,psd_x,label='numpy.fft()')
plt.loglog(f_x2,psd_x2,label='scipy.signal.welch()')
plt.loglog(f_x,[h2/(2*math.pi)**2 ]*len(f_x),label='h2/(4*pi^2)'  )
plt.legend(framealpha=0.5)
plt.title('PSD of phase (time)')
plt.xlabel('Frequeny / Hz')
plt.ylabel('one-sided PSD / S_x(f)')
plt.grid()

# ADEV figure
plt.figure()
taus=[tt for tt in np.logspace(-7,4,100)]
(taus_y, devs_y, errs_y, ns_y) = allantools.oadev(y,data_type='freq', rate=fs, taus=taus)
(taus_x, devs_x, errs_x, ns_x) = allantools.oadev(x,data_type='phase', rate=fs, taus=taus)
plt.loglog(taus_y,devs_y,'o',label='ADEV from y')
plt.loglog(taus_x,devs_x,'*',label='ADEV from x')

print devs_y
print devs_x
fh = 0.5*fs # this restricts the noise power to below fh
adev_y = [math.sqrt( 3*fh/(4*math.pi**2) * h2*(1.0/tt**2) ) for tt in taus]
plt.loglog(taus,adev_y,label='sqrt( 3*fh/(4*pi^2) * h2*tau^-2 )')
plt.xlim((1e-7,1e3))
plt.legend(framealpha=0.6)
plt.title('Allan deviation')
plt.xlabel('Tau / s')
plt.ylabel('Allan deviation')
plt.grid()