Exemple #1
0
def expBroaden(y, t, expMod):
    fy = F.fft(y)
    a = N.exp(-1 * expMod * N.arange(0, len(y)) / t)
    fa = F.fft(a)
    fy1 = fy * fa
    yb = (F.ifft(fy1).real) / N.sum(a)
    return yb
    def test_vector1(self):
        """check that mkl_fft gives the same result of numpy.fft"""
        f1 = mkl_fft.fft(self.xz1)
        f2 = np_fft.fft(self.xz1)
        assert_allclose(f1,f2, rtol=1e-7, atol=2e-12)

        f1 = mkl_fft.fft(self.xc1)
        f2 = np_fft.fft(self.xc1)
        assert_allclose(f1,f2, rtol=2e-6, atol=2e-6)
Exemple #3
0
def generate_dashboard(data):
    if len(data) == 0:
        return 'Empty data set'
    data.sort(key=lambda x: x['timestamp'])
    x = map(lambda x: x['timestamp'], data)
    # this base_plot is just for xrange synchronization
    base_plot = bokeh.plotting.figure(width=800,
                                      height=250,
                                      x_axis_type="datetime")
    base_plot.circle(x, x)
    figures = []
    for key in data[0]['data'].keys():
        figure = bokeh.plotting.figure(width=800,
                                       height=250,
                                       title=key,
                                       x_axis_type="datetime",
                                       x_range=base_plot.x_range)
        y = map(lambda x: x['data'][key], data)
        figure.circle(x, y)
        figure2 = bokeh.plotting.figure(width=800,
                                        height=250,
                                        title='FFT: %s' % key)
        y2 = map(lambda x: x.real, fftpack.fft(y))
        x2 = range(len(y))
        figure2.line(x2, y2)
        figures.append(bokeh.plotting.hplot(figure, figure2))

    return file_html(bokeh.plotting.vplot(*figures), CDN, "my plot")
Exemple #4
0
 def rfftn_fix(a, s=None, axes=None, norm=None):
     a = numpy.array(a, copy=True, dtype=float)
     s, axes = fftpk._cook_nd_args(a, s, axes)
     a = rfft_fix(a, s[-1], axes[-1], norm)
     for ii in range(len(axes) - 1):
         a = fftpk.fft(a, s[ii], axes[ii], norm)
     return a
Exemple #5
0
def chebt1(f):
    #TODO
    """chebyshev transformation, see chebfun"""
    n = len(f)
    oncircle = concatenate((f[-1::-1], f[1:-1]))
    fftcoef = real(fft(oncircle))/(2*n-2)
    return fftcoef[n-1::-1]
    def update_data(self, x, taps, psd, syms, table):
        try:
            eqdata_key = 'dtv_atsc_equalizer0::taps'
            symdata_key = 'dtv_atsc_equalizer0::data'
            rs_nump_key = 'dtv_atsc_rs_decoder0::num_packets'
            rs_numbp_key = 'dtv_atsc_rs_decoder0::num_bad_packets'
            rs_numerrs_key = 'dtv_atsc_rs_decoder0::num_errors_corrected'
            vt_metrics_key = 'dtv_atsc_viterbi_decoder0::decoder_metrics'
            snr_key = 'probe2_f0::SNR'

            data = self.radio.getKnobs([])
            eqdata = data[eqdata_key]
            symdata = data[symdata_key]
            rs_num_packets = data[rs_nump_key]
            rs_num_bad_packets = data[rs_numbp_key]
            rs_num_errors_corrected = data[rs_numerrs_key]
            vt_decoder_metrics = data[vt_metrics_key]
            snr_est = data[snr_key]

            vt_decoder_metrics = numpy.mean(vt_decoder_metrics.value)
            self._viterbi_metric.pop()
            self._viterbi_metric.insert(0, vt_decoder_metrics)

        except TTransportException:
            sys.stderr.write("Lost connection, exiting")
            sys.exit(1)

        ntaps = len(eqdata.value)
        taps.set_ydata(eqdata.value)
        taps.set_xdata(list(range(ntaps)))
        self._sp0.set_xlim(0, ntaps)
        self._sp0.set_ylim(min(eqdata.value), max(eqdata.value))

        fs = 6.25e6
        freq = numpy.linspace(-fs / 2, fs / 2, 10000)
        H = numpy.fft.fftshift(fftpack.fft(eqdata.value, 10000))
        HdB = 20.0*numpy.log10(abs(H))
        psd.set_ydata(HdB)
        psd.set_xdata(freq)
        self._sp1.set_xlim(0, fs / 2)
        self._sp1.set_ylim([min(HdB), max(HdB)])
        self._sp1.set_yticks([min(HdB), max(HdB)])
        self._sp1.set_yticklabels(["min", "max"])

        nsyms = len(symdata.value)
        syms.set_ydata(symdata.value)
        syms.set_xdata(nsyms*[0,])
        self._sp2.set_xlim([-1, 1])
        self._sp2.set_ylim([-10, 10])

        per = float(rs_num_bad_packets.value) / float(rs_num_packets.value)
        ber = float(rs_num_errors_corrected.value) / float(187*rs_num_packets.value)

        table._cells[(1,0)]._text.set_text("{0}".format(rs_num_packets.value))
        table._cells[(1,1)]._text.set_text("{0:.2g}".format(ber))
        table._cells[(1,2)]._text.set_text("{0:.2g}".format(per))
        table._cells[(1,3)]._text.set_text("{0:.1f}".format(numpy.mean(self._viterbi_metric)))
        table._cells[(1,4)]._text.set_text("{0:.4f}".format(snr_est.value[0]))

        return (taps, psd, syms, table)
 def rfftn_fix(a, s=None, axes=None, norm=None):
     a = numpy.array(a, copy=True, dtype=float)
     s, axes = fftpk._cook_nd_args(a, s, axes)
     a = rfft_fix(a, s[-1], axes[-1], norm)
     for ii in range(len(axes)-1):
         a = fftpk.fft(a, s[ii], axes[ii], norm)
     return a
 def dofft(self, iq):
     N = len(iq)
     iq_fft = numpy.fft.fftshift(fftpack.fft(iq))  # fft and shift axis
     iq_fft = 20 * numpy.log10(abs(
         (iq_fft + 1e-15) / N))  # convert to decibels, adjust power
     # adding 1e-15 (-300 dB) to protect against value errors if an item in iq_fft is 0
     return iq_fft
Exemple #9
0
def chebt1(f):
    #TODO
    """chebyshev transformation, see chebfun"""
    n = len(f)
    oncircle = concatenate((f[-1::-1], f[1:-1]))
    fftcoef = real(fft(oncircle))/(2*n-2)
    return fftcoef[n-1::-1]
Exemple #10
0
def plot_dft_abs_phase(signal: np.array.__class__,
                       frequency_discretization=1,
                       is_in_db=False):
    spectrum = fftshift(fft(signal))

    fft_frequencies = fftshift(
        fftfreq(signal.shape[0], 1 / frequency_discretization))

    abs_values = np.abs(spectrum)
    if is_in_db:
        abs_values = power_samples_in_db(abs_values)

    plt.figure()

    plt.subplot(211)
    plt.plot(fft_frequencies, abs_values, color='b')
    plt.ylabel('Amplitude [dB]', color='b')
    plt.xlabel('Frequency')
    plt.grid()

    plt.subplot(212)
    plt.plot(fft_frequencies, np.angle(spectrum), color='g')
    plt.ylabel('Phase [rad]', color='g')
    plt.xlabel('Frequency')
    plt.grid()

    plt.show()
Exemple #11
0
def chebt2(f):
    """chebyshev transformation, coefficients in expansion using
    Chebyshev polynomials T_n(x), see chebfun for details"""
    n = len(f)
    oncircle = concatenate((f[-1::-1], f[1:-1]))
    fftcoef = real(fft(oncircle))/(2*n-2)
    #print n, len(fftcoef)
    #print fftcoef[n-1:]
    #print fftcoef[n-1:0:-1]
    fftcoef[n-1:0:-1] += fftcoef[n-1:] # z+conj(z)
    return fftcoef[n-1::-1]
