Пример #1
0
def build_cwt(timeseries,
              max_scale=256,
              mother_freq=2,
              Norm=True,
              fmin=1000.0,
              fmax=4096,
              maplen=2048):

    # Make sure the timeseries peaks in the middle of the map
    paddata = np.zeros(maplen)
    peakidx = np.argmax(timeseries.data)
    paddata[0.5 * maplen - peakidx:0.5 * maplen] = timeseries.data[:peakidx]
    paddata[0.5 * maplen:0.5 * maplen + len(timeseries.data) -
            peakidx] = timeseries.data[peakidx:]

    timeseries = pycbc.types.TimeSeries(paddata, delta_t=timeseries.delta_t)

    sample_rate = 1. / timeseries.delta_t

    # Range of wavelet scales we're interested in
    scales = 1 + np.arange(max_scale)
    #scales = np.logspace(0,np.log10(max_scale),max_scale)

    # Construct the 'mother wavelet'; we'll begin using a Morlet wavelet
    # (sine-Gaussian) but we should/could investigate others
    # Could also experiment with values of f0.  See cwt.Morlet for info

    mother_wavelet = cwt.Morlet(len_signal = \
            len(timeseries), scales = scales,
            sampf=sample_rate, f0=mother_freq)

    # Compute the CWT
    wavelet = cwt.cwt(timeseries.data, mother_wavelet)

    # Take the absolute values of coefficients
    tfmap = np.abs(wavelet.coefs)

    # Reduce to useful frequencies
    freqs = sample_rate * wavelet.motherwavelet.fc \
            / wavelet.motherwavelet.scales
    tfmap[(freqs < fmin) + (freqs > fmax), :] = 0.0

    # Normalise
    tfmap /= max(map(max, abs(wavelet.coefs)))

    # Return a dictionary
    timefreq = dict()
    timefreq['analysed_data'] = timeseries
    timefreq['map'] = tfmap
    timefreq['times'] = timeseries.sample_times.data
    timefreq['frequencies'] = freqs
    timefreq['scales'] = scales
    timefreq['mother_wavelet'] = mother_wavelet
    timefreq['image_shape'] = np.shape(tfmap)

    return timefreq
Пример #2
0
data = noisysignal.data.data[startidx:startidx+400]
#data = noiselesssignal.data.data[startidx:startidx+512]
data_noisefree = noiselesssignal.data.data[startidx:startidx+400]

motherfreq = 1.5
scalerange = motherfreq/(np.array([10,0.5*sample_rate])*(1.0/sample_rate))

scales = np.arange(scalerange[1],scalerange[0])

mother_wavelet = cwt.Morlet(len_signal = len(data), scales = scales,
        sampf=sample_rate, f0=motherfreq)

#mother_wavelet = cwt.SDG(len_signal = len(data), scales = scales, normalize = True,
#        fc = 'center')

wavelet = cwt.cwt(data, mother_wavelet)

# --- Plotting

# convert to pseudo frequency
freqs = scale2hertz(mother_wavelet.fc, scales, sample_rate)

peaktime = np.argmax(abs(data_noisefree))/16384.
time = np.arange(0, len(data)/16384.0, 1.0/16384) - peaktime

#collevs=np.linspace(0, max(map(max,abs(wavelet.coefs)**2)), 100)

fpeakmin=2000.0
collevs=np.linspace(0, 1*max(wavelet.get_wps()[freqs>fpeakmin]), 100)

fig, ax_cont = pl.subplots(figsize=(10,8))
Пример #3
0
import matplotlib.pyplot as plt
import cwt


fs = 1e3
t = np.linspace(0, 1, fs+1, endpoint=True)
x = np.cos(2*np.pi*32*t) * np.logical_and(t >= 0.1, t < 0.3) + np.sin(2*np.pi*64*t) * (t > 0.7)
wgnNoise = 0.05 * np.random.standard_normal(t.shape)
x += wgnNoise
c, f = cwt.cwt(x, 'morl', sampling_frequency=fs)

fig, ax = plt.subplots()
ax.imshow(np.absolute(wt), aspect='auto')
Пример #4
0
#
# Construct CWT (continuous wavelet transform) using pyCWT module
#

# Range of wavelet scales we're interested in
scales = 1+np.arange(256)

# Construct the 'mother wavelet'; we'll begin using a Morlet wavelet
# (sine-Gaussian) but we should/could investigate others
# Could also experiment with values of f0.  See cwt.Morlet for info
mother_wavelet = cwt.Morlet(len_signal = len(signal), scales = scales,
        sampf=sample_rate, f0=1)

# Compute the CWT
wavelet = cwt.cwt(signal.data, mother_wavelet)

# ------------------------
#
# --- Plot The Results --- 
# 
# ------------------------

# Compute the center frequencies corresponding to each scale
freqs = 0.5 * sample_rate * wavelet.motherwavelet.fc / wavelet.motherwavelet.scales

# Choose the number of colour levels to plo
collevs=np.linspace(0, max(map(max,abs(wavelet.coefs)**2)), 100)

