def findoffBB(self, t, plane, MADTwiss, betalist): print "METHOD => Starting to calculate off-momentum beta-beat" self.bpms = intersect(t) self.bpms = modelIntersect(self.bpms, MADTwiss) MADTwiss.chrombeat() self.slope = {} self.slopeE = {} self.slopeM = {} dpplist = [] for i in range(len(betalist)): #### for sorting dpplist.append(betalist[i]['DPP']) dpplist.sort() #if dpplist[0]>dpplist[1] #dpplist.reverse() for i in range(len(self.bpms)): bn = upper(self.bpms[i][1]) check = 0 slopei = 0.0 slopeiM = 0.0 beta = [] k = 0 for k in range(len(dpplist)): count = 0 for j in range(len(betalist)): if dpplist[k] == betalist[j]['DPP']: if count == 0: beta.append(betalist[j][bn][0]) count = 1 [slope, offset, R, slope_error, offset_error] = linreg.linreg(dpplist, beta) a = FIT(dpplist, beta, 1, 1e-15) #print ' list '+str(dpplist) coef, error = a.linreg() if plane == 'H': slopeiM = MADTwiss.dbx[MADTwiss.indx[upper(bn)]] else: slopeiM = MADTwiss.dby[MADTwiss.indx[upper(bn)]] #self.slope[bn]=coef[0] self.slope[bn] = coef[0] / 100 #self.slopeE[bn]=error[0] self.slopeE[bn] = error[0] / 100 self.slopeM[bn] = slopeiM
def startUp(self): #generate dummy data to plot at start-up X = np.arange(800, 2000, 2) Y1 = FIT.lorents(X, 1800, 1358, 110) Y2 = FIT.lorents(X, 1700, 1590, 50) self.subplot.plot(X, (Y1+Y2)+20*np.random.randn(len(X)), 'o') self.subplot.plot(X, Y1+Y2, 'r--', label = 'Sample data') self.subplot.legend() self.subplot.plot(X, Y1) self.subplot.plot(X, Y2) self.subplot.set_xlim(np.min(X), np.max(X)) self.plotAdjust()
def previewAll(self): if not np.shape(self.data.X): self.errorBox('There is no data', 'No data...') return self.subplot.clear() self.subplot.plot(self.data.X, self.data.current, label = 'Experimental data') cols = self.tableWidget.columnCount() rows = self.tableWidget.rowCount() cumulative = np.zeros(len(self.data.X)) intensity = [float(self.tableWidget.item(row, 5).text()) for row in range(rows) if self.tableWidget.item(row, 0).checkState()&Qt.Checked] norm = max(self.data.current)/max(intensity) for row in range(rows): if self.tableWidget.item(row, 0).checkState() & Qt.Checked: error = [self.itemCheck(self.tableWidget.item(row, col), silent=True) for col in range(1, cols-1)] if True in error: self.errorBox("Bad parameters", "Bad values") return params =[float(self.tableWidget.item(row, col).text()) for col in [5, 6, 2]] params[0] *= norm label = self.tableWidget.item(row, 1).text() shape = self.tableWidget.cellWidget(row, 7).currentText().strip()[0] if shape == 'V': params = np.append(params, 0.5) elif shape == 'B': params = np.append(params, 0.02) p = FIT.Peak(FIT, self.data.X, *params, shape = shape) cumulative += p self.subplot.plot(self.data.X, p, label = label) self.subplot.plot(self.data.X, cumulative, 'r--', label = "Cumulative") self.plotAdjust()
def previewBand(self, row): if not np.shape(self.data.X): self.errorBox('There is no data', 'No data...') return cols = self.tableWidget.columnCount() params =[self.tableWidget.item(row, col).text() for col in range(1, cols-1)] shape = self.tableWidget.cellWidget(row, cols-1).currentText().strip()[0] label = params[0] params = np.asarray([params[4], params[5], params[1]]).astype(float) if shape == 'V': params = np.append(params, 0.5) elif shape == 'B': params = np.append(params, 0.02) self.Plot(self.data.X, self.data.current, "Experimental data") self.subplot.plot(self.data.X, FIT.Peak(FIT, self.data.X, *params, shape = shape), label = label) self.subplot.legend() self.canvas.draw()
def bound(nr, parameters): names = parameters['labels'][:nr] shape = parameters['shape'][:nr] fit = FIT(shape, names) #load the initial guess parguess =np.concatenate( [[parameters['intens'][i], parameters['width'][i], parameters['freq'][i], parameters['voigt'][i]] if shape[i]=='V' else [parameters['intens'][i], parameters['width'][i], parameters['freq'][i]] for i in np.arange(0, len(names))]) #lower bound lower = np.concatenate( [[parameters['intens_min'][i], parameters['width_min'][i], parameters['freq_min'][i], parameters['voigt_min'][i]] if shape[i]=='V' else [parameters['intens_min'][i], parameters['width_min'][i], parameters['freq_min'][i]] for i in np.arange(0, len(names))]) #higher bound upper = np.concatenate( [[parameters['intens_max'][i], parameters['width_max'][i], parameters['freq_max'][i], parameters['voigt_max'][i]] if shape[i]=='V' else [parameters['intens_max'][i], parameters['width_max'][i], parameters['freq_max'][i]] for i in np.arange(0, len(names))]) return fit, parguess, [lower, upper]
def prepDataForDeconv(self, **kwargs): #prepare the data for deconvolution #the function first checks if the data is present and that the baseline was removed #fitting parameters are then taken from the table and put in a list batch = kwargs.get('batch', False) if not np.shape(self.data.X) and not batch: self.errorBox('There is no data', 'No data...') return -1, -1, -1 if not np.shape(self.data.baseline) and not batch: result = QMessageBox.question(self, "Baseline...", "The baseline is still present!\nWould you like to remove it first?", QMessageBox.Yes| QMessageBox.No) if result == QMessageBox.Yes: res = self.Baseline() if res == -1: return -1, -1, -1 else: return -1, -1, -1 rows = self.tableWidget.rowCount() cols = self.tableWidget.columnCount() params = pd.DataFrame(columns = ['lb', 'pos', 'pos_min', 'pos_max', 'int', 'width', 'shape']) for row in range(rows): if self.tableWidget.item(row, 0).checkState() & Qt.Checked: error = [self.itemCheck(self.tableWidget.item(row, col), silent=True) for col in range(1, cols-1)] if True in error: self.errorBox("Bad parameters", "Bad values") self.dockGuess.raise_() return -1, -1, -1 d =[self.tableWidget.item(row, col).text() for col in range(1, cols-1)] p_shape = self.tableWidget.cellWidget(row, cols-1).currentText().strip()[0] params = params.append({'lb': d[0], 'pos' : d[1], 'pos_min' : d[2], 'pos_max' : d[3], 'int' : d[4], 'width' : d[5], 'shape' : p_shape}, ignore_index =True) self.fit = FIT(params['shape'], params['lb']) parguess = np.concatenate([[params['int'][i], params['width'][i], params['pos'][i]] for i in range(len(params['lb'])) ]).astype(float) lower = np.concatenate([[5, 5, params['pos_min'][i]] for i in range(len(params['lb'])) ]).astype(float) upper = np.concatenate([[float('inf'), float('inf'), params['pos_max'][i]] for i in range(len(params['lb'])) ]).astype(float) return parguess, lower, upper
def BatchWorker(*params): f, names, shape, bsParams, crop, peakLimits, parguess, bounds, index, folder = params dt = DATA() result = pd.Series(name = os.path.basename(f), index = index, dtype = object) try: dt.loadData(f) dt.crop(crop.min, crop.max) dt.fitBaseline(bsParams, peakLimits, abs = True) text = '' for deg in np.arange(0, dt.bsDegree+1): if dt.bsCoef[deg]>=0 and deg!=0: text += '+' text += '{:.4E}*x^{}'.format(dt.bsCoef[deg], dt.bsDegree-deg) result.loc['baseline'] = text except Exception as e: print("Error {}".format(e)) try: fit = FIT(shape, names) fit.deconvolute(dt, parguess, bounds, batch=True) for i, pars in enumerate(zip(names, shape)): result.loc[pars[0]+'_'+'Position'] = fit.pars[int(np.sum(fit.args[:i])+2)] result.loc[pars[0]+'_'+'Amplitude'] = fit.pars[int(np.sum(fit.args[:i]))] result.loc[pars[0]+'_'+'FWHM'] = fit.fwhm[i] result.loc[pars[0]+'_'+'Area'] = fit.area[i] if pars[1] == 'V': result.loc[pars[0]+'_'+'L/G'] = fit.pars[int(np.sum(fit.args[:i])+3)] elif pars[1] == 'B': result.loc[pars[0]+'_'+'1/q'] = fit.pars[int(np.sum(fit.args[:i])+3)] # result.iloc[1::4] = fit.pars[2::3] # result.iloc[2::4] = fit.pars[::3] # result.iloc[3::4] = fit.fwhm # result.iloc[4::4] = fit.area except Exception as e: print('Could not deconvolute the {} file'.format(f)) result.iloc[1:len(index)] = -1*np.ones(len(index)-1) print(e) path = folder+ '/' +os.path.basename(f)+'.png' fig = plt.figure(figsize=(12,8)) fit.plot(figure = fig, path = path) return result
def findoffPhase(self, t, plane, MADTwiss, phaselist): print "METHOD => Start calculating off-momentum phase" # t is collection of twiss files dpplist = [] for i in range(len(phaselist)): #### for sorting dpplist.append(phaselist[i]['DPP']) dpplist.sort() if len(t) < 2: print " Not enough files \n ... I cannot work like this! => sys.exit()" sys.exit() self.bpms = intersect(t) self.bpms = modelIntersect(self.bpms, MADTwiss) self.slope = {} self.slopeE = {} self.slopeM = {} print "The lenght of the bpms " + str(len(self.bpms)) for i in range(len(self.bpms)): print i if i == len(self.bpms) - 1: bn = upper(self.bpms[i][1]) print bn print "hereeeeeee" bn2 = upper(self.bpms[0][1]) else: bn = upper(self.bpms[i][1]) bn2 = upper(self.bpms[i + 1][1]) phase = [] if plane == 'H': slopeMp = MADTwiss.DMUX[MADTwiss.indx[bn2]] - MADTwiss.DMUX[ MADTwiss.indx[bn]] else: slopeMp = MADTwiss.DMUY[MADTwiss.indx[bn2]] - MADTwiss.DMUY[ MADTwiss.indx[bn]] for k in range(len(dpplist)): count = 0 for j in range(len(phaselist)): if dpplist[k] == phaselist[j]['DPP']: if count == 0: phase.append(phaselist[j][bn][0]) count = 1 a = FIT(dpplist, phase, 1, 1e-15) coef, error = a.linreg() self.slope[bn] = coef[0] self.slopeE[bn] = error[0] self.slopeM[bn] = slopeMp
def findoffPhase(self,t,plane,MADTwiss,phaselist): print "METHOD => Start calculating off-momentum phase" # t is collection of twiss files dpplist=[] for i in range(len(phaselist)): #### for sorting dpplist.append(phaselist[i]['DPP']) dpplist.sort() if len(t)<2: print " Not enough files \n ... I cannot work like this! => sys.exit()" sys.exit() self.bpms=intersect(t) self.bpms=modelIntersect(self.bpms, MADTwiss) self.slope={} self.slopeE={} self.slopeM={} print "The lenght of the bpms "+str(len(self.bpms)) for i in range(len(self.bpms)): print i if i==len(self.bpms)-1: bn=upper(self.bpms[i][1]) print bn print "hereeeeeee" bn2=upper(self.bpms[0][1]) else: bn=upper(self.bpms[i][1]) bn2=upper(self.bpms[i+1][1]) phase=[] if plane=='H': slopeMp=MADTwiss.DMUX[MADTwiss.indx[bn2]]-MADTwiss.DMUX[MADTwiss.indx[bn]] else: slopeMp=MADTwiss.DMUY[MADTwiss.indx[bn2]]-MADTwiss.DMUY[MADTwiss.indx[bn]] for k in range(len(dpplist)): count=0 for j in range(len(phaselist)): if dpplist[k]==phaselist[j]['DPP']: if count==0: phase.append(phaselist[j][bn][0]) count=1 a=FIT(dpplist,phase,1,1e-15) coef,error=a.linreg() self.slope[bn]=coef[0] self.slopeE[bn]=error[0] self.slopeM[bn]=slopeMp
def findoffBB(self,t,plane,MADTwiss,betalist): print "METHOD => Starting to calculate off-momentum beta-beat" self.bpms=intersect(t) self.bpms=modelIntersect(self.bpms, MADTwiss) MADTwiss.chrombeat() self.slope={} self.slopeE={} self.slopeM={} dpplist=[] for i in range(len(betalist)): #### for sorting dpplist.append(betalist[i]['DPP']) dpplist.sort() #if dpplist[0]>dpplist[1] #dpplist.reverse() for i in range(len(self.bpms)): bn=upper(self.bpms[i][1]) check=0 slopei=0.0 slopeiM=0.0 beta=[] k=0 for k in range(len(dpplist)): count=0 for j in range(len(betalist)): if dpplist[k]==betalist[j]['DPP']: if count==0: beta.append(betalist[j][bn][0]) count=1 [slope, offset, R, slope_error, offset_error]=linreg.linreg(dpplist,beta) a=FIT(dpplist,beta,1,1e-15) #print ' list '+str(dpplist) coef,error=a.linreg() if plane=='H': slopeiM=MADTwiss.dbx[MADTwiss.indx[upper(bn)]] else: slopeiM=MADTwiss.dby[MADTwiss.indx[upper(bn)]] #self.slope[bn]=coef[0] self.slope[bn]=coef[0]/100 #self.slopeE[bn]=error[0] self.slopeE[bn]=error[0]/100 self.slopeM[bn]=slopeiM