def plotOfFreqResponse(): # Get the filter coefficients so we can check its frequency response. b, a = butter_lowpass(cutoffFreq, samplingRate, filterOrder) # calc frequency response w, h = freqz(b, a, worN=8000) gain = _np.abs(h) phase = _np.unwrap(_np.angle(h)) * 180 / _np.pi # generate gain plot p1 = _plot.plot() p1.xLim = [0, 0.5 * samplingRate] p1.xLabel = 'Frequency [Hz]' p1.subtitle = "Gain Response" p1.yLabel = 'Gain' p1.yLim = [0, 1.] p1.title = 'Butterworth filter. Order=%d. Cutoff Freq=%.1f. Sampling Rate = %.1f Hz. Type = %s.' % ( filterOrder, cutoffFreq, samplingRate, filterType) p1.xData.append(0.5 * samplingRate * w / _np.pi) p1.yData.append(gain) p1.yLegendLabel.append('Frequency Response') p1.xData.append(_np.array([cutoffFreq, cutoffFreq])) p1.yData.append(_np.array([0, 1])) #0.5*_np.sqrt(2) p1.yLegendLabel.append('Cuttoff Frequency') # generate phase plot p2 = _plot.plot() p2.xLim = [0, 0.5 * samplingRate] p2.xLabel = 'Frequency [Hz]' p2.subtitle = "Phase Response" p2.yLabel = 'Phase [Degrees]' p2.yLim = [_np.min(phase), 0] p2.xData.append(0.5 * samplingRate * w / _np.pi) p2.yData.append(phase) p2.yLegendLabel.append('Frequency Response') p2.xData.append(_np.array([cutoffFreq, cutoffFreq])) p2.yData.append(_np.array([_np.min(phase), 0])) #0.5*_np.sqrt(2) p2.yLegendLabel.append('Cuttoff Frequency') # combine into subplot sp1 = _plot.subPlot([p1, p2], plot=False) return sp1
def plot(self): """ plot raw data and exp fit """ # exp fit xFit=_np.arange(self.expRegionMinVoltage,self.expRegionMaxVoltage,0.1) yFit=self._exponenial_func(xFit,self.expFitParameters[0], self.expFitParameters[1], self.expFitParameters[2]) # extrapolated exp fit xFitExtrap=_np.arange(_np.min(self.V),_np.max(self.V),0.1) yFitExtrap=self._exponenial_func(xFitExtrap,self.expFitParameters[0], self.expFitParameters[1], self.expFitParameters[2]) # generate plot p1=_plot.plot(title='I-V Profile',xLabel='Probe Voltage [V]', yLabel='Probe Current [A]') p1.addTrace(xData=self.V,yData=self.I,marker='.',linestyle='', yLegendLabel='Raw data',alpha=0.5) p1.addTrace(xData=xFit,yData=yFit, yLegendLabel='Exp fit') p1.addTrace(xData=xFitExtrap,yData=yFitExtrap, yLegendLabel='Extrapolated exp fit',linestyle=':') p1.plot() return p1
def __init__(self, yData, xData,order=2, plot=True): title = str(order)+' order Polynomial fit' ### do fit self.coefs=_np.polyfit(xData, yData, order) self.ffit = _np.poly1d(self.coefs) self.fitData=self.ffit(xData) ### generate plot self.plotOfFit=_plot.plot(); self.plotOfFit.xLabel='x' self.plotOfFit.yLabel='y' self.plotOfFit.title=title; ### raw data self.plotOfFit.xData.append(xData) self.plotOfFit.yData.append(yData) self.plotOfFit.marker.append('.') self.plotOfFit.linestyle.append('') self.plotOfFit.alpha.append(.15) self.plotOfFit.yLegendLabel.append('raw data') ### fit x=_np.linspace(_np.min(xData),_np.max(xData),1000); self.plotOfFit.xData.append(x) self.plotOfFit.yData.append(self.ffit(x)) self.plotOfFit.marker.append('') self.plotOfFit.linestyle.append('-') self.plotOfFit.alpha.append(1.) self.plotOfFit.yLegendLabel.append('poly fit order %d'%order) if plot==True: self.plotOfFit.plot()
def plotOfFitDep(self): """ plot of fit vs dependent data. important if there are multiple independent variables. """ p1=_plot.plot(); p1.yLabel='fit data' p1.xLabel='raw data' p1.aspect="equal" p1.xData.append(self.y) p1.yData.append(self.yFit) p1.yLegendLabel.append('actual fit') p1.marker.append('.') p1.linestyle.append('') p1.color.append('b') p1.alpha.append(0.3) p1.xData.append(_np.array([_np.min(self.y),_np.max(self.y)])) p1.yData.append(_np.array([_np.min(self.y),_np.max(self.y)])) p1.yLegendLabel.append('ideal fit line') p1.marker.append('') p1.linestyle.append('-') p1.color.append('r') p1.alpha.append(1.) p1.legendLoc= 'upper left' p1.title=r'Fit quality. R$^2$ = %.5f' % self.rSquared return p1
def plotOfResults(): p1=_plot.plot() p1.xData.append(x) p1.yData.append(y) p1.yLegendLabel.append('Unfiltered Data') p1.xData.append(x) p1.yData.append(filteredData) p1.yLegendLabel.append('Filtered Data') return p1
def plotSmoothingFunction(): """ plots smoothing function """ p1=_plot.plot() x=_np.arange(0,len(smoothingFunction)) p1.xData=[x] p1.yData=[smoothingFunction] p1.yLegendLabel=['smoothing function'] p1.marker=['o'] p1.linestyle=['-'] p1.title='%d point, %s smoothing function'% (numPoints,method) p1.plot()
def plotResults(): """ plots before and after of smoothing """ p1=_plot.plot() x=_np.arange(0,len(data)) p1.xData=[x,x] p1.yData=[data,smoothedData] p1.yLegendLabel=['raw data','smoothed data'] p1.marker=['.',''] p1.linestyle=['','-'] p1.title='%d point, %s smoothing'% (numPoints,method) p1.plot()
def plotResults(): """ plots results (before and after smoothing) """ p1=_plot.plot() x=_np.arange(0,len(data)) p1.xData=[x,x] p1.yData=[data,smoothedData] p1.yLegendLabel=['raw data','smoothed data'] p1.marker=['.',''] p1.linestyle=['','-'] p1.title='%d point, Savitzky-Golay smoothing of order %s'% (numPoints,polynomialOrder) p1.plot()
def plotOfFit(self): """ plots raw and fit data vs. its indep. variable. Notes ----- this function only works if there is a single indep. variable """ # make sure that there is only a single indep. variable if type(self.x) is _np.ndarray or len(self.x)==1: p1=_plot.plot(); p1.yLabel='y' p1.xLabel='x' p1.title=r'Fit results. R$^2$ = %.5f' % self.rSquared if isinstance(self.x,list): x=self.x[0] else: x=self.x # raw data p1.xData.append(x) p1.yData.append(self.y) p1.yLegendLabel.append('raw data') p1.marker.append('.') p1.linestyle.append('') p1.color.append('b') p1.alpha.append(0.3) # fit data p1.xData.append(x) p1.yData.append(self.yFit) p1.yLegendLabel.append('fit') p1.marker.append('') p1.linestyle.append('-') p1.color.append('r') p1.alpha.append(1.) # the true data (if applicable) if self.yTrue!=[]: p1.xData.append(x) p1.yData.append(self.yTrue) p1.yLegendLabel.append('True Soln') p1.marker.append('') p1.linestyle.append('-') p1.plotOfFit.color.append('k') p1.plotOfFit.alpha.append(1.) return p1
def __init__(self, V, I, expRegionMinVoltage=None, expRegionMaxVoltage=None, ionSatRegionMaxVoltage=None, area=0.000580644, plot=False, expFitGuess=(6, 20, -5)): ## physical constants # eV=1.60218e-19; # mi=1.6737236 * 10**(-27) * 2 # q=1.6e-19 # parameters self.probeArea=area self.expRegionMinVoltage=expRegionMinVoltage self.expRegionMaxVoltage=expRegionMaxVoltage self.ionSatRegionMaxVoltage=ionSatRegionMaxVoltage # ensure V and I are arrays self.V=_np.array(V); self.I=_np.array(I) # sort V in ascending order i=_np.argsort(self.V) self.V=self.V[i] self.I=self.I[i] # initialize plot p1=_plot.plot() p1.addTrace(xData=self.V,yData=self.I,marker='.',linestyle='', yLegendLabel='raw data') # if expRegionMinVoltage or expRegionMaxVoltage were not specified, the code will plot the I-V # profile and ask that you provide the floating and/or plasma # potential. These values are used as the lower and upper limits for # the exponential fit if expRegionMinVoltage==None or expRegionMaxVoltage==None or ionSatRegionMaxVoltage==None: p1.plot() _plt.show() _plt.pause(1.0) # a pause is required for the plot to show correctly if expRegionMinVoltage==None: self.expRegionMinVoltage=float(raw_input("Please provide the approximate lower voltage (units in volts) limit to be used in the exp fit by looking at the I-V plot: ")) if expRegionMaxVoltage==None: self.expRegionMaxVoltage=float(raw_input("Please provide the approximate upper voltage (units in volts) limit to be used in the exp fit by looking at the I-V plot: ")) if ionSatRegionMaxVoltage==None: self.ionSatRegionMaxVoltage=float(raw_input("Please provide the approximate maximum voltage (units in volts) limit for the ion saturation region by looking at the I-V plot: ")) # exp. curve fit setup from scipy.optimize import curve_fit # perform exp curve fit popt, pcov = curve_fit(self._exponenial_func, V, I, p0=expFitGuess) self.expFitParameters=popt # print popt # temperature self.temperatureInEV=self.calcTempInEV(popt[1])#q*popt[1]/eV print("Temperature = " + str(self.temperatureInEV) + ' eV') # density calculation from the exp fit offset self.densityFromExpFitOffset=self.calcDensity(popt[2], probeArea=self.probeArea, temperatureInEV=self.temperatureInEV) print("Density from the exp. fit offset current = " + str(self.densityFromExpFitOffset) + ' m^3') # density calculation from averaging the values in the ion sat region i=self.V<self.ionSatRegionMaxVoltage aveIonSatCurrent=_np.average(self.I[i]) print("Average Current in the ion sat. region = " + str(aveIonSatCurrent)) self.densityFromAveIonSatRegion=self.calcDensity(aveIonSatCurrent, probeArea=self.probeArea, temperatureInEV=self.temperatureInEV) print("Density from the average current in the ion sat. region = " + str(self.densityFromAveIonSatRegion) + ' m^3') # optional plot if plot==True: self.plot()
def nPoleFilter(data,xData=None,numPoles=1,alpha=0.0625,filterType='lowPass',plot=False): """ n-pole filter. Parameters ---------- data : numpy.ndarray data to be smoothed xData : numpy.ndarray or NoneType (optional) array of x-data numPoles : int number of poles for the filter alpha : float weight of the filter, float between 0 and 1. Close to zero for a low pass and close to 1 for a high pass filterType : str 'lowPass' - Low pass filter 'highPhass' - High pass filter plot : bool plots results if true Returns ------- filteredData : 2D numpy.ndarray filtered data References ---------- http://techteach.no/simview/lowpass_filter/doc/filter_algorithm.pdf https://en.wikipedia.org/wiki/Low-pass_filter#Discrete-time_realization https://en.wikipedia.org/wiki/High-pass_filter#Discrete-time_realization Notes ----- this method is pulled from Qian Peng's 2016 GPU code. his highpass filter does NOT follow this code Example #1 ---------- t=np.arange(0,.01,6e-8); y2=np.sin(2*np.pi*300*t)+np.sin(2*np.pi*30000*t) alpha=0.00625; hbt.process.nPoleFilter(y2,t,numPoles=2,filterType='lowPass',plot=True,alpha=alpha) hbt.process.nPoleFilter(y2,t,numPoles=2,filterType='highPass',plot=True,alpha=1.0-0.000625) Example #2 ---------- t=np.arange(0,.01,6e-6); from scipy.signal import square y=square(t,0.001) hbt.process.nPoleFilter(y,t,numPoles=2,filterType='lowPass',plot=True) hbt.process.nPoleFilter(y,t,numPoles=2,filterType='highPass',plot=True) """ # initialize data arrays procData=_np.zeros((numPoles+1,len(data))); procData[0,:]=data; # filter. for loop controls the number of poles for i in range(1,numPoles+1): if filterType=='lowPass': for j in range(0,len(data)-1): procData[i,j+1]=procData[i,j]+alpha*(procData[i-1,j]-procData[i,j]) elif filterType=='highPass': for j in range(0,len(data)-1): procData[i,j+1]=alpha*(procData[i,j]+procData[i-1,j+1]-procData[i-1,j]) # plot results if plot==True: p1=_plot.plot(title=str(numPoles)+" pole "+filterType+" filter, alpha="+str(alpha), xLabel="x-axis",yLabel='y-axis') if type(xData)==type(None): xData=_np.arange(0,len(data)); p1.addTrace(xData=xData,yData=data,yLegendLabel='raw') for i in range(1,numPoles+1): p1.addTrace(xData=xData,yData=procData[i,:],yLegendLabel=str(i)) p1.plot() # return results return procData