Exemple #12
0
def chebt2(f):
    """chebyshev transformation, coefficients in expansion using
    Chebyshev polynomials T_n(x), see chebfun for details"""
    n = len(f)
    oncircle = concatenate((f[-1::-1], f[1:-1]))
    fftcoef = real(fft(oncircle))/(2*n-2)
    #print n, len(fftcoef)
    #print fftcoef[n-1:]
    #print fftcoef[n-1:0:-1]
    fftcoef[n-1:0:-1] += fftcoef[n-1:] # z+conj(z)
    return fftcoef[n-1::-1]
Exemple #13
0
def dofft(iq, reverse=False):
    if reverse:
        # iq_ifft = np.fft.ifftshift(fftpack.ifft(iq))
        iq_ifft = fftpack.ifft(iq)
        return iq_ifft
    else:
        # iq_fft = np.fft.fftshift(fftpack.fft(iq))  # fft and shift axis
        iq_fft = fftpack.fft(iq)  # fft and shift axis
        # iq_fft = fftpack.fft(iq)  # fft no shift axis
        # iq_fft = 20 * np.log10(abs((iq_fft + 1e-15) / N))  # convert to decibels, adjust power

        # adding 1e-15 (-300 dB) to protect against value errors if an item in iq_fft is 0
        return iq_fft
Exemple #14
0
def plot_dft_real_image(signal: np.array.__class__,
                        frequency_discretization=1,
                        is_in_db=False):

    spectrum = fftshift(fft(signal))

    if is_in_db:
        spectrum = power_samples_in_db(
            np.real(spectrum)) + 1j * power_samples_in_db(np.imag(spectrum))

    fft_frequencies = fftshift(
        fftfreq(signal.shape[0], 1 / frequency_discretization))
    plt.subplot(211)
    plt.plot(fft_frequencies, np.real(spectrum))
    plt.subplot(212)
    plt.plot(fft_frequencies, np.imag(spectrum))
    # plt.ion()
    plt.show()
Exemple #15
0
def hilbert(mag):
    """Compute the modified 1D discrete Hilbert transform

    Parameters
    ----------
    mag : ndarray
        The magnitude spectrum. Should be 1D with an even length, and
        preferably a fast length for FFT/IFFT.
    """
    # Adapted based on code by Niranjan Damera-Venkata,
    # Brian L. Evans and Shawn R. McCaslin (see refs for `minimum_phase`)
    sig = np.zeros(len(mag))
    # Leave Nyquist and DC at 0, knowing np.abs(fftfreq(N)[midpt]) == 0.5
    midpt = len(mag) // 2
    sig[1:midpt] = 1
    sig[midpt+1:] = -1
    # eventually if we want to support complex filters, we will need a
    # np.abs() on the mag inside the log, and should remove the .real
    recon = ifft(mag * np.exp(fft(sig * ifft(np.log(mag))))).real
    return recon
Exemple #16
0
ptA=N.ones(WINDOW_SIZE);
t_fft=0
t_mult=0

for i in xrange(MAX_ELEMENTS):

    tA=N.zeros(WINDOW_SIZE)
    for j in xrange(MAX_ISOTOPES):
        if A[i][j,0] != 0:
            #removed +1 after R)+1 --we're using python which counts from 0
            tA[N.round(A[i][j,0]*R)]=A[i][j,1]#;  % put isotopic distribution in tA

    print 'Calculate FFT...'
    t0 = time.clock()
    tA=F.fft(tA) # FFT along elements isotopic distribution  O(nlogn)
    t_fft = time.clock()-t0
    print 'Multiply vectors...'
    t0 = time.clock()
    tA=tA**M[i]#  % O(n)
    #################
    ptA = ptA*tA#  % O(n)#this is where it is messing UP
    #################
    t1 = time.clock()
    t_mult=t1-t0


print 'Time for FFT: %4.2f s'%t_fft
print 'Time for multiplications: %4.2f s'%t_mult

print 'Calculate IFFT...'
Exemple #17
0
def fft_real_freq(sig, dt):
    S = fft(sig)
    S_F = np.linspace(0, 1, len(S) / 2) / dt / 2.0

    return S_F, S[0:len(S_F)]
Exemple #18
0
 def dofft(self, iq):
     N = len(iq)
     iq_fft = numpy.fft.fftshift(fftpack.fft(iq))       # fft and shift axis
     iq_fft = 20*numpy.log10(abs((iq_fft+1e-15) / N)) # convert to decibels, adjust power
     # adding 1e-15 (-300 dB) to protect against value errors if an item in iq_fft is 0
     return iq_fft
Exemple #19
0
ptA = N.ones(WINDOW_SIZE)
t_fft = 0
t_mult = 0

for i in xrange(MAX_ELEMENTS):

    tA = N.zeros(WINDOW_SIZE)
    for j in xrange(MAX_ISOTOPES):
        if A[i][j, 0] != 0:
            #removed +1 after R)+1 --we're using python which counts from 0
            tA[N.round(A[i][j, 0] *
                       R)] = A[i][j, 1]  #;  % put isotopic distribution in tA

    print 'Calculate FFT...'
    t0 = time.clock()
    tA = F.fft(tA)  # FFT along elements isotopic distribution  O(nlogn)
    t_fft = time.clock() - t0
    print 'Multiply vectors...'
    t0 = time.clock()
    tA = tA**M[i]  #  % O(n)
    #################
    ptA = ptA * tA  #  % O(n)#this is where it is messing UP
    #################
    t1 = time.clock()
    t_mult = t1 - t0

print 'Time for FFT: %4.2f s' % t_fft
print 'Time for multiplications: %4.2f s' % t_mult

print 'Calculate IFFT...'
t0 = time.clock()
Exemple #20
0
def Proj_F1(s):
    N   = len(s)
    return ifft(Proj_M1(fft(s, 2*N)))[0:N]
