def PhiObsMe2(self, lambda_obs, m, z): z_vect = lambda_obs / self.lambda_eff - 1. phi_vect = np.zeros(len(z_vect)) + 1.e-30 ind_gt0 = np.where(z_vect > 0)[0] ind_eq0 = np.where(z_vect == 0)[0] phi_vect[ind_gt0] = np.array([ self.PhiMe(z_vect[i], m, self.phistar0_vect[i], self.p_vect[i], self.Mstar0_vect[i], self.q_vect[i], self.alpha0_vect[i], self.r_vect[i]) for i in ind_gt0 ]) phi_vect[ind_eq0] = self.PhiMe(0.01, m, self.phistar0_vect[ind_eq0], self.p_vect[ind_eq0], self.Mstar0_vect[ind_eq0], self.q_vect[ind_eq0], self.alpha0_vect[ind_eq0], self.r_vect[ind_eq0]) if (z_vect[0] >= 4.): phi_vect[0] = self.PhiMeHigh(z_vect[0], m) if ((z > z_vect[0]) or (z < z_vect[-1])): return 1.e-30 else: ind_low, ind_high = tools.find_nearest(z, z_vect) #if ((z_vect[ind_low] <= 0) or (z_vect[ind_high] <=0)) : # return 0. #else: return tools.lininterp(z, z_vect[ind_low], z_vect[ind_high], phi_vect[ind_low], phi_vect[ind_high])
def compute_category(self, item): b = self.model_brand p = self.model_price if self.train: brand_position = self.brand_position price_position = self.price_position else: brand_position = self.brand_position_test price_position = self.price_position_test no_brand = NO_BRAND if not smart_in(b.brands, item[brand_position]): brand = no_brand else: brand = item[brand_position] price = float(item[price_position]) if price < 0: cat = b.cat_from_brand(brand) else: price = p.transform(price) prix = None prix = find_nearest(p.p_list, price) price = prix if b.proba[brand]['proba'] > p.proba[price][ 'proba'] and brand != no_brand: cat = b.cat_from_brand(brand) else: cat = p.cat_from_price(price) return cat
def compute_category(self,item): b=self.model_brand p=self.model_price if self.train: brand_position = self.brand_position price_position = self.price_position else: brand_position = self.brand_position_test price_position = self.price_position_test no_brand = NO_BRAND if not smart_in(b.brands,item[brand_position]): brand = no_brand else: brand = item[brand_position] price = float(item[price_position]) if price<0: cat=b.cat_from_brand(brand) else: price = p.transform(price) prix = None prix = find_nearest(p.p_list,price) price=prix if b.proba[brand]['proba']>p.proba[price]['proba'] and brand!=no_brand: cat=b.cat_from_brand(brand) else: cat=p.cat_from_price(price) return cat
def calculateTafel(self, startvalue, endvalue, tafelcurr): #FIXME: get all lines #line = self.canvas.theplot[0] xdata, ydata = self.canvas.theplot[0].get_data() if tafelcurr: dataregion = xdata else: dataregion = xdata[0:int(len(xdata) / 2)] ind1, indvalue1 = find_nearest(np.array(dataregion).astype(float), float(startvalue)) ind2, indvalue2 = find_nearest(np.array(dataregion).astype(float), float(endvalue)) print(ind1, indvalue1) print(ind2, indvalue2) xdata = xdata[ind1:ind2] ydata = ydata[ind1:ind2] print("xdata: ", xdata) print("ydata: ", ydata) if tafelcurr: lognumber = np.log10(np.array(xdata).astype(float)) yplot = ydata else: lognumber = np.log10(np.array(ydata).astype(float)) yplot = xdata fig, axis = plt.subplots(1,1) line2, = axis.plot(lognumber, yplot, ls="-") slope1, intercept1, r_value1, p_value1, std_err1 = stats.linregress(lognumber, np.array(yplot).astype(float)) linefit = slope1 * np.array(lognumber) + intercept1 axis.plot(lognumber, linefit, ':', label=str(int(round(slope1, 3) * 1000)) + " mV/dec") # print ('slope: ', slope1, '; intercept: ', intercept1) axis.set_xlabel("Log i") axis.set_ylabel("E") leg = axis.legend(loc='best', shadow=False) fig.tight_layout() #print("lines: ", axis.lines) savebutton = QPushButton("CSV") savebutton.clicked.connect(lambda: self.exportData(axis, True)) fig.canvas.manager.toolbar.addWidget(savebutton) fig.show()
def ps_interp(z, k, matrix, z_vect, k_vect): if (z < np.min(z_vect) or (z > np.max(z_vect)) or (k < np.min(k_vect)) or (k > np.max(k_vect))): return 0. ind_z_low, ind_z_up = tools.find_nearest(z_vect, z) ind_k_low, ind_k_up = tools.find_nearest(k_vect, k) z_low = z_vect[ind_z_low] z_up = z_vect[ind_z_up] k_low = k_vect[ind_k_low] k_up = k_vect[ind_k_up] if ((matrix[ind_k_low, ind_z_low] <= 0.) or (matrix[ind_k_up, ind_z_low] <= 0) or (matrix[ind_k_low, ind_z_up] <= 0) or (matrix[ind_k_up, ind_z_up] <= 0)): return 0. else: ps_z_low = 10.**tools.lininterp(k, k_low, k_up, np.log10(matrix[ind_k_low, ind_z_low]), np.log10(matrix[ind_k_up, ind_z_low])) ps_z_up = 10.**tools.lininterp(k, k_low, k_up, np.log10(matrix[ind_k_low, ind_z_up]), np.log10(matrix[ind_k_up, ind_z_up])) return tools.lininterp(z, z_low, z_up, ps_z_low, ps_z_up)
def SSE(self): subset = {} for i in range(len(self.centers)): subset[i] = [] for example in self.examples: index = tools.find_nearest(example, self.centers) subset[i].append(example) sse = 0 for key in subset: es = subset[key] for e in es: nc = numpy.array(self.centers[key]) ne = numpy.array(e) nsse = (nc - ne) * (nc - ne) sse += nsse.sum() return sse
def compute_category(self, item): #Core function, associating an item with a category #item is a vector just read from the file if self.train: price_position = self.price_position else: price_position = self.price_position_test price = float(item[price_position]) if price <= 0: cat = '1000015309' else: price = self.transform(price) p = None p = find_nearest(self.p_list, price) cat = self.cat_from_price(p) return cat
def compute_category(self,item): #Core function, associating an item with a category #item is a vector just read from the file if self.train: price_position = self.price_position else: price_position = self.price_position_test price = float(item[price_position]) if price <= 0: cat = '1000015309' else: price = self.transform(price) p = None p = find_nearest(self.p_list,price) cat = self.cat_from_price(p) return cat
def fit(self, examples): # init centers self.examples = examples max_range = max(map(max, examples)) min_range = min(map(min, examples)) lenth = len(examples[0]) def get_rangdom(): c = [] for i in range(lenth): c.append(random.randrange(min_range, max_range, _int=float)) return c centers = [get_rangdom() for i in range(self.k)] while True: ifchange = False subset = {} for i in range(len(centers)): subset[i] = [] # split for e in examples: index = tools.find_nearest(e, centers) subset[index].append(e) # new center new_centers = [] for i in range(len(centers)): if len(subset[i]) == 0: continue # basic k-means nc = tools.get_centers(subset[i]) new_centers.append(nc) if len(new_centers) != len(centers): centers = new_centers continue if self.ifchange(new_centers, centers): centers = new_centers break centers = new_centers self.centers = centers
def fitCurve(self, startpot, endpot, forward, scanrate): #FIXME: get all lines #line = self.canvas.theplot[0] xdata, ydata = self.canvas.theplot[0].get_data() ydata = savgol_filter(np.array(ydata).astype(np.float), 11, 1) #FIXME: when not cyclic voltammetry (same number of forward/backward data points) if forward: limit0 = 0 limit1 = int(len(xdata)/2) offset = len(xdata) - limit1 else: limit0 = int(len(xdata)/2) limit1 = len(xdata) offset = limit1-limit0 #limit0 = 0 #limit1 = len(xdata) #offset = limit1-limit0 print("limits: ", limit0, " ", limit1) print("potentials: ", startpot, " ", endpot) ind1, indvalue1 = find_nearest(np.array(xdata[limit0:limit1]).astype(float), float(startpot)) ind2, indvalue2 = find_nearest(np.array(xdata[limit0:limit1]).astype(float), float(endpot)) print (ind1, indvalue1) print (ind2, indvalue2) if not forward: ind1 += offset ind2 += offset print("ind1, ind2: ", ind1, ind2) xdata = xdata[ind1:ind2] ydata = ydata[ind1:ind2] xdata = np.array(xdata).astype(float) ydata = np.array(ydata).astype(float) if not forward: ydata = -ydata baseline = peakutils.baseline(ydata, 1) diff = np.array(ydata) - np.array(baseline) from scipy.integrate import simps # Compute the area using the composite trapezoidal rule. xdatatime = np.array(xdata).astype(float) / float(scanrate) # convert to s print ("potentia range: ", xdata) print("scanrate: ", scanrate) print("time: ", xdatatime) ydataamps = np.array(diff).astype(float) / 1000 # convert to A print ("currents: ", ydataamps) area = trapz(y=ydataamps, x=xdatatime, dx=100) print("area = %.6f C" % area) indexes = peakutils.indexes(ydata, thres=0.01, min_dist=0.01) print(indexes) peaks_x = peakutils.interpolate(xdata, ydata, ind=indexes) print("peaks: ", peaks_x) peakheights = [] for i in range(len(indexes)): height = ydata[indexes[i]] - baseline[indexes[i]] peakheights.append(height) peakpotentials = xdata[indexes] print("peak potentials: ", peakpotentials) print("peak heights: ", peakheights) # # from scipy import optimize # # def gaussian(x, height, center, width, offset): # #return height * np.exp(-(x - center) ** 2 / (2 * width ** 2)) + offset # # return height * width ** 2 / ((x - center) ** 2 + width ** 2) # # def three_gaussians(x, h1, c1, w1, h2, c2, w2, h3, c3, w3, offset): # return (gaussian(x, h1, c1, w1, offset=0) + # gaussian(x, h2, c2, w2, offset=0) + # gaussian(x, h3, c3, w3, offset=0) + offset) # # def two_gaussians(x, h1, c1, w1, h2, c2, w2, offset): # return three_gaussians(x, h1, c1, w1, h2, c2, w2, 0, 0, 1, offset) # # #errfunc3 = lambda p, x, y: (three_gaussians(x, *p) - y) ** 2 # errfunc2 = lambda p, x, y: (two_gaussians(x, *p) - y) ** 2 # # #guess3 = [0.49, 0.55, 0.01, 0.6, 0.61, 0.01, 1, 0.64, 0.01, 0] # # I guess there are 3 peaks, 2 are clear, but between them there seems to be another one, based on the change in slope smoothness there # guess2 = [8, 0.07, 0.01, 2, 0.27, 0.01, 0] # I removed the peak I'm not too sure about # #optim3, success = optimize.leastsq(errfunc3, guess3[:], args=(xdata, diff)) # optim2, success = optimize.leastsq(errfunc2, guess2[:], args=(xdata, diff)) # # plt.plot(xdata, diff, lw=5, c='g', label='measurement') # #plt.plot(xdata, three_gaussians(xdata, *optim3), lw=3, c='b', label='fit of 3 Gaussians') # plt.plot(xdata, two_gaussians(xdata, *optim2), lw=1, c='r', ls='--', label='fit of 2 Gaussians') # plt.legend(loc='best') # #plt.savefig('result.png') # plt.show() # from scipy.optimize import curve_fit # # from scipy.special import erf # # def asym_peak(t, pars): # 'from Anal. Chem. 1994, 66, 1294-1301' # a0 = pars[0] # peak area # a1 = pars[1] # elution time # a2 = pars[2] # width of gaussian # a3 = pars[3] # exponential damping term # f = (a0 / 2 / a3 * np.exp(a2 ** 2 / 2.0 / a3 ** 2 + (a1 - t) / a3) # * (erf((t - a1) / (np.sqrt(2.0) * a2) - a2 / np.sqrt(2.0) / a3) + 1.0)) # return f # # def two_peaks(t, *pars): # 'function of two overlapping peaks' # a10 = pars[0] # peak area # a11 = pars[1] # elution time # a12 = pars[2] # width of gaussian # a13 = pars[3] # exponential damping term # a20 = pars[4] # peak area # a21 = pars[5] # elution time # a22 = pars[6] # width of gaussian # a23 = pars[7] # exponential damping term # p1 = asym_peak(t, [a10, a11, a12, a13]) # p2 = asym_peak(t, [a20, a21, a22, a23]) # return p1 + p2 # # parguess = (50, 0.07, 0.05, 0.1, 50, 0.27, 0.05, 0.1) # popt, pcov = curve_fit(two_peaks, xdata, diff, parguess) # # pars1 = popt[0:4] # pars2 = popt[4:8] # # peak1 = asym_peak(xdata, pars1) # peak2 = asym_peak(xdata, pars2) # # plt.figure() # plt.plot(xdata, diff) # plt.plot(xdata, peak1, 'r-') # plt.plot(xdata, peak2, 'g-') # plt.show() #a,b,c = peakutils.gaussian_fit(xdata, ydata, center_only=False) #print("gauss: ", a, " ", b, " ", c) #ygauss = peakutils.gaussian(xdata, a,b,c) # from scipy.optimize import curve_fit # from scipy import asarray as ar, exp # # n = len(xdata) # the number of data # mean = sum(xdata * ydata) / n # note this correction # sigma = sum(ydata * (xdata - mean) ** 2) / n # note this correction # # def gaus(x, a, x0, sigma): # #return a * sigma ** 2 / ((x - x0) ** 2 + sigma ** 2) # return a * exp(-(x - x0) ** 2 / (2 * sigma ** 2)) # # popt, pcov = curve_fit(gaus, xdata, ydata, p0=[1, mean, sigma]) # # plt.plot(xdata, ydata, 'b+:', label='data') # plt.plot(xdata, gaus(xdata, *popt), 'ro:', label='fit') # plt.legend() # plt.title('Fig. 3 - Fit for Time Constant') # plt.xlabel('Time (s)') # plt.ylabel('Voltage (V)') # plt.show() # import fitraman # # TODO: adjust number of peaks to find, initialwidth, curve type, sigmavalue # peaks_to_find = 2 # initialwidth = 0.05 # fitraman.CURVE = "Gaussian" # # fitraman.SIGMAVALUE = np.full(len(subtract), 5) # params, fit, ys, n_peaks = fitraman.predict_and_plot_lorentzians(xdata, diff, peaks_to_find, initialwidth) # print ('params: ', params) # # peakdata = [] # for j in range(0, len(params), 3): # ctr = params[j] # amp = params[j + 1] # width = params[j + 2] # peakdata.append(["%.2f" % ctr, "%.2f" % amp, "%.2f" % width]) # ysignal = fitraman.lorentzian(xdata, amp, ctr, width) # ymax = np.max(ysignal) # idxmax = np.argmax(ysignal) # # plot max points in fitted curves # # plt.plot(xdata[idxmax], ymax, ls='', marker='x') # #Plot max points in experimental curve # plt.plot(xdata[idxmax], diff[idxmax], ls='', marker='x') # plt.plot(xdata, ysignal, ls='-', label="ysignal") # # #self.printpeakdata(peakdata) # #plt.plot(xdata, fit, 'r-', label='fit', c='red', lw=1.2, ls='--') # plt.plot(xdata, diff, label="data") # # plt.legend(loc='upper right', fontsize=10, shadow=True) # plt.show() if not forward: ydata = -ydata diff = -diff baseline = -baseline fig, axis = plt.subplots(1, 1) #lognumber = np.log10(np.array(ydata).astype(float)) line2, = axis.plot(xdata, ydata, ls="-", label="data") line3, = axis.plot(xdata, baseline, ls=":", label="baseline") line3, = axis.plot(xdata, diff, ls=":", label="corrected") #line4, = axis.plot(xdata[indexes], ydata[indexes], "r+") #line5, = axis.plot(xdata, ygauss, ls=":", label="gauss") #slope1, intercept1, r_value1, p_value1, std_err1 = stats.linregress(lognumber, np.array(xdata).astype(float)) #linefit = slope1 * np.array(lognumber) + intercept1 #axis.plot(lognumber, linefit, ':', label=str(int(round(slope1, 3) * 1000)) + " mV/dec") # print ('slope: ', slope1, '; intercept: ', intercept1) axis.set_xlabel("E") axis.set_ylabel("i") plt.title("Charge = %.6f C" % area, fontsize=12) leg = axis.legend(loc='best', shadow=False) fig.tight_layout() fig.show()
# Print nice channel column headers. print('Reading ADS1x15 values, press Ctrl-C to quit...') print('| {0:>6} | {1:>6} | {2:>6} |'.format(*range(4))) print('-' * 37) # Measurements while (True): # Read all the ADC channel values in a list. values = [0]*4 # Read the specified ADC channel using the previously set gain value. #Display Voltage in mV: values[0] = ((adc.read_adc(0, gain=GAIN))*4096/32767) #Display Resistance: values[1] = values[0]/current #Display Temperature: values[2] = find_nearest(conv_list, values[1]) # Print the ADC values. print('| {0:>6} | {1:>6} | {2:>6} |'.format(*values)) # Pause for two seconds. time.sleep(2)