# Open the figure
fig, ax_cont = pl.subplots(figsize=(10,5))
Пример #5
0
def print_eic_ms(mzML_file):

    basename0=os.path.basename(mzML_file)
    print(basename0)
    ms1_scans=['MS1']
    ms2_scans=['MS2']

    tree=ET.parse(open(mzML_file,'rb'))

    for element in tree.iter(tag='{http://psi.hupo.org/ms/mzml}spectrum'):
        if element.findtext(".//*{http://psi.hupo.org/ms/mzml}binary"):
            mslevel_elem=element.find("*[@accession='MS:1000511']")
            if mslevel_elem is None:
                ref_id=element.find("{http://psi.hupo.org/ms/mzml}referenceableParamGroupRef").attrib['ref']
                mslevel_elem=(tree.find(".//*{http://psi.hupo.org/ms/mzml}referenceableParamGroup[@id='"+ref_id+"']/*[@accession='MS:1000511']"))
                centroid_elem=(tree.find(".//*{http://psi.hupo.org/ms/mzml}referenceableParamGroup[@id='"+ref_id+"']/*[@accession='MS:1000127']"))
            else:
                centroid_elem=element.find("*[@accession='MS:1000127']")
            if centroid_elem is None:
                print("error: profile mode!")
                sys.exit()
            mslevel=mslevel_elem.attrib['value']
            if mslevel=='1':
                ms1_scans.append(store_scan(element))
            elif mslevel=='2':
                ...
            else:
                sys.exit()
        element.clear()
    del element
    del tree

    print(len(ms1_scans)-1,' MS1 scans')


    def mz_slice(ms_scans):
        rtdict={rt:n for n,rt in enumerate(sorted({sc.rt for sc in ms_scans[1:]}))}
        ofile.write('scan '+ms_scans[0]+'\n')
        ofile.write('\t'.join([str(x) for x in rtdict])+'\n')
        data_points=[Point(scan.rt,mz,i) for scan in ms_scans[1:] for mz,i in zip(scan.mz,scan.I)]
        data_points.sort(key=operator.attrgetter('mz'))


        mzlist=array('d',(mz for _,mz,_ in data_points))
        for ent in lib_ent:
            for ii in [-.03,-.015,0]:
                mbd=ent.Mmass+ii
                pos0 = bisect_left(mzlist, mbd)
                pos1 = bisect_left(mzlist, mbd+.03)
                if ent.rt!='NA':
                    dp_sub=[x for x in data_points[pos0:pos1] if abs(ent.rt-x[0])<RT_shift+30]
                else:
                    dp_sub=data_points[pos0:pos1]
                if len(dp_sub)>min_group_size and max(I for _,_,I in dp_sub)>min_highest_I:
                    eic_dict=dict() # highest intensity in this m/z range
                    for rt,mz,I in dp_sub:
                        if rt not in eic_dict or eic_dict[rt][1]<I:
                            eic_dict[rt]=(mz,I)
                    if min_group_size<=len({r for r,(_,i) in eic_dict.items() if i>group_I_threshold}):
                        for rt,mz_i in sorted(eic_dict.items()):
                            ofile.write('{}\t{}\t{}\n'.format(rt,*mz_i))
                        ofile.write('-\n')
        ofile.write('\n')


    with open('eic_'+basename0+'.txt','w') as ofile:
        mz_slice(ms1_scans)

    cwt.cwt(mzML_file)
Пример #6
0
motherfreq = 2
scalerange = motherfreq / (np.array([10, 0.5 * sample_rate]) *
                           (1.0 / sample_rate))

scales = np.arange(scalerange[1], scalerange[0])

mother_wavelet = cwt.Morlet(len_signal=len(data),
                            scales=scales,
                            sampf=sample_rate,
                            f0=motherfreq)

#mother_wavelet = cwt.SDG(len_signal = len(data), scales = scales, normalize = True,
#        fc = 'center')

wavelet = cwt.cwt(data, mother_wavelet)

# --- Plotting

# convert to pseudo frequency
freqs = scale2hertz(mother_wavelet.fc, scales, sample_rate)

#collevs=np.linspace(0, max(map(max,abs(wavelet.coefs)**2)), 100)

fpeakmin = 2000.0
collevs = np.linspace(0, 5 * max(wavelet.get_wps()[freqs > fpeakmin]), 100)

fig, ax_cont = pl.subplots(figsize=(10, 5))
c = ax_cont.contourf(time,
                     freqs,
                     np.abs(wavelet.coefs)**2,
Пример #7
0
def _padded_cwt(params, dt, dj, s0, J,mother, padding_len):
    padded = np.concatenate([params,params,params])
    #padded = np.pad(params, padding_len, mode='edge')
    wavelet_matrix, scales, freqs, coi, fft, fftfreqs = cwt.cwt(padded, dt, dj, s0, J,mother)
    wavelet_matrix = _unpad(wavelet_matrix, len(params)) 
    return (wavelet_matrix, scales, freqs, coi, fft, fftfreqs)