def main():
    parser = ArgumentParser(conflict_handler="resolve")
    parser.add_argument(
        "-N",
        "--nsamples",
        type=int,
        default=2000,
        help="Set the number of samples to process [default=%(default)r]")
    parser.add_argument(
        "-S",
        "--sps",
        type=int,
        default=4,
        help="Set the samples per symbol [default=%(default)r]")
    parser.add_argument("-r",
                        "--rolloff",
                        type=eng_float,
                        default=0.35,
                        help="Set the rolloff factor [default=%(default)r]")
    parser.add_argument(
        "-W",
        "--bandwidth",
        type=eng_float,
        default=2 * numpy.pi / 100.0,
        help="Set the loop bandwidth (PFB) or gain (M&M) [default=%(default)r]"
    )
    parser.add_argument(
        "-n",
        "--ntaps",
        type=int,
        default=45,
        help="Set the number of taps in the filters [default=%(default)r]")
    parser.add_argument(
        "--noise",
        type=eng_float,
        default=0.0,
        help="Set the simulation noise voltage [default=%(default)r]")
    parser.add_argument(
        "-f",
        "--foffset",
        type=eng_float,
        default=0.0,
        help=
        "Set the simulation's normalized frequency offset (in Hz) [default=%(default)r]"
    )
    parser.add_argument(
        "-t",
        "--toffset",
        type=eng_float,
        default=1.0,
        help="Set the simulation's timing offset [default=%(default)r]")
    parser.add_argument(
        "-p",
        "--poffset",
        type=eng_float,
        default=0.0,
        help="Set the simulation's phase offset [default=%(default)r]")
    parser.add_argument(
        "-M",
        "--mode",
        type=int,
        default=0,
        help=
        "Set the recovery mode (0: polyphase, 1: M&M) [default=%(default)r]")
    args = parser.parse_args()

    # Adjust N for the interpolation by sps
    args.nsamples = args.nsamples // args.sps

    # Set up the program-under-test
    put = example_timing(args.nsamples, args.sps, args.rolloff, args.ntaps,
                         args.bandwidth, args.noise, args.foffset,
                         args.toffset, args.poffset, args.mode)
    put.run()

    if args.mode == 0:
        data_src = numpy.array(put.vsnk_src.data()[20:])
        data_clk = numpy.array(put.vsnk_clk.data()[20:])

        data_err = numpy.array(put.vsnk_err.data()[20:])
        data_rat = numpy.array(put.vsnk_rat.data()[20:])
        data_phs = numpy.array(put.vsnk_phs.data()[20:])

        f1 = pyplot.figure(1, figsize=(12, 10), facecolor='w')

        # Plot the IQ symbols
        s1 = f1.add_subplot(2, 2, 1)
        s1.plot(data_src.real, data_src.imag, "bo")
        s1.plot(data_clk.real, data_clk.imag, "ro")
        s1.set_title("IQ")
        s1.set_xlabel("Real part")
        s1.set_ylabel("Imag part")
        s1.set_xlim([-2, 2])
        s1.set_ylim([-2, 2])

        # Plot the symbols in time
        delay = put.delay
        m = len(data_clk.real)
        s2 = f1.add_subplot(2, 2, 2)
        s2.plot(data_src.real, "bs", markersize=10, label="Input")
        s2.plot(data_clk.real[delay:], "ro", label="Recovered")
        s2.set_title("Symbols")
        s2.set_xlabel("Samples")
        s2.set_ylabel("Real Part of Signals")
        s2.legend()

        # Plot the clock recovery loop's error
        s3 = f1.add_subplot(2, 2, 3)
        s3.plot(data_err, label="Error")
        s3.plot(data_rat, 'r', label="Update rate")
        s3.set_title("Clock Recovery Loop Error")
        s3.set_xlabel("Samples")
        s3.set_ylabel("Error")
        s3.set_ylim([-0.5, 0.5])
        s3.legend()

        # Plot the clock recovery loop's error
        s4 = f1.add_subplot(2, 2, 4)
        s4.plot(data_phs)
        s4.set_title("Clock Recovery Loop Filter Phase")
        s4.set_xlabel("Samples")
        s4.set_ylabel("Filter Phase")

        diff_taps = put.dtaps
        ntaps = len(diff_taps[0])
        nfilts = len(diff_taps)
        t = numpy.arange(0, ntaps * nfilts)

        f3 = pyplot.figure(3, figsize=(12, 10), facecolor='w')
        s31 = f3.add_subplot(2, 1, 1)
        s32 = f3.add_subplot(2, 1, 2)
        s31.set_title("Differential Filters")
        s32.set_title("FFT of Differential Filters")

        for i, d in enumerate(diff_taps):
            D = 20.0 * numpy.log10(
                1e-20 + abs(numpy.fft.fftshift(fftpack.fft(d, 10000))))
            s31.plot(t[i::nfilts].real, d, "-o")
            s32.plot(D)
        s32.set_ylim([-120, 10])

    # If testing the M&M clock recovery loop
    else:
        data_src = numpy.array(put.vsnk_src.data()[20:])
        data_clk = numpy.array(put.vsnk_clk.data()[20:])

        data_err = numpy.array(put.vsnk_err.data()[20:])

        f1 = pyplot.figure(1, figsize=(12, 10), facecolor='w')

        # Plot the IQ symbols
        s1 = f1.add_subplot(2, 2, 1)
        s1.plot(data_src.real, data_src.imag, "o")
        s1.plot(data_clk.real, data_clk.imag, "ro")
        s1.set_title("IQ")
        s1.set_xlabel("Real part")
        s1.set_ylabel("Imag part")
        s1.set_xlim([-2, 2])
        s1.set_ylim([-2, 2])

        # Plot the symbols in time
        s2 = f1.add_subplot(2, 2, 2)
        s2.plot(data_src.real, "bs", markersize=10, label="Input")
        s2.plot(data_clk.real, "ro", label="Recovered")
        s2.set_title("Symbols")
        s2.set_xlabel("Samples")
        s2.set_ylabel("Real Part of Signals")
        s2.legend()

        # Plot the clock recovery loop's error
        s3 = f1.add_subplot(2, 2, 3)
        s3.plot(data_err)
        s3.set_title("Clock Recovery Loop Error")
        s3.set_xlabel("Samples")
        s3.set_ylabel("Error")

    pyplot.show()
Exemple #22
0
    def cal_isotopic(self):
        MAX_ELEMENTS=5+1  # add 1 due to mass correction 'element'
        MAX_ISOTOPES=4    # maxiumum # of isotopes for one element
        CUTOFF=1e-4       # relative intensity cutoff for plotting
        
        WINDOW_SIZE = 500
        #WINDOW_SIZE=input('Window size (in Da) ---> ');
        
        #RESOLUTION=input('Resolution (in Da) ----> ');  % mass unit used in vectors
        RESOLUTION = 1
        if RESOLUTION < 0.00001:#  % minimal mass step allowed
          RESOLUTION = 0.00001
        elif RESOLUTION > 0.5:  # maximal mass step allowed
          RESOLUTION = 0.5
        
        R=0.00001/RESOLUTION#  % R is used to scale nuclide masses (see below)
        
        WINDOW_SIZE=WINDOW_SIZE/RESOLUTION; 
        self.xx=WINDOW_SIZE  # convert window size to new mass units
        WINDOW_SIZE=self.next2pow();  # fast radix-2 fast-Fourier transform algorithm
        
        if WINDOW_SIZE < np.round(496708*R)+1:
          WINDOW_SIZE = self.next2pow(np.round(496708*R)+1)  # just to make sure window is big enough
        
        
        #H378 C254 N65 O75 S6
        M=np.array([int(self.H),int(self.C),int(self.N),int(self.O),0,0]) #% empiric formula, e.g. bovine insulin
        
        # isotopic abundances stored in matrix A (one row for each element)
        A=np.zeros((MAX_ELEMENTS,MAX_ISOTOPES,2));
        
        A[0][0,:] = [100783,0.9998443]#                 % 1H
        A[0][1,:] = [201410,0.0001557]#                 % 2H
        A[1][0,:] = [100000,0.98889]#                   % 12C
        A[1][1,:] = [200336,0.01111]#                   % 13C
        A[2][0,:] = [100307,0.99634]#                   % 14N
        A[2][1,:] = [200011,0.00366]#                   % 15N
        A[3][0,:] = [99492,0.997628]#                  % 16O
        A[3][1,:] = [199913,0.000372]#                  % 17O
        A[3][2,:] = [299916,0.002000]#                  % 18O
        A[4][0,:] = [97207,0.95018]#                   % 32S
        A[4][1,:] = [197146,0.00750]#                   % 33S
        A[4][2,:] = [296787,0.04215]#                   % 34S
        A[4][3,:] = [496708,0.00017]#                   % 36S
        A[5][0,:] = [100000,1.00000]#                   % for shifting mass so that Mmi is
        #                                             % near left limit of window
        
        Mmi=np.array([np.round(100783*R), np.round(100000*R),\
                     np.round(100307*R),np.round(99492*R), np.round(97207*R), 0])*M#  % (Virtual) monoisotopic mass in new units
        Mmi = Mmi.sum()
        #% mass shift so Mmi is in left limit of window:
        FOLDED=np.floor(Mmi/(WINDOW_SIZE-1))+1#  % folded FOLDED times (always one folding due to shift below)
        #% shift distribution to 1 Da from lower window limit:
        M[MAX_ELEMENTS-1]=np.ceil(((WINDOW_SIZE-1)-np.mod(Mmi,WINDOW_SIZE-1)+np.round(100000*R))*RESOLUTION)
        
        MASS_REMOVED=np.array([0,11,13,15,31,-1])*M#% correction for 'virtual' elements and mass shift
        begin=WINDOW_SIZE*RESOLUTION+MASS_REMOVED.sum()
        end=2*(WINDOW_SIZE-1)*RESOLUTION+MASS_REMOVED.sum()
        
        ptA=np.ones(WINDOW_SIZE);
        t_fft=0
        t_mult=0
        
        for i in xrange(MAX_ELEMENTS):
        
            tA=np.zeros(WINDOW_SIZE)
            for j in xrange(MAX_ISOTOPES):
                if A[i][j,0] != 0:
                    #removed +1 after R)+1 --we're using python
                    tA[np.round(A[i][j,0]*R)]=A[i][j,1]#;  % put isotopic distribution in tA
            t0 = time.clock()
            tA=F.fft(tA) # FFT along elements isotopic distribution  O(nlogn)
            t_fft = time.clock()-t0
            t0 = time.clock()
            tA=tA**M[i]#  % O(n)
            #################
            ptA = ptA*tA#  % O(n)#this is where it is messing UP
            #################
            t1 = time.clock()
            t_mult=t1-t0
        

        t0=time.clock()
        ptA=F.ifft(ptA).real#;  % O(nlogn)

        t0=time.clock()
        
        MA=np.linspace(begin,end,WINDOW_SIZE-1)
        ind=np.where(ptA>CUTOFF)[0]
        
        self.x = MA[ind]
        self.y = ptA[ind]
        self.x_min=int(np.min(self.x)-(np.max(self.x)-np.min(self.x)))
        self.x_max=int(np.min(self.x)+(np.max(self.x)-np.min(self.x)))
        
        self.mass_y=np.ones(len(self.x))
        mass_diff=np.ones(len(self.x))
        
        mzInd= np.logical_and((self.mz>=self.x_min),(self.mz<=self.x_max))
        self.mass_y=self.mass[mzInd]
        self.mass_x=self.mz[mzInd]
        
        
#         for i in range(len(self.x)):
#             self.mass_y[i]=self.mass[int(self.x[i])]
        self.massy=np.max(self.mass_y)
        print self.massy
        self.mass_y=self.mass_y/max(self.mass_y)*100
        self.y=self.y/max(self.y)*100
#        k=(self.mass_y*self.y).sum()/(self.mass_y*self.mass_y).sum()
#        self.fit=((k*self.mass_y-self.y)*(k*self.mass_y-self.y)).sum()/(self.y*self.y).sum()
        for i in range(len(self.y)):
            mass_diff[i]=np.abs(self.mass_y[i]-self.y[i])/(self.mass_y[i]+self.y[i])
        self.mass_diff=(1-mass_diff.sum()/len(mass_diff))*100
Exemple #23
0
# Original data
exp_data = [0.0, 65.60500001907349, 1825.5309998989105, 1861.1949999332428, 3616.5469999313354, 3652.177999973297, 5413.882999897003, 5449.318000078201, 7207.401999950409, 7243.092000007629, 8328.25200009346, 9006.778000116348, 9042.30999994278, 10797.611999988556, 10863.18799996376, 12623.076999902725, 12658.436000108719, 14415.46900010109, 14450.895999908447, 16213.163000106812, 16248.641000032425, 18005.18600010872, 18070.802999973297, 18522.302000045776, 19803.196000099182, 19868.661999940872, 20802.37299990654, 21594.209000110626, 21659.77800011635, 23422.048000097275, 23457.487999916077, 25214.668999910355, 25250.15300011635, 27011.65199995041, 27047.0569999218, 28803.25200009346, 28868.885999917984, 30222.260999917984, 30599.648000001907, 30665.289000034332, 32419.674999952316, 32455.194000005722, 34214.93099999428, 34250.35400009155, 36008.079999923706, 36043.68400001526, 37804.78500008583, 37870.19900012016, 38442.32400012016, 39594.3789999485, 39665.11899995804, 41424.59200000763, 41460.00900006294, 43217.22499990463, 43252.643000125885, 45012.87599992752, 45048.49799990654, 46848.959000110626, 46914.168999910355, 47809.790999889374, 47874.954999923706, 48406.518000125885, 48471.700000047684]


N = 50000

# Test 1

T = N / 80      # T = 625

k = randint(0, T)

x = [1 if i%T == k else 0 for i in range(N)]

y = fft(x)

y_real = [yi.real for yi in y]
y_imag = [yi.imag for yi in y]

y_phase = [cmath.phase(yi) for yi in y]
y_magnitude = [magnitude(yi) for yi in y]


# Test 2

T1 = N / 80     # T1 = 625
T2 = N / 200    # T2 = 250 

k1 = randint(0, T)
k2 = randint(0, T)
Exemple #24
0
import pylab as P


MAX_ELEMENTS = 5
MAX_MASS = 2**13      #% fast radix-2 fast-Fourier transform algorithm is used

M = N.array([378,234,65,75,6])               #% empirical formula, e.g. bovine insulin

A = N.zeros((MAX_ELEMENTS,MAX_MASS))#                 % isotopic abundancies stored in A

A[0,1:3]=[0.9998443,0.0001557]#                 % H
A[1,12:14]=[0.98889,0.01111]#                   % C
A[2,14:16]=[0.99634,0.00366]#                   % N
A[3,16:19]=[0.997628,0.000372,0.002000]#        % O
A[4,32:37]=[0.95018,0.00750,0.04215,0,0.00017]# % S (extend to other elements as needed)

tA=F.fft(A,axis=1)#                     % FFT along each element's isotopic distribution

ptA=N.ones(MAX_MASS);
for i in xrange(MAX_ELEMENTS-1):
    ptA = ptA*(tA[i,:]**M[i])#;         % multiply transforms (elementwise)


riptA=F.ifft(ptA).real#              % inverse FFT to get convolutions

id=N.zeros(MAX_MASS)
id[0:MAX_MASS-1]=riptA[1:MAX_MASS]#; % shift to real mass

print id.argmax(), id.max()
P.plot(riptA)
P.show()
Exemple #25
0
def Proj_F1(s):
    N = len(s)
    return ifft(Proj_M1(fft(s, 2 * N)))[0:N]
Exemple #26
0
MAX_MASS = 2**13  #% fast radix-2 fast-Fourier transform algorithm is used

M = N.array([378, 234, 65, 75, 6])  #% empirical formula, e.g. bovine insulin

A = N.zeros((MAX_ELEMENTS,
             MAX_MASS))  #                 % isotopic abundancies stored in A

A[0, 1:3] = [0.9998443, 0.0001557]  #                 % H
A[1, 12:14] = [0.98889, 0.01111]  #                   % C
A[2, 14:16] = [0.99634, 0.00366]  #                   % N
A[3, 16:19] = [0.997628, 0.000372, 0.002000]  #        % O
A[4, 32:37] = [0.95018, 0.00750, 0.04215, 0,
               0.00017]  # % S (extend to other elements as needed)

tA = F.fft(
    A, axis=1
)  #                     % FFT along each element's isotopic distribution

ptA = N.ones(MAX_MASS)
for i in xrange(MAX_ELEMENTS - 1):
    ptA = ptA * (tA[i, :]**M[i]
                 )  #;         % multiply transforms (elementwise)

riptA = F.ifft(ptA).real  #              % inverse FFT to get convolutions

id = N.zeros(MAX_MASS)
id[0:MAX_MASS - 1] = riptA[1:MAX_MASS]  #; % shift to real mass

print id.argmax(), id.max()
P.plot(riptA)
P.show()
Exemple #27
0
def taylor_coeff(fun, N):
    """From L. Trefethen, Ten digits algorithms """
    zz = exp(2j*pi*(array(list(range(N))))/N)
    c = fft(fun(zz))/N
    return real(c)
def isotopefn(givenmass):
    def next2pow(x):
        return 2**int(N.ceil(N.log(float(x))/N.log(2.0)))


    MAX_ELEMENTS=5+1  # add 1 due to mass correction 'element'
    MAX_ISOTOPES=4    # maxiumum # of isotopes for one element
    CUTOFF=1e-8       # relative intensity cutoff for plotting

    WINDOW_SIZE = 500
    #WINDOW_SIZE=input('Window size (in Da) ---> ');

    #RESOLUTION=input('Resolution (in Da) ----> ');  % mass unit used in vectors
    RESOLUTION = 0.5
    if RESOLUTION < 0.00001:#  % minimal mass step allowed
      RESOLUTION = 0.00001
    elif RESOLUTION > 0.5:  # maximal mass step allowed
      RESOLUTION = 0.5

    R=0.00001/RESOLUTION#  % R is used to scale nuclide masses (see below)

    WINDOW_SIZE=WINDOW_SIZE/RESOLUTION;   # convert window size to new mass units
    WINDOW_SIZE=next2pow(WINDOW_SIZE);  # fast radix-2 fast-Fourier transform algorithm

    if WINDOW_SIZE < N.round(496708*R)+1:
      WINDOW_SIZE = nextpow2(N.round(496708*R)+1)  # just to make sure window is big enough

    #print 'Vector size: 1x%d'%WINDOW_SIZE

    #H378 C254 N65 O75 S6
    resnumber=N.round(float(givenmass)/110,0)
    #print resnumber
    abuns=[7.593,4.869,1.351,1.492,0.051]
    myarr=[N.round(resnumber*k,0) for k in abuns]
    #myarr=[98,63,18,13,1]
    myarr.append(0)
    #print myarr
    M=N.array(myarr) #% empiric formula, e.g. bovine insulin

    # isotopic abundances stored in matrix A (one row for each element)
    A=N.zeros((MAX_ELEMENTS,MAX_ISOTOPES,2));

    A[0][0,:] = [100783,0.9998443]#                 % 1H
    A[0][1,:] = [201410,0.0001557]#                 % 2H
    A[1][0,:] = [100000,0.98889]#                   % 12C
    A[1][1,:] = [200336,0.01111]#                   % 13C
    A[2][0,:] = [100307,0.99634]#                   % 14N
    A[2][1,:] = [200011,0.00366]#                   % 15N
    A[3][0,:] = [99492,0.997628]#                  % 16O
    A[3][1,:] = [199913,0.000372]#                  % 17O
    A[3][2,:] = [299916,0.002000]#                  % 18O
    A[4][0,:] = [97207,0.95018]#                   % 32S
    A[4][1,:] = [197146,0.00750]#                   % 33S
    A[4][2,:] = [296787,0.04215]#                   % 34S
    A[4][2,:] = [496708,0.00017]#                   % 36S
    A[5][0,:] = [100000,1.00000]#                   % for shifting mass so that Mmi is
    #                                             % near left limit of window

    Mmi=N.array([N.round(100783*R), N.round(100000*R),\
                 N.round(100307*R), N.round(99492*R), N.round(97207*R), 0])*M#  % (Virtual) monoisotopic mass in new units
    Mmi = Mmi.sum()
    #% mass shift so Mmi is in left limit of window:
    #print "Mmi",Mmi
    #print "Window", WINDOW_SIZE
    FOLDED=N.floor(Mmi/(WINDOW_SIZE-1))+1#  % folded FOLDED times (always one folding due to shift below)

    #% shift distribution to 1 Da from lower window limit:
    M[MAX_ELEMENTS-1]=N.ceil(((WINDOW_SIZE-1)-N.mod(Mmi,WINDOW_SIZE-1)+N.round(100000*R))*RESOLUTION)
    MASS_REMOVED=N.array([0,11,13,15,31,-1])*M#';  % correction for 'virtual' elements and mass shift
    MASS_REMOVED = MASS_REMOVED.sum()

    ptA=N.ones(WINDOW_SIZE);
    t_fft=0
    t_mult=0

    for i in xrange(MAX_ELEMENTS):

        tA=N.zeros(WINDOW_SIZE)
        for j in xrange(MAX_ISOTOPES):
            if A[i][j,0] != 0:
                #removed +1 after R)+1 --we're using python
                tA[N.round(A[i][j,0]*R)]=A[i][j,1]#;  % put isotopic distribution in tA

        #print 'Calculate FFT...'
        
        tA=F.fft(tA) # FFT along elements isotopic distribution  O(nlogn)
        
        #print 'Multiply vectors...'
        
        tA=tA**M[i]#  % O(n)
        #################
        ptA = ptA*tA#  % O(n)#this is where it is messing UP
        #################
        
        


    #rint 'Time for FFT: %4.2f s'%t_fft
    #print 'Time for multiplications: %4.2f s'%t_mult

    #print 'Calculate IFFT...'
    
    ptA=F.ifft(ptA).real#;  % O(nlogn)

    #print 'Time for IFFT: %4.2f s'%(time.clock()-t0)

    #print 'Plotting...'
    


    start = (FOLDED*(WINDOW_SIZE-1)+1)*RESOLUTION+MASS_REMOVED,(FOLDED+1)*(WINDOW_SIZE-1)*RESOLUTION+MASS_REMOVED
    stop = WINDOW_SIZE - 1

    MA=N.linspace((FOLDED*(WINDOW_SIZE-1)+1)*RESOLUTION+MASS_REMOVED,(FOLDED+1)*(WINDOW_SIZE-1)*RESOLUTION+MASS_REMOVED, WINDOW_SIZE-1)

    ind=N.where(ptA>CUTOFF)[0]


    y = ptA[ind]
    y2=[x/y[0] for x in y]
    return y2
def isotopefn(sequence, ion_number):

    massDict = mass.Composition(sequence[:ion_number])

    massDict['C'] -= 1
    massDict['H'] -= 2
    massDict['O'] -= 2

    if 'S' not in massDict:
        massDict['S'] = 0

    def next2pow(x):
        return 2**int(np.ceil(np.log(float(x)) / np.log(2.0)))

    MAX_ELEMENTS = 5 + 1  # add 1 due to mass correction 'element'
    MAX_ISOTOPES = 4  # maxiumum # of isotopes for one element
    CUTOFF = 1e-8  # relative intensity cutoff for plotting

    WINDOW_SIZE = 500
    # WINDOW_SIZE=input('Window size (in Da) ---> ');

    # RESOLUTION=input('Resolution (in Da) ----> ');  % mass unit used in vectors
    RESOLUTION = 0.5
    if RESOLUTION < 0.00001:  # % minimal mass step allowed
        RESOLUTION = 0.00001
    elif RESOLUTION > 0.5:  # maximal mass step allowed
        RESOLUTION = 0.5

    R = 0.00001 / RESOLUTION  # % R is used to scale nuclide masses (see below)

    WINDOW_SIZE = WINDOW_SIZE / RESOLUTION
    # convert window size to new mass units
    WINDOW_SIZE = next2pow(WINDOW_SIZE)
    # fast radix-2 fast-Fourier transform algorithm

    if WINDOW_SIZE < np.round(496708 * R) + 1:
        WINDOW_SIZE = next2pow(np.round(496708 * R) +
                               1)  # just to make sure window is big enough

    # print 'Vector size: 1x%d'%WINDOW_SIZE

    # H378 C254 N65 O75 S6
    M = np.array([
        massDict['H'], massDict['C'], massDict['N'], massDict['O'],
        massDict['S'], 1
    ])

    # isotopic abundances stored in matrix A (one row for each element)
    A = np.zeros((MAX_ELEMENTS, MAX_ISOTOPES, 2))

    A[0][0, :] = [100783, 0.9998443]  # % 1H
    A[0][1, :] = [201410, 0.0001557]  # % 2H
    A[1][0, :] = [100000, 0.98889]  # % 12C
    A[1][1, :] = [200336, 0.01111]  # % 13C
    A[2][0, :] = [100307, 0.99634]  # % 14N
    A[2][1, :] = [200011, 0.00366]  # % 15N
    A[3][0, :] = [99492, 0.997628]  # % 16O
    A[3][1, :] = [199913, 0.000372]  # % 17O
    A[3][2, :] = [299916, 0.002000]  # % 18O
    A[4][0, :] = [97207, 0.95018]  # % 32S
    A[4][1, :] = [197146, 0.00750]  # % 33S
    A[4][2, :] = [296787, 0.04215]  # % 34S
    A[4][2, :] = [496708, 0.00017]  # % 36S
    A[5][0, :] = [100000, 1.00000]  # % for shifting mass so that Mmi is
    #                                             % near left limit of window

    Mmi = np.array([np.round(100783 * R), np.round(100000 * R), \
                    np.round(100307 * R), np.round(99492 * R), np.round(97207 * R),
                    0]) * M  # % (Virtual) monoisotopic mass in new units
    Mmi = Mmi.sum()
    # % mass shift so Mmi is in left limit of window:
    # print "Mmi",Mmi
    # print "Window", WINDOW_SIZE
    FOLDED = np.floor(
        Mmi / (WINDOW_SIZE - 1)
    ) + 1  # % folded FOLDED times (always one folding due to shift below)

    # % shift distribution to 1 Da from lower window limit:
    M[MAX_ELEMENTS - 1] = np.ceil(
        ((WINDOW_SIZE - 1) - np.mod(Mmi, WINDOW_SIZE - 1) +
         np.round(100000 * R)) * RESOLUTION)
    MASS_REMOVED = np.array([
        0, 11, 13, 15, 31, -1
    ]) * M  # ';  % correction for 'virtual' elements and mass shift
    MASS_REMOVED = MASS_REMOVED.sum()

    ptA = np.ones(WINDOW_SIZE)
    t_fft = 0
    t_mult = 0

    for i in xrange(MAX_ELEMENTS):

        tA = np.zeros(WINDOW_SIZE)
        for j in xrange(MAX_ISOTOPES):
            if A[i][j, 0] != 0:
                # removed +1 after R)+1 --we're using python
                tA[np.int(np.round(
                    A[i][j, 0] *
                    R))] = A[i][j, 1]  # ;  % put isotopic distribution in tA

        # print 'Calculate FFT...'

        tA = F.fft(tA)  # FFT along elements isotopic distribution  O(nlogn)

        # print 'Multiply vectors...'

        tA = tA**M[i]  # % O(n)
        #################
        ptA = ptA * tA  # % O(n)#this is where it is messing UP
        #################

    # rint 'Time for FFT: %4.2f s'%t_fft
    # print 'Time for multiplications: %4.2f s'%t_mult

    # print 'Calculate IFFT...'

    ptA = F.ifft(ptA).real  # ;  % O(nlogn)

    # print 'Time for IFFT: %4.2f s'%(time.clock()-t0)

    # print 'Plotting...'

    start = (FOLDED * (WINDOW_SIZE - 1) + 1) * RESOLUTION + MASS_REMOVED, (
        FOLDED + 1) * (WINDOW_SIZE - 1) * RESOLUTION + MASS_REMOVED
    stop = WINDOW_SIZE - 1

    MA = np.linspace(
        (FOLDED * (WINDOW_SIZE - 1) + 1) * RESOLUTION + MASS_REMOVED,
        (FOLDED + 1) * (WINDOW_SIZE - 1) * RESOLUTION + MASS_REMOVED,
        WINDOW_SIZE - 1)

    ind = np.where(ptA > CUTOFF)[0]

    y = ptA[ind]
    y2 = y / np.max(y)
    return y2
Exemple #30
0
def taylor_coeff(fun, N):
    """From L. Trefethen, Ten digits algorithms """
    zz = exp(2j*pi*(array(range(N)))/N)
    c = fft(fun(zz))/N
    return real(c)
    def update_data(self, x, taps, psd, syms, table):
        try:
            eqdata_key = 'dtv_atsc_equalizer0::taps'
            symdata_key = 'dtv_atsc_equalizer0::data'
            rs_nump_key = 'dtv_atsc_rs_decoder0::num_packets'
            rs_numbp_key = 'dtv_atsc_rs_decoder0::num_bad_packets'
            rs_numerrs_key = 'dtv_atsc_rs_decoder0::num_errors_corrected'
            vt_metrics_key = 'dtv_atsc_viterbi_decoder0::decoder_metrics'
            snr_key = 'probe2_f0::SNR'

            data = self.radio.getKnobs([])
            eqdata = data[eqdata_key]
            symdata = data[symdata_key]
            rs_num_packets = data[rs_nump_key]
            rs_num_bad_packets = data[rs_numbp_key]
            rs_num_errors_corrected = data[rs_numerrs_key]
            vt_decoder_metrics = data[vt_metrics_key]
            snr_est = data[snr_key]

            vt_decoder_metrics = numpy.mean(vt_decoder_metrics.value)
            self._viterbi_metric.pop()
            self._viterbi_metric.insert(0, vt_decoder_metrics)

        except TTransportException:
            sys.stderr.write("Lost connection, exiting")
            sys.exit(1)

        ntaps = len(eqdata.value)
        taps.set_ydata(eqdata.value)
        taps.set_xdata(list(range(ntaps)))
        self._sp0.set_xlim(0, ntaps)
        self._sp0.set_ylim(min(eqdata.value), max(eqdata.value))

        fs = 6.25e6
        freq = numpy.linspace(-fs / 2, fs / 2, 10000)
        H = numpy.fft.fftshift(fftpack.fft(eqdata.value, 10000))
        HdB = 20.0 * numpy.log10(abs(H))
        psd.set_ydata(HdB)
        psd.set_xdata(freq)
        self._sp1.set_xlim(0, fs / 2)
        self._sp1.set_ylim([min(HdB), max(HdB)])
        self._sp1.set_yticks([min(HdB), max(HdB)])
        self._sp1.set_yticklabels(["min", "max"])

        nsyms = len(symdata.value)
        syms.set_ydata(symdata.value)
        syms.set_xdata(nsyms * [
            0,
        ])
        self._sp2.set_xlim([-1, 1])
        self._sp2.set_ylim([-10, 10])

        per = float(rs_num_bad_packets.value) / float(rs_num_packets.value)
        ber = float(rs_num_errors_corrected.value) / float(
            187 * rs_num_packets.value)

        table._cells[(1, 0)]._text.set_text("{0}".format(rs_num_packets.value))
        table._cells[(1, 1)]._text.set_text("{0:.2g}".format(ber))
        table._cells[(1, 2)]._text.set_text("{0:.2g}".format(per))
        table._cells[(1, 3)]._text.set_text("{0:.1f}".format(
            numpy.mean(self._viterbi_metric)))
        table._cells[(1, 4)]._text.set_text("{0:.4f}".format(snr_est.value[0]))

        return (taps, psd, syms, table)
Exemple #32
0
def isotope(fVec,DAbund):
    '''
    %
    % Calculates isotopic distributions including isotopic fine structure
    % of molecules using FFT and various scaling 'tricks'. Easily adopted
    % to molecules of any elemental composition (by altering MAX_ELEMENTS
    % and the nuclide matrix A). To simulate spectra, convolute with peak
    % shape using FFT.
    %
    % (C) 1999 by Magnus Palmblad, Division of Ion Physics, Uppsala Univ.
    % Acknowledgements:
    % Lars Larsson-Cohn, Dept. of Mathematical Statistics, Uppsala Univ.,
    % for help on theory of convolutions and FFT.
    % Jan Axelsson, Div. of Ion Physics, Uppsala Univ. for comments and ideas
    %
    % Contact Magnus Palmblad at [email protected] if you should
    % have any questions or comments.
    %

    Converted to Python 1/10/08 by
    Brian H. Clowers [email protected]

    October 31, 2014
    Added Phosphorous and chemical formula parsing
    Added conditional specification of stable isotope composition
    Ben Bowen, [email protected]

    fVec is a vector representing the chemical formula including deuterium
    # [H, C, N, O, S, P, D]
    DAbund is the amount of deuterium [0-1], 0.05 is typical
    '''
    import numpy as np
    import numpy.fft.fftpack as F
    # import time
    # import pylab as P


    def next2pow(x):
        return 2**int(np.ceil(np.log(float(x))/np.log(2.0)))

    scaleFactor = 100000
    MAX_ELEMENTS=7+1  # add 1 due to mass correction 'element'
    MAX_ISOTOPES=4    # maxiumum # of isotopes for one element
    CUTOFF=1e-4     # relative intensity cutoff for plotting

    WINDOW_SIZE = 500
    #WINDOW_SIZE=input('Window size (in Da) ---> ');

    #RESOLUTION=input('Resolution (in Da) ----> ');  % mass unit used in vectors
    RESOLUTION = 0.5
    if RESOLUTION < 0.00001:#  % minimal mass step allowed
      RESOLUTION = 0.00001
    elif RESOLUTION > 0.5:  # maximal mass step allowed
      RESOLUTION = 0.5

    R=0.00001/RESOLUTION#  % R is used to scale nuclide masses (see below)

    WINDOW_SIZE=WINDOW_SIZE/RESOLUTION;   # convert window size to new mass units
    WINDOW_SIZE=next2pow(WINDOW_SIZE);  # fast radix-2 fast-Fourier transform algorithm

    if WINDOW_SIZE < np.round(496708*R)+1:
      WINDOW_SIZE = nextpow2(np.round(496708*R)+1)  # just to make sure window is big enough

    # print 'Vector size: 1x%d'%WINDOW_SIZE

    #H378 C254 N65 O75 S6
    
    # M=np.array([378,254,65,75,6,0]) #% empiric formula, e.g. bovine insulin
    M=np.array(fVec) #% empiric formula, e.g. bovine insulin

    # isotopic abundances stored in matrix A (one row for each element)
    A=np.zeros((MAX_ELEMENTS,MAX_ISOTOPES,2));

    A[0][0,:] = [100783,0.9998443]#                 % 1H
    A[0][1,:] = [201410,0.0001557]#                 % 2H
    A[1][0,:] = [100000,0.98889]#                   % 12C
    A[1][1,:] = [200336,0.01111]#                   % 13C
    A[2][0,:] = [100307,0.99634]#                   % 14N
    A[2][1,:] = [200011,0.00366]#                   % 15N
    A[3][0,:] = [99492,0.997628]#                  % 16O
    A[3][1,:] = [199913,0.000372]#                  % 17O
    A[3][2,:] = [299916,0.002000]#                  % 18O
    A[4][0,:] = [97207,0.95018]#                   % 32S
    A[4][1,:] = [197146,0.00750]#                   % 33S
    A[4][2,:] = [296787,0.04215]#                   % 34S
    A[4][3,:] = [496708,0.00017]#                   % 36S
    A[5][0,:] = [97376,1.0]# Phosphorous
    A[6][0,:] = [100783,1.0-DAbund]#                 % 1H
    A[6][1,:] = [201410,DAbund]#                 % 2H
    A[7][0,:] = [100000,1.00000]#                   % for shifting mass so that Mmi is
    #                                             % near left limit of window
    mass_removed_vec = [0,11,13,15,31,30,0,-1]
    monoisotopic = 0.0
    for i,e in enumerate(fVec):
        monoisotopic = monoisotopic + ( (mass_removed_vec[i]*scaleFactor+A[i][0,0])*e / scaleFactor)

    Mmi=np.array([np.round(100783*R), np.round(100000*R),\
                 np.round(100307*R), np.round(99492*R), np.round(97207*R), np.round(97376*R), np.round(100783*R), 0])*M#  % (Virtual) monoisotopic mass in new units
    Mmi = Mmi.sum()
    #% mass shift so Mmi is in left limit of window:
    #print "Mmi",Mmi
    #print "Window", WINDOW_SIZE
    FOLDED=np.floor(Mmi/(WINDOW_SIZE-1))+1#  % folded FOLDED times (always one folding due to shift below)

    #% shift distribution to 1 Da from lower window limit:
    M[MAX_ELEMENTS-1]=np.ceil(((WINDOW_SIZE-1)-np.mod(Mmi,WINDOW_SIZE-1)+np.round(100000*R))*RESOLUTION)
    MASS_REMOVED=np.array(mass_removed_vec)*M#';  % correction for 'virtual' elements and mass shift
    MASS_REMOVED = MASS_REMOVED.sum()

    ptA=np.ones(WINDOW_SIZE);
    t_fft=0
    t_mult=0

    for i in xrange(MAX_ELEMENTS):
        tA=np.zeros(WINDOW_SIZE)
        for j in xrange(MAX_ISOTOPES):
            if A[i][j,0] != 0:
                tA[np.round(A[i][j,0]*R)]=A[i][j,1]#;  % put isotopic distribution in tA

        tA=F.fft(tA) # FFT along elements isotopic distribution  O(nlogn)
        tA=tA**M[i]#  % O(n)
        ptA = ptA*tA#  % O(n)#this is where it is messing UP

    ptA=F.ifft(ptA).real#;  % O(nlogn)

    start = (FOLDED*(WINDOW_SIZE-1)+1)*RESOLUTION+MASS_REMOVED,(FOLDED+1)*(WINDOW_SIZE-1)*RESOLUTION+MASS_REMOVED
    stop = WINDOW_SIZE - 1

    MA=np.linspace((FOLDED*(WINDOW_SIZE-1)+1)*RESOLUTION+MASS_REMOVED,(FOLDED+1)*(WINDOW_SIZE-1)*RESOLUTION+MASS_REMOVED, WINDOW_SIZE-1)

    ind=np.where(ptA>CUTOFF)[0]

    x = MA[ind]
    y = ptA[ind]

    for i,xi in enumerate(x):
        x[i] = monoisotopic + (i*1.003355)


    return x,y,monoisotopic
Exemple #33
0
def fft_real_freq(sig, dt):
    S = fft(sig)
    S_F = np.linspace(0, 1, len(S)/2) / dt / 2.0

    return S_F, S[0:len(S_F)]
def isotope(fVec,DAbund):
	'''
	%
	% Calculates isotopic distributions including isotopic fine structure
	% of molecules using FFT and various scaling 'tricks'. Easily adopted
	% to molecules of any elemental composition (by altering MAX_ELEMENTS
	% and the nuclide matrix A). To simulate spectra, convolute with peak
	% shape using FFT.
	%
	% (C) 1999 by Magnus Palmblad, Division of Ion Physics, Uppsala Univ.
	% Acknowledgements:
	% Lars Larsson-Cohn, Dept. of Mathematical Statistics, Uppsala Univ.,
	% for help on theory of convolutions and FFT.
	% Jan Axelsson, Div. of Ion Physics, Uppsala Univ. for comments and ideas
	%
	% Contact Magnus Palmblad at [email protected] if you should
	% have any questions or comments.
	%

	Converted to Python 1/10/08 by
	Brian H. Clowers [email protected]

	October 31, 2014
	Added Phosphorous and chemical formula parsing
	Added conditional specification of stable isotope composition
	Ben Bowen, [email protected]

	fVec is a vector representing the chemical formula including deuterium
	# [H, C, N, O, S, P, D]
	DAbund is the amount of deuterium [0-1], 0.05 is typical
	'''
	import numpy as np
	import numpy.fft.fftpack as F
	# import time
	# import pylab as P


	def next2pow(x):
	    return 2**int(np.ceil(np.log(float(x))/np.log(2.0)))

	scaleFactor = 100000
	MAX_ELEMENTS=7+1  # add 1 due to mass correction 'element'
	MAX_ISOTOPES=4    # maxiumum # of isotopes for one element
	CUTOFF=1e-4    # relative intensity cutoff for plotting

	WINDOW_SIZE = 500
	#WINDOW_SIZE=input('Window size (in Da) ---> ');

	#RESOLUTION=input('Resolution (in Da) ----> ');  % mass unit used in vectors
	RESOLUTION = 0.5
	if RESOLUTION < 0.00001:#  % minimal mass step allowed
	  RESOLUTION = 0.00001
	elif RESOLUTION > 0.5:  # maximal mass step allowed
	  RESOLUTION = 0.5

	R=0.00001/RESOLUTION#  % R is used to scale nuclide masses (see below)

	WINDOW_SIZE=WINDOW_SIZE/RESOLUTION;   # convert window size to new mass units
	WINDOW_SIZE=next2pow(WINDOW_SIZE);  # fast radix-2 fast-Fourier transform algorithm

	if WINDOW_SIZE < np.round(496708*R)+1:
	  WINDOW_SIZE = nextpow2(np.round(496708*R)+1)  # just to make sure window is big enough

	# print 'Vector size: 1x%d'%WINDOW_SIZE

	#H378 C254 N65 O75 S6
	
	# M=np.array([378,254,65,75,6,0]) #% empiric formula, e.g. bovine insulin
	M=np.array(fVec) #% empiric formula, e.g. bovine insulin

	# isotopic abundances stored in matrix A (one row for each element)
	A=np.zeros((MAX_ELEMENTS,MAX_ISOTOPES,2));

	A[0][0,:] = [100783,0.9998443]#                 % 1H
	A[0][1,:] = [201410,0.0001557]#                 % 2H
	A[1][0,:] = [100000,0.98889]#                   % 12C
	A[1][1,:] = [200336,0.01111]#                   % 13C
	A[2][0,:] = [100307,0.99634]#                   % 14N
	A[2][1,:] = [200011,0.00366]#                   % 15N
	A[3][0,:] = [99492,0.997628]#                  % 16O
	A[3][1,:] = [199913,0.000372]#                  % 17O
	A[3][2,:] = [299916,0.002000]#                  % 18O
	A[4][0,:] = [97207,0.95018]#                   % 32S
	A[4][1,:] = [197146,0.00750]#                   % 33S
	A[4][2,:] = [296787,0.04215]#                   % 34S
	A[4][3,:] = [496708,0.00017]#                   % 36S
	A[5][0,:] = [97376,1.0]# Phosphorous
	A[6][0,:] = [100783,1.0-DAbund]#                 % 1H
	A[6][1,:] = [201410,DAbund]#                 % 2H
	A[7][0,:] = [100000,1.00000]#                   % for shifting mass so that Mmi is
	#                                             % near left limit of window
	mass_removed_vec = [0,11,13,15,31,30,0,-1]
	monoisotopic = 0.0
	for i,e in enumerate(fVec):
		monoisotopic = monoisotopic + ( (mass_removed_vec[i]*scaleFactor+A[i][0,0])*e / scaleFactor)

	Mmi=np.array([np.round(100783*R), np.round(100000*R),\
	             np.round(100307*R), np.round(99492*R), np.round(97207*R), np.round(97376*R), np.round(100783*R), 0])*M#  % (Virtual) monoisotopic mass in new units
	Mmi = Mmi.sum()
	#% mass shift so Mmi is in left limit of window:
	#print "Mmi",Mmi
	#print "Window", WINDOW_SIZE
	FOLDED=np.floor(Mmi/(WINDOW_SIZE-1))+1#  % folded FOLDED times (always one folding due to shift below)

	#% shift distribution to 1 Da from lower window limit:
	M[MAX_ELEMENTS-1]=np.ceil(((WINDOW_SIZE-1)-np.mod(Mmi,WINDOW_SIZE-1)+np.round(100000*R))*RESOLUTION)
	MASS_REMOVED=np.array(mass_removed_vec)*M#';  % correction for 'virtual' elements and mass shift
	MASS_REMOVED = MASS_REMOVED.sum()

	ptA=np.ones(WINDOW_SIZE);
	t_fft=0
	t_mult=0

	for i in xrange(MAX_ELEMENTS):
	    tA=np.zeros(WINDOW_SIZE)
	    for j in xrange(MAX_ISOTOPES):
	        if A[i][j,0] != 0:
	            tA[np.round(A[i][j,0]*R)]=A[i][j,1]#;  % put isotopic distribution in tA

	    tA=F.fft(tA) # FFT along elements isotopic distribution  O(nlogn)
	    tA=tA**M[i]#  % O(n)
	    ptA = ptA*tA#  % O(n)#this is where it is messing UP

	ptA=F.ifft(ptA).real#;  % O(nlogn)

	start = (FOLDED*(WINDOW_SIZE-1)+1)*RESOLUTION+MASS_REMOVED,(FOLDED+1)*(WINDOW_SIZE-1)*RESOLUTION+MASS_REMOVED
	stop = WINDOW_SIZE - 1

	MA=np.linspace((FOLDED*(WINDOW_SIZE-1)+1)*RESOLUTION+MASS_REMOVED,(FOLDED+1)*(WINDOW_SIZE-1)*RESOLUTION+MASS_REMOVED, WINDOW_SIZE-1)

	ind=np.where(ptA>CUTOFF)[0]

	x = MA[ind]
	y = ptA[ind]

	for i,xi in enumerate(x):
		x[i] = monoisotopic + (i*1.003355)


	return x,y,monoisotopic
Exemple #35
0
def main():
    parser = ArgumentParser(conflict_handler="resolve")
    parser.add_argument("-N", "--nsamples", type=int, default=2000,
                      help="Set the number of samples to process [default=%(default)r]")
    parser.add_argument("-S", "--sps", type=int, default=4,
                      help="Set the samples per symbol [default=%(default)r]")
    parser.add_argument("-r", "--rolloff", type=eng_float, default=0.35,
                      help="Set the rolloff factor [default=%(default)r]")
    parser.add_argument("-W", "--bandwidth", type=eng_float, default=2*numpy.pi/100.0,
                      help="Set the loop bandwidth (PFB) or gain (M&M) [default=%(default)r]")
    parser.add_argument("-n", "--ntaps", type=int, default=45,
                      help="Set the number of taps in the filters [default=%(default)r]")
    parser.add_argument("--noise", type=eng_float, default=0.0,
                      help="Set the simulation noise voltage [default=%(default)r]")
    parser.add_argument("-f", "--foffset", type=eng_float, default=0.0,
                      help="Set the simulation's normalized frequency offset (in Hz) [default=%(default)r]")
    parser.add_argument("-t", "--toffset", type=eng_float, default=1.0,
                      help="Set the simulation's timing offset [default=%(default)r]")
    parser.add_argument("-p", "--poffset", type=eng_float, default=0.0,
                      help="Set the simulation's phase offset [default=%(default)r]")
    parser.add_argument("-M", "--mode", type=int, default=0,
                      help="Set the recovery mode (0: polyphase, 1: M&M) [default=%(default)r]")
    args = parser.parse_args()

    # Adjust N for the interpolation by sps
    args.nsamples = args.nsamples // args.sps

    # Set up the program-under-test
    put = example_timing(args.nsamples, args.sps, args.rolloff,
                         args.ntaps, args.bandwidth, args.noise,
                         args.foffset, args.toffset, args.poffset,
                         args.mode)
    put.run()

    if args.mode == 0:
        data_src = numpy.array(put.vsnk_src.data()[20:])
        data_clk = numpy.array(put.vsnk_clk.data()[20:])

        data_err = numpy.array(put.vsnk_err.data()[20:])
        data_rat = numpy.array(put.vsnk_rat.data()[20:])
        data_phs = numpy.array(put.vsnk_phs.data()[20:])

        f1 = pyplot.figure(1, figsize=(12,10), facecolor='w')

        # Plot the IQ symbols
        s1 = f1.add_subplot(2,2,1)
        s1.plot(data_src.real, data_src.imag, "bo")
        s1.plot(data_clk.real, data_clk.imag, "ro")
        s1.set_title("IQ")
        s1.set_xlabel("Real part")
        s1.set_ylabel("Imag part")
        s1.set_xlim([-2, 2])
        s1.set_ylim([-2, 2])

        # Plot the symbols in time
        delay = put.delay
        m = len(data_clk.real)
        s2 = f1.add_subplot(2,2,2)
        s2.plot(data_src.real, "bs", markersize=10, label="Input")
        s2.plot(data_clk.real[delay:], "ro", label="Recovered")
        s2.set_title("Symbols")
        s2.set_xlabel("Samples")
        s2.set_ylabel("Real Part of Signals")
        s2.legend()

        # Plot the clock recovery loop's error
        s3 = f1.add_subplot(2,2,3)
        s3.plot(data_err, label="Error")
        s3.plot(data_rat, 'r', label="Update rate")
        s3.set_title("Clock Recovery Loop Error")
        s3.set_xlabel("Samples")
        s3.set_ylabel("Error")
        s3.set_ylim([-0.5, 0.5])
        s3.legend()

        # Plot the clock recovery loop's error
        s4 = f1.add_subplot(2,2,4)
        s4.plot(data_phs)
        s4.set_title("Clock Recovery Loop Filter Phase")
        s4.set_xlabel("Samples")
        s4.set_ylabel("Filter Phase")


        diff_taps = put.dtaps
        ntaps = len(diff_taps[0])
        nfilts = len(diff_taps)
        t = numpy.arange(0, ntaps*nfilts)

        f3 = pyplot.figure(3, figsize=(12,10), facecolor='w')
        s31 = f3.add_subplot(2,1,1)
        s32 = f3.add_subplot(2,1,2)
        s31.set_title("Differential Filters")
        s32.set_title("FFT of Differential Filters")

        for i,d in enumerate(diff_taps):
            D = 20.0*numpy.log10(1e-20+abs(numpy.fft.fftshift(fftpack.fft(d, 10000))))
            s31.plot(t[i::nfilts].real, d, "-o")
            s32.plot(D)
        s32.set_ylim([-120, 10])

    # If testing the M&M clock recovery loop
    else:
        data_src = numpy.array(put.vsnk_src.data()[20:])
        data_clk = numpy.array(put.vsnk_clk.data()[20:])

        data_err = numpy.array(put.vsnk_err.data()[20:])

        f1 = pyplot.figure(1, figsize=(12,10), facecolor='w')

        # Plot the IQ symbols
        s1 = f1.add_subplot(2,2,1)
        s1.plot(data_src.real, data_src.imag, "o")
        s1.plot(data_clk.real, data_clk.imag, "ro")
        s1.set_title("IQ")
        s1.set_xlabel("Real part")
        s1.set_ylabel("Imag part")
        s1.set_xlim([-2, 2])
        s1.set_ylim([-2, 2])

        # Plot the symbols in time
        s2 = f1.add_subplot(2,2,2)
        s2.plot(data_src.real, "bs", markersize=10, label="Input")
        s2.plot(data_clk.real, "ro", label="Recovered")
        s2.set_title("Symbols")
        s2.set_xlabel("Samples")
        s2.set_ylabel("Real Part of Signals")
        s2.legend()

        # Plot the clock recovery loop's error
        s3 = f1.add_subplot(2,2,3)
        s3.plot(data_err)
        s3.set_title("Clock Recovery Loop Error")
        s3.set_xlabel("Samples")
        s3.set_ylabel("Error")

    pyplot.show()