def calc_dft(sig_src_arr): sig_dest_imx_arr = [None] * int((len(sig_src_arr) / 2)) sig_dest_rex_arr = [None] * int((len(sig_src_arr) / 2)) sig_dest_mag_arr = [None] * int((len(sig_src_arr) / 2)) for j in range(int(len(sig_src_arr) / 2)): sig_dest_rex_arr[j] = 0 sig_dest_imx_arr[j] = 0 for k in range(int(len(sig_src_arr) / 2)): for i in range(len(sig_src_arr)): sig_dest_rex_arr[k] = sig_dest_rex_arr[k] + sig_src_arr[ i] * math.cos(2 * math.pi * k * i / len(sig_src_arr)) sig_dest_imx_arr[k] = sig_dest_imx_arr[k] - sig_src_arr[ i] * math.sin(2 * math.pi * k * i / len(sig_src_arr)) for x in range(int(len(sig_src_arr) / 2)): sig_dest_mag_arr[x] = math.sqrt( math.pow(sig_dest_rex_arr[x], 2) + math.pow(sig_dest_imx_arr[x], 2)) style.use('ggplot') f, plt_arr = plt.subplots(1, sharex=True) f.suptitle("Discrete Fourier Transform (DFT)") plt.xlim(0, 500) plt.ylim(0, 20000) plt.stem(sig_dest_mag_arr)
def matlab_fourier_anal(data, sample_rate = 1.0): n = data.shape[0] t = np.arange(n) P.figure() P.plot(t/sample_rate,data) P.xlabel('Time Units') P.ylabel('Data Magnitude') Y = fftpack.fft(data); freqs = np.arange(n/2.0) * sample_rate / n power = np.abs(Y[:n/2.0]) P.figure() markerline, stemlines, baseline = P.stem(freqs, power, '--') P.setp(markerline, 'markerfacecolor', 'b') # P.setp(baseline, 'color','r', 'linewidth', 2) P.xlabel('Cycles/ Unit Time') P.ylabel('Power') P.title('Periodogram') period = 1. / freqs k = np.arange(50) f = k / float(n) power2 = power[k]; P.figure() markerline, stemlines, baseline = P.stem(f, power2, '--') P.setp(markerline, 'markerfacecolor', 'b') P.setp(baseline, 'color','r', 'linewidth', 2) P.xlabel('Unit Time / Cycle') P.ylabel('Power') P.title('Periodogram: First 50 periods')
def Skew_Tent_map_reseed(init, b, seed_funct, seed_step, steps): xs = np.arange(steps) ys = np.zeros((steps)) ss = np.zeros((steps)) zs = seed_funct(xs) seedxs = [] seedys = [] sym = "" ys[0] = init for i in range(1, steps): y = ys[i - 1] if (i % seed_step == 0): ys[i] = seed_funct(i) seedxs.append([i]) seedys.append([ys[i]]) elif (y <= 1.0 and y >= 0.0): ys[i] = np.exp(b) * y sym += "A" elif (y > 1.0 and y <= (1 + np.exp(-0.5 * b))): ys[i] = -1 * np.exp(1.5 * b) * y + (np.exp(b) + np.exp(1.5 * b)) sym += "B" elif (y > (1 + np.exp(-0.5 * b))): ys[i] = np.exp(b) * y - (np.exp(0.5 * b) + np.exp(b)) sym += "C" if (ys[i] >= 0.5): ss[i] = 1.0 print(sym) pl.plot(xs, ys) #pl.plot(xs,zs) pl.plot(xs, ss) pl.stem(seedxs, seedys, linefmt='r') pl.show()
def display_fit(xs, target, method, color=None, acronym=None, xmax=None, linewidth=2): if not hasattr(method, "__iter__"): method = (method,) if not color is None: color = (color,) if not acronym is None: acronym = (acronym,) if not xs.shape[0] == 1: raise ValueError("univariate data expected") if xmax == None: xmax = int(np.max(np.abs(xs.squeeze()))) + 1 x = np.linspace(-xmax, xmax, 2 * xmax / 0.01) x = np.reshape(x, (1, x.size)) fits = [m.fit(x) for m in method] if color is None: for fit in fits: plt.plot(x.squeeze(), fit, linewidth=linewidth) else: for fit, col in zip(fits, color): plt.plot(x.squeeze(), fit, col, linewidth=linewidth) if not acronym is None: plt.legend(acronym) target_xs = np.exp(target(xs.squeeze())) target_x = np.exp(target(x.squeeze())) plt.stem(xs.squeeze(), target_xs, linefmt="k-", markerfmt="ko", basefmt="k-") plt.plot(x.squeeze(), target_x, "k") x0, x1, y0, y1 = plt.axis() plt.plot((x0, x1), (0, 0), "k") plt.show()
def plot(self, marker='o', color='red', m=0, M=6000): """Plots the position / height of the peaks in the well .. plot:: :include-source: from fragment_analyser import Line, fa_data l = Line(fa_data("alternate/peaktable.csv")) well = l.wells[0] well.plot() """ import pylab if len(self.df) == 0: print("Nothing to plot (no peaks)") return x = self.df['Size (bp)'].astype(float).values y = self.df['RFU'].astype(float).values pylab.stem(x, y, marker=marker, color=color) pylab.semilogx() pylab.xlim([1, M]) pylab.ylim([0, max(y)*1.2]) pylab.grid(True) pylab.xlabel("size (bp)") pylab.ylabel("RFU") return x, y
def plot_weights(self): import pylab x,w = zip(*self.distribution) pylab.stem(x,100*numpy.array(w)) pylab.title('Weight distribution') pylab.xlabel(self.P.name) pylab.ylabel('Percentage')
def plot_weights(self): import pylab x, w = zip(*self.distribution) pylab.stem(x, 100*numpy.array(w)) pylab.title('Weight distribution') pylab.xlabel(self.P.name) pylab.ylabel('Percentage')
def plot(self, marker='o', color='red', m=0, M=6000): """Plots the position / height of the peaks in the well .. plot:: :include-source: from fragment_analyser import Line, fa_data l = Line(fa_data("alternate/peaktable.csv")) well = l.wells[0] well.plot() """ import pylab if len(self.df) == 0: print("Nothing to plot (no peaks)") return x = self.df['Size (bp)'].astype(float).values y = self.df['RFU'].astype(float).values pylab.stem(x, y, marker=marker, color=color) pylab.semilogx() pylab.xlim([1, M]) pylab.ylim([0, max(y) * 1.2]) pylab.grid(True) pylab.xlabel("size (bp)") pylab.ylabel("RFU") return x, y
def calc_dft(sig_src_arr): sig_dest_imx_arr = [None]*int((len(sig_src_arr)/2)) sig_dest_rex_arr = [None]*int((len(sig_src_arr)/2)) sig_dest_mag_arr = [None]*int((len(sig_src_arr)/2)) for j in range(int(len(sig_src_arr)/2)): sig_dest_rex_arr[j] =0 sig_dest_imx_arr[j] =0 for k in range(int(len(sig_src_arr)/2)): for i in range(len(sig_src_arr)): sig_dest_rex_arr[k] = sig_dest_rex_arr[k] + sig_src_arr[i]*math.cos(2*math.pi*k*i/len(sig_src_arr)) sig_dest_imx_arr[k] = sig_dest_imx_arr[k] - sig_src_arr[i]*math.sin(2*math.pi*k*i/len(sig_src_arr)) for x in range(int(len(sig_src_arr)/2)): sig_dest_mag_arr[x] = math.sqrt(math.pow(sig_dest_rex_arr[x],2)+math.pow(sig_dest_imx_arr[x],2)) style.use('ggplot') f,plt_arr = plt.subplots(1, sharex=True) f.suptitle("Discrete Fourier Transform (DFT)") #plt_arr[0].plot(sig_src_arr, color='red') #plt_arr[0].set_title("Input Signal",color='red') #plt_arr[1].plot(sig_dest_rex_arr, color='green') #plt_arr[1].set_title("Frequency Domain(Real part)",color='green') #plt_arr[2].plot(sig_dest_imx_arr, color='green') #plt_arr[2].set_title("Frequency Domain(Imaginary part)",color='green') #plt_arr[3].plot(sig_dest_mag_arr, color='magenta') #plt_arr[3].set_title("Frequency Domain (Magnitude))",color='magenta') plt.xlim(0,200) #plt.ylim(0,1000) plt.stem(sig_dest_mag_arr)
def decode_symbols(r, i, corr_index, r0, i0, Nbits, fs=48000, baud=300, plot=False): Ns = fs/baud r = r[corr_index:] i = i[corr_index:] r0 = r0[corr_index:] i0 = i0[corr_index:] #print len(r) #print len(r0) #print len(i0) r = r/np.max(r)*2.2 #change this 2 depending on the input amplitude i = i/np.max(i)*2.2 #change this 2 depending on the input amplitude if plot: fig = plt.figure(figsize = (16,4)) plt.plot(2*r0) plt.plot(r) plt.title('Real part, raw input and normalized') fig = plt.figure(figsize = (16,4)) plt.plot(2*i0) plt.plot(i) plt.title('Imaginary part, raw input and normalized') ####Decode idx = np.r_[Ns/2:len(r):Ns] #r = np.around(r) #i = np.around(i) r_dec = np.around(r[idx]) i_dec = np.around(i[idx]) if plot: fig = plt.figure(figsize = (16,4)) plt.plot(2*r0) plt.plot(r) plt.plot(np.around(r)) plt.stem(idx, r_dec) plt.title('Real part, decoded by sampling values as indicated') fig = plt.figure(figsize = (16,4)) plt.plot(2*i0) plt.plot(i) plt.plot(np.around(i)) plt.stem(idx, i_dec) plt.title('Imaginary part, decoded by sampling values as indicated') fig = plt.figure(figsize = (8,8)) plt.scatter(r0*2, i0*2, c='r') plt.scatter(r_dec, i_dec, c='g') plt.title('Constellation of input message vs decoded symbols') return r_dec + 1j*i_dec
def plot_reflection(self): from pylab import stem, title, xlabel, ylabel if self.reflection is not None: stem(list(range(0, len(self.reflection))), abs(self.reflection)) title('Reflection coefficient evolution') xlabel('Order') ylabel('Reflection Coefficient absolute values') else: logging.warning("Reflection coefficients not available or not yet computed.")
def print_spectrum(spectrum, filename): x = spectrum.mz y = spectrum.intensity pylab.stem(x, y, markerfmt='b,') pylab.xlabel('m/z') pylab.ylabel('Transformed intensity') pylab.grid() pylab.xlim(0.95*min(x), 1.05*max(x)) pylab.savefig(filename)
def binom(self): n = 10 k = np.arange(n + 1) pcoin = stats.binom.pmf(k, n, 0.5) pl.stem(k, pcoin, basefmt='k-') pl.margins(0, 1) pl.savefig('./task1.png') pl.show()
def plot_reflection(self): from pylab import stem, title, xlabel, ylabel if self.reflection is not None: stem(list(range(0, len(self.reflection))), abs(self.reflection)) title('Reflection coefficient evolution') xlabel('Order') ylabel('Reflection Coefficient absolute values') else: logging.warning( "Reflection coefficients not available or not yet computed.")
def plot_reflection(self): from pylab import stem, title, xlabel, ylabel if self.reflection is not None: stem(list(range(0, len(self.reflection))), abs(self.reflection)) title('Reflection coefficient evolution') xlabel('Order') ylabel('Reflection Coefficient absolute values') else: import warnings warnings.warn("""Reflection coefficients not available with the current method.""")
def nzcols_hist(P,file=None): if file==None: pylab.ion() else: pylab.ioff() nzcols = +P.nzcols Nmax = max(nzcols) y = matrix(0,(Nmax,1)) for n in nzcols: y[n-1] += 1 y = sparse(y) f = pylab.figure(); f.clf() pylab.stem(y.I+1,y.V)#; pylab.xlim(-1,Nmax+2) if file: pylab.savefig(P._pname + "_nzcols_hist.png")
def plot_spectra(self): """ Plots the original spectrum and the sum of cisoids. """ import pylab as plt plt.plot(self.psd[0], self.psd[1]) freqs = [el[0] for el in self.soc] ampls = [el[1] for el in self.soc] plt.stem(freqs, ampls) plt.xlabel(r'$f$ in Hz') plt.ylabel(r'$S(f)$') plt.show()
def fourier_analysis(sig, time_step = 1.0, top_freqs = 5, zoomed_num = 15): time_vec = np.arange(0, len(sig), time_step) sample_freq = fftpack.fftfreq(sig.size, d=time_step) sig_fft = fftpack.fft(sig) # Only take first half of sampling frequency pidxs = np.where(sample_freq > 0) freqs, power = sample_freq[pidxs], np.abs(sig_fft)[pidxs] # plot with zoomed in sub plot P.figure() P.plot(freqs, power) P.ylabel('Power') P.xlabel('Frequency [Hz]') axes = P.axes([0.3, 0.3, 0.5, 0.5]) P.title('Peak frequency') P.stem(freqs[:zoomed_num], power[:zoomed_num]) #P.setp(axes, yticks=[]) #P.savefig('source/fftpack-frequency.png') # Find top x frequencies to use in reconstruction full_sort_idx = power.argsort() find_idx = full_sort_idx >= top_freqs sorted_power = power[sort_idx][::-1] # Sort decending component_freqs = freqs[sort_idx[:top_freqs]] # copy fft reduced_sig_fft = sig_fft.copy() # set all values not in component freqs to 0 L = np.array(reduced_sig_fft, dtype = bool) L[sort_idx[:top_freqs]] = False reduced_sig_fft[L] = 0 # Reconstruct signal reconstruct_sig = fftpack.ifft(reduced_sig_fft) # Plot original and reconstructed signal P.figure() P.plot(time_vec, sig) P.plot(time_vec, reconstruct_sig, linewidth=2) P.ylabel('Amplitude') P.xlabel('Time [s]') return sig_fft, reduced_sig_fft, reconstruct_sig, freqs, power, component_freqs
def demo(text=None): from nltk.corpus import brown import pylab tt = TextTilingTokenizer(demo_mode=True) if text is None: text = brown.raw()[:10000] s, ss, d, b = tt.tokenize(text) pylab.xlabel("Sentence Gap index") pylab.ylabel("Gap Scores") pylab.plot(range(len(s)), s, label="Gap Scores") pylab.plot(range(len(ss)), ss, label="Smoothed Gap scores") pylab.plot(range(len(d)), d, label="Depth scores") pylab.stem(range(len(b)), b) pylab.legend() pylab.show()
def demo(text=None): from nltk.corpus import brown import pylab tt=TextTilingTokenizer(demo_mode=True) if text is None: text=brown.raw()[:10000] s,ss,d,b=tt.tokenize(text) pylab.xlabel("Sentence Gap index") pylab.ylabel("Gap Scores") pylab.plot(range(len(s)), s, label="Gap Scores") pylab.plot(range(len(ss)), ss, label="Smoothed Gap scores") pylab.plot(range(len(d)), d, label="Depth scores") pylab.stem(range(len(b)),b) pylab.legend() pylab.show()
def main_Show(self, LIST, name, Num): fix = np.ones(Num) y = [] x = [] T = [] for i in range(Num): x.append(i + 1) y.append(LIST[i]) markerline, stemlines, baseline = pylab.stem(x, y, bottom=0.5) pylab.setp(markerline, 'markerfacecolor', 'b') pylab.setp(baseline, 'color', 'g', 'linewidth', 2) pylab.lines = pylab.plot(x, 0.6 * fix, x, 0.4 * fix) pylab.setp(pylab.lines, 'color', 'r', 'linewidth', 2) pylab.xlabel('Examination') pylab.ylabel('Discrimination Level') #xticks(range(len(x)), T, size='small') pylab.savefig('chart/{:>}.png'.format(name)) pylab.show() lines = [] pylab.clf()
def plot_inflections(x, y): """ Plot inflection points in a curve. """ m = (y[2:] - y[:-2]) / (x[2:] - x[:-2]) b = y[2:] - m * x[2:] delta = y[1:-1] - (m * x[1:-1] + b) t = linspace(x[0], x[-1], 400) import pylab ax1 = pylab.subplot(211) pylab.plot(t, monospline(x, y, t), '-b', x, y, 'ob') pylab.subplot(212, sharex=ax1) delta_x = x[1:-1] pylab.stem(delta_x, delta) pylab.plot(delta_x[delta < 0], delta[delta < 0], 'og') pylab.axis([x[0], x[-1], min(min(delta), 0), max(max(delta), 0)])
def hist_mtx(mtx, tstr=''): """ Given a piano-roll matrix, 128 MIDI piches x beats, plot the pitch class histogram """ i_min, i_max = np.where(mtx.mean(1))[0][[0,-1]] P.figure(figsize=(14.5,8)) P.stem(np.arange(i_max+1-i_min),mtx[i_min:i_max+1,:].sum(1)) ttl = 'Note Frequency' if tstr: ttl+=': '+tstr P.title(ttl,fontsize=16) t=P.xticks(np.arange(0,i_max+1-i_min,3),pc_labels[i_min:i_max+1:3],fontsize=14) P.xlabel('Pitch Class', fontsize=14) P.ylabel('Frequency', fontsize=14) ax = P.axis() P.axis(xmin=-0.5) P.grid()
def plot_inflections(x,y): """ Plot inflection points in the spline curve. """ m = (y[2:]-y[:-2])/(x[2:]-x[:-2]) b = y[2:] - m*x[2:] delta = y[1:-1] - (m*x[1:-1] + b) t = linspace(x[0],x[-1],400) import pylab ax1=pylab.subplot(211) pylab.plot(t,monospline(x,y,t),'-b',x,y,'ob') pylab.subplot(212, sharex=ax1) delta_x = x[1:-1] pylab.stem(delta_x,delta) pylab.plot(delta_x[delta<0],delta[delta<0],'og') pylab.axis([x[0],x[-1],min(min(delta),0),max(max(delta),0)])
def redraw(self): self.clearStems() for i in range(0, 3): axes = pylab.subplot('13' + str(1 + i)) if (self.mode == "phase"): self.plots[i][0].set_ydata( scipy.angle(self.fts[self.index + i])) else: mag = abs(self.fts[self.index + i]) self.plots[i][0].set_ydata(mag) peak = max(mag) peakInd = list(mag).index(peak) stem_marker, stem_lines, stem_base = pylab.stem([peakInd], [peak], 'r-', 'ro') self.stemMarkers.append(stem_marker) self.stemBase.append(stem_base) self.stemLines.append(stem_lines) xres = self.fov / self.xsize pylab.xlabel(self.axis[i] + ':' + '{0:.3}'.format(xres * (peakInd - len(mag) / 2)) + ' mm') pylab.draw()
def impz(b,a=1): impulse = np.repeat(0.,50); impulse[0] =1. x = np.arange(0,50) response = signal.lfilter(b,a,impulse) pl.subplot(211) pl.stem(x, response) pl.ylabel('Amplitude') pl.xlabel(r'n (samples)') pl.title(r'Impulse response') pl.subplot(212) step = np.cumsum(response) pl.stem(x, step) pl.ylabel('Amplitude') pl.xlabel(r'n (samples)') pl.title(r'Step response') pl.subplots_adjust(hspace=0.5)
def impz(b,a=1): l = len(b) impulse = numpy.repeat(0.,l); impulse[0] =1. x = numpy.arange(0,l) response = scipy.signal.lfilter(b,a,impulse) pylab.subplot(211) pylab.stem(x, response) pylab.ylabel('Amplitude') pylab.xlabel(r'n (samples)') pylab.title(r'Impulse response') pylab.subplot(212) step = numpy.cumsum(response) pylab.stem(x, step) pylab.ylabel('Amplitude') pylab.xlabel(r'n (samples)') pylab.title(r'Step response') pylab.subplots_adjust(hspace=0.5)
def plot_spectra(self): """ Plots the original Spectrum and the sum of sinusoids. """ import matplotlib as mp mp.rc('font', family='serif', size=22) import pylab as plt freqs = [f[0] for f in self.sos] negfreqs = [-f[0] for f in self.sos] # convert the amplitudes of the sinusoids to a psd ampls = [(a[1] / 2) ** 2 for a in self.sos] plt.stem(freqs, ampls) plt.stem(negfreqs, ampls) plt.xlim(1.5 * negfreqs[-1], 1.5 * freqs[-1]) plt.ylim(0, 1.5 * max(ampls)) plt.xlabel(r'$f$ in Hz') plt.ylabel(r'$\| S(f) \|$') plt.show()
def graficarConvolucion(): limiteSup = 5 limiteInf = -5 imp = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11] print type(imp) try: print "graficarConvolucion impulso" X = np.linspace(limiteInf, limiteSup, 11, endpoint=True) Y = np.array(imp) pl.stem(X, imp) #pl.step(X,imp) #fig, ax = plt.subplots() #ax.stem(X, Y) #plt.show() pl.show() except Exception as ex: print "Error inesperado en gaficarConvolucion(): ", type(ex)
def impz(b,a=1): ''' #Plot step and impulse response from http://mpastell.com/2010/01/18/fir-with-scipy/ ''' l = len(b) impulse = pylab.repeat(0.,l); impulse[0] =1. x = numpy.arange(0,l) response = signal.lfilter(b,a,impulse) pylab.subplot(211) pylab.stem(x, response) pylab.ylabel('Amplitude') pylab.xlabel(r'n (samples)') pylab.title(r'Impulse response') pylab.subplot(212) step = numpy.cumsum(response) pylab.stem(x, step) pylab.ylabel('Amplitude') pylab.xlabel(r'n (samples)') pylab.title(r'Step response') pylab.subplots_adjust(hspace=0.5)
def test_volterra(): f = array([-1200., -1000., 1000., 1200.]) v = array([2., 2., 2., 2.]) w = Waveform(f, v) v1, v2, v31, v32 = lna_volterra(w) pylab.subplot(4, 1, 1) pylab.stem(v1.get_x()[0], v1.get_y()) pylab.subplot(4, 1, 2) pylab.stem(v2.get_x()[0], v2.get_y()) pylab.subplot(4, 1, 3) pylab.stem(v31.get_x()[0], v31.get_y()) pylab.subplot(4, 1, 4) pylab.stem(v32.get_x()[0], v32.get_y()) pylab.show()
def test_volterra(): f=array([-1200.,-1000.,1000.,1200.]) v=array([2.,2.,2.,2.]) w=Waveform(f,v) v1,v2,v31,v32=lna_volterra(w) pylab.subplot(4,1,1) pylab.stem(v1.get_x()[0],v1.get_y()) pylab.subplot(4,1,2) pylab.stem(v2.get_x()[0],v2.get_y()) pylab.subplot(4,1,3) pylab.stem(v31.get_x()[0],v31.get_y()) pylab.subplot(4,1,4) pylab.stem(v32.get_x()[0],v32.get_y()) pylab.show()
def _add_stems_to_plot(interval, stem_bed, samples, plot): stems = _get_stems_by_callers(stem_bed.tabix_intervals(interval)) callers = sorted(stems.keys()) caller_colormap = _get_caller_colormap(callers) caller_heights = _get_caller_heights(callers, plot) for caller in callers: stem_color = caller_colormap[caller] caller_stems = stems[caller] stem_heights = list(repeat(caller_heights[caller], len(caller_stems))) markerline, _, baseline = stem(caller_stems, stem_heights, "-.", label=caller) setp(markerline, "markerfacecolor", stem_color) setp(baseline, "color", "r", "linewidth", 0) plt.legend()
def view_filter(h, fp=None, fs=None): '''view filter''' w, H = signal.freqz(h, 1) H_phase = pl.unwrap([pl.degrees(cmath.phase(H[i])) for i in range(len(H))], 180) H = 20 * pl.log10(abs(H[:])) x = range(0, len(h)) step = pl.cumsum(h) pl.figure(figsize=(16, 6.6), dpi=80) pl.subplot(221) pl.stem(x, h) pl.ylabel('Amplitude') pl.xlabel(r'n (samples)') pl.title(r'Impulse response') pl.text(0.2, 0.7, 'N_taps = {0}'.format(len(h))) pl.subplot(222) pl.stem(x, step) pl.ylabel('Amplitude') pl.xlabel(r'n (samples)') pl.title(r'Step response') pl.subplot(223) pl.plot(w / (2.0 * pl.pi), H) pl.ylabel('Magnitude (db)') pl.xlabel(r'Normalized Frequency (x$\pi$rad/sample)') pl.title(r'Frequency response') if fp != None: pl.axvline(fp, linewidth=1, color='k', ls='-') if fs != None: pl.axvline(fs, linewidth=1, color='k', ls='-') pl.subplot(224) pl.plot(w / (2.0 * pl.pi), H_phase) pl.ylabel('Phase (radians)') pl.xlabel(r'Normalized Frequency (Hz)') pl.title(r'Phase response')
def impz(b, a=1): ''' #Plot step and impulse response from http://mpastell.com/2010/01/18/fir-with-scipy/ ''' l = len(b) impulse = pylab.repeat(0., l) impulse[0] = 1. x = numpy.arange(0, l) response = signal.lfilter(b, a, impulse) pylab.subplot(211) pylab.stem(x, response) pylab.ylabel('Amplitude') pylab.xlabel(r'n (samples)') pylab.title(r'Impulse response') pylab.subplot(212) step = numpy.cumsum(response) pylab.stem(x, step) pylab.ylabel('Amplitude') pylab.xlabel(r'n (samples)') pylab.title(r'Step response') pylab.subplots_adjust(hspace=0.5)
def view_filter(h, fp=None, fs=None): '''view filter''' w, H = signal.freqz(h,1) H_phase = pl.unwrap([pl.degrees(cmath.phase(H[i])) for i in range(len(H))], 180) H = 20 * pl.log10 (abs(H[:])) x = range(0,len(h)) step = pl.cumsum(h) pl.figure(figsize=(16, 6.6), dpi=80) pl.subplot(221) pl.stem(x, h) pl.ylabel('Amplitude') pl.xlabel(r'n (samples)') pl.title(r'Impulse response') pl.text(0.2, 0.7, 'N_taps = {0}'.format(len(h))) pl.subplot(222) pl.stem(x, step) pl.ylabel('Amplitude') pl.xlabel(r'n (samples)') pl.title(r'Step response') pl.subplot(223) pl.plot(w/(2.0*pl.pi), H) pl.ylabel('Magnitude (db)') pl.xlabel(r'Normalized Frequency (x$\pi$rad/sample)') pl.title(r'Frequency response') if fp != None: pl.axvline(fp, linewidth=1, color='k', ls='-') if fs != None: pl.axvline(fs, linewidth=1, color='k', ls='-') pl.subplot(224) pl.plot(w/(2.0*pl.pi), H_phase) pl.ylabel('Phase (radians)') pl.xlabel(r'Normalized Frequency (Hz)') pl.title(r'Phase response')
def _add_stems_to_plot(interval, stem_bed, samples, plot): stems = _get_stems_by_callers(stem_bed.tabix_intervals(interval)) callers = sorted(stems.keys()) caller_colormap = _get_caller_colormap(callers) caller_heights = _get_caller_heights(callers, plot) for caller in callers: stem_color = caller_colormap[caller] caller_stems = stems[caller] stem_heights = list(repeat(caller_heights[caller], len(caller_stems))) markerline, _, baseline = stem(caller_stems, stem_heights, '-.', label=caller) setp(markerline, 'markerfacecolor', stem_color) setp(baseline, 'color', 'r', 'linewidth', 0) plt.legend()
def demo(text=None): from nltk.corpus import brown import pylab tt = TextTilingTokenizer(demo_mode=True) if text is None: text = brown.raw()[:10000] s, ss, d, b = tt.tokenize(text) pylab.xlabel("Sentence Gap index") pylab.ylabel("Gap Scores") pylab.plot(range(len(s)), s, label="Gap Scores") pylab.plot(range(len(ss)), ss, label="Smoothed Gap scores") pylab.plot(range(len(d)), d, label="Depth scores") pylab.stem(range(len(b)), b) pylab.legend() pylab.show() """s = tt.tokenize(text) FILE = open("tiled","w") FILE.writelines(s) FILE.close()""" # if __name__ == '__main__': # content = open('toTile', 'r').read() # demo(content)
def main(): x = pylab.randn(100) t0 = time.clock() y1 = ks_loop(x, 0.9, 10) t_loop = time.clock() - t0 t0 = time.clock() y2 = ks(x, 0.9, 10) t_matrix = time.clock() - t0 print("Loop method took %g seconds." % t_loop) print("Matrix method took %g seconds." % t_matrix) # Make sure y1 and y2 are same within very small numeric # error. assert(pylab.sum(pylab.absolute(y1 - y2)) < 1e-10) # Plot x and y pylab.figure() pylab.subplot(211) pylab.stem(x) pylab.ylabel('x') pylab.subplot(212) pylab.stem(y2) pylab.ylabel('y') pylab.xlabel('samples') print("Generating the opening chord of Hard day's night by The Beatles ...") Fs, T, chord = generate_cord() pylab.figure() pylab.plot(pylab.arange(0.0, T, 1.0/Fs), chord) pylab.xlabel('time (sec)') pylab.title('First Chord of Hard Days Night') print("Writing the chord to chord.wav ...") C = max(pylab.absolute(chord)) scipy.io.wavfile.write("chord.wav", Fs, pylab.int16((2**15 - 1) * chord / C)) print("Done.") pylab.show()
def lollipop(x, y, color=None, lw=2, ybot=0): """Plot lollipops (o's and sticks) **Parameters:** x, y : ndarrays The data to be plotted color : any matplotlib color, optional plotting color lw : float, optional line width value in points ybot : float, optional Dummy parameter available for compatibility **Returns:** None **Example:** .. plot:: import matplotlib.pyplot as plt import numpy as np from deltasigma import lollipop t = np.arange(1, 20)*1e-3 f = 20. a = np.sin(2*np.pi*f*t) lollipop(t, a) plt.gcf().set_size_inches((8, 4)) plt.grid(True) plt.show() """ if ybot: warn('lollipop() got a non-zero ybot, but only ybot=0 is ' + \ 'supported. Setting ybot to 0.') markerline, stemlines, baseline = plt.stem(x, y, '-') if not color or color == 'None': color = stemlines[0].get_color() lolli_fmt = {'linewidth': lw, 'color': color} pop_fmt = {'mec': color, 'markerfacecolor':'None', \ 'markersize':10, 'markeredgewidth': lw*1.1} plt.setp(markerline, **pop_fmt) plt.setp(stemlines, **lolli_fmt) plt.setp(baseline, 'color','k')
def plotSignalAndRecoveredSignal(t, u, v, fig_title, spikes=False, denoised=None): """ Compare two signals and plot the difference between them. Parameters ---------- t : ndarray of floats Times (s) at which the signal is defined. u, v : ndarrays of floats Signal samples. """ p.figure(figsize=(15, 10)) p.clf() p.gcf().canvas.set_window_title(fig_title) # p.subplot(211) p.plot(t, u, 'b', label='u(t)') if (spikes): p.stem(t, v, 'r', label='u_rec(t)', use_line_collection=True) else: p.plot(t, v, 'r', label='u_rec(t)') if (denoised != None): p.plot(t, denoised, 'o', label='denoised u(t)') p.xlabel('t (s)') p.ylabel('u(t)') p.legend() p.title(fig_title) p.gca().set_xlim(min(t), max(t)) p.draw_if_interactive()
def clique_hist(P,file=None): if not P.ischordal: raise TypeError, "Nonchordal" if file==None: pylab.ion() else: pylab.ioff() V = +P.V p = chompack.maxcardsearch(V) #Vc,n = chompack.embed(V,p) symb = chompack.symbolic(V,p) #D = chompack.info(Vc); N = len(D) N = symb.Nsn #Ns = [len(v['S']) for v in D]; Nu = [len(v['U']) for v in D] #Nw = [len(v['U']) + len(v['S']) for v in D] Ns = [len(v) for v in symb.supernodes()] Nu = [len(v) for v in symb.separators()] Nw = [len(v) for v in symb.cliques()] f = pylab.figure(); f.clf() f.text(0.58,0.40,"Number of cliques: %i" % (len(Nw))) f.text(0.61,0.40-1*0.07,"$\sum | W_i | = %i$" % (sum(Nw))) f.text(0.61,0.40-2*0.07,"$\sum | V_i | = %i$" % (sum(Ns))) f.text(0.61,0.40-3*0.07,"$\sum | U_i | = %i$" % (sum(Nu))) f.text(0.61,0.40-4*0.07,"$\max_i\,| W_i | = %i$" % (max(Nw))) pylab.subplot(221) Nmax = max(Nw) y = matrix(0,(Nmax,1)) for n in Nw : y[n-1] += 1 y = sparse(y) pylab.stem(y.I+1,y.V,'k'); pylab.xlim(0, Nmax+1) pylab.title("Cliques") Nmax = max(Nu) y = matrix(0,(Nmax,1)) if Nmax > 0: pylab.subplot(222) for n in Nu : y[n-1] += 1 y = sparse(y) pylab.stem(y.I+1,y.V,'k'); pylab.xlim(0, Nmax+1) pylab.title("Separators") pylab.subplot(223) Nmax = max(Ns) y = matrix(0,(Nmax,1)) for n in Ns : y[n-1] += 1 y = sparse(y) pylab.stem(y.I+1,y.V,'k'); pylab.xlim(0, Nmax+1) pylab.title("Residuals") if file: pylab.savefig(file)
pi = pl.pi t = pl.arange(0,end) f = 100 amps = [1.,0,1./3,0,1./5,0,1./7,0,1./9.] ph = -pi/2 s = pl.zeros(end) pl.subplot(311) pl.title("harmonics") pl.xlim(0,end) k = 1 for a in amps: p = a*pl.cos(2*pi*f*k*t/sr + ph) pl.plot(t, p) s += p k += 1 pl.subplot(312) pl.title("square wave") pl.xlim(0,end) pl.plot(t, s) pl.subplot(313) pl.title("spectrum") end = len(amps)+1 pl.xlim(0,end) pl.ylim(0,1.1) pl.stem(pl.arange(1,end),amps,markerfmt=" ") pl.tight_layout() pl.show()
def main(): """Show simple use cases for functionality provided by this module. Each example below attempts to mimic the examples provided by mathworks MATLAB documentation, http://www.mathworks.com/help/toolbox/signal/ """ import pylab argv = sys.argv if len(argv) != 1: print >>sys.stderr, 'usage: python -m pim.sp.multirate' sys.exit(2) #Downsample x = numpy.arange(1, 11) print 'Down Sampling %s by 3' % x print downsample(x, 3) print 'Down Sampling %s by 3 with phase offset 2' % x print downsample(x, 3, phase=2) #Upsample x = numpy.arange(1, 5) print 'Up Sampling %s by 3' % x print upsample(x, 3) print 'Up Sampling %s by 3 with phase offset 2' % x print upsample(x, 3, 2) #Decimate t = numpy.arange(0, 1, 0.00025) x = numpy.sin(2*numpy.pi*30*t) + numpy.sin(2*numpy.pi*60*t) y = decimate(x,4) pylab.figure() pylab.subplot(2, 1, 1) pylab.title('Original Signal') pylab.stem(numpy.arange(len(x[0:120])), x[0:120]) pylab.subplot(2, 1, 2) pylab.title('Decimated Signal') pylab.stem(numpy.arange(len(y[0:30])), y[0:30]) #Interp t = numpy.arange(0, 1, 0.001) x = numpy.sin(2*numpy.pi*30*t) + numpy.sin(2*numpy.pi*60*t) y = interp(x,4) pylab.figure() pylab.subplot(2, 1, 1) pylab.title('Original Signal') pylab.stem(numpy.arange(len(x[0:30])), x[0:30]) pylab.subplot(2, 1, 2) pylab.title('Interpolated Signal') pylab.stem(numpy.arange(len(y[0:120])), y[0:120]) #upfirdn L = 147.0 M = 160.0 N = 24.0*L h = signal.firwin(N-1, 1/M, window=('kaiser', 7.8562)) h = L*h Fs = 48000.0 n = numpy.arange(0, 10239) x = numpy.sin(2*numpy.pi*1000/Fs*n) y = upfirdn(x, h, L, M) pylab.figure() pylab.stem(n[1:49]/Fs, x[1:49]) pylab.stem(n[1:45]/(Fs*L/M), y[13:57], 'r', markerfmt='ro',) pylab.xlabel('Time (sec)') pylab.ylabel('Signal value') #resample fs1 = 10.0 t1 = numpy.arange(0, 1 + 1.0/fs1, 1.0/fs1) x = t1 y = resample(x, 3, 2) t2 = numpy.arange(0,(len(y)))*2.0/(3.0*fs1) pylab.figure() pylab.plot(t1, x, '*') pylab.plot(t2, y, 'o') pylab.plot(numpy.arange(-0.5,1.5, 0.01), numpy.arange(-0.5,1.5, 0.01), ':') pylab.legend(('original','resampled')) pylab.xlabel('Time') x = numpy.hstack([numpy.arange(1,11), numpy.arange(9,0,-1)]) y = resample(x,3,2) pylab.figure() pylab.subplot(2, 1, 1) pylab.title('Edge Effects Not Noticeable') pylab.plot(numpy.arange(19)+1, x, '*') pylab.plot(numpy.arange(29)*2/3.0 + 1, y, 'o') pylab.legend(('original', 'resampled')) x = numpy.hstack([numpy.arange(10, 0, -1), numpy.arange(2,11)]) y = resample(x,3,2) pylab.subplot(2, 1, 2) pylab.plot(numpy.arange(19)+1, x, '*') pylab.plot(numpy.arange(29)*2/3.0 + 1, y, 'o') pylab.title('Edge Effects Very Noticeable') pylab.legend(('original', 'resampled')) pylab.show() return 0
while sample_points < len(sampled): sampled[sample_points] = xa[sample_points] sample_points = sample_points+ init sampled1 = np.sin(2 * np.pi *f * t * 0) print len(sampled1) sample_points1 = ((1.0 * f)/fs2)*1000 init = sample_points1 while sample_points1< len(sampled1): sampled1[sample_points1] = xa[sample_points1] sample_points1 = sample_points1+ init print sample_points1 # Putting in subplots py.subplot(3, 1, 1) py.plot(t, xa) py.subplot(3, 1, 2) py.stem(t, sampled,'-') py.subplot(3, 1, 3) py.stem(t, sampled1,'-') py.ylabel('Amplitude(Normalized)',size='medium') py.xlabel('Time(in ms)',size='medium') py.savefig('ouputdifferent.png',dpi=(300)) py.close() # Putting in a single graph py.plot(t, xa,t, sampled,t,sampled1) py.title('Sampled waveforms') py.legend(['Waveform','3KHz Sampling','5KHz Sampling']) py.xlabel("Time(ms)") py.ylabel("Amplitude(normalized)") py.savefig('outputcombined.png',dpi=(300)) py.close() # Sampling in 15KHz
def main(): """Show simple use cases for functionality provided by this module. Each example below attempts to mimic the examples provided by mathworks MATLAB documentation, http://www.mathworks.com/help/toolbox/signal/ """ import pylab argv = sys.argv if len(argv) != 1: print('usage: python -m pim.sp.multirate', file=sys.stderr) sys.exit(2) #Downsample x = numpy.arange(1, 11) print('Down Sampling %s by 3' % x) print(downsample(x, 3)) print('Down Sampling %s by 3 with phase offset 2' % x) print(downsample(x, 3, phase=2)) #Upsample x = numpy.arange(1, 5) print('Up Sampling %s by 3' % x) print(upsample(x, 3)) print('Up Sampling %s by 3 with phase offset 2' % x) print(upsample(x, 3, 2)) #Decimate t = numpy.arange(0, 1, 0.00025) x = numpy.sin(2 * numpy.pi * 30 * t) + numpy.sin(2 * numpy.pi * 60 * t) y = decimate(x, 4) pylab.figure() pylab.subplot(2, 1, 1) pylab.title('Original Signal') pylab.stem(numpy.arange(len(x[0:120])), x[0:120]) pylab.subplot(2, 1, 2) pylab.title('Decimated Signal') pylab.stem(numpy.arange(len(y[0:30])), y[0:30]) #Interp t = numpy.arange(0, 1, 0.001) x = numpy.sin(2 * numpy.pi * 30 * t) + numpy.sin(2 * numpy.pi * 60 * t) y = interp(x, 4) pylab.figure() pylab.subplot(2, 1, 1) pylab.title('Original Signal') pylab.stem(numpy.arange(len(x[0:30])), x[0:30]) pylab.subplot(2, 1, 2) pylab.title('Interpolated Signal') pylab.stem(numpy.arange(len(y[0:120])), y[0:120]) #upfirdn L = 147.0 M = 160.0 N = 24.0 * L h = signal.firwin(N - 1, 1 / M, window=('kaiser', 7.8562)) h = L * h Fs = 48000.0 n = numpy.arange(0, 10239) x = numpy.sin(2 * numpy.pi * 1000 / Fs * n) y = upfirdn(x, h, L, M) pylab.figure() pylab.stem(n[1:49] / Fs, x[1:49]) pylab.stem( n[1:45] / (Fs * L / M), y[13:57], 'r', markerfmt='ro', ) pylab.xlabel('Time (sec)') pylab.ylabel('Signal value') #resample fs1 = 10.0 t1 = numpy.arange(0, 1 + 1.0 / fs1, 1.0 / fs1) x = t1 y = resample(x, 3, 2) t2 = numpy.arange(0, (len(y))) * 2.0 / (3.0 * fs1) pylab.figure() pylab.plot(t1, x, '*') pylab.plot(t2, y, 'o') pylab.plot(numpy.arange(-0.5, 1.5, 0.01), numpy.arange(-0.5, 1.5, 0.01), ':') pylab.legend(('original', 'resampled')) pylab.xlabel('Time') x = numpy.hstack([numpy.arange(1, 11), numpy.arange(9, 0, -1)]) y = resample(x, 3, 2) pylab.figure() pylab.subplot(2, 1, 1) pylab.title('Edge Effects Not Noticeable') pylab.plot(numpy.arange(19) + 1, x, '*') pylab.plot(numpy.arange(29) * 2 / 3.0 + 1, y, 'o') pylab.legend(('original', 'resampled')) x = numpy.hstack([numpy.arange(10, 0, -1), numpy.arange(2, 11)]) y = resample(x, 3, 2) pylab.subplot(2, 1, 2) pylab.plot(numpy.arange(19) + 1, x, '*') pylab.plot(numpy.arange(29) * 2 / 3.0 + 1, y, 'o') pylab.title('Edge Effects Very Noticeable') pylab.legend(('original', 'resampled')) pylab.show() return 0
wspec = whitening.process(spec) pitch, saliency = pitchACF.process(wspec) if interactivePlot: pylab.subplot(211) pylab.hold(False) pylab.plot(wspec[0, :plotSize]) acorred = acorr.process(wspec) pylab.subplot(212) pylab.hold(False) pylab.plot(acorred[0, :plotSize], label='Noise Suppressed Spectrum') pylab.hold(True) pylab.stem(pitch / sampleRate * fftSize, saliency) specs.append(spec[0, :]) wspecs.append(wspec[0, :]) pitches.append(pitch) saliencies.append(saliency) if interactivePlot: pylab.ioff() specs = scipy.array(specs) wspecs = scipy.array(wspecs) pitches = scipy.array(pitches)[:, 0] saliencies = scipy.array(saliencies)[:, 0] frameCount = specs.shape[0] - 1
from pylab import hist, plot, show, stem, figure # Sample two normal distributions # and create a bi-modal distribution rv1 = stats.norm() rv2 = stats.norm(2.0, 0.8) samples = hstack([rv1.rvs(size=100), rv2.rvs(size=100)]) # Use a Gaussian kernel density to # estimate the PDF for the samples. approximate_pdf = gaussian_kde(samples) x = linspace(-3, 6, 200) # Compare the histogram of the samples to # the PDF approximation. figure(1) hist(samples, bins=25, normed=True) plot(x, approximate_pdf(x), 'r') # Example 2: A bunch of points at 0, one at 1. samples2 = [0.0]*10 + [1.0] pdf2 = gaussian_kde(samples2) x2 = linspace(-1.0, 2, 500) figure(2) plot(x2, pdf2(x2), 'r') stem([0,1], [1, 0.1]) show()
'meraki_auto_dl' ] fig = pylab.figure(figsize=(16,12)) lns = None for log in logs: wifi_log = "%s_wireless.log" % log f = open(wifi_log,'r') latencies = [] for line in f.readlines()[1:-1]: vals = string.split(line,'|') print vals[1] try: lat = float(vals[1]) except: lat = -1.0 latencies.append(lat) if lns: lns += pylab.stem(range(0, len(latencies)), latencies,'-.', label=log) else: lns = pylab.stem(range(0, len(latencies)), latencies, '-.') f.close() #labels = [l.get_label() for l in lns] pylab.xlabel('time (s)') pylab.ylabel('Latency (ms)') #pylab.legend(lns, labels) pylab.grid() pylab.title('WiFi Latency (%s)' % output) pylab.savefig("%s.pdf" % output)
def main(N, M=1): # Generate uniform noise (each column is a realization). noise1 = uniform_noise(N, M, a=-1.7, b=1.7) # Generate Gaussian noise (each column is a realization). noise2 = gaussian_noise(N, M) write_and_play(8192, noise1[:, 0], "noise1") write_and_play(8192, noise2[:, 0], "noise2") pl.figure() pl.subplot(211) pl.stem(noise1[:100, 0]) pl.ylabel("noise1") pl.subplot(212) pl.stem(noise2[:100, 0]) pl.ylabel("noise2") pl.xlabel("samples") Noise1 = numpy.fft.fft(noise1, n=2**nextpow2(N), axis=0) Noise2 = numpy.fft.fft(noise2, n=2**nextpow2(N), axis=0) psdNoise1 = numpy.mean(numpy.abs(Noise1)**2, 1) / N psdNoise2 = numpy.mean(numpy.abs(Noise2)**2, 1) / N pl.figure() pl.subplot(211) pl.plot(numpy.arange(len(psdNoise1))/len(psdNoise1), psdNoise1) pl.ylim(0, 1.5) pl.ylabel("psdNoise1") pl.subplot(212) pl.plot(numpy.arange(len(psdNoise2))/len(psdNoise2), psdNoise2) pl.ylim(0, 1.5) pl.ylabel("psdNoise2") pl.xlabel("normalized frequencies") pl.figure() pl.subplot(211) pl.hist(noise1[:, 0], bins=50) pl.ylabel("noise1 recurrences") pl.subplot(212) pl.hist(noise2[:, 0], bins=50) pl.ylabel("noise2 recurrences") pl.xlabel("values") # Leaky integrator (filter). h = leaky_integrator() H = numpy.fft.fft(h, 2**nextpow2(N)) absH2 = numpy.abs(H)**2 # Filter noise. N2 = N -len(h) + 1 yy2 = numpy.zeros((N2, M)) for i in range(M): yy2[:, i] = numpy.convolve(noise2[:, i], h, mode="valid") write_and_play(8192, yy2[:, 0], "filtered_noise2") psdY2 = numpy.mean(numpy.abs(numpy.fft.fft( yy2, n=2**nextpow2(N2), axis=0))**2, 1) / N2 pl.figure() pl.subplot(311) pl.plot(numpy.arange(len(psdNoise2))/len(psdNoise2), psdNoise2) pl.ylim(0, 1.5) pl.ylabel("psdNoise2") pl.subplot(312) pl.plot(numpy.arange(len(absH2))/len(absH2), absH2) pl.ylim(0, 1.5) pl.ylabel("squareMagH") pl.subplot(313) pl.plot(numpy.arange(len(psdY2))/len(psdY2), psdY2) pl.ylim(0, 1.5) pl.ylabel("psdY2") pl.xlabel("normalized frequencies") pl.show()
X=np.asarray(all_data[0]) X=np.r_[X,X+3] color_iter = itertools.cycle(['r', 'g', 'b', 'c', 'm']) vbgmm=mixture.VBGMM(n_components=30, alpha=1.00,covariance_type='full') vbgmm.fit(X) Y_=vbgmm.predict(X) pl.subplot(4,1,1) pl.plot(X) pl.ylabel('value') pl.subplot(4,1,2) pl.plot(vbgmm.weights_,'-s') pl.ylabel('mixing prob') pl.subplot(4,1,3) pl.stem(vbgmm.means_, '-.') pl.ylabel('means') pl.xlabel('components') pl.subplot(4,1,4) for i, (mean, color) in enumerate(zip(vbgmm.means_, color_iter)): if not np.any(Y_==i): continue (X_idx,)=(Y_==i).nonzero() pl.plot(X_idx,X[Y_==i], color=color) pl.ylabel('centroid')