def test_plot_by_id_line_and_heatmap(experiment): """ Test that line plots and heatmaps can be plotted together """ inst = DummyInstrument('dummy', gates=['s1', 'm1', 's2', 'm2']) inst.m1.get = np.random.randn inst.m2.get = lambda: np.random.randint(0, 5) meas = Measurement() meas.register_parameter(inst.s1) meas.register_parameter(inst.s2) meas.register_parameter(inst.m2, setpoints=(inst.s1, inst.s2)) meas.register_parameter(inst.m1, setpoints=(inst.s1, )) with meas.run() as datasaver: for outer in range(10): datasaver.add_result((inst.s1, outer), (inst.m1, inst.m1())) for inner in range(10): datasaver.add_result((inst.s1, outer), (inst.s2, inner), (inst.m2, inst.m2())) dataid = datasaver.run_id plot_by_id(dataid) plot_by_id(dataid, cmap='bone')
def record_S21_sweep_power_sweep_frequency(self): # -- setting vna parameters # vna.sweep_mode.set('CONT') self.vna.power.set(self.vnapower) self.vna.center.set(self.center_frequency) self.vna.span.set(self.frequency_span) self.vna.points.set(self.numberofpoints) self.vna.if_bandwidth.set(self.ifbandwidth) self.vna.trace.set(self.measuredtrace) self.vna.auto_sweep.set(False) #vna.groupdelay.set(groupdelayref) #does not work yet meas = Measurement() meas.register_parameter(self.vna.power) # register the first independent parameter meas.register_parameter(self.vna.real, setpoints=(self.vna.power,)) # register the second independent parameter # ^ (? Why would vna.real be an independent parameter?) Does it not get measured (dependent) as a function of freq? meas.register_parameter(self.vna.imaginary, setpoints=(self.vna.power,)) # now register the dependent one meas.register_parameter(self.vna.phase, setpoints=(self.vna.power,)) # now register the dependent one meas.register_parameter(self.vna.magnitude, setpoints=(self.vna.power,)) # now register the dependent one # -- taking data with meas.run() as datasaver: for v1 in np.linspace(self.powersweepstart, self.powersweepstop, self.powersweepnum, endpoint=True): self.vna.active_trace.set(1) power = self.vna.power.set(v1) print(self.vna.power.get()) # check #vna.auto_sweep.set(False) #vna.auto_sweep.set(True) self.vna.traces.tr1.run_sweep()#some bug not taking the last row therefore two sweeps #power=vna.power() #vna.auto_sweep.set(False) imag = self.vna.imaginary() real = self.vna.real() phase = self.vna.phase() mag = self.vna.magnitude() #vna.active_trace.set(2) #vna.traces.tr2.run_sweep() power = self.vna.power() # should still be the same as a few lines above #time.sleep(2) datasaver.add_result((self.vna.magnitude, mag), (self.vna.phase, phase), (self.vna.real, real), (self.vna.imaginary, imag), (self.vna.power, power)) print(self.vna.power.get()) plot_by_id(datasaver.run_id) self.set_of_parameter_data = datasaver.dataset.get_parameter_data()
def test_extend(dataset_with_outliers): # this one should clipp the upper values run_id = dataset_with_outliers.run_id _, cb = plot_by_id(run_id, auto_color_scale=False) assert cb[0].extend == 'neither' _, cb = plot_by_id(run_id, auto_color_scale=True, cutoff_percentile=(0, 0.5)) assert cb[0].extend == 'min' _, cb = plot_by_id(run_id, auto_color_scale=True, cutoff_percentile=(0.5, 0)) assert cb[0].extend == 'max' plt.close()
def IV_up_ithaco(station, voltages, stanford_gain_V, ithaco_gain_I): now = datetime.now() # dd/mm/YY H:M:S dt_string = now.strftime("%d/%m/%Y %H:%M:%S") print(dt_string) R_I = 1e4 #The value of the resistor used to measure the current print(f'Stanford Gain V ={stanford_gain_V}') print(f'Ithaco Gain I ={ithaco_gain_I}') print(f'Voltage Max V_max = {voltages[-1]}') int_time = 1 #Integration time of the dmm's station.dmm1.volt() station.dmm1.NPLC(int_time) station.dmm2.volt() station.dmm2.NPLC(int_time) print(f'Integration time = {int_time*0.02} s') station.yoko.output('off') station.yoko.source_mode("VOLT") station.yoko.output('on') station.yoko.voltage.step = 0.1e-6 station.yoko.voltage.inter_delay = 5e-4 meas = Measurement() meas.register_parameter(station.yoko.voltage) meas.register_parameter(station.dmm2.volt) meas.register_custom_parameter("Current", unit="A") meas.register_parameter(station.dmm1.volt, setpoints=("Current",)) with meas.run() as datasaver: for v in voltages: station.yoko.voltage(v) voltage_meas = station.dmm1.volt()/stanford_gain_V current_meas = -1*station.dmm2.volt()/ithaco_gain_I datasaver.add_result((station.yoko.voltage,v), (station.dmm2.volt,station.dmm2.volt()), ("Current",current_meas), (station.dmm1.volt,voltage_meas)) ID_exp = datasaver.run_id station.yoko.voltage(0) plot_by_id(ID_exp)
def scanfreqamp(inst, avg, plot = False): inst.avg(avg) # Number of traces to avarage over, the "quality" of the measurement meas = Measurement() # Creates new measurement meas.register_parameter(inst.freq_sweep) with meas.run() as datasaver: datasaver.add_result((inst.frequency_axis, inst.frequency_axis.get()), (inst.freq_sweep, inst.freq_sweep.get(),)) dataid = datasaver.run_id if plot: plot_by_id(dataid) # Plots the measurement return datasaver
def take_screen_anritsu_all_traces(self): # self.vna.active_trace.set(False) # is this needed at all? # t1.trace.set("S22") meas = Measurement() # qcodes measurement # self.vna.auto_sweep(False) # from qcodes import Parameter # smatrix_elem_str = Parameter("smatrix_elem", self.vna) # import pdb; pdb.set_trace() # noqa BREAKPOINT traces = self.vna.traces # import pdb; pdb.set_trace() # noqa BREAKPOINT for trace in traces: meas.register_parameter(trace.trace_parameter, paramtype="text") # this is actually the label "S11, S12, ..." of the trace meas.register_parameter(trace.real) meas.register_parameter(trace.imaginary) meas.register_parameter(trace.magnitude) meas.register_parameter(trace.phase) # actually get the data with meas.run() as datasaver: # try to run the measurement (? but this doesn't yet write to the database) data = [] for trace in traces: # self.vna.active_trace.set(n) # there may be even 4 traces (S-matrix elements) # self.vna.traces.tr1.run_sweep() # smatrix_elem = self.vna.smatrix_elem() tp = trace.trace_parameter() imag = trace.imaginary() real = trace.real() mag = trace.magnitude() phase = trace.phase() data.append((trace.trace_parameter, tp)) data.append((trace.imaginary, imag)) data.append((trace.real, real)) data.append((trace.magnitude, mag)) data.append((trace.phase, phase)) datasaver.add_result(*data) dataid = datasaver.run_id plot_by_id(dataid)
def _create_plots(datasaver: DataSaver) -> AxesTupleList: dataid = datasaver.run_id plt.ioff() start = time.time() axes, cbs = plot_by_id(dataid) stop = time.time() print(f"plot by id took {stop - start}") mainfolder = config.user.mainfolder experiment_name = datasaver._dataset.exp_name sample_name = datasaver._dataset.sample_name storage_dir = os.path.join(mainfolder, experiment_name, sample_name) os.makedirs(storage_dir, exist_ok=True) png_dir = os.path.join(storage_dir, 'png') pdf_dif = os.path.join(storage_dir, 'pdf') os.makedirs(png_dir, exist_ok=True) os.makedirs(pdf_dif, exist_ok=True) save_pdf = True save_png = True for i, ax in enumerate(axes): if save_pdf: full_path = os.path.join(pdf_dif, f'{dataid}_{i}.pdf') ax.figure.savefig(full_path, dpi=500) if save_png: full_path = os.path.join(png_dir, f'{dataid}_{i}.png') ax.figure.savefig(full_path, dpi=500) plt.ion() res = dataid, axes, cbs return res
def test_defaults(dataset_with_outliers): run_id = dataset_with_outliers.run_id # plot_by_id loads from the database location provided in the qcodes # config. But the tests are supposed to run with the standard config. # Therefore we need to backup the db location and add it to the default # config context. db_location = qcodes.config.core.db_location with default_config(): qcodes.config.core.db_location = db_location _, cb = plot_by_id(run_id) assert cb[0].extend == 'neither' qcodes.config.plotting.auto_color_scale.enabled = True _, cb = plot_by_id(run_id) assert cb[0].extend == 'both' plt.close()
def take_buffer_keysight(self): """ takes a frequency sweep, not setting any values on the hardware """ from qcodes import Station station = Station() station.add_component(self.vna) # import pdb; pdb.set_trace() meas = Measurement(station=station) # qcodes measurement # self.vna.points.set(20) self.vna.auto_sweep(False) meas.register_parameter(self.vna.real) meas.register_parameter(self.vna.imaginary) meas.register_parameter(self.vna.magnitude) meas.register_parameter(self.vna.phase) # actually get the data with meas.run( ) as datasaver: # try to run the measurement (? but this doesn't yet write to the database) self.vna.active_trace.set(1) # there are Tr1 and Tr2 # self.vna.traces.tr1.run_sweep() imag = self.vna.imaginary() real = self.vna.real() mag = self.vna.magnitude() phase = self.vna.phase() datasaver.add_result( (self.vna.magnitude, mag), (self.vna.phase, phase), (self.vna.real, real), (self.vna.imaginary, imag)) dataid = datasaver.run_id pd = datasaver.dataset.get_parameter_data() snapshot = datasaver.dataset.snapshot plot_by_id(dataid)
def redraw(run_id, axes, cbars): '''Call plot_by_id to plot the available data on axes.''' pause_time = 0.001 dataset = load_by_id(run_id) if not dataset: # there is not data available yet axes, cbars = [], [] elif not axes: # there is data available but no plot yet axes, cbars = plot_by_id(run_id) else: # there is a plot already for axis in axes: axis.clear() for cbar in cbars: if cbar is not None: cbar.remove() axes, cbars = plot_by_id(run_id, axes) title = make_title(dataset) for axis in axes: axis.set_title(title) plt.pause(pause_time) return axes, cbars
def print_label( dataid: int, db_name: str, db_folder: Optional[str] = None, plot_data: Optional[bool] = True, ) -> None: """""" if db_folder is None: db_folder = nt.config["db_folder"] ds = load_by_id(dataid) if plot_data: plot_by_id(dataid) print("dataset {} in {}: ".format(dataid, db_name)) quality_mapping = {1: "good", 0: "poor"} for label in LABELS: if label != "good": if int(ds.get_metadata(label)) == 1: quality = quality_mapping[int(ds.get_metadata("good"))] print("{} {}.".format(quality, label))
def batch_plot_by_id(ids, ax=None, labels=None, **kwargs): if ax is None: fig, ax = plt.subplots() if 'marker' not in kwargs.keys(): kwargs['marker'] = 'o' if 'ls' not in kwargs.keys(): kwargs['ls'] = 'None' for i, idx in enumerate(ids): if labels is not None: label = labels[i] else: label = '' plot_by_id(idx, axes=ax, label=label, **kwargs) ax.legend() return ax
def _save_image(datasaver) -> AxesTupleList: """ Save the plots created by datasaver as pdf and png Args: datasaver: a measurement datasaver that contains a dataset to be saved as plot. """ plt.ioff() dataid = datasaver.run_id start = time.time() axes, cbs = plot_by_id(dataid) stop = time.time() print(f"plot by id took {stop-start}") mainfolder = config.user.mainfolder experiment_name = datasaver._dataset.exp_name sample_name = datasaver._dataset.sample_name storage_dir = os.path.join(mainfolder, experiment_name, sample_name) os.makedirs(storage_dir, exist_ok=True) png_dir = os.path.join(storage_dir, 'png') pdf_dif = os.path.join(storage_dir, 'pdf') os.makedirs(png_dir, exist_ok=True) os.makedirs(pdf_dif, exist_ok=True) save_pdf = True save_png = True for i, ax in enumerate(axes): if save_pdf: full_path = os.path.join(pdf_dif, f'{dataid}_{i}.pdf') ax.figure.savefig(full_path, dpi=500) if save_png: full_path = os.path.join(png_dir, f'{dataid}_{i}.png') ax.figure.savefig(full_path, dpi=500) plt.ion() return axes, cbs
def pbi(idx, **kwargs): if 'marker' not in kwargs.keys(): kwargs['marker'] = 'o' if 'ls' not in kwargs.keys(): kwargs['ls'] = 'None' if 'interactive' in kwargs.keys(): interactive = kwargs.pop('interactive') else: interactive = False axes, _ = plot_by_id(idx, **kwargs) ax = axes[0] if interactive: connect_interactive(ax) return ax
def fit(self, dataid, fitclass, save_plots=True, p0=None, **kwargs): ax_list, _ = plot_by_id(dataid) popt_list = [] pcov_list = [] for i, ax in enumerate(ax_list): if ax.lines == []: print(f'No line found in plot {i}.') else: xdata = ax.lines[0].get_xdata() ydata = ax.lines[0].get_ydata() # Get initial guess on parameter is guess function is defined if (p0 is None and hasattr(fitclass, 'guess')): p0 = getattr(fitclass, 'guess')(xdata, ydata) popt, pcov = curve_fit(fitclass.fun, xdata, ydata, p0=p0, **kwargs) popt_list.append(popt) pcov_list.append(pcov) if save_plots: self.plot_1D(ax, xdata, ydata, fitclass, popt) dataset = load_by_id(dataid) mainfolder = config.user.mainfolder experiment_name = dataset.exp_name sample_name = dataset.sample_name storage_dir = os.path.join(mainfolder, experiment_name, sample_name) analysis_dir = os.path.join(storage_dir, 'Analysis') os.makedirs(analysis_dir, exist_ok=True) full_path = os.path.join(analysis_dir, f'{dataid}_{i}.png') ax.figure.savefig(full_path, dpi=500) return popt_list, pcov_list
def Hall_gate(station, v_gates, V_polar, field_range_Y, stanford_gain_1, stanford_gain_2, stanford_gain_3): R_polar = 1e6 print(f'I_polar = {V_polar/R_polar}') R_I = 1e4 # dmm1 is voltage station.dmm1.NPLC(100) # dmm2 is current station.dmm2.NPLC(10) station.dmm3.NPLC(100) station.yoko.voltage.step = 1e-4 station.yoko.voltage.inter_delay = 0.0001 meas = Measurement() meas.register_parameter(station.yoko.voltage) meas.register_parameter(station.mag.y_target) meas.register_parameter(station.mag.y_measured) meas.register_parameter(station.mdac_8.ch01.voltage) meas.register_parameter(station.dmm1.volt, setpoints = (station.mag.y_target,station.mdac_8.ch01.voltage)) meas.register_parameter(station.dmm2.volt, setpoints = (station.mag.y_target,station.mdac_8.ch01.voltage)) meas.register_parameter(station.dmm3.volt, setpoints = (station.mag.y_target,station.mdac_8.ch01.voltage)) meas.register_custom_parameter("R_h", unit = "Ohms", setpoints = (station.mag.y_target,station.mdac_8.ch01.voltage)) meas.register_custom_parameter("R_xx", unit = "Ohms", setpoints = (station.mag.y_target,station.mdac_8.ch01.voltage)) with meas.run() as datasaver: for b in field_range_Y: station.mag.y_target(b) station.mag.ramp('simul') while abs(station.mag.y_measured()-b)>0.001: time.sleep(2) time.sleep(5) l_y = station.mag.y_measured() print(l_y) for v_g in v_gates: station.mdac_8.ch01.ramp(v_g, 0.01) while abs(station.mdac_8.ch01.voltage()-v_g)>0.001: time.sleep(2) time.sleep(2) print(f'V_g = {v_g} V') station.yoko.voltage(-V_polar) time.sleep(1) volt_h_m = station.dmm1.volt()/stanford_gain_1 curr_m = station.dmm2.volt()/(R_I*stanford_gain_2) volt_m = station.dmm3.volt()/stanford_gain_3 time.sleep(1) station.yoko.voltage(V_polar) time.sleep(1) volt_h_p = station.dmm1.volt()/stanford_gain_1 curr_p = station.dmm2.volt()/(R_I*stanford_gain_2) volt_p = station.dmm3.volt()/stanford_gain_3 time.sleep(1) V_av = (volt_p - volt_m)/2 I_av = (curr_p - curr_m)/2 V_h_av = (volt_h_p - volt_h_m)/2 R_av = V_av/I_av R_h_av = V_h_av/I_av print(R_av) datasaver.add_result((station.mdac_8.ch01.voltage, v_g), (station.yoko.voltage, V_polar), (station.dmm2.volt, curr_p), (station.dmm1.volt, V_h_av), (station.dmm3.volt, V_av), (station.mag.y_measured, l_y), (station.mag.y_target, b), ("R_h", R_h_av), ("R_xx",R_av)) station.yoko.voltage(0) ID_exp = datasaver.run_id plot_by_id(ID_exp)
def GV_IV_yoko_up(station, voltages, amplitude, stanford_gain_V_ac, stanford_gain_I, stanford_gain_V): now = datetime.now() # dd/mm/YY H:M:S dt_string = now.strftime("%d/%m/%Y %H:%M:%S") print(dt_string) print(f'Stanford Gain V_AC ={stanford_gain_V_ac}') print(f'Stanford Gain V_DC ={stanford_gain_V}') print(f'Stanford Gain I ={stanford_gain_I}') print(f'V_max = {voltages[-1]} V') int_time = 1 #Integration time of the dmm's station.dmm1.volt() station.dmm1.NPLC(int_time) station.dmm2.volt() station.dmm2.NPLC(int_time) #station.dmm2.volt() #station.dmm2.NPLC(int_time) print(f'Integration time DC = {int_time*0.02} s') time_constant = station.lockin_2.time_constant() print(f'Integration time lockins {time_constant} s') #print(f'Stanford Gain V ={stanford_gain_V}') TO DO #print(f'Stanford Gain I ={stanford_gain_I}') print(f'Voltage Max V_max = {voltages[-1]}') #station.yoko.output('off') #station.yoko.source_mode("VOLT") #station.yoko.output('on') station.yoko.voltage.step = 0.1e-6 station.yoko.voltage.inter_delay = 5e-4 # station.lockin_2.amplitude(amplitude) meas = Measurement() meas.register_parameter(station.yoko.voltage) meas.register_parameter(station.lockin_2.amplitude) meas.register_parameter(station.dmm1.volt) meas.register_parameter(station.dmm2.volt, setpoints=(station.dmm1.volt, )) meas.register_parameter(station.lockin_1.Y, setpoints=(station.dmm1.volt, )) meas.register_parameter(station.lockin_2.Y, setpoints=(station.dmm1.volt, )) meas.register_parameter(station.lockin_1.X, setpoints=(station.dmm1.volt, )) meas.register_parameter(station.lockin_2.X, setpoints=(station.dmm1.volt, )) meas.register_custom_parameter("G_ac", unit="S", setpoints=(station.dmm1.volt, )) meas.register_custom_parameter("I_dc", unit="A", setpoints=(station.dmm1.volt, )) print(f'Frequency Lockin : {station.lockin_1.frequency()} Hz') station.lockin_2.amplitude(amplitude) print(f'V_ac polarization : {amplitude*1e3} mV') print(f'Filter lockin 1 : {station.lockin_1.filter_slope()} dB roll off') print(f'Sensitivity lockin 1 : {station.lockin_1.sensitivity()} V') print(f'Filter lockin 2 : {station.lockin_2.filter_slope()} dB roll off') print(f'Sensitivity lockin 2 : {station.lockin_2.sensitivity()} A') v_init = voltages[0] v_final = voltages[-1] L = int(len(voltages) / 2) volt_sweep_init = np.linspace(0.0, v_init, L) volt_sweep_final = np.linspace(v_final, 0.0, L) with meas.run() as datasaver: for v in volt_sweep_init: station.yoko.voltage(v) time.sleep(100e-3) time.sleep(1) for v in voltages: station.yoko.voltage(v) v_dc = station.dmm1.volt() / stanford_gain_V i_dc = -station.dmm2.volt() / stanford_gain_I #Using ithaco #i_dc = v_i_dc/R_I time.sleep(6 * time_constant) current_X_AC = station.lockin_2.X() / stanford_gain_I voltage_X_AC = station.lockin_1.X() / stanford_gain_V_ac current_Y_AC = station.lockin_2.Y() / stanford_gain_I voltage_Y_AC = station.lockin_1.Y() / stanford_gain_V_ac G_ac = current_X_AC / voltage_X_AC datasaver.add_result(("G_ac", G_ac), (station.dmm1.volt, v_dc), (station.dmm2.volt, i_dc), ("I_dc", i_dc), (station.yoko.voltage, v), (station.lockin_1.Y, current_Y_AC), (station.lockin_2.Y, voltage_Y_AC), (station.lockin_1.X, current_X_AC), (station.lockin_2.X, voltage_X_AC)) for v in volt_sweep_final: station.yoko.voltage(v) time.sleep(100e-3) ID_exp = datasaver.run_id station.yoko.voltage(0) plot_by_id(ID_exp)
def GV_B_yoko(station, voltages, currents, amplitude, stanford_gain_V_ac, stanford_gain_V, stanford_gain_I): #Before using this code change these values according to your own setup : R_I = 1e4 #value of the resistor used to measure the current now = datetime.now() dt_string = now.strftime("%d/%m/%Y %H:%M:%S") # dd/mm/YY H:M:S print(dt_string) print(f'Stanford Gain V_AC ={stanford_gain_V_ac}') print(f'Stanford Gain I_DC ={stanford_gain_I}') print(f'Stanford Gain V_DC ={stanford_gain_V}') print(f'Voltage Max V_max = {voltages[-1]} V') int_time = 10 #Integration time of the dmm's station.dmm1.volt() station.dmm1.NPLC(int_time) station.dmm2.volt() station.dmm2.NPLC(int_time) print(f'Integration time DC = {int_time*0.02} s') time_constant = station.lockin_2.time_constant() print(f'Integration time lockins {time_constant} s') #station.yoko.output('off') #station.yoko.source_mode("VOLT") #station.yoko.output('on') #station.yoko.voltage.step = 5e-3 #station.yoko.voltage.inter_delay = 10e-3 meas = Measurement() meas.register_parameter(station.lockin_2.amplitude) meas.register_parameter(station.lockin_2.sine_outdc) meas.register_custom_parameter("V_dc_polar", unit="V") meas.register_parameter(station.yoko.current) meas.register_parameter(station.dmm1.volt) meas.register_parameter(station.dmm2.volt, setpoints=(station.dmm1.volt, station.yoko.current)) meas.register_parameter(station.lockin_1.Y, setpoints=(station.dmm1.volt, station.yoko.current)) meas.register_parameter(station.lockin_2.Y, setpoints=(station.dmm1.volt, station.yoko.current)) meas.register_parameter(station.lockin_1.X, setpoints=(station.dmm1.volt, station.yoko.current)) meas.register_parameter(station.lockin_2.X, setpoints=(station.dmm1.volt, station.yoko.current)) meas.register_custom_parameter("I_dc", unit="A", setpoints=(station.dmm1.volt, station.yoko.current)) meas.register_custom_parameter("G_ac", unit="S", setpoints=(station.dmm1.volt, station.yoko.current)) meas.register_custom_parameter("R_dc", unit="Ohm", setpoints=(station.dmm1.volt, station.yoko.current)) print(f'Frequency Lockin : {station.lockin_1.frequency()} Hz') station.lockin_2.amplitude(amplitude) print(f'V_ac polarization : {amplitude*1e3} mV') print(f'Filter lockin 1 : {station.lockin_1.filter_slope()} dB roll off') print(f'Sensitivity lockin 1 : {station.lockin_1.sensitivity()} V') print(f'Filter lockin 2 : {station.lockin_2.filter_slope()} dB roll off') print(f'Sensitivity lockin 2 : {station.lockin_2.sensitivity()} A') station.yoko.current.step = 1e-6 station.yoko.current.inter_delay = 1e-3 #Preparing the measurement : v_init = voltages[0] v_final = voltages[-1] L = int(len(voltages) / 2) volt_sweep_init = np.linspace(0.0, v_init, L) volt_sweep_back = np.linspace(v_final, v_init, 2 * L) M = len(voltages) N = len(currents) G_ac_plot = np.full((M, N), 0.0) win = qcm.pyplot.PlotWindow(title="JJ dev. A") win.resize(500, 750) voltages_live = voltages * 1e6 plot1 = win.addPlot(title="G_ac(V_dc, V_g)") plot1.plot(setpoint_x=voltages_live, setpoint_y=field_rang_Y) plot1.left_axis.label = "V_g" plot1.left_axis.units = "V" plot1.bot_axis.label = "V_dc_polar" plot1.bot_axis.units = "uV" with meas.run() as datasaver: for v in volt_sweep_init: station.lockin_2.sine_outdc(v) time.sleep(200e-3) for i, I in enumerate(currents): station.yoko.current(I) print(I) for j, v in enumerate(voltages): station.lockin_2.sine_outdc(v) v_dc_polar = v v_dc = station.dmm1.volt() / stanford_gain_V v_i_dc = station.dmm2.volt() / stanford_gain_I I_dc = v_i_dc / R_I R_dc = v_dc / I_dc time.sleep(9 * time_constant) voltage_X_AC = station.lockin_1.X() / stanford_gain_V_ac current_X_AC = station.lockin_2.X() voltage_Y_AC = station.lockin_1.Y() / stanford_gain_V_ac current_Y_AC = station.lockin_2.Y() G_ac = current_X_AC / voltage_X_AC G_ac_plot[j, i] = G_ac plot1.traces[0].update(G_ac_plot) datasaver.add_result( ("V_dc_polar", v_dc_polar), (station.yoko.current, I), ("I_dc", I_dc), ("G_ac", G_ac), ("R_dc", R_dc), (station.dmm1.volt, v_dc), (station.dmm2.volt, v_i_dc), (station.lockin_2.amplitude, amplitude), (station.lockin_2.sine_outdc, v), (station.lockin_2.Y, current_Y_AC), (station.lockin_1.Y, voltage_Y_AC), (station.lockin_2.X, current_X_AC), (station.lockin_1.X, voltage_X_AC)) for v in volt_sweep_back: station.lockin_2.sine_outdc(v) time.sleep(100e-3) time.sleep(3) ID_exp = datasaver.run_id station.lockin_2.sine_outdc(0) plot_by_id(ID_exp) win.export('figures/Gac_B_plot_ID_exp_' + str(ID_exp) + '.png')
def plot(self): plot_by_id(self._run_id)
def elem_on_plot(id: int) -> tuple: fig, ax = plt.subplots(1) axes, cbaxes = plot_by_id(id, axes=ax) line = LineBuilder(axes[0], ax, 'red') plt.show() return (line.xs, line.ys, line.ramp)
def record_S21_sweep_frequency(self, use_default_values=False, override_default_values=False, **kwargs): """ takes a frequency sweep, keeping all parameters the same (getting them from the instrument) except for specific ones set in kwargs, which are set in the instrument before performing the sweep. """ for key, value in kwargs.items(): # check if the qcodes driver has this parameter self.vna. self.driver_exposed_parameters = __dict__.update(kwargs) self.vna.power(self.vnapower) self.vna.start(self.start_frequency) self.vna.stop(self.stop_frequency) self.vna.points(self.num_freq_points) self.vna.trace(self.measuredtrace) # num_freq_points = self.vna.points.get() # get current number of points from VNA settings meas = Measurement() # qcodes measurement # self.vna.points.set(20) self.vna.auto_sweep(False) meas.register_parameter(self.vna.real) meas.register_parameter(self.vna.imaginary) meas.register_parameter(self.vna.magnitude) meas.register_parameter(self.vna.phase) # actually get the data with meas.run() as datasaver: # try to run the measurement (? but this doesn't yet write to the database) # self.vna.active_trace.set(1) # there are Tr1 and Tr2 self.vna.traces.tr1.run_sweep() imag = self.vna.imaginary() real = self.vna.real() mag = self.vna.magnitude() phase = self.vna.phase() datasaver.add_result((self.vna.magnitude, mag), (self.vna.phase, phase), (self.vna.real, real), (self.vna.imaginary, imag)) dataid = datasaver.run_id pd = datasaver.dataset.get_parameter_data() plot_by_id(dataid) export = np.zeros((self.num_freq_points, 5)) export[:, 0] = pd[self.vna_name + "_tr1_magnitude"][self.vna_name + '_tr1_frequency'][0] export[:, 1] = pd[self.vna_name + '_tr1_magnitude'][self.vna_name + '_tr1_magnitude'][0] export[:, 2] = pd[self.vna_name + '_tr1_phase'][self.vna_name + '_tr1_phase'][0] export[:, 3] = pd[self.vna_name + '_tr1_real'][self.vna_name + '_tr1_real'][0] export[:, 4] = pd[self.vna_name + '_tr1_imaginary'][self.vna_name + '_tr1_imaginary'][0] np.savetxt(os.path.join(self.raw_path_with_date, str(datasaver.run_id)+'_nosweep' + '_'+str(self.exp_name)+'.txt'), export) plt.plot(export[:, 0], export[:, 1]) plt.xlabel('Frequency (Hz)') plt.ylabel('Magnitude (dB)') plt.savefig(os.path.join(self.raw_path_with_date, str(datasaver.run_id)+'_nosweep' + '_'+str(self.exp_name)+'_magnitude.png')) plt.cla() plt.plot(export[:, 0], export[:, 2]) plt.xlabel('Frequency (Hz)') plt.ylabel('Phase (deg)') plt.savefig(os.path.join(self.raw_path_with_date, str(datasaver.run_id)+'_nosweep' + '_'+str(self.exp_name)+'_phase.png'))
def G_up(station, v_gates, v_polar, amplitude, stanford_gain_V_ac): #Before using this code change these values according to your own setup : R_polar = 1e6 #value of the polarization resistor now = datetime.now() dt_string = now.strftime("%d/%m/%Y %H:%M:%S") # dd/mm/YY H:M:S print(dt_string) #print date and time of the measurement #Start the measurement meas = Measurement() meas.register_parameter(station.lockin_2.amplitude) meas.register_parameter(station.lockin_2.sine_outdc) meas.register_parameter(station.mdac_8.ch01.voltage) meas.register_parameter(station.lockin_1.Y, setpoints=(station.mdac_8.ch01.voltage, )) meas.register_parameter(station.lockin_2.Y, setpoints=(station.mdac_8.ch01.voltage, )) meas.register_parameter(station.lockin_1.X, setpoints=(station.mdac_8.ch01.voltage, )) meas.register_parameter(station.lockin_2.X, setpoints=(station.mdac_8.ch01.voltage, )) meas.register_custom_parameter("R_ac", unit="Ohm", setpoints=(station.mdac_8.ch01.voltage, )) #Prepare the live plot win = qcm.pyplot.PlotWindow(title="Gate Sweep 1D") win.resize(600, 400) plot = win.addPlot(title="R_ac(V_g)") plot.update_axes(station.mdac_8.ch01.voltage, station.lockin_1.X) R_ac_all = np.full(len(v_gates), np.nan) #Print the main lockin settings print(f'Stanford Gain V_AC ={stanford_gain_V_ac}') time_constant = station.lockin_2.time_constant() print(f'Integration time lockins {time_constant} s') print(f'Frequency Lockin : {station.lockin_2.frequency()} Hz') print(f'Filter lockin 1 : {station.lockin_1.filter_slope()} dB roll off') print(f'Sensitivity lockin 1 : {station.lockin_1.sensitivity()} V') print(f'Filter lockin 2 : {station.lockin_2.filter_slope()} dB roll off') print(f'Sensitivity lockin 2 : {station.lockin_2.sensitivity()} A') #Initialisation of the lockin station.lockin_2.amplitude(amplitude) print(f'V_ac polarization : {amplitude/1e-3} mV') station.lockin_2.sine_outdc(v_polar) print(f'V_dc polarization : {v_polar/1e-3} mV') with meas.run() as datasaver: for i, v_g in enumerate(v_gates): station.mdac_8.ch01.ramp(v_g, 0.01) station.mdac_8.ch02.ramp(v_g, 0.01) station.mdac_8.ch03.ramp(v_g, 0.01) station.mdac_8.ch01.block() station.mdac_8.ch02.block() station.mdac_8.ch03.block() print(v_g) time.sleep(5 * time_constant) voltage_X_AC = station.lockin_1.X() / stanford_gain_V_ac current_X_AC = station.lockin_2.X() voltage_Y_AC = station.lockin_1.Y() / stanford_gain_V_ac current_Y_AC = station.lockin_2.Y() R_ac = voltage_X_AC / current_X_AC R_ac_all[i] = R_ac trace = plot.plot(setpoint_x=v_gates, pen=(0, 0, 255), name="R_ac") trace.update(R_ac_all) datasaver.add_result(("R_ac", R_ac), (station.lockin_2.amplitude, amplitude), (station.lockin_2.sine_outdc, v_polar), (station.mdac_8.ch01.voltage, v_g), (station.lockin_2.Y, current_Y_AC), (station.lockin_1.Y, voltage_Y_AC), (station.lockin_2.X, current_X_AC), (station.lockin_1.X, voltage_X_AC)) ID_exp = datasaver.run_id station.lockin_2.sine_outdc(0) station.lockin_2.amplitude(0) win.export('figures/Rac_Gate_sweep_1D_ID_exp_' + str(ID_exp) + '.png') plot_by_id(ID_exp)
def doNd(param_set, spaces, settle_times, param_meas, name='', comment='', meander=False, extra_cmd=None, extra_cmd_val=None, wait_first_datapoint=1, checkstepinterdelay=True, manualsetpoints=False): if manualsetpoints == False: if len(param_set) is not len(spaces): errstr = 'Error: number of param_set is ' + str(len(param_set)) + ', while number of spaces is ' + str(len(spaces)) + '.' sys.exit(errstr) if manualsetpoints == True: if isinstance(spaces,np.ndarray) == False: errstr = 'Error: spaces is of type '+ str(type(spaces)) +' not a numpy error as required when manualsetpoints=True.' sys.exit(errstr) elif len(param_set) is not spaces.shape[1]: errstr = 'Error: number of param_set is ' + str(len(param_set)) + ', while dimension of spaces array is ' + str(spaces.shape[1]) + '.' sys.exit(errstr) if len(param_set) is not len(settle_times): errstr = 'Error: number of param_set is ' + str(len(param_set)) + ', while number of settle_times is ' + str(len(settle_times)) + '.' sys.exit(errstr) # Register measid as global parameter global measid measid = None # Useless if statement, because why not if __name__ != '__main__': #Create Event event = Event() # Create event shared by threads # Define p1 (run_measurement) and p2 (run_dbextractor) as two function to thread if param_set: p1 = Thread(target = run_measurement, args=(event, param_set, param_meas, spaces, settle_times, name, comment, meander, extra_cmd, extra_cmd_val, wait_first_datapoint, checkstepinterdelay, manualsetpoints)) else: p1 = Thread(target = run_zerodim, args=(event, param_meas, name, comment, wait_first_datapoint)) # Set writeinterval db_extractor dbextractor_write_interval = 30 #sec p2 = Thread(target = run_dbextractor, args=(event,dbextractor_write_interval)) # Kill main thread is subthreads are killed, not necessary here I think.. #p1.daemon = True #p2.daemon = True #Starting the threads in a try except to catch kernel interrupts try: # Start the threads p1.start() p2.start() # If the child thread is still running while p1.is_alive(): # Try to join the child thread back to parent for 0.5 seconds p1.join(0.5) p2.join(0.5) # When kernel interrupt is received (as keyboardinterrupt) except KeyboardInterrupt as e: # Set the alive attribute to false p1.alive = False p2.alive = False # Block until child thread is joined back to the parent p1.join() p2.join(5) # Exit with error code sys.exit(e) qctools.db_extraction.db_extractor(dbloc = qc.dataset.sqlite.database.get_DB_location(), ids=[measid], overwrite=True, newline_slowaxes=True, no_folders=False, suppress_output=True, useopendbconnection = True) if len(param_set) > 2: print('QCoDeS currently does not support plotting of higher dimensional data, plotting skipped.') else: plot_by_id(measid)
def G_up_B(station, field_max, v_polar, amplitude, stanford_gain_V_ac): #Before using this code change these values according to your own setup : R_polar = 1e6 #value of the polarization resistor now = datetime.now() dt_string = now.strftime("%d/%m/%Y %H:%M:%S") # dd/mm/YY H:M:S print(dt_string) #print date and time of the measurement #Start the measurement meas = Measurement() meas.register_parameter(station.lockin_2.amplitude) meas.register_parameter(station.lockin_2.sine_outdc) meas.register_parameter(station.mag.y_measured) meas.register_parameter(station.lockin_1.Y, setpoints=(station.mag.y_measured,)) meas.register_parameter(station.lockin_2.Y, setpoints=(station.mag.y_measured,)) meas.register_parameter(station.lockin_1.X, setpoints=(station.mag.y_measured,)) meas.register_parameter(station.lockin_2.X, setpoints=(station.mag.y_measured,)) meas.register_custom_parameter("R_ac", unit="Ohm",setpoints=(station.mag.y_measured,)) #Prepare the live plot win = qcm.pyplot.PlotWindow(title="Field Sweep 1D") win.resize(600,400) num_points = 0 array_size = 1 B_array = np.full((1,), np.nan) r_array = np.full((1,), np.nan) plot1 = win.addPlot(title ="R_ac(B)") plotdata = plot1.plot(setpoint_x = B_array) plot1.left_axis.label = "Resistance" plot1.left_axis.units = "Ohms" plot1.bot_axis.label = "B" plot1.bot_axis.units = "T" #Print the main lockin settings print(f'Stanford Gain V_AC ={stanford_gain_V_ac}') time_constant = station.lockin_2.time_constant() print(f'Integration time lockins {time_constant} s') print(f'Frequency Lockin : {station.lockin_2.frequency()} Hz') print(f'Filter lockin 1 : {station.lockin_1.filter_slope()} dB roll off') print(f'Sensitivity lockin 1 : {station.lockin_1.sensitivity()} V') print(f'Filter lockin 2 : {station.lockin_2.filter_slope()} dB roll off') print(f'Sensitivity lockin 2 : {station.lockin_2.sensitivity()} A') #Initialisation of the lockin station.lockin_2.amplitude(amplitude) print(f'V_ac polarization : {amplitude/1e-3} mV') station.lockin_2.sine_outdc(v_polar) print(f'V_dc polarization : {v_polar/1e-3} mV') with meas.run() as datasaver: station.mag.y_target(field_max) station.mag.ramp('simul') while abs(station.mag.y_measured()-field_max)>0.001: time.sleep(5*time_constant) b_y = station.mag.y_measured() voltage_X_AC = station.lockin_1.X()/stanford_gain_V_ac current_X_AC = station.lockin_2.X() voltage_Y_AC = station.lockin_1.Y()/stanford_gain_V_ac current_Y_AC = station.lockin_2.Y() R_ac = voltage_X_AC/current_X_AC datasaver.add_result(("R_ac", R_ac), (station.lockin_2.amplitude, amplitude), (station.lockin_2.sine_outdc, v_polar), (station.mag.y_measured, b_y), (station.lockin_2.Y,current_Y_AC), (station.lockin_1.Y,voltage_Y_AC), (station.lockin_2.X,current_X_AC), (station.lockin_1.X,voltage_X_AC)) B_array[num_points] = b_y r_array[num_points] = R_ac plotdata.xData = B_array plotdata.update(r_array) num_points += 1 if num_points == array_size: array_size *= 2 B_array.resize(array_size) B_array[array_size//2:] = np.nan r_array.resize(array_size) r_array[array_size//2:] = np.nan ID_exp = datasaver.run_id station.lockin_2.sine_outdc(0) win.export('figures/Rac_Field_sweep_1D_ID_exp_'+str(ID_exp)+'.png') plot_by_id(ID_exp)
def measure_power_sweep_and_2d_plot(self, # numberofpoints, # vnapower, # center_frequency, frequency_span, # measuredtrace, ifbandwidth, # powersweepstart, powersweepstop, # powersweepnum ): # -- setting vna parameters # vna.sweep_mode.set('CONT') self.vna.power.set(self.vnapower) self.vna.center.set(self.center_frequency) self.vna.span.set(self.frequency_span) self.vna.points.set(self.numberofpoints) self.vna.if_bandwidth.set(self.ifbandwidth) self.vna.trace.set(self.measuredtrace) self.vna.auto_sweep.set(False) #vna.groupdelay.set(groupdelayref) #does not work yet meas = Measurement() meas.register_parameter(self.vna.power) # register the first independent parameter meas.register_parameter(self.vna.real, setpoints=(self.vna.power,)) # register the second independent parameter # ^ (? Why would vna.real be an independent parameter?) Does it not get measured (dependent) as a function of freq? meas.register_parameter(self.vna.imaginary, setpoints=(self.vna.power,)) # now register the dependent one meas.register_parameter(self.vna.phase, setpoints=(self.vna.power,)) # now register the dependent one meas.register_parameter(self.vna.magnitude, setpoints=(self.vna.power,)) # now register the dependent one # -- taking data with meas.run() as datasaver: for v1 in np.linspace(self.powersweepstart, self.powersweepstop, self.powersweepnum, endpoint=True): self.vna.active_trace.set(1) power = self.vna.power.set(v1) print(self.vna.power.get()) # check #vna.auto_sweep.set(False) #vna.auto_sweep.set(True) self.vna.traces.tr1.run_sweep()#some bug not taking the last row therefore two sweeps #power=vna.power() #vna.auto_sweep.set(False) imag = self.vna.imaginary() real = self.vna.real() phase = self.vna.phase() mag = self.vna.magnitude() #vna.active_trace.set(2) #vna.traces.tr2.run_sweep() power = self.vna.power() # should still be the same as a few lines above #time.sleep(2) datasaver.add_result((self.vna.magnitude, mag), (self.vna.phase, phase), (self.vna.real, real), (self.vna.imaginary, imag), (self.vna.power, power)) print(self.vna.power.get()) #time.sleep(0.1) #print(x) x = datasaver.dataset.get_parameter_data() self.export = np.zeros(((self.numberofpoints)*(self.powersweepnum), 6)) self.export[:,0] = list(x['VNA_tr1_magnitude']['VNA_tr1_frequency']) self.export[:,1] = list(x['VNA_tr1_magnitude']['VNA_tr1_magnitude']) self.export[:,2] = list(x['VNA_tr1_phase']['VNA_tr1_phase']) self.export[:,3] = list(x['VNA_tr1_real']['VNA_tr1_real']) self.export[:,4] = list(x['VNA_tr1_imaginary']['VNA_tr1_imaginary']) self.export[:,5] = list(x['VNA_tr1_imaginary']['VNA_power']) table_ampl = np.zeros((self.numberofpoints + 1, self.powersweepnum+1)) table_phase = np.zeros((self.numberofpoints + 1, self.powersweepnum+1)) table_ampl[1:(self.numberofpoints + 1), 0] = self.export[0:(self.numberofpoints), 0] table_ampl[0, 1:(self.powersweepnum + 1)] = self.export[0:(len(self.export[:,0]) - 1):self.numberofpoints, 5] table_phase[1:(self.numberofpoints + 1), 0] = self.export[0:(self.numberofpoints), 0] table_phase[0, 1:(self.powersweepnum + 1)] = self.export[0:(len(self.export[:,0]) - 1):self.numberofpoints, 5] for i in range(self.powersweepnum): table_ampl[1:(self.numberofpoints + 1), i + 1] = self.export[(self.numberofpoints*i):(self.numberofpoints*(i + 1)), 1] ampl = table_ampl[1:(self.numberofpoints + 1), i + 1] table_phase[1:(self.numberofpoints + 1), i + 1] = self.export[(self.numberofpoints*i):(self.numberofpoints*(i + 1)), 2] phase=table_phase[1:(self.numberofpoints + 1), i + 1] np.savetxt(os.path.join(self.raw_path_with_date, str(datasaver.run_id) + '_powersweep' + '_' + str(self.exp_name) + '_phase.txt'), self.export) print(len(self.export[:, 0])) #print(self.export) np.savetxt(os.path.join(self.raw_path_with_date, str(datasaver.run_id) + '_powersweep' + '_' + str(self.exp_name) + '_all.txt'), self.export) plot_by_id(datasaver.run_id) plt.show()
def measure_frequency_sweep(self # , numberofpoints, # vnapower, start_frequency, # stop_frequency, measuredtrace, # ifbandwidth ): """ run a sweep and measure parameters (apparently, record_vna_screen merely takes a momentary capture of the screen. The device itself might be already sweeping automatically (mode of operation would be set by the device itself, not remotely via qcodes), so that record_vna_screen records a part of the last sweep in addition to a part of the current sweep) """ self.vna.sweep_mode.set('CONT') # look this command up in the anritsu's manual # settting parameters (which are regsitered in a VisaInstrument # class via e.g. add_parameter('power')) self.vna.power.set(self.vnapower) self.vna.start.set(self.start_frequency) self.vna.stop.set(self.stop_frequency) self.vna.points.set(self.numberofpoints) self.vna.if_bandwidth.set(self.ifbandwidth) self.vna.trace.set(self.measuredtrace) #self.vna.groupdelay.set(groupdelayref)#does not work yet #self.vna.auto_sweep.set(True) self.vna.active_trace.set(False) meas = Measurement() meas.register_parameter(self.vna.magnitude) meas.register_parameter(self.vna.phase) meas.register_parameter(self.vna.real) meas.register_parameter(self.vna.imaginary) with meas.run() as datasaver: self.vna.active_trace.set(1) # expore the traces object by debugging self.vna.traces.tr1.run_sweep() # may run a sweep again which is not necessary imag = self.vna.imaginary() #self.vna.auto_sweep.set(False) #self.vna.active_trace.set(2) #self.vna.traces.tr2.run_sweep() phase = self.vna.phase() real = self.vna.real() mag = self.vna.magnitude() # print(len(mag)) datasaver.add_result((self.vna.magnitude, mag), (self.vna.phase, phase), (self.vna.real, real), (self.vna.imaginary, imag)) x = datasaver.dataset.get_parameter_data() #print(x) self.export = np.zeros((self.numberofpoints, 5)) self.export[:,0]=list(x['VNA_tr1_magnitude']['VNA_tr1_frequency']) self.export[:,1]=list(x['VNA_tr1_magnitude']['VNA_tr1_magnitude']) self.export[:,2]=list(x['VNA_tr1_phase']['VNA_tr1_phase']) self.export[:,3]=list(x['VNA_tr1_real']['VNA_tr1_real']) self.export[:,4]=list(x['VNA_tr1_imaginary']['VNA_tr1_imaginary']) sweeppower = int(self.vna.power.get()) np.savetxt(os.path.join(self.raw_path_with_date, (str(datasaver.run_id) + '_sweep' + '_' + str(self.exp_name) + '_' + str(sweeppower) + 'dB' + '.txt')), self.export) plot_by_id(datasaver.run_id) # qcodes self.vna.sweep_mode.set('CONT') # why setting it here again? plt.cla() plt.plot(self.export[:,0], self.export[:,1]) plt.xlabel('Frequency (Hz)') plt.ylabel('Magnitude (dB)') plt.savefig(os.path.join(self.raw_path_with_date, str(datasaver.run_id) + '_sweep' + '_' + str(self.exp_name) + '_ampl.png')) plt.cla() plt.plot(self.export[:,0], self.export[:,2]) plt.xlabel('Frequency (Hz)') plt.ylabel('Phase (deg)') plt.savefig(os.path.join(self.raw_path_with_date, str(datasaver.run_id) + '_sweep' + '_' + str(self.exp_name) + '_phase.png')) print("txt and plots written to", self.raw_path_with_date)
def run_measurement(event, param_set, param_meas, spaces, settle_times, name, comment, meander, extra_cmd, extra_cmd_val, wait_first_datapoint, checkstepinterdelay, manualsetpoints): # Local reference of THIS thread object t = current_thread() # Thread is alive by default t.alive = True # Create measurement object meas = Measurement() # Apply name meas.name = name #Generating setpoints if manualsetpoints==False: if meander == True: setpoints = cartprodmeander(*spaces) else: setpoints = cartprod(*spaces) else: setpoints = spaces ### Filling station for snapshotting fill_station(param_set,param_meas) ### Checking and setting safety rates and delays if checkstepinterdelay: safetyratesdelays(param_set,spaces) meas.write_period = 1 #Make array showing changes between setpoints on axes changesetpoints = setpoints - np.roll(setpoints, 1, axis=0) #Forcing the first setpoint in changesetpoints to 1 to make sure it is always set. changesetpoints[0,:] = 1 # Registering set parameters param_setstring = '' param_setnames = [None]*len(param_set) param_setunits = [None]*len(param_set) for i,parameter in enumerate(param_set): meas.register_parameter(parameter) param_setstring += parameter.name + ', ' param_setnames[i] = parameter.name param_setunits[i] = parameter.unit output = [None]*len(param_meas) # Registering readout parameters param_measstring = '' param_measnames = [None]*len(param_meas) param_measunits = [None]*len(param_meas) param_measnames_sub = [None]*len(param_meas) paramtype = [None]*len(param_meas) for i, parameter in enumerate(param_meas): meas.register_parameter(parameter, setpoints=(*param_set,)) output[i]= [parameter, None] param_measstring += parameter.name + ', ' param_measnames[i] = parameter.name if isinstance(parameter, qc.instrument.parameter.ParameterWithSetpoints): param_measunits[i] = parameter.unit param_measnames_sub[i] = '' paramtype[i] = 'ParameterWithSetpoints' elif isinstance(parameter, qc.instrument.parameter.MultiParameter): param_measunits[i] = parameter.units param_measnames_sub[i] = parameter.names paramtype[i] = 'MultiParameter' elif isinstance(parameter, qc.instrument.parameter.Parameter): param_measunits[i] = parameter.unit paramtype[i] = 'Parameter' # Start measurement routine with meas.run() as datasaver: global measid measid = datasaver.run_id # Getting dimensionality of measurement ndims = setpoints.shape[1] # Add comment to metadata in database datasaver.dataset.add_metadata('Comment', comment) # Main loop for setting values for i in range(0,setpoints.shape[0]): #Check for nonzero axis to apply new setpoints by looking in changesetpoints arrays resultlist = [None]*ndims if i==0: #On first datapoint change set_params from slow to fast axis dimlist = range(0,ndims) else: #On all other datapoints change fast axis first dimlist = reversed(range(0,ndims)) for j in dimlist: if not np.isclose(changesetpoints[i,j] , 0, atol=0): # Only set set params that need to be changed if i==0 and not t.alive: # Allows killing of thread in-between initialisiation of set_parameters for first datapoint. event.set() # Trigger closing of run_dbextractor raise KeyboardInterrupt('User interrupted doNd during initialisation of first setpoint.') # Break out of for loop break param_set[j].set(setpoints[i,j]) time.sleep(settle_times[j]) # Apply appropriate settle_time resultlist[j] = (param_set[j],setpoints[i,j]) # Make a list of result if i==0: # Add additional waiting time for first measurement point before readout and start timers time.sleep(wait_first_datapoint) # Start various timers starttime = datetime.datetime.now() + datetime.timedelta(0,-1) lastwrittime = starttime lastprinttime = starttime for k, parameter in enumerate(param_meas): # Readout all measurement parameters at this setpoint i if extra_cmd is not None: # Optional extra command + value that is run before each measurement paremeter is read out. if extra_cmd[k] is not None: if extra_cmd_val[k] is not None: (extra_cmd[k])(extra_cmd_val[k]) else: (extra_cmd[k])() output[k][1] = parameter.get() datasaver.add_result(*resultlist, # Add everything to the database *output) setvals = list(zip(param_setnames,[f"{x:.{6}}" for x in setpoints[i,:]],param_setunits)) outputparsed = [None]*len(param_meas) for k,x in enumerate([row[1] for row in output]): if paramtype[k] == 'MultiParameter': valsparsed = [None]*len(x) for l,y in enumerate(x): if isinstance(y, (list,tuple,np.ndarray)): if len(y) > 5: vals = ['{:.6f}'.format(x) for x in y[0:5]] vals.append('.......') else: vals = ['{:.6f}'.format(x) for x in y] newvals = [[vals[i]] for i in range(0,len(vals))] valsparsed[l] = tabulate(newvals,tablefmt='plain') else: valsparsed[l] = f"{y:.{6}}" outputparsed[k] = tabulate(list(zip(param_measnames_sub[k],valsparsed,param_measunits[k])), tablefmt='plain', colalign=('left','left','left')) if paramtype[k] == 'Parameter': outputparsed[k] = tabulate([[f"{x:.{6}}",param_measunits[k]]], tablefmt='plain') if paramtype[k] == 'ParameterWithSetpoints': outputparsed[k] = '{Parameter with setpoints, not shown.}' measvals = list(zip(param_measnames,outputparsed)) if not t.alive: # Check if user tried to kill the thread by keyboard interrupt, if so kill it event.set() # Trigger closing of run_dbextractor qctools.db_extraction.db_extractor(dbloc = qc.dataset.sqlite.database.get_DB_location(), # Run db_extractor once more ids=[measid], overwrite=True, newline_slowaxes=True, no_folders=False, suppress_output=True, useopendbconnection = True) plot_by_id(measid) raise KeyboardInterrupt('User interrupted doNd. All data flushed to database and extracted to *.dat file.') # Break out of for loop break #Time estimation printinterval = 0.025 # Increase printinterval to save CPU now = datetime.datetime.now() finish =['',''] if (now-lastprinttime).total_seconds() > printinterval or i == len(setpoints)-1: # Calculate and print time estimation frac_complete = (i+1)/len(setpoints) duration_in_sec = (now-starttime).total_seconds()/frac_complete elapsed_in_sec = (now-starttime).total_seconds() remaining_in_sec = duration_in_sec-elapsed_in_sec perc_complete = np.round(100*frac_complete,2) clear_output(wait=True) if i == len(setpoints)-1: finish[0] = 'Finished: ' + str((now).strftime('%Y-%m-%d')) finish[1] = str((now).strftime('%H:%M:%S')) l1 = tabulate([['----------------------' ,'-------------------------------------------------'], ['Starting runid:', str(measid)], # Time estimation now in properly aligned table format ['Name:', name], ['Comment:', comment], ['Set parameter(s):', tabulate(setvals, tablefmt='plain', colalign=('left','left','left'))], ['Readout parameter(s):', tabulate(measvals, tablefmt='plain', colalign=('left','left'))], ['______________________' ,'_________________________________________________'], ['Setpoint: ' + str(i+1) + ' of ' + str(len(setpoints)), '%.2f' % perc_complete + ' % complete.'], ['Started: ' + starttime.strftime('%Y-%m-%d'), starttime.strftime('%H:%M:%S')], ['ETA: ' + str((datetime.timedelta(seconds=np.round(duration_in_sec))+starttime).strftime('%Y-%m-%d')), str((datetime.timedelta(seconds=np.round(duration_in_sec))+starttime).strftime('%H:%M:%S'))], [finish[0],finish[1]], ['Total duration:', str(datetime.timedelta(seconds=np.round(duration_in_sec)))], ['Elapsed time:', str(datetime.timedelta(seconds=np.round(elapsed_in_sec)))], ['Remaining time:', str(datetime.timedelta(seconds=np.round(remaining_in_sec)))], ], colalign=('right','left'), tablefmt='plain') print(l1) lastprinttime = now event.set() # Trigger closing of run_dbextractor
def GV_yoko_up(station, voltages, amplitude, stanford_gain_V_ac, stanford_gain_I_ac): R_I = 1e4 #value of the resistor used to measure the current now = datetime.now() # dd/mm/YY H:M:S dt_string = now.strftime("%d/%m/%Y %H:%M:%S") print(dt_string) print(f'Stanford Gain V_AC ={stanford_gain_V_ac}') print(f'V_max = {voltages[-1]} V') time_constant = station.lockin_2.time_constant() print(f'Integration time lockins {time_constant} s') station.yoko.output('off') station.yoko.source_mode("VOLT") station.yoko.output('on') station.yoko.voltage.step = 1e-3 station.yoko.voltage.inter_delay = 10e-3 station.lockin_2.amplitude(amplitude) meas = Measurement() meas.register_parameter(station.yoko.voltage) meas.register_parameter(station.lockin_2.amplitude) meas.register_parameter(station.lockin_1.Y, setpoints=(station.yoko.voltage, )) meas.register_parameter(station.lockin_2.Y, setpoints=(station.yoko.voltage, )) meas.register_parameter(station.lockin_1.X, setpoints=(station.yoko.voltage, )) meas.register_parameter(station.lockin_2.X, setpoints=(station.yoko.voltage, )) meas.register_custom_parameter("G_ac", unit="S", setpoints=(station.yoko.voltage, )) meas.register_custom_parameter("I_dc", unit="A", setpoints=(station.yoko.voltage, )) print(f'Frequency Lockin : {station.lockin_1.frequency()} Hz') station.lockin_2.amplitude(amplitude) print(f'V_ac polarization : {amplitude*1e3} mV') print(f'Filter lockin 1 : {station.lockin_1.filter_slope()} dB roll off') print(f'Sensitivity lockin 1 : {station.lockin_1.sensitivity()} V') print(f'Filter lockin 2 : {station.lockin_2.filter_slope()} dB roll off') print(f'Sensitivity lockin 2 : {station.lockin_2.sensitivity()} A') v_init = voltages[0] v_final = voltages[-1] L = int(len(voltages) / 2) volt_sweep_init = np.linspace(0.0, v_init, L) volt_sweep_final = np.linspace(v_final, 0.0, L) with meas.run() as datasaver: for v in volt_sweep_init: station.yoko.voltage(v) time.sleep(1) for v in voltages: station.yoko.voltage(v) time.sleep(9 * time_constant) current_X_AC = station.lockin_2.X() / stanford_gain_I_ac voltage_X_AC = station.lockin_1.X() / stanford_gain_V_ac current_Y_AC = station.lockin_2.Y() / stanford_gain_I_ac voltage_Y_AC = station.lockin_1.Y() / stanford_gain_V_ac G_ac = current_X_AC / voltage_X_AC datasaver.add_result(("G_ac", G_ac), (station.yoko.voltage, v), (station.lockin_1.Y, current_Y_AC), (station.lockin_2.Y, voltage_Y_AC), (station.lockin_1.X, current_X_AC), (station.lockin_2.X, voltage_X_AC)) for v in volt_sweep_final: station.yoko.voltage(v) ID_exp = datasaver.run_id station.yoko.voltage(0) plot_by_id(ID_exp)
def record_vna_screen(self): numberofpoints = self.vna.points.get() # get current number of points from VNA settings # control the vna from inside qcodes -> set a parameter self.vna.active_trace.set(False) # ? is the trace just the screen shown in the ShockLine program? # -- Get the measurable values from the intrument, through the driver/Qcodes interface, # which provides access to current parameter and measurement values through methods # of the instrument's instance (-> pretty easy from the user's perspective) meas = Measurement() # qcodes measurement # if S21 is a complex number (? it must be calculated from something real which is actually measured) # get it's data (? whole array that is showing at runtime in the window, or last complete sweep (buffered)) meas.register_parameter(self.vna.real) meas.register_parameter(self.vna.imaginary) # ? aren't these redundant and are just calculated from real and imaginary parts? meas.register_parameter(self.vna.magnitude) meas.register_parameter(self.vna.phase) # actually get the data print("before taking data") with meas.run() as datasaver: # try to run the measurement (? but this doesn't yet write to the database) self.vna.active_trace.set(1) # there are Tr1 and Tr2 # vna.traces.tr1.run_sweep() imag = self.vna.imaginary() # vna.active_trace.set(2) # vna.traces.tr2.run_sweep() # call the vna driver's methods to get measurement values # parameters, after saving them in a 'runner' (returned from run()), have unique names # which can be explored by printing the keys of the runner's dataset (get_parameter_data(...)) phase = self.vna.phase() real = self.vna.real() mag = self.vna.magnitude() # pass pairs of (function, acquired value) to the datasaver (for later saving into the database) datasaver.add_result((self.vna.magnitude, mag), (self.vna.phase, phase), (self.vna.real, real), (self.vna.imaginary, imag)) # dataid1 = datasaver.run_id print("after taking data") # -- extract data from datasaver # datasaver object has been declared in the head of the with block # but is still accessible here x = datasaver.dataset.get_parameter_data() self.export = np.zeros((numberofpoints, 5)) # in the anritsu vna, there are several S21 vs freq graph windows (tr1 and tr2) # here, presumably, only tr1 is listened to # the database keys (below) can be explored by e.g. # just printing the dictionary on the jupyter console # these key names are generated in the Anritsu's driver's `traces` function self.export[:,0] = list(x['VNA_tr1_magnitude']['VNA_tr1_frequency']) self.export[:,1] = list(x['VNA_tr1_magnitude']['VNA_tr1_magnitude']) self.export[:,2] = list(x['VNA_tr1_phase']['VNA_tr1_phase']) self.export[:,3] = list(x['VNA_tr1_real']['VNA_tr1_real']) self.export[:,4] = list(x['VNA_tr1_imaginary']['VNA_tr1_imaginary']) np.savetxt( os.path.join(self.raw_path_with_date, str(datasaver.run_id) + '_nosweep' + '_' + str(self.exp_name) + '.txt'), self.export) # "folder%i.txt"%+(int(number)+1) # -- plotting -> qcodes' plotting routine + matplotlib plot_by_id(datasaver.run_id) # qcodes can plot the datasaver data plt.cla() plt.plot(self.export[:,0], self.export[:,1]) plt.xlabel('Frequency (Hz)') plt.ylabel('Magnitude (dB)') plt.savefig(os.path.join(self.raw_path_with_date, str(datasaver.run_id) + '_nosweep' + '_' + str(self.exp_name) + '_ampl.png')) plt.cla() plt.plot(self.export[:,0], self.export[:,2]) plt.xlabel('Frequency (Hz)') plt.ylabel('Phase (deg)') plt.savefig(os.path.join(self.raw_path_with_date, str(datasaver.run_id) + '_nosweep' + '_' + str(self.exp_name) + '_phase.png')) print("txt and plots written to", self.raw_path_with_date)
def record_S21_sweep_power_sweep_frequency(self): # -- setting vna parameters # vna.sweep_mode.set('CONT') self.vna.power.set(self.vnapower) self.vna.center.set(self.center_frequency) self.vna.span.set(self.frequency_span) self.vna.points.set(self.num_freq_points) self.vna.if_bandwidth.set(self.ifbandwidth) self.vna.trace.set(self.measuredtrace) self.vna.auto_sweep.set(False) # vna.groupdelay.set(groupdelayref) #does not work yet meas = Measurement() # register the first independent parameter meas.register_parameter(self.vna.power) # register the second independent parameter meas.register_parameter(self.vna.real, setpoints=(self.vna.power,)) # ^ (? Why would vna.real be an independent parameter?) Does it not get measured (dependent) as a function of freq? meas.register_parameter(self.vna.imaginary, setpoints=( self.vna.power,)) # now register the dependent one meas.register_parameter(self.vna.phase, setpoints=( self.vna.power,)) # now register the dependent one meas.register_parameter(self.vna.magnitude, setpoints=( self.vna.power,)) # now register the dependent one # -- taking data with meas.run() as datasaver: for v1 in np.linspace(self.powersweepstart, self.powersweepstop, self.num_power_points, endpoint=True): self.vna.active_trace.set(1) power = self.vna.power.set(v1) print(self.vna.power.get()) # check # vna.auto_sweep.set(False) # vna.auto_sweep.set(True) # some bug not taking the last row therefore two sweeps self.vna.traces.tr1.run_sweep() # power=vna.power() # vna.auto_sweep.set(False) imag = self.vna.imaginary() real = self.vna.real() phase = self.vna.phase() mag = self.vna.magnitude() # vna.active_trace.set(2) # vna.traces.tr2.run_sweep() power = self.vna.power() # should still be the same as a few lines above # time.sleep(2) datasaver.add_result((self.vna.magnitude, mag), (self.vna.phase, phase), (self.vna.real, real), (self.vna.imaginary, imag), (self.vna.power, power)) print(self.vna.power.get()) plot_by_id(datasaver.run_id) pd = datasaver.dataset.get_parameter_data() # import pdb; pdb.set_trace() # noqa BREAKPOINT magnitude_table = np.vstack((np.ravel(pd[self.vna_name + "_tr1_magnitude"][self.vna_name + "_power"]), np.ravel(pd[self.vna_name + "_tr1_magnitude"][self.vna_name + "_tr1_frequency"]), np.ravel(pd[self.vna_name + "_tr1_magnitude"][self.vna_name + "_tr1_magnitude"]))) phase_table = np.vstack((np.ravel(pd[self.vna_name + "_tr1_phase"][self.vna_name + "_power"]), np.ravel(pd[self.vna_name + "_tr1_phase"][self.vna_name + "_tr1_frequency"]), np.ravel(pd[self.vna_name + "_tr1_phase"][self.vna_name + "_tr1_phase"]))) real_table = np.vstack((np.ravel(pd[self.vna_name + "_tr1_real"][self.vna_name + "_power"]), np.ravel(pd[self.vna_name + "_tr1_real"][self.vna_name + "_tr1_frequency"]), np.ravel(pd[self.vna_name + "_tr1_real"][self.vna_name + "_tr1_real"]))) imaginary_table = np.vstack((np.ravel(pd[self.vna_name + "_tr1_imaginary"][self.vna_name + "_power"]), np.ravel(pd[self.vna_name + "_tr1_imaginary"][self.vna_name + "_tr1_frequency"]), np.ravel(pd[self.vna_name + "_tr1_imaginary"][self.vna_name + "_tr1_imaginary"]))) np.savetxt(os.path.join(self.raw_path_with_date, str(datasaver.run_id)+'_powersweep' + '_'+str(self.exp_name)+'_magnitude.txt'), magnitude_table) np.savetxt(os.path.join(self.raw_path_with_date, str(datasaver.run_id)+'_powersweep'+'_' + str(self.exp_name)+'_phase.txt'), phase_table) np.savetxt(os.path.join(self.raw_path_with_date, str(datasaver.run_id)+'_powersweep' + '_'+str(self.exp_name)+'_real.txt'), real_table) np.savetxt(os.path.join(self.raw_path_with_date, str(datasaver.run_id)+'_powersweep' + '_'+str(self.exp_name)+'_imaginary.txt'), imaginary_table)