def plot_coord_mapping(mapper, sheet, style='b-'): """ Plot a coordinate mapping for a sheet. Given a CoordinateMapperFn (as for a CFProjection) and a sheet of the projection, plot a grid showing where the sheet's units are mapped. """ from pylab import plot, hold, ishold xs = sheet.sheet_rows() ys = sheet.sheet_cols() hold_on = ishold() if not hold_on: plot() hold(True) for y in ys: pts = [mapper(x, y) for x in xs] plot([u for u, v in pts], [v for u, v in pts], style) for x in xs: pts = [mapper(x, y) for y in ys] plot([u for u, v in pts], [v for u, v in pts], style) hold(hold_on)
def plot_coord_mapping(mapper,sheet,style='b-'): """ Plot a coordinate mapping for a sheet. Given a CoordinateMapperFn (as for a CFProjection) and a sheet of the projection, plot a grid showing where the sheet's units are mapped. """ from pylab import plot,hold,ishold xs = sheet.sheet_rows() ys = sheet.sheet_cols() hold_on = ishold() if not hold_on: plot() hold(True) for y in ys: pts = [mapper(x,y) for x in xs] plot([u for u,v in pts], [v for u,v in pts], style) for x in xs: pts = [mapper(x,y) for y in ys] plot([u for u,v in pts], [v for u,v in pts], style) hold(hold_on)
def plot_regression(x,y,smoothing=.3): fit=sm.nonparametric.lowess(y,x,frac=smoothing) df=(fit[:,1]-y)**2 fit_var=sm.nonparametric.lowess(df,x,frac=smoothing) isheld = pl.ishold() pl.hold(1) pl.plot(fit[:,0],fit[:,1]) pl.fill_between(fit_var[:,0],fit[:,1]-1*pl.sqrt(fit_var[:,1]),fit[:,1]+1*pl.sqrt(fit_var[:,1]),color=((0,0,.99,.2),)) pl.plot(x,y,'.') pl.hold(isheld)
def plot(self, *args, **kwargs): from pylab import plot, ioff, ion, show, ishold, cla ioff() if kwargs.get('hold')==0 or not ishold(): cla() kwargs['hold']=1 for i,w in enumerate(self.iterwhiskers()): plot( w.x + 0.1*i, w.y + 0.1*i , *args, **kwargs) ion() show()
def plot_regression(x, y, smoothing=.3): fit = sm.nonparametric.lowess(y, x, frac=smoothing) df = (fit[:, 1] - y)**2 fit_var = sm.nonparametric.lowess(df, x, frac=smoothing) isheld = pl.ishold() pl.hold(1) pl.plot(fit[:, 0], fit[:, 1]) pl.fill_between(fit_var[:, 0], fit[:, 1] - 1 * pl.sqrt(fit_var[:, 1]), fit[:, 1] + 1 * pl.sqrt(fit_var[:, 1]), color=((0, 0, .99, .2), )) pl.plot(x, y, '.') pl.hold(isheld)
def plotPZ(H, color='b', markersize=5, showlist=False): """Plot the poles and zeros of a transfer function. **Parameters:** H : transfer function Any supported transfer function representation, eg num/den, zpk, lti... color : Any matplotlib-compatible color descr, optional For example, 'r' for 'red' or '#000080' for 'navy'. You can also specify separately poles and zeros, in a tuple. markersize : scalar, optional The markers size in points. showlist : boolean, optional Superimpose a list of the poles and zeros on the plot. .. plot:: import pylab as plt from deltasigma import synthesizeNTF, plotPZ order = 5 osr = 32 f0 = 0. Hinf = 1.5 ntf = synthesizeNTF(order, osr, 2, Hinf, f0) plt.figure(figsize=(8, 6)) plotPZ(ntf, color=('r', 'b'), showlist=True) plt.title("NTF singularities") plt.show() """ # Parts of the code come from 'pydsm' # # Original copyright notices: # # For pydsm # Copyright (c) 2012, Sergio Callegari # All rights reserved. # # For Richard Schreier's Delta Sigma toolbox # Copyright (c) 2009, Richard Schreier z, p, _ = _get_zpk(H) p = np.real_if_close(np.round(p, 5)) z = np.real_if_close(np.round(z, 5)) pole_fmt = {'marker': 'x', 'markersize': markersize} zero_fmt = {'marker': 'o', 'markersize': markersize} if isinstance(color, list) or isinstance(color, tuple): pole_fmt['color'] = color[0] zero_fmt['color'] = color[1] else: pole_fmt['color'] = color zero_fmt['color'] = color hold_status = plt.ishold() plt.grid(True) # Plot x and o for poles and zeros, respectively plt.plot(p.real, p.imag, linestyle='None', **pole_fmt) plt.hold(True) if len(z) > 0: plt.plot(z.real, z.imag, linestyle='None', **zero_fmt) # Draw unit circle, real axis and imag axis circle = np.exp(2j * np.pi * np.linspace(0, 1, 100)) plt.plot(circle.real, circle.imag) ax = plt.gca() ax.set_autoscale_on(False) if showlist: ax = plt.gca() x1, x2, y1, y2 = ax.axis() x2 = np.round((x2 - x1) * 1.48 + x1, 1) ax.axis((x1, x2, y1, y2)) markers = [] descr = [] ps = p[p.imag >= 0] for pi in ps: markers += [plt.Line2D((), (), linestyle='None', **pole_fmt)] if np.allclose(pi.imag, 0, atol=1e-5): descr += ['%+.4f' % pi.real] else: descr += ['%+.4f+/-j%.4f' % (pi.real, pi.imag)] if len(z) > 0: for zi in z[z.imag >= 0]: markers += [plt.Line2D((), (), linestyle='None', **zero_fmt)] if zi.imag == 0: descr += ['%+.4f' % zi.real] else: descr += ['%+.4f +/-j%.4f' % (zi.real, zi.imag)] plt.legend(markers, descr, title="Poles (x) and zeros (o)", ncol=1, loc='best', handlelength=.55, prop={'size': 10}) else: plt.xlim((-1.1, 1.1)) plt.ylim((-1.1, 1.1)) plt.gca().set_aspect('equal') # plt.axes().set_aspect('equal', 'datalim') plt.ylabel('Imag') plt.xlabel('Real') if not hold_status: plt.hold(False)
def peakSNR(snr, amp): """Find the snr peak by fitting a smooth curve to the top end of the SNR vs input amplitude data. The curve fitted is y = ax + b/(x-c). Parameters: snr: ndarray amp: ndarray Returns: peak_snr, peak_amp Notes: * Both amp and snr are expressed in dB. * The two arrays snr and amp should have the same size. """ # Delete garbage data for check in (np.isinf, np.isnan): i = check(snr) snr = np.delete(snr, np.where(i)) amp = np.delete(amp, np.where(i)) # sanitize inputs for x in (snr, amp): if not hasattr(x, 'ndim'): x = np.array(x) if len(x.shape) > 1 and np.prod(x.shape) != max(x.shape): raise ValueError("snr and amp should be vectors (ndim=1)" + "snr.shape: %s, amp.shape: %s" % (snr.shape, amp.shape)) x = x.squeeze # All good max_snr = np.max(snr) i = np.flatnonzero(snr > max_snr - 10) min_i = np.min(i) max_i = np.max(i) j = np.flatnonzero(snr[min_i:max_i + 1] < max_snr - 15) if j: max_i = min_i + np.min(j) - 2 i = np.arange(min_i, max_i + 1) snr = 10.0**(snr[i]/20) amp = 10.0**(amp[i]/20) #n = max(i.shape) # unused variable, REP? c = np.max(amp)*1.05 # fit y = ax + b/(x-c) to the data A = np.hstack((amp.reshape(-1, 1), 1.0/(amp.reshape(-1, 1) - c))) ab = np.linalg.lstsq(A, snr.reshape((-1, 1)))[0] peak_amp = c - np.sqrt(ab[1, 0]/ab[0, 0]) peak_snr = np.dot(np.array([[peak_amp, 1./(peak_amp-c)]]), ab) #None check mcode peak_snr = dbv(peak_snr) peak_amp = dbv(peak_amp) if _debug: import pylab as plt pred = np.dot(A, ab) hold = plt.ishold() plt.hold(True) plt.plot(dbv(amp), dbv(pred), '-', color='b') plt.hold(hold) return peak_snr, peak_amp
def peakSNR(snr, amp): """Find the SNR peak by fitting the SNR curve. A smooth curve is fitted to the top end of the SNR vs input amplitude data with Legendre's least-squares method. The curve fitted to the data is: .. math:: y = ax + \\frac{b}{x - c} **Parameters:** snr : 1D ndarray or array-like Signal to Noise Ratio array, expressed in decibels (dB). amp : 1D ndarray or array-like Amplitude array, expressed in decibels (dB). The two arrays ``snr`` and ``amp`` should have the same size. **Returns:** (peak_snr, peak_amp) : tuple The peak SNR value and its corresponding amplitude, expressed in dB. """ # sanitize inputs snr = np.atleast_1d(np.asarray(snr)) amp = np.atleast_1d(np.asarray(amp)) # Delete garbage data for check in (np.isinf, np.isnan): i = check(snr) snr = np.delete(snr, np.where(i)) amp = np.delete(amp, np.where(i)) for x in (snr, amp): if len(x.shape) > 1 and np.prod(x.shape) != max(x.shape): raise ValueError("snr and amp should be vectors (ndim=1)" + "snr.shape: %s, amp.shape: %s" % (snr.shape, amp.shape)) # All good max_snr = np.max(snr) i = np.flatnonzero(snr > max_snr - 10) min_i = np.min(i) max_i = np.max(i) j = np.flatnonzero(snr[min_i:max_i + 1] < max_snr - 15) if j: max_i = min_i + np.min(j) - 2 i = np.arange(min_i, max_i + 1) snr = 10.0**(snr[i]/20) amp = 10.0**(amp[i]/20) #n = max(i.shape) # unused variable, REP? c = np.max(amp)*1.05 # fit y = ax + b/(x-c) to the data A = np.hstack((amp.reshape(-1, 1), 1.0/(amp.reshape(-1, 1) - c))) ab = np.linalg.lstsq(A, snr.reshape((-1, 1)))[0] peak_amp = c - np.sqrt(ab[1, 0]/ab[0, 0]) peak_snr = np.dot(np.array([[peak_amp, 1./(peak_amp-c)]]), ab) #None check mcode peak_snr = dbv(peak_snr) peak_amp = dbv(peak_amp) if _debug: import pylab as plt pred = np.dot(A, ab) hold = plt.ishold() plt.hold(True) plt.plot(dbv(amp), dbv(pred), '-', color='b') plt.hold(hold) return peak_snr, peak_amp
def plotPZ(H, color='b', markersize=5, showlist=False): """Plot the poles and zeros of a transfer function. **Parameters:** H : transfer function Any supported transfer function representation, eg num/den, zpk, lti... color : Any matplotlib-compatible color descr, optional For example, 'r' for 'red' or '#000080' for 'navy'. You can also specify separately poles and zeros, in a tuple. markersize : scalar, optional The markers size in points. showlist : boolean, optional Superimpose a list of the poles and zeros on the plot. .. plot:: import pylab as plt from deltasigma import synthesizeNTF, plotPZ order = 5 osr = 32 f0 = 0. Hinf = 1.5 ntf = synthesizeNTF(order, osr, 2, Hinf, f0) plt.figure(figsize=(8, 6)) plotPZ(ntf, color=('r', 'b'), showlist=True) plt.title("NTF singularities") plt.show() """ # Parts of the code come from 'pydsm' # # Original copyright notices: # # For pydsm # Copyright (c) 2012, Sergio Callegari # All rights reserved. # # For Richard Schreier's Delta Sigma toolbox # Copyright (c) 2009, Richard Schreier z, p, _ = _get_zpk(H) p = np.real_if_close(np.round(p, 5)) z = np.real_if_close(np.round(z, 5)) pole_fmt = {'marker': 'x', 'markersize': markersize} zero_fmt = {'marker': 'o', 'markersize': markersize} if isinstance(color, list) or isinstance(color, tuple): pole_fmt['color'] = color[0] zero_fmt['color'] = color[1] else: pole_fmt['color'] = color zero_fmt['color'] = color hold_status = plt.ishold() plt.grid(True) # Plot x and o for poles and zeros, respectively plt.plot(p.real, p.imag, linestyle='None', **pole_fmt) plt.hold(True) if len(z) > 0: plt.plot(z.real, z.imag, linestyle='None', **zero_fmt) # Draw unit circle, real axis and imag axis circle = np.exp(2j*np.pi*np.linspace(0, 1, 100)) plt.plot(circle.real, circle.imag) ax = plt.gca() ax.set_autoscale_on(False) if showlist: ax = plt.gca() x1, x2, y1, y2 = ax.axis() x2 = np.round((x2 - x1)*1.48 + x1, 1) ax.axis((x1, x2, y1, y2)) markers = [] descr = [] ps = p[p.imag >= 0] for pi in ps: markers += [plt.Line2D((), (), linestyle='None', **pole_fmt)] if np.allclose(pi.imag, 0, atol=1e-5): descr += ['%+.4f' % pi.real] else: descr += ['%+.4f+/-j%.4f' % (pi.real, pi.imag)] if len(z) > 0: for zi in z[z.imag >= 0]: markers += [plt.Line2D((), (), linestyle='None', **zero_fmt)] if zi.imag == 0: descr += ['%+.4f' % zi.real] else: descr += ['%+.4f +/-j%.4f' % (zi.real, zi.imag)] plt.legend(markers, descr, title="Poles (x) and zeros (o)", ncol=1, loc='best', handlelength=.55, prop={'size':10}) else: plt.xlim((-1.1, 1.1)) plt.ylim((-1.1, 1.1)) plt.gca().set_aspect('equal') # plt.axes().set_aspect('equal', 'datalim') plt.ylabel('Imag') plt.xlabel('Real') if not hold_status: plt.hold(False)
def peakSNR(snr, amp): """Find the SNR peak by fitting the SNR curve. A smooth curve is fitted to the top end of the SNR vs input amplitude data with Legendre's least-squares method. The curve fitted to the data is: .. math:: y = ax + \\frac{b}{x - c} **Parameters:** snr : 1D ndarray or array-like Signal to Noise Ratio array, expressed in decibels (dB). amp : 1D ndarray or array-like Amplitude array, expressed in decibels (dB). The two arrays ``snr`` and ``amp`` should have the same size. **Returns:** (peak_snr, peak_amp) : tuple The peak SNR value and its corresponding amplitude, expressed in dB. """ # sanitize inputs snr = np.atleast_1d(np.asarray(snr)) amp = np.atleast_1d(np.asarray(amp)) # Delete garbage data for check in (np.isinf, np.isnan): i = check(snr) snr = np.delete(snr, np.where(i)) amp = np.delete(amp, np.where(i)) for x in (snr, amp): if len(x.shape) > 1 and np.prod(x.shape) != max(x.shape): raise ValueError("snr and amp should be vectors (ndim=1)" + "snr.shape: %s, amp.shape: %s" % (snr.shape, amp.shape)) # All good max_snr = np.max(snr) i = np.flatnonzero(snr > max_snr - 10) min_i = np.min(i) max_i = np.max(i) j = np.flatnonzero(snr[min_i:max_i + 1] < max_snr - 15) if j: max_i = min_i + np.min(j) - 2 i = np.arange(min_i, max_i + 1) snr = 10.0**(snr[i] / 20) amp = 10.0**(amp[i] / 20) #n = max(i.shape) # unused variable, REP? c = np.max(amp) * 1.05 # fit y = ax + b/(x-c) to the data A = np.hstack((amp.reshape(-1, 1), 1.0 / (amp.reshape(-1, 1) - c))) ab = np.linalg.lstsq(A, snr.reshape((-1, 1)))[0] peak_amp = c - np.sqrt(ab[1, 0] / ab[0, 0]) peak_snr = np.dot(np.array([[peak_amp, 1. / (peak_amp - c)]]), ab) #None check mcode peak_snr = dbv(peak_snr) peak_amp = dbv(peak_amp) if _debug: import pylab as plt pred = np.dot(A, ab) hold = plt.ishold() plt.hold(True) plt.plot(dbv(amp), dbv(pred), '-', color='b') plt.hold(hold) return peak_snr, peak_amp