def iv(self, channel, start=0, stop=3, step=0.2, delay=0.2): ''' Take an IV on channel chan: - start / stop in V - steps ''' biaspar = 'bias%d' % channel vmeaspar = 'vmeas%d' % channel r = self.get_resistance() / 1000.0 # Not sure why this is dividing. Bug? n = (int(abs(stop - start) / step)) + 1 data = qt.Data(name='iv') data.add_coordinate('Vbias', units='V') data.add_value('Vmeas', units='V') data.create_file() for i in range(n): v_out = start + i * step current = v_out/r self.set(biaspar, v_out, check=False) qt.msleep(delay) v_meas = self.get(vmeaspar) print 'v_out, current_out, v_meas: %f, %f, %f' %(v_out, current, v_meas) data.add_data_point(v_out, v_meas) self.set(biaspar, 0) qt.plot(data, name='iv', clear=True) return data
def plot_last_histogram(self): y, x = self._hist, self._hist_bins[ 1:] * self._hist_binsize_ns #np.histogram(self._dts_ns, bins = np.linspace(self.get_roi_min(), self.get_roi_max(),pts))#np.min(dts[dts>0]),np.max(dts),pts)) plotname = self.get_name() + '_histogram' qt.plot(x, y, name=plotname, clear=True) f = common.fit_exp_decay_shifted_with_offset #A * exp(-(x-x0)/tau) + a #['g_a', 'g_A', 'g_tau', 'g_x0'] args = [1, np.max(y) * 0.1, 12, x[np.argmax(y) + 2.]] first_fit_bin = int( np.round(self._plot_extra_range / self._hist_binsize_ns)) xf, yf = x[first_fit_bin:], y[first_fit_bin:] fitres = fit.fit1d(xf, yf, f, *args, fixed=[0], do_print=False, ret=True, maxfev=100) plot_pts = 200 x_p = np.linspace(min(xf), max(xf), plot_pts) if fitres['success']: y_p = fitres['fitfunc'](x_p) print 'fit success' else: y_p = f(*args)[1](x_p) print 'fit failed' print fitres['params_dict'] qt.plot(x_p, y_p, 'b', name=plotname, clear=False) self.y = y self.x = x
def plot_trace(self): ''' performs a measurement and plots the data. ''' freqs, reply = self.get_trace() qt.plot(freqs, reply, name='netan', xlabel='freq [Hz]', ylabel='S_ij [dB]', clear=True)
def save_spectrum(self, ret=False): spec = andor.get_spectrum() specd = qt.Data(name='spectrum') specd.add_value('Counts') specd.create_file() specd.add_data_point(spec) specd.close_file() qt.plot(specd, name='saved_spectrum', clear=True) if ret: return spec
def save_spectrum(self, ret=False): spec = winspec.get_spectrum() specd = qt.Data(name='spectrum') specd.add_coordinate('Wavelength', units='nm') specd.add_value('Counts') specd.create_file() specd.add_data_point(spec) specd.close_file() qt.plot(specd, name='saved_spectrum', clear=True) if ret: return spec
def save_spectrum(self, ret=False): spec = winspec.get_spectrum() specd = qt.Data(name="spectrum") specd.add_coordinate("Wavelength", units="nm") specd.add_value("Counts") specd.create_file() specd.add_data_point(spec) specd.close_file() qt.plot(specd, name="saved_spectrum", clear=True) if ret: return spec
def iv_counts_disc_sr400(self, channel, start=0, stop=10, step=0.25, delay=0.2, discarray = [0.2]): ''' Take an IV on channel chan and measure count rate: - start / stop in V - steps ''' print '' sr400 = qt.instruments['sr400'] biaspar = 'bias%d' % channel vmeaspar = 'vmeas%d' % channel r = self.get_resistance() / 1000.0 n = (int(abs(stop - start) / step)) + 1 data = qt.Data(name='iv') data.add_coordinate('Vbias', units='V') data.add_value('Vmeas', units='V') data.add_value('Counts', units='') data.create_file() plot3d = qt.Plot3D(data, name='3D', style='image', coorddims=(1,0), valdim=2) for disc in discarray: if (msvcrt.kbhit() and (msvcrt.getch() == 'q')): break sr400.set_disc_levelA(disc) sr400.set_disc_levelB(disc) for i in range(n): if (msvcrt.kbhit() and (msvcrt.getch() == 'q')): break v_out = start + i * step current = v_out/r self.set(biaspar, v_out, check=False) time.sleep(delay) v_meas = self.get(vmeaspar) if channel == 0: counts = sr400.get_countA() else: counts = sr400.get_countB() print 'v_out, current_out, v_meas, counts: %f, %f, %f, %d' % (v_out, current, v_meas, counts) data.add_data_point(v_out, v_meas, counts) data.add_data_point(v_out, disc, counts) if v_meas > 0.5: break self.set(biaspar, 0) qt.plot(data, name='ivcounts', clear=True) qt.plot(data, name='ivcounts', valdim=2, right=True) return data
def optimize(self, plot=0, dims='Vdim', cycles=1): if 'laserscan_plot' in qt.plots: qt.plots['laserscan_plot'].clear() qt.plot(name='laserscan_plot',clear=True,needtempfile=False) for c in range(cycles): ret = True #print '%s' % self.dimensions['V'] for d in self.dimensions[dims]: #print 'dims is %s d is %s' % (dims, d) scan_length = self.dimensions[d]['scan_length'] nr_of_points = self.dimensions[d]['nr_of_points'] if d == 'V': # Get the current voltage from the Toptica cur_V = self._topt.get_piezo_voltage() if cur_V == None: logging.warning(__name__ + 'Current position is none! Toptica voltage not initialized?') break self._opt_pos_prev['V'] = cur_V # Create the desired array of points to measure point_array = np.linspace(cur_V-scan_length/2.0,cur_V+scan_length/2.0,nr_of_points) count_array = self.sweep_laser_and_count(point_array) # Find the difference between readouts to get the counts measured # at a certain point, then divide by the period to get the estimate # of the counts per second # Call the fitting routine to determine optimal position # and set it as self._opt_pos['x'], in this case. ret = self.process_fit(point_array, count_array, 'V', 10.0) print 'Previous V/sigma: %.3f/%.3f, new optimum V: %.3f (delta %.1f V)' % (self._opt_pos_prev['V'], self._opt_sigma_prev['V'], self._opt_pos['V'], self._opt_pos['V']-self._opt_pos_prev['V']) # if np.array(point_array).min() < self._opt_pos['V'] < np.array(point_array).max(): self._topt.set_piezo_voltage(self._opt_pos['V']) else: self._topt.set_piezo_voltage(self._opt_pos_prev['V']) self._opt_pos['V'] = self._opt_pos_prev['V'] print 'Optimum outside scan range: Position is set to previous maximum' ret = False qt.msleep(0.05) if msvcrt.kbhit(): kb_char=msvcrt.getch() if kb_char == "q" : break return ret
def focus_plot(self): samples = 12000 rate = 240000 channel = self.FP_params['aiport'] while True: rsamples = self.read_sweep(samples, rate, channel) time_axis = np.linspace(0.0,float(np.size(rsamples))/rate,np.size(rsamples)) qt.plot(time_axis,rsamples,name='fp_focusplot',traceofs=0.2, clear=True,linewidth=6) time.sleep(0.5) if msvcrt.kbhit(): kb_char=msvcrt.getch() if kb_char == "q" : break return
def iv_counts_sr400(self, channel, start=0, stop=10, step=0.25, delay=0.2): ''' Take an IV on channel chan and measure count rate: - start / stop in V - steps ''' print '' sr400 = qt.instruments['sr400'] biaspar = 'bias%d' % channel vmeaspar = 'vmeas%d' % channel r = self.get_resistance() / 1000.0 n = (int(abs(stop - start) / step)) + 1 data = qt.Data(name='iv') data.add_coordinate('Vbias', units='V') data.add_value('Vmeas', units='V') data.add_value('Counts', units='') data.create_file() for i in range(n): v_out = start + i * step current = v_out/r self.set(biaspar, v_out, check=False) time.sleep(delay) v_meas = self.get(vmeaspar) if channel == 0: counts = sr400.get_countA() else: counts = sr400.get_countB() print 'v_out, current_out, v_meas, counts: %f, %f, %f, %d' % (v_out, current, v_meas, counts) data.add_data_point(v_out, v_meas, counts) if v_meas > 0.5: break self.set(biaspar, 0) qt.plot(data, name='ivcounts', clear=True) qt.plot(data, name='ivcounts', valdim=2, right=True) return data
def find_initial_values_lorentzian(x_data, y_data, moving_average=2, plot_res=False): ''' finds the initial values for a lorentzian dip or peak p[0] = x0 p[1] = 2*HM dip height p[2] = dx width p[3] = y0 offset ''' p = 4 * [0] diffy = mva.movingaverage(diff(y_data), moving_average) if plot_res: pl = plot(name='find_resonance') pl.clear() plot(diffy, title='moving_average of diff_y', name='find_resonance') plot(y_data, title='y_data', name='find_resonance') dymax = max(diffy) i_dymax = diffy.tolist().index(dymax) dymin = min(diffy) i_dymin = diffy.tolist().index(dymin) if i_dymin > i_dymax: ''' means its a peak ''' peak = 1 y0 = min(y_data) else: ''' means its a dip ''' peak = -1 y0 = max(y_data) dx = abs(x_data[i_dymin] - x_data[i_dymax]) x0 = (x_data[i_dymin] + x_data[i_dymax]) / 2 HM = peak * abs(y_data[i_dymax] - y_data[floor((i_dymin + i_dymax) / 2)]) p[0] = x0 p[1] = 2 * HM p[2] = dx p[3] = y0 return p
def find_initial_values_lorentzian(x_data,y_data,moving_average = 2, plot_res = False): ''' finds the initial values for a lorentzian dip or peak p[0] = x0 p[1] = 2*HM dip height p[2] = dx width p[3] = y0 offset ''' p=4*[0] diffy = mva.movingaverage(diff(y_data),moving_average) if plot_res: pl = plot(name='find_resonance') pl.clear() plot(diffy,title='moving_average of diff_y',name='find_resonance') plot(y_data,title='y_data',name='find_resonance') dymax = max(diffy) i_dymax = diffy.tolist().index(dymax) dymin = min(diffy) i_dymin = diffy.tolist().index(dymin) if i_dymin>i_dymax: ''' means its a peak ''' peak = 1 y0 = min(y_data) else: ''' means its a dip ''' peak = -1 y0 = max(y_data) dx = abs(x_data[i_dymin] - x_data[i_dymax]) x0 = (x_data[i_dymin] + x_data[i_dymax])/2 HM = peak*abs(y_data[i_dymax] - y_data[floor((i_dymin+i_dymax)/2)]) p[0] = x0 p[1] = 2*HM p[2] = dx p[3] = y0 return p
def save_ROI_data(self, x, y, z, sweepname='sweep_value'): roix = y roiy = z[:,self.ROI_min:self.ROI_max].sum(axis=1) np.savetxt(os.path.join(self.save_folder, self.save_filebase+'_ROI_sum.dat'), np.vstack((roix,roiy)).T) p = qt.plot(roix, roiy, 'rO-', name='ROI_summed', clear=True, xlabel=sweepname, ylabel='counts', title='ROI summed') p.reset() h,ts = os.path.split(self.save_folder) h,date = os.path.split(h) p.set_plottitle(date+'/'+ts+': '+'ROI_summed') p.save_png(os.path.join(self.save_folder, self.save_filebase))
def optimize(self): self.initialize() for i in range(int(self._iterations)): print 'Iteration %d, cur_f %.2f' % (i, self._cur_f) self.iterate() print 'Current x location is: %s, %s' % (np.array(self._cur_x), self._cur_f) time.sleep(0.1) print 'Done!' self._optimization_is_on = False if self._complete_poll == True: hist = np.array(self._history) plot2d_1 = qt.plot(np.arange(hist.size),hist,name='mads_optimize',clear=True) #plot2d = qt.plot(self._hypd, coorddim=0, valdim=1,name='optT4',clear=True) #plot2d.add_data(self._hypd, coorddim=0, valdim=2, maxtraces=1) #plot2d.add_data(self._hypd, coorddim=0, valdim=3, maxtraces=1) # # plota1 = qt.plot(self._hypd, coorddim=0, valdim=4,name='angle1',clear=True) # plota2 = qt.plot(self._hypd, coorddim=0, valdim=5,name='angle2',clear=True) # plotcmax = qt.plot(self._hypd, coorddim=0, valdim=6,name='cmax',clear=True) # plotfevals = qt.plot(self._hypd, coorddim=0, valdim=8, maxtraces=1, clear=True) # plotmmax = qt.plot(self._hypd, coorddim=0, valdim=9, name='mmax', maxtraces=1, clear=True) else: hist = np.array(self._history) plot2d_1 = qt.plot(np.arange(hist.size),hist,name='mads_optimize',clear=True) # # plota1 = qt.plot(self._hypd, coorddim=0, valdim=1,name='angle1',clear=True) # plota2 = qt.plot(self._hypd, coorddim=0, valdim=2,name='angle2',clear=True) # plotcmax = qt.plot(self._hypd, coorddim=0, valdim=3,name='cmax',clear=True) # plotfevals = qt.plot(self._hypd, coorddim=0, valdim=5, maxtraces=1, clear=True) # plotmmax = qt.plot(self._hypd, coorddim=0, valdim=6, maxtraces=1, clear=True, name='mmax') print 'Total function evals: %d' % self._nfeval # plotff = qt.plot(self._fed, coorddim=0, valdim=1, maxtraces=1, name='fevalp', clear=True) return np.array(self._cur_x)
def max_intensity_plot(self): samples = 500 rate = 10000 channel = self.FP_params['aiport'] data = qt.Data(name='max_int_data') data.add_coordinate('time') data.add_value('intensity') t0 = time.time() miplot = qt.plot(data,name='maxintplot',traceofs=0.2, coorddim=0, valdim=1, maxpoints=100, linewidth=6, clear=True) while True: rsamples = self.read_sweep(samples, rate, channel) data.add_data_point((time.time()-t0),np.max(rsamples)) miplot.update() time.sleep(0.5) if msvcrt.kbhit(): kb_char=msvcrt.getch() if kb_char == "q" : break return
def save_trace(self, filepath=None, plot=True): ''' runs 'get_trace()' and saves the output to a file. Input: filepath (string): Path to where the file should be saved.(optional) Output: filepath (string): The filepath where the file has been created. ''' #TODO: change value label 'S_ij' to represent actual measurement freqs, reply = self.get_trace() d = qt.Data(name='netan') d.add_coordinate('freq [Hz]') d.add_value('S_ij [dB]') d.create_file(filepath=filepath) d.add_data_point(zip(freqs, reply)) d.close_file() if plot: p = qt.plot(d, name='netan', clear=True) p.save_png() p.save_gp() return d.get_filepath()
def save_ROI_data(self, x, y, z, sweepname='sweep_value'): roix = y roiy = z[:, self.ROI_min:self.ROI_max].sum(axis=1) np.savetxt( os.path.join(self.save_folder, self.save_filebase + '_ROI_sum.dat'), np.vstack((roix, roiy)).T) p = qt.plot(roix, roiy, 'rO-', name='ROI_summed', clear=True, xlabel=sweepname, ylabel='counts', title='ROI summed') p.reset() h, ts = os.path.split(self.save_folder) h, date = os.path.split(h) p.set_plottitle(date + '/' + ts + ': ' + 'ROI_summed') p.save_png(os.path.join(self.save_folder, self.save_filebase))
def avg_max_intensity_plot(self): samples = 500 rate = 10000 channel = self.FP_params['aiport'] data = qt.Data(name='avg_max_int_data') data.add_coordinate('time') data.add_value('intensity') t0 = time.time() miplot = qt.plot(data,name='avgmaxintplot',traceofs=0.2, coorddim=0, valdim=1, maxpoints=100,linewidth=7,clear=True) while True: rsamples = self.read_sweep(samples, rate, channel) time_axis = np.linspace(0.0,float(np.size(rsamples))/rate,np.size(rsamples)) p = pf.PeakFinder(time_axis,rsamples, maxpeaks = 4,threshold = 4,fitwidth=35,fitfunc='FIT_LORENTZIAN',amp_threshold=0.2) peaks = p.find(sign=1, bgorder=1) peak_array = np.array(peaks) data.add_data_point((time.time()-t0),np.mean(peak_array[:,1])) miplot.update() time.sleep(0.5) if msvcrt.kbhit(): kb_char=msvcrt.getch() if kb_char == "q" : break return
import numpy as np import qt x = np.arange(-10, 10, 0.2) y = np.sinc(x) yerr = 0.1 * np.random.rand(len(x)) d = qt.Data() d.add_coordinate("x") d.add_coordinate("y") d.add_coordinate("yerr") d.create_file() d.add_data_point(x, y, yerr) p = qt.Plot2D() p.add_data(d, coorddim=0, valdim=1, yerrdim=2) # or: qt.plot(x, y, yerr=yerr, name="test2")
def plot(self): if not self._dev: return import qt x, trace = self._dev.get_block() qt.plot(trace, name='picoharp', clear=True)
def process_fit(self, p, cr, dimension): # p is position array # cr is countrate array # d is a string corresponding to the dimension # Get the Gaussian width sigma guess from the dimensions dictionary sigma_guess = self.dimensions[dimension]['sigma'] # Always do a Gaussian fit, for now self._gaussian_fit = True if self._gaussian_fit: # Come up with some robust estimates, for low signal/noise conditions a_guess = np.array(cr).min() A_guess = np.array(cr).max()-np.array(cr).min() p_size = np.size(p) x0_guess = p[np.round(p_size/2.0)] #np.sum(np.array(cr) * np.array(p))/np.sum(np.array(cr)**2) #sigma_guess = 1.0#np.sqrt(np.sum(((np.array(cr)-x0_guess)**2)*(np.array(p))) / np.sum((np.array(p)))) #print 'Guesses: %r %r %r %r' % (a_guess, x0_guess,A_guess,sigma_guess) gaussian_fit = fit.fit1d(np.array(p,dtype=float), np.array(cr,dtype=float),common.fit_gauss, a_guess, x0_guess,A_guess, sigma_guess, do_print=False,ret=True) ababfunc = a_guess + A_guess*np.exp(-(p-x0_guess)**2/(2.0*sigma_guess**2)) if type(gaussian_fit) != dict: pamax = np.argmax(cr) self._opt_pos[dimension] = p[pamax] ret = False print '(%s) fit failed! Set to maximum.' % dimension else: if gaussian_fit['success'] != False: self._fit_result = [gaussian_fit['params'][1], gaussian_fit['params'][2], gaussian_fit['params'][3], gaussian_fit['params'][0] ] self._fit_error = [gaussian_fit['error'][1], gaussian_fit['error'][2], gaussian_fit['error'][3], gaussian_fit['error'][0] ] self._opt_pos[dimension] = self._fit_result[0] ret = True final_fit_func = gaussian_fit['params'][0] + gaussian_fit['params'][2]*np.exp(-(p-gaussian_fit['params'][1])**2/(2.0*gaussian_fit['params'][3]**2)) qt.plot(p,cr,p,ababfunc,p,final_fit_func,name='fbl_plot',needtempfile=False) #print '(%s) optimize succeeded!' % self.get_name() else: self.set_data('fit', zeros(len(p))) ret = False print '(%s) optimize failed! Set to maximum.' % dimension self._opt_pos[dimension] = p[np.argmax(cr)] qt.plot(p,cr,p,ababfunc,name='fbl_plot',clear=True,needtempfile=False) return ret
def num2str(num, precision): return "%0.*f" % (precision, num) A = fit.Parameter(max(measured_power - BG) / 2) B = fit.Parameter(max(measured_power - BG) / 2) f = fit.Parameter(1 / 2.5) phi = fit.Parameter(0) def fit_cos(x): return A() + B() * cos(2 * pi * f() * x + phi()) ret = fit.fit1d(V_EOM.reshape(-1), measured_power.reshape(-1) - BG, None, fitfunc=fit_cos, p0=[A, B, f, phi], do_plot=True, do_print=True, ret=True) p = qt.plots['EOM Calibration curve'] V = linspace(EOM_min_voltage, EOM_max_voltage, V_step_size / 10) qt.plot(V, fit_cos(V), 'r-', name='EOM Calibration curve') plt.save_png(file_directory[0:65] + 'calibration_EOM_curve.png') print 'Extinction = max/min = ' + num2str( max(measured_power - BG) / min(measured_power - BG), 0) print 'Done'
def optimize(self, plot=0, dims='xyz', cycles=1): if 'fbl_plot' in qt.plots: qt.plots['fbl_plot'].clear() qt.plot(name='fbl_plot',clear=True,needtempfile=False) for c in range(cycles): ret = True for d in self.dimensions[dims]: scan_length = self.dimensions[d]['scan_length'] nr_of_points = self.dimensions[d]['nr_of_points'] if d == 'x': # Get the current position from the FSM - only works if the # FSM has been written to at least once! cur_pos = self._fsm.get_abs_positionX() if cur_pos == None: print 'Current position is none! FSM not initialized?' break self._opt_pos_prev['x'] = cur_pos # Create the desired array of points to measure point_array = np.linspace(cur_pos-scan_length/2.0,cur_pos+scan_length/2.0,nr_of_points) # Add the beginning point so that it's in the array twice # at the beginning. This is because we're looking for the # difference between counter reads to get the counts per # second at a position. temp_point_array = np.insert(point_array,0,cur_pos-scan_length/2.0,axis=0) # Use AO Smooth Goto code to smoothly go to the beginning point self._fsm.AO_smooth(cur_pos, cur_pos-scan_length/2.0, 'X') # Now write the points and get the counts fsm_rate = 40.0 # Hz counts = self._fsm.sweep_and_count(temp_point_array,fsm_rate, 'ctr0','PFI0','X') # Find the difference between readouts to get the counts measured # at a certain point, then divide by the period to get the estimate # of the counts per second cps = np.diff(counts)*fsm_rate # Call the fitting routine to determine optimal position # and set it as self._opt_pos['x'], in this case. ret = self.process_fit(point_array, np.diff(counts), 'x', fsm_rate) print 'Previous x: %.3f, new optimum: %.3f (delta %.1f nm)' % (self._opt_pos_prev['x'], self._opt_pos['x'], self._opt_pos['x']*1E3-self._opt_pos_prev['x']*1E3) # if np.array(point_array).min() < self._opt_pos['x'] < np.array(point_array).max(): self._fsm.set_abs_positionX(self._opt_pos['x']) else: self._fsm.set_abs_positionX(self._opt_pos_prev['x']) self._opt_pos['x'] = self._opt_pos_prev['x'] print'Optimum outside scan range: Position is set to previous maximum' ret = False #print 'Position changed %d nm' % (self._opt_pos['x']*1E3-self._opt_pos_prev['x']*1E3) if d == 'y': # Get the current position from the FSM - only works if the # FSM has been written to at least once! cur_pos = self._fsm.get_abs_positionY() self._opt_pos_prev['y'] = cur_pos # Create the desired array of points to measure point_array = np.linspace(cur_pos-scan_length/2.0,cur_pos+scan_length/2.0,nr_of_points) # Add the beginning point so that it's in the array twice # at the beginning. This is because we're looking for the # difference between counter reads to get the counts per # second at a position. temp_point_array = np.insert(point_array,0,cur_pos-scan_length/2.0,axis=0) ##print 'y temp point array %s' % temp_point_array # Use AO Smooth Goto code to smoothly go to the beginning point self._fsm.AO_smooth(cur_pos, cur_pos-scan_length/2.0, 'Y') # Now write the points and get the counts fsm_rate = 40.0 # Hz counts = self._fsm.sweep_and_count(temp_point_array,fsm_rate, 'ctr0','PFI0','Y') # Find the difference between readouts to get the counts measured # at a certain point, then divide by the period to get the estimate # of the counts per second cps = np.diff(counts)*fsm_rate # Call the fitting routine to determine optimal position # and set it as self._opt_pos['y'], in this case. ret = self.process_fit(point_array, np.diff(counts), 'y', fsm_rate) print 'Previous y: %.3f, new optimum: %.3f (delta %.1f nm)' % (self._opt_pos_prev['y'], self._opt_pos['y'], self._opt_pos['y']*1.0E3-self._opt_pos_prev['y']*1.0E3) if np.array(point_array).min() < self._opt_pos['y'] < np.array(point_array).max(): self._fsm.set_abs_positionY(self._opt_pos['y']) else: self._fsm.set_abs_positionY(self._opt_pos_prev['y']) self._opt_pos['y'] = self._opt_pos_prev['y'] print 'Optimum outside scan range: Position is set to previous maximum' ret = False #print 'Position changed %d nm' % (self._opt_pos['y']*1.0E3-self._opt_pos_prev['y']*1.0E3) if d == 'z': # Get the current position from the FSM - only works if the # FSM has been written to at least once! cur_pos = self._xps.get_abs_positionZ() # In mm, not um! self._opt_pos_prev['z'] = cur_pos # In mm # Create the desired array of points to measure # Note 0.001 converts from mm to um! point_array = np.linspace(cur_pos-scan_length*0.001/2.0,cur_pos+scan_length*0.001/2.0,nr_of_points) # No need to double up on initial position in the point array # since the counts will be read out step-by-step and not in # a synchronized DAQ read. # Set the position on the XPS to the initial point; sort of redundant self._xps.set_abs_positionZ((cur_pos-0.001*scan_length/2.0)) # Now write the points and get the counts counts = np.zeros(nr_of_points) # HARDCODED SETUP FOR COUNT READING xps_rate = 40.0 # Hz xps_settle_time = 10.0*0.001 # 10 ms prev_ctr0_src = self._ni63.get_ctr0_src() self._ni63.set_ctr0_src('PFI0') prev_count_time = self._ni63.get_count_time() self._ni63.set_count_time(1.0/xps_rate) for i in range(nr_of_points): # Point array is in mm, so this should work self._xps.set_abs_positionZ((point_array[i])) qt.msleep(xps_settle_time) counts[i] = self._ni63.get_ctr0() self._ni63.set_count_time(prev_count_time) self._ni63.set_ctr0_src(prev_ctr0_src) # Find the difference between readouts to get the counts measured # at a certain point, then divide by the period to get the estimate # of the counts per second cps = counts*xps_rate # Call the fitting routine to determine optimal position # and set it as self._opt_pos['z'], in this case. ret = self.process_fit(point_array, counts, 'z', xps_rate) print 'Previous z: %.6f, new optimum is %.6f (delta %.1f nm)' % (self._opt_pos_prev['z'], self._opt_pos['z'], self._opt_pos['z']*1.0E6-self._opt_pos_prev['z']*1.0E6) # if np.array(point_array).min() < self._opt_pos['z'] < np.array(point_array).max(): self._xps.set_abs_positionZ(self._opt_pos['z']) else: self._xps.set_abs_positionZ(self._opt_pos_prev['z']) print 'Optimum outside scan range: Position is set to previous maximum' self._opt_pos['z'] = self._opt_pos_prev['z'] ret = False # Use 10^6 instead of 10^3 to convert from mm to nm qt.msleep(0.1) qt.msleep(0.05) if msvcrt.kbhit(): kb_char=msvcrt.getch() if kb_char == "q" : break return ret
def num2str(num, precision): return "%0.*f" % (precision, num) A = fit.Parameter(max(measured_power - BG) / 2) B = fit.Parameter(max(measured_power - BG) / 2) f = fit.Parameter(1 / 2.5) phi = fit.Parameter(0) def fit_cos(x): return A() + B() * cos(2 * pi * f() * x + phi()) ret = fit.fit1d( V_EOM.reshape(-1), measured_power.reshape(-1) - BG, None, fitfunc=fit_cos, p0=[A, B, f, phi], do_plot=True, do_print=True, ret=True, ) p = qt.plots["EOM Calibration curve"] V = linspace(EOM_min_voltage, EOM_max_voltage, V_step_size / 10) qt.plot(V, fit_cos(V), "r-", name="EOM Calibration curve") plt.save_png(file_directory[0:65] + "calibration_EOM_curve.png") print "Extinction = max/min = " + num2str(max(measured_power - BG) / min(measured_power - BG), 0) print "Done"
def take_spectrum(self, ret=False): spec = winspec.get_spectrum() qt.plot(spec, name='winspec_spectrum', clear=True) if ret: return spec
def take_spectrum(self, ret=False): spec = andor.get_spectrum() qt.plot(spec, name='andor_spectrum', clear=True) if ret: return spec
def fit1D(x,y,fit_func, **kw): ''' parameters x : tuple of indep. variables y : dep. var. (data) fit_func : function to be fitted structure fit_fun(x, p0) with p0 parameters known KW init_guess : vector of initial estimates for p0 guess_func : function that guesses the initial parameters p0 full_output : True by default onscreen : print reuslts on screen ret_fit : return an array fit_func(x, Pfit) plot_results=False ''' full_output = kw.pop('full_output',True) onscreen = kw.pop('onscreen',True) kw_c=kw.copy() qt.mstart() try: p0 = kw_c.pop('init_guess') except KeyError: print('No initial guess given, trying guess func instead') p0 = kw_c.pop('guess_func')(x,y) if type(x)==type((0,)): var = x+(y,) else : x=(x,) var=x+(y,) if type(p0)==type((0,)): pass else : p0=tuple(p0) plres=kw.pop('plot_results', False) if plres: pltr=plot(name='fit monitor') pltr.clear() init_guess_arr = fit_func(*(x+tuple(p0))) plot(x[0], init_guess_arr, title = 'initial guess',name='fit monitor') plot(x[0], y, title = 'data',name='fit monitor') plsq,cov,info,mesg,success = leastsq(_residuals_m, \ p0, args=(fit_func,)+var, full_output = 1, maxfev=10000)#,xtol=kw.pop('xtol',1.e-10)) try : len(plsq) except TypeError : plsq=[plsq] if onscreen: print('plsq',plsq) print('mesg',mesg) print(cov) #print 'info: ',info dof = max(np.shape(y)) - len(plsq) errors = estimate_errors(plsq,info,cov,dof) k=0 if plres: fresarr = fit_func(*(x+tuple(plsq))) plot(x[0],fresarr , title = 'fit',name='fit monitor') if onscreen: for p in plsq: print('p%s = %s +/- %s'%(k,p,errors[k])) k+=1 if kw.pop('ret_fit',False): return plsq, errors, fit_func(*(x+tuple(plsq))),cov,info else: return plsq, errors qt.mstop()
import numpy as np import qt x = np.arange(-10, 10, 0.2) y = np.sinc(x) yerr = 0.1*np.random.rand(len(x)) d = qt.Data() d.add_coordinate('ixs') d.add_coordinate('ylon') d.add_coordinate('yerr') d.create_file() d.add_data_point(x,y,yerr) p = qt.Plot2D() p.add_data(d, coorddim=0, valdim=1, yerrdim=2) # or: ('ok' is style for black circles) qt.plot(x, y, 'ok', yerr=yerr, name='test2')
def process_fit(self, p, cr, dimension, rate): # p is position array # cr is countrate array # d is a string corresponding to the dimension # Get the Gaussian width sigma guess from the dimensions dictionary sigma_guess = self.dimensions[dimension]['sigma'] # Always do a Gaussian fit, for now self._gaussian_fit = True if self._gaussian_fit: # Come up with some robust estimates, for low signal/noise conditions a_guess = np.array(cr).min()*0.9 A_guess = np.array(cr).max()-np.array(cr).min() p_size = np.size(p) x0_guess = p[np.round(p_size/2.0)] #np.sum(np.array(cr) * np.array(p))/np.sum(np.array(cr)**2) #sigma_guess = 1.0#np.sqrt(np.sum(((np.array(cr)-x0_guess)**2)*(np.array(p))) / np.sum((np.array(p)))) #print 'Guesses: %r %r %r %r' % (a_guess, x0_guess,A_guess,sigma_guess) # The following statement is that if the old sigma is within a factor of 2 of the initial fixed value # then use the old sigma as the guess for the fit. if np.abs(self._opt_sigma_prev[dimension]/self.dimensions[dimension]['sigma']) < 2.0 and np.abs(self._opt_sigma_prev[dimension]/self.dimensions[dimension]['sigma']) > 0.3: sigma_guess = self._opt_sigma_prev[dimension] else: sigma_guess = self.dimensions[dimension]['sigma'] ababfunc = (a_guess + A_guess*np.exp(-(p-x0_guess)**2/(2.0*sigma_guess**2)))*rate # New method for fitting # Purpose of this new method is to improve the robustness of both the numerical optimization and the 'mistracks' # that can occur because of nearby luminescence. # I think that the numerical robustness can be improved by using a # multiple start technique -- start the optimization at a series of # guesses across the frequency range, and note the 'best fit' value # of each. Pick the one with the best fit of each of these fits, and # return it, subject to the condition that the center of the peak is # within the min/max of the scan range. This way, it will be no # worse than the existing method and significantly more robust to # finding the global minimum. # The second modification is to reduce the probability of a fit to # a nearby peak that isn't the one we want, which I call a 'mistrack'. # This can be done by multiplying the likelihood by a prior, making # it a Bayesian method, that incorporates our knowledge that the # peak we want will not drift too far from scan to scan. Therefore, # given two peaks that fit equally well, the one nearest to the old # peak location should be selected preferentially. The exception to # this is if the other peak fits exceedingly well; these statements # are quantified by the exact prior probability distribution used. bf_ret = self.bayesian_fit(p, cr, np.array((A_guess, x0_guess, sigma_guess, a_guess)),self.dimensions[dimension]['drift_prior']) # check if fit result is in range, process it accordingly if not (bf_ret[1] > np.min(p)) and (bf_ret[1] < np.max(p)): # fit out of range, set location to max pamax = np.argmax(cr) self._opt_pos[dimension] = p[pamax] ret = False print '(%s) fit failed! Set to maximum.' % dimension else: self._opt_pos[dimension] = bf_ret[1] self._opt_sigma_prev[dimension] = bf_ret[2] ret = True final_fit_func = (bf_ret[3] + bf_ret[0]*np.exp(-(p-bf_ret[1])**2/(2.0*bf_ret[2]**2)))*rate qt.plot(p,cr*rate,p,ababfunc,p,final_fit_func,name='fbl_plot',needtempfile=False) #print '(%s) optimize succeeded!' % self.get_name() return ret
def read_sweep_plot(self, samples, rate, channel): rsamples = self.read_sweep(samples, rate, channel) time_axis = np.linspace(0.0,float(np.size(rsamples))/rate,np.size(rsamples)) qt.plot(time_axis,rsamples,name='fpplot1',traceofs=0.2, maxtraces=20) return
import numpy as np import qt x = np.arange(-10, 10, 0.2) y = np.sinc(x) yerr = 0.1 * np.random.rand(len(x)) d = qt.Data() d.add_coordinate('x') d.add_coordinate('y') d.add_coordinate('yerr') d.create_file() d.add_data_point(x, y, yerr) p = qt.Plot2D() p.add_data(d, coorddim=0, valdim=1, yerrdim=2) # or: qt.plot(x, y, yerr=yerr, name='test2')
def save_2D_data(self, timename='t (ns)', sweepname='sweep_value', ret=False): grp=h5.DataGroup('p7889_raw_data',self.h5data,base=self.h5base) self.save_params(grp=grp.group) x,yint,z = self._get_p7889_data() #### convert x to bins.... because this is what we see on the y=self.params['sweep_pts'] xx, yy = np.meshgrid(x,y) #dat=h5.HDF5Data(name=self.name) grp.add_coordinate(name='t (ns)',data=x, dtype='f8') grp.add_coordinate(name=self.params['sweep_name'],data=y) grp.add_value(name='Counts',data=z) # m2.save_instrument_settings_file(grp.group) #do post-processing grp1=h5.DataGroup('processed data',self.h5data,base=self.h5base) if self.params['Eval_ROI_start']<np.amin(x): startind=[0] else: startind=np.where(x==self.params['Eval_ROI_start']) if self.params['Eval_ROI_end']>np.amax(x): endind=[x.size-1] else: endind=np.where(x==self.params['Eval_ROI_end']) #strip the count array of points in time that lie outside of the specified ROIs # print x # print startind,endind sliced=z[:,startind[0]:endind[0]] # print sliced summation=np.array(range(self.params['pts'])) for i,row in enumerate(sliced): summation[i]=np.sum(row) grp1.add_coordinate(name=self.params['sweep_name'],data=y) grp1.add_value(name='Counts in ROI',data=summation) plt=qt.plot(name=self.mprefix+self.name,clear=True) plt.add(y,summation,'rO',yerr=np.sqrt(summation)) plt.add(y,summation,'r-') plt.set_plottitle(self.name) plt.set_legend(False) plt.set_xlabel(self.params['sweep_name']) plt.set_ylabel('counts') plt.save_png(self.datafolder+'\\'+self.name+'.png') self.h5data.flush() if ret: return x,y,z else: self.h5data.flush()
def updated_measurement(self): """ Incorporates live plotting for the p7889. """ self.p7889.Start() qt.msleep(0.5) self.awg.start() counter = 0 opt_ins = qt.instruments['optimiz0r'] # added for long measurements MJD GreenAOM = qt.instruments['GreenAOM'] last_time = time.time() sample_time = 5.0 while self.p7889.get_state(): qt.msleep(0.1) counter += 1 if counter % 1500 == 0: # idem added for long measurement GreenAOM.set_power(self.params['GreenAOM_power']) opt_ins.optimize(dims=['x','y','z'], cycles=1) opt_ins.optimize(dims=['x','y','z'], cycles=1) GreenAOM.turn_off() elif msvcrt.kbhit(): kb_char=msvcrt.getch() if kb_char == "q": stop = True break if (time.time() - last_time) > sample_time: last_time = time.time() x,z = self.p7889.get_P7889data() y=self.params['sweep_pts'] if self.params['Eval_ROI_start']<np.amin(x): startind=[0] else: startind=np.where(x==self.params['Eval_ROI_start']) if self.params['Eval_ROI_end']>np.amax(x): endind=[x.size-1] else: endind=np.where(x==self.params['Eval_ROI_end']) #strip the count array of points in time that lie outside of the specified ROIs # print x # print startind,endind sliced=z[:,startind[0]:endind[0]] # print sliced summation=np.array(range(self.params['pts'])) for i,row in enumerate(sliced): summation[i]=np.sum(row) plt=qt.plot(name=self.mprefix+self.name,clear=True) plt.add(y,summation,'rO',yerr=np.sqrt(summation)) plt.add(y,summation,'r-') plt.set_plottitle(self.name) plt.set_legend(False) plt.set_xlabel(self.params['sweep_name']) plt.set_ylabel('counts') self.stop_sequence()