def test_load_and_append_from_file(self): from pylabcontrol.core.read_write_functions import load_b26_file filename = 'C:\\Users\Experiment\PycharmProjects\\user_data\pythonlab_config_lev_test.b26' in_data = load_b26_file(filename) instruments = in_data[ 'instruments'] if 'instruments' in in_data else {} scripts = in_data['scripts'] if 'scripts' in in_data else {} probes = in_data['probes'] if 'probes' in in_data else {} script_info = list(scripts.values())[0] module, script_class_name, script_settings, script_instruments, script_sub_scripts, script_doc, package = Script.get_script_information( script_info) print(('module', module.__name__.split('.')[0])) print(('script_class_name', script_class_name)) print(('package', script_info['package'])) assert module.__name__.split('.')[0] == script_info['package'] instruments_loaded, failed = Instrument.load_and_append(instruments) if len(failed) > 0: print(('WARNING! Following instruments could not be loaded: ', failed)) print( '========================================================================\n\n' ) scripts_loaded, failed, instruments_loaded = Script.load_and_append( script_dict=scripts, instruments=instruments_loaded)
def export_default_scripts(target_folder, source_folder=None, raise_errors=False, verbose=False): """ tries to instantiate all the scripts that are imported in /scripts/__init__.py saves each script that could be instantiated into a .b26 file in the folder path Args: target_folder: target path for .b26 files source_folder: location of python script files """ scripts_to_load = get_classes_in_folder(source_folder, Script) if verbose: print(('attempt to load {:d} scripts: '.format(len(scripts_to_load)))) loaded_scripts, failed, loaded_instruments = Script.load_and_append( scripts_to_load, raise_errors=raise_errors) for name, value in loaded_scripts.items(): filename = os.path.join(target_folder, '{:s}.b26'.format(name)) value.save_b26(filename) if verbose: print('\n================================================') print('================================================') print( ('saved {:d} scripts, {:d} failed'.format(len(loaded_scripts), len(failed)))) if failed != {}: for error_name, error in failed.items(): print(('failed to create script: ', error_name, error))
def test_loading_and_saving(self): from pylabcontrol.core.read_write_functions import load_b26_file filename = "Z:\Lab\Cantilever\Measurements\\__tmp\\XYX.b26" scripts, loaded_failed, instruments = Script.load_and_append( {"some script": 'ScriptDummyWithInstrument'}) script = scripts['some script'] script.save_b26(filename) data = load_b26_file(filename) scripts = {} instruments = {} scripts, scripts_failed, instruments_2 = Script.load_and_append( data['scripts'], scripts, instruments)
def test_xy8_double_init(self): updated_scripts, load_failed, updated_instruments = Script.load_and_append({'XY8': 'XY8_double_init'}, package='b26_toolkit') xy8 = updated_scripts['XY8'] xy8.update({'Tracking': { 'on/off': False}}) # turn off tracking because this will cause an error if we don't run findnv print(xy8) xy8.is_valid()
def test_xy8_double_init(self): updated_scripts, load_failed, updated_instruments = Script.load_and_append( {'XY8': 'XY8_double_init'}, package='b26_toolkit') xy8 = updated_scripts['XY8'] xy8.update( {'Tracking': { 'on/off': False }} ) # turn off tracking because this will cause an error if we don't run findnv print(xy8) xy8.is_valid()
def python_file_to_b26(list_of_python_files, target_folder, class_type, raise_errors=False): if class_type == 'Script': loaded, failed, loaded_instruments = Script.load_and_append( list_of_python_files, raise_errors=raise_errors) elif class_type == 'Instrument': loaded, failed = Instrument.load_and_append(list_of_python_files, raise_errors=raise_errors) for name, value in loaded.iteritems(): filename = os.path.join(target_folder, '{:s}.b26'.format(name)) value.save_b26(filename)
def load_scripts(self, verbose=False): """ opens file dialog to load scripts into gui """ # update scripts so that current settings do not get lost for index in range(self.tree_scripts.topLevelItemCount()): script_item = self.tree_scripts.topLevelItem(index) self.update_script_from_item(script_item) dialog = LoadDialogB26(elements_type="scripts", elements_old=self.scripts, filename=self.gui_settings['scripts_folder']) if dialog.exec_(): self.gui_settings['scripts_folder'] = str(dialog.txt_probe_log_path.text()) scripts = dialog.get_values() added_scripts = set(scripts.keys()) - set(self.scripts.keys()) removed_scripts = set(self.scripts.keys()) - set(scripts.keys()) if verbose: print(('load_scripts.scripts', scripts)) print(('load_scripts.added_scripts', added_scripts)) print(('load_scripts.removed_scripts', removed_scripts)) if 'data_folder' in list(self.gui_settings.keys()) and os.path.exists(self.gui_settings['data_folder']): data_folder_name = self.gui_settings['data_folder'] else: data_folder_name = None script_dict = {name: scripts[name] for name in added_scripts} if verbose: print(('load_scripts.script_dict', script_dict)) print(('scripts, instruments', self.scripts, self.instruments)) # create instances of new instruments/scripts self.scripts, loaded_failed, self.instruments = Script.load_and_append( script_dict=script_dict, scripts=self.scripts, instruments=self.instruments, log_function=self.log, data_path=data_folder_name) assert not 'self.scripts' == {} if verbose: print(('self.scripts', self.scripts)) # delete instances of new instruments/scripts that have been deselected for name in removed_scripts: del self.scripts[name]
else: self.log("All generated pulse sequences are valid. No tau times will be skipped in this experiment.") self.log("{:d} different tau times have passed validation".format(len(valid_tau_list))) return valid_pulse_sequences, valid_tau_list, measurement_gate_width def stop(self): """ Stop currently executed pulse blaster sequence NOT CURRENTLY WORKING, WILL CRASH PULSEBLASTER """ # self.instruments['PB']['instance'].stop() super(PulsedExperimentBaseScript, self).stop() if __name__ == '__main__': script = {} instr = {} script, failed, instr = Script.load_and_append({'ExecutePulseBlasterSequence': 'ExecutePulseBlasterSequence'}, script, instr) script, failed, instr = Script.load_and_append({'ExecutePulseBlasterSequence': {'class':'ExecutePulseBlasterSequence', 'package':'b26toolkit'}}, script, instr) print(script) print(failed) print(instr)
'daq_type'] == 'PCI': plot_esr(axes_list[0], data['frequency'], data['norm_data'], linestyle='None', marker='o') def get_axes_layout(self, figure_list): """ returns the axes objects the script needs to plot its data the default creates a single axes object on each figure This can/should be overwritten in a child script if more axes objects are needed Args: figure_list: a list of figure objects Returns: axes_list: a list of axes objects """ new_figure_list = [figure_list[1]] return super(ESR_FM_Dither, self).get_axes_layout(new_figure_list) if __name__ == '__main__': script = {} instr = {} script, failed, instr = Script.load_and_append({'ESR': 'ESR_dithering'}, script, instr) print(script) print(failed) print(instr)
freq = freq[np.isfinite(r)] phase = data['phase'] phase = phase[np.isfinite(r)] r = r[np.isfinite(r)] x_scaling = self.settings['xmapping'][0:3] y_scaling = self.settings['ymapping'][0:3] # plot amplitude axes = axes_list[0] axes.hold(False) plot_psd(freq, r, axes, x_scaling=x_scaling, y_scaling=y_scaling) # axes.set_xlim([min(freq), max(freq)]) axes.set_ylim([min(r), max(r)]) axes.set_ylabel('amplitude (Vrms)') # plot phase if not trace_only: axes = axes_list[1] axes.hold(False) plot_psd(freq, phase, axes, x_scaling=x_scaling, y_scaling='lin') # axes.set_xlim([min(freq), max(freq)]) axes.set_ylim([min(phase), max(phase)]) axes.set_ylabel('phase (rad)') if __name__ == '__main__': script, failed, instruments = Script.load_and_append( script_dict={'ZISweeper': 'ZISweeper'})
if data is None: data = self.data if not self.settings['track_laser_power']['on/off']: plot_esr(axes_list[0], data['frequency'], data['data'], linestyle = 'None', marker = 'o') elif self.settings['track_laser_power']['on/off'] and self.settings['daq_type'] == 'PCI': plot_esr(axes_list[0], data['frequency'], data['norm_data'], linestyle = 'None', marker = 'o') def get_axes_layout(self, figure_list): """ returns the axes objects the script needs to plot its data the default creates a single axes object on each figure This can/should be overwritten in a child script if more axes objects are needed Args: figure_list: a list of figure objects Returns: axes_list: a list of axes objects """ new_figure_list = [figure_list[1]] return super(ESR_FM_Dither, self).get_axes_layout(new_figure_list) if __name__ == '__main__': script = {} instr = {} script, failed, instr = Script.load_and_append({'ESR': 'ESR_dithering'}, script, instr) print(script) print(failed) print(instr)
self.log('set inner instr: ' + str(inner_instr) + ' to ' + str(new_pos[1]) + ' mm') outer_instr.settings['position'] = new_pos[ 0] # update the position setting of the instrument inner_instr.settings['position'] = new_pos[1] outer_instr.set_position( ) # actually move the instrument to that location. If this is not within the safety inner_instr.set_position( ) # limits of the instruments, it will not actually move and say so in the log # run daq_read_counter or the relevant script to get fluorescence self.scripts['daq_read_ai'].run() time.sleep(self.settings['time_per_pt']) self.scripts['daq_read_ai'].stop() data = self.scripts['daq_read_ai'].data['voltage'] self.data['counts'][index_in][index_out] = np.mean(data) self.progress = tot_index * 100. / ( self.settings['inner_loop']['num_points'] * self.settings['outer_loop']['num_points']) self.updateProgress.emit(int(self.progress)) tot_index = tot_index + 1 if __name__ == '__main__': succeeded, failed, _ = Script.load_and_append({'ServoScan': ServoScan}) print(succeeded)
self.settings['outer_loop']['min_pos'], self.settings['outer_loop']['max_pos'] ] if data is None: data = self.data if data: plot_fluorescence_pos(data['counts'], extent, axes_list[0]) def _update_plot(self, axes_list): update_fluorescence(self.data['counts'], axes_list[0]) if __name__ == '__main__': script, failed, instr = Script.load_and_append({'AttoStep': 'AttoStep'}) print(script) print(failed) print(instr) # fp = Find_Points(settings={'path': 'Z:/Lab/Cantilever/Measurements/__tmp__', 'tag':'nvs'}) # fp.run() # plt.pcolor(fp.data['image']) # print(fp.data['image_gaussian'].shape) # plt.pcolor(fp.data['image']) # plt.imshow(fp.data['image'], cmap = 'pink', interpolation = 'nearest') # # # for x in fp.data['NV_positions']: # plt.plot(x[0],x[1],'ro')
pt = self.get_voltage(self.settings['attenuation']) if pt < min_volts or pt > max_volts: raise ValueError("Invalid voltage. Must be between 0 and 5 volts") task = self.daq_out.setup_AO(self.settings['DAQ_channels'], pt) self.daq_out.run(task) self.daq_out.waitToFinish(task) self.daq_out.stop(task) self.log('laser set to attenuation'.format( self.settings['attenuation'])) def get_voltage(self, attenuation): # this function returns the voltage needed for a given attenuation # fit to a quartic polynomial voltage = a4 * attenuation ^ 4 + a3 * attenuation ^ 3 + a2 * attenuation ^ 2 + a1 * attenuation + a0 return voltage if __name__ == '__main__': from pylabcontrol.core import Instrument # instruments, instruments_failed = Instrument.load_and_append({'daq': 'NI6259'}) script, failed, instruments = Script.load_and_append( script_dict={'SetLaserPower': 'SetLaserPower'}) print(script) print(failed) # print(instruments)
min_volts = 0.0 max_volts = 5.0 pt = self.get_voltage(self.settings['attenuation']) if pt < min_volts or pt > max_volts: raise ValueError("Invalid voltage. Must be between 0 and 5 volts") task = self.daq_out.setup_AO(self.settings['DAQ_channels'], pt) self.daq_out.run(task) self.daq_out.waitToFinish(task) self.daq_out.stop(task) self.log('laser set to attenuation'.format(self.settings['attenuation'])) def get_voltage(self, attenuation): # this function returns the voltage needed for a given attenuation # fit to a quartic polynomial voltage = a4*attenuation^4 + a3*attenuation^3 + a2*attenuation^2 + a1*attenuation + a0 return voltage if __name__ == '__main__': from pylabcontrol.core import Instrument # instruments, instruments_failed = Instrument.load_and_append({'daq': 'NI6259'}) script, failed, instruments = Script.load_and_append(script_dict={'SetLaserPower': 'SetLaserPower'}) print(script) print(failed) # print(instruments)
def _plot(self, axes_list): if self._current_subscript_stage['current_subscript'] == self.scripts[ 'FindNV']: self.scripts['FindNV']._plot(axes_list) elif self._current_subscript_stage[ 'current_subscript'] == self.scripts['ESR']: self.scripts['ESR']._plot(axes_list) elif self._current_subscript_stage[ 'current_subscript'] == self.scripts['Correlate']: self.scripts['Correlate']._plot(axes_list) #must be passed figure with galvo plot on first axis def _update_plot(self, axes_list): if self._current_subscript_stage['current_subscript'] == self.scripts[ 'FindNV']: self.scripts['FindNV']._update_plot(axes_list) elif self._current_subscript_stage[ 'current_subscript'] == self.scripts['ESR']: self.scripts['ESR']._update_plot(axes_list) elif self._current_subscript_stage[ 'current_subscript'] == self.scripts['Correlate']: self.scripts['Correlate']._update_plot(axes_list) if __name__ == '__main__': script, failed, instruments = Script.load_and_append( script_dict={'AlignFieldToNV': 'AlignFieldToNV'}) print(script) print(failed) # print(instruments)
self.instruments['daq']['instance'].DI_stop() diffData = np.diff(xLineData) summedData = np.zeros(len(self.x_array) / self.clockAdjust) for i in range(0, int((len(self.x_array) / self.clockAdjust))): summedData[i] = np.sum(diffData[(i * self.clockAdjust + 1):(i * self.clockAdjust + self.clockAdjust - 1)]) # also normalizing to kcounts/sec return summedData * (.001 / self.settings['time_per_pt']) if __name__ == '__main__': from pylabcontrol.core import Instrument # from b26_toolkit.pylabcontrol.instruments import NI7845RMain # # fpga = NI7845RMain() # # # g = GalvoScanFPGA(instruments={'NI7845RMain':fpga}, name='test_fpga_scan', settings=None, log_function=None, data_path=None) # print(fpga) # instruments, failed = Instrument.load_and_append(instrument_dict ={'NI7845RMain': 'NI7845RMain'}, raise_errors=True ) script, failed, instruments = Script.load_and_append( script_dict={'GalvoScanFPGA': 'GalvoScanFPGA'}, raise_errors=True) # print(script) print(failed) # # print(instruments)
phase = data['phase'] phase = phase[np.isfinite(r)] r = r[np.isfinite(r)] x_scaling = self.settings['xmapping'][0:3] y_scaling = self.settings['ymapping'][0:3] # plot amplitude axes = axes_list[0] axes.hold(False) plot_psd(freq, r, axes, x_scaling = x_scaling, y_scaling = y_scaling) # axes.set_xlim([min(freq), max(freq)]) axes.set_ylim([min(r), max(r)]) axes.set_ylabel('amplitude (Vrms)') # plot phase if not trace_only: axes = axes_list[1] axes.hold(False) plot_psd(freq, phase, axes, x_scaling=x_scaling, y_scaling='lin') # axes.set_xlim([min(freq), max(freq)]) axes.set_ylim([min(phase), max(phase)]) axes.set_ylabel('phase (rad)') if __name__ == '__main__': script, failed, instruments = Script.load_and_append(script_dict={'ZISweeper': 'ZISweeper'})
self.settings['width'], 'height': self.settings['height'] }) def _function(self): """ This is the actual function that will be executed. It uses only information that is provided in the settings property will be overwritten in the __init__ """ self.data = { 'image_data': self.instruments['Camera']['instance'].get_frame(), 'extent': [0, self.settings['width'], self.settings['height'], 0] } def _plot(self, axes_list, data=None): """ Plots camera image to first axis :param axes_list: list containing axis to plot to as zeroth element :param data: """ plot_fluorescence_new(self.data['image_data'], self.data['extent'], axes_list[0]) if __name__ == '__main__': script, failed, instruments = Script.load_and_append( script_dict={'TakeImage': 'TakeImage'}) print(script) print(failed)
return valid_pulse_sequences, valid_tau_list, measurement_gate_width def stop(self): """ Stop currently executed pulse blaster sequence NOT CURRENTLY WORKING, WILL CRASH PULSEBLASTER """ # self.instruments['PB']['instance'].stop() super(PulsedExperimentBaseScript, self).stop() if __name__ == '__main__': script = {} instr = {} script, failed, instr = Script.load_and_append( {'ExecutePulseBlasterSequence': 'ExecutePulseBlasterSequence'}, script, instr) script, failed, instr = Script.load_and_append( { 'ExecutePulseBlasterSequence': { 'class': 'ExecutePulseBlasterSequence', 'package': 'b26toolkit' } }, script, instr) print(script) print(failed) print(instr)
self.instruments['daq']['instance'].DI_stop() diffData = np.diff(xLineData) summedData = np.zeros(len(self.x_array) / self.clockAdjust) for i in range(0, int((len(self.x_array) / self.clockAdjust))): summedData[i] = np.sum(diffData[(i * self.clockAdjust + 1):(i * self.clockAdjust + self.clockAdjust - 1)]) # also normalizing to kcounts/sec return summedData * (.001 / self.settings['time_per_pt']) if __name__ == '__main__': from pylabcontrol.core import Instrument # from b26_toolkit.pylabcontrol.instruments import NI7845RMain # # fpga = NI7845RMain() # # # g = GalvoScanFPGA(instruments={'NI7845RMain':fpga}, name='test_fpga_scan', settings=None, log_function=None, data_path=None) # print(fpga) # instruments, failed = Instrument.load_and_append(instrument_dict ={'NI7845RMain': 'NI7845RMain'}, raise_errors=True ) script, failed, instruments = Script.load_and_append(script_dict={'GalvoScanFPGA': 'GalvoScanFPGA'}, raise_errors=True) # print(script) print(failed) # # print(instruments)
def test_load_and_append(self): filepath = 'C:\\Users\\Experiment\\PycharmProjects\\pylabcontrol\\pylabcontrol\\scripts\\example_scripts.py' script_dict = { 'DefaultName': { 'info': 'Enter docstring here', 'scripts': { 'ScriptDummy': { 'info': '\nExample Script that has all different types of parameters (integer, str, fload, point, list of parameters). Plots 1D and 2D data.\n ', 'settings': { 'count': 3, 'name': 'this is a counter', 'wait_time': 0.1, 'point2': { 'y': 0.1, 'x': 0.1 }, 'tag': 'scriptdummy', 'path': '', 'save': False, 'plot_style': 'main' }, 'class': 'ScriptDummy', 'filepath': filepath } }, 'class': 'ScriptIterator', 'settings': { 'script_order': { 'ScriptDummy': 0 }, 'iterator_type': 'Loop' }, 'package': 'b26_toolkit' } } scripts = {} instruments = {} scripts, loaded_failed, instruments = Script.load_and_append( script_dict=script_dict, scripts=scripts, instruments=instruments, raise_errors=True) print(('scripts', scripts)) print(('loaded_failed', loaded_failed)) print(('instruments', instruments)) print('----x') print((scripts['DefaultName'].__class__.__name__)) print('----x') print((scripts['DefaultName'].__class__.__name__.split('.')[0], script_dict['DefaultName']['package'])) assert scripts['DefaultName'].__class__.__name__.split( '.')[0] == script_dict['DefaultName']['package'] print((type(scripts['DefaultName'].__module__))) module, script_class_name, script_settings, script_instruments, script_sub_scripts, script_doc, package = Script.get_script_information( script_dict['DefaultName']) print(module) print(script_class_name)
data = self.data if data: if self.settings['track_laser_power_photodiode1'][ 'on/off'] == True: array_to_plot = np.delete( np.divide( np.multiply(self.data['counts'], np.mean(self.data['laser_power'])), self.data['laser_power']), 0) else: array_to_plot = np.delete(data['counts'], 0) update_counts_vs_pos( axes_list[0], array_to_plot, np.linspace(0, len(array_to_plot), len(array_to_plot))) class Daq_Read_Counter_NI6259(Daq_Read_Counter): _INSTRUMENTS = {'daq': NI6259} if __name__ == '__main__': script = {} instr = {} script, failed, instr = Script.load_and_append( {'Daq_Read_Cntr': 'Daq_Read_Cntr'}, script, instr) print(script) print(failed) print(instr)
axes_list[2]) else: plot_fluorescence_new(self.new_processed_image, self.data['new_image_extent'], axes_list[2]) axes_list[2].set_title( 'new image shifted by dx={:0.3f} dy={:0.3f}'.format( self.data['shift'][0], self.data['shift'][1])) def _update_plot(self, axes_list): ''' Plots the newly taken galvo scan to axis 2, and the correlation image to axis 1 Args: axes_list: list of axes to plot to. Uses two axes. ''' if self.scripts['take_baseline_image'].is_running: self.scripts['take_baseline_image']._update_plot(axes_list) elif self.scripts['take_new_image'].is_running: self.scripts['take_new_image']._update_plot(axes_list) else: self._plot(axes_list) if __name__ == '__main__': script, failed, instr = Script.load_and_append( {'Correlate_Images': Take_And_Correlate_Images}) print(script) print(failed) print(instr)
sets the current position of the galvo galvo_position: list with two floats, which give the x and y position of the galvo mirror """ if galvo_position[0] > 1 or galvo_position[0] < -1 or galvo_position[ 1] > 1 or galvo_position[1] < -1: raise ValueError( 'The script attempted to set the galvo position to an illegal position outside of +- 1 V' ) pt = galvo_position # daq API only accepts either one point and one channel or multiple points and multiple channels pt = np.transpose(np.column_stack((pt[0], pt[1]))) pt = (np.repeat(pt, 2, axis=1)) task = self.daq_out.setup_AO([ self.settings['DAQ_channels']['x_ao_channel'], self.settings['DAQ_channels']['y_ao_channel'] ], pt) self.daq_out.run(task) self.daq_out.waitToFinish(task) self.daq_out.stop(task) if __name__ == '__main__': script, failed, instruments = Script.load_and_append( script_dict={'GalvoScanPhotodiode': 'GalvoScanPhotodiode'}) print(script) print(failed) # print(instruments)
self.instruments['MagnetCoils'] ['instance'].settings['magnetic_fields']['z_field'])) print(('requested fields', self.instruments['MagnetCoils']['instance'].requested_fields)) print(('applied fields', self.instruments['MagnetCoils']['instance'].applied_fields)) self.data['new_voltages'] = self.instruments['MagnetCoils'][ 'instance'].new_voltages self.data['requested_fields'] = self.instruments['MagnetCoils'][ 'instance'].requested_fields self.data['applied_fields'] = self.instruments['MagnetCoils'][ 'instance'].applied_fields if __name__ == '__main__': from pylabcontrol.core import Instrument instruments, instruments_failed = Instrument.load_and_append( {'MagnetCoils': MagnetCoils}) script, failed, instruments = Script.load_and_append( script_dict={'SetMagneticCoils': SetMagneticCoils}, instruments=instruments) script['SetMagneticCoils']._function() print(script) print(failed) # print(instruments)
initial_position = [] return initial_position def set_galvo_location(self, galvo_position): """ sets the current position of the galvo galvo_position: list with two floats, which give the x and y position of the galvo mirror """ if galvo_position[0] > 1 or galvo_position[0] < -1 or galvo_position[1] > 1 or galvo_position[1] < -1: raise ValueError('The script attempted to set the galvo position to an illegal position outside of +- 1 V') pt = galvo_position # daq API only accepts either one point and one channel or multiple points and multiple channels pt = np.transpose(np.column_stack((pt[0], pt[1]))) pt = (np.repeat(pt, 2, axis=1)) task = self.daq_out.setup_AO( [self.settings['DAQ_channels']['x_ao_channel'], self.settings['DAQ_channels']['y_ao_channel']], pt) self.daq_out.run(task) self.daq_out.waitToFinish(task) self.daq_out.stop(task) if __name__ == '__main__': script, failed, instruments = Script.load_and_append(script_dict={'GalvoScanPhotodiode': 'GalvoScanPhotodiode'}) print(script) print(failed) # print(instruments)
# take settings defined in the script and update with settings for the fields dictator = self.instruments['MagnetCoils']['settings'] dictator.update({'magnetic_fields': {'x_field': float(new_x_field), 'y_field': float(new_y_field), 'z_field': float(new_z_field)}}) self.instruments['MagnetCoils']['instance'].update(dictator) # self.log('Magnetic Field set to Bx={:.4}G, By={:.4}G, Bz={:.4}G'.format(self.instruments['MagnetCoils']['instance'].settings['magnetic_fields']['x_field'], self.instruments['MagnetCoils']['instance'].settings['magnetic_fields']['y_field'], self.instruments['MagnetCoils']['instance'].settings['magnetic_fields']['z_field']) ) print(('requested fields', self.instruments['MagnetCoils']['instance'].requested_fields)) print(('applied fields', self.instruments['MagnetCoils']['instance'].applied_fields)) self.data['new_voltages'] = self.instruments['MagnetCoils']['instance'].new_voltages self.data['requested_fields'] = self.instruments['MagnetCoils']['instance'].requested_fields self.data['applied_fields'] = self.instruments['MagnetCoils']['instance'].applied_fields if __name__ == '__main__': from pylabcontrol.core import Instrument instruments, instruments_failed = Instrument.load_and_append({'MagnetCoils': MagnetCoils }) script, failed, instruments = Script.load_and_append(script_dict={'SetMagneticCoils': SetMagneticCoils}, instruments = instruments) script['SetMagneticCoils']._function() print(script) print(failed) # print(instruments)
def __init__(self, instruments = None, scripts = None, name = None, settings = None, log_function = None, data_path = None): """ Sets up script and sends width and height settings to camera Args: name (optional): name of script, if empty same as class name settings (optional): settings for this script, if empty same as default settings """ Script.__init__(self, name, settings = settings, instruments = instruments, scripts = scripts, log_function= log_function, data_path = data_path) self.instruments['Camera']['instance'].update({'width': self.settings['width'], 'height': self.settings['height']}) def _function(self): """ This is the actual function that will be executed. It uses only information that is provided in the settings property will be overwritten in the __init__ """ self.data = {'image_data': self.instruments['Camera']['instance'].get_frame(), 'extent': [0,self.settings['width'], self.settings['height'], 0]} def _plot(self, axes_list, data = None): """ Plots camera image to first axis :param axes_list: list containing axis to plot to as zeroth element :param data: """ plot_fluorescence_new(self.data['image_data'], self.data['extent'], axes_list[0]) if __name__ == '__main__': script, failed, instruments = Script.load_and_append(script_dict={'TakeImage': 'TakeImage'}) print(script) print(failed)
#calculates angle based on the always positive results, so always returns angles in first octant. Thus, after #switching polarity, then just plug this angle in [_, theta, phi] = cartesian_to_spherical([results['x'], results['y'], results['z']]) self.data = {'nv_axis_direction': [theta, phi], 'switch_polarity': switch_polarity} #must be passed figure with galvo plot on first axis def _plot(self, axes_list): if self._current_subscript_stage['current_subscript'] == self.scripts['FindNV']: self.scripts['FindNV']._plot(axes_list) elif self._current_subscript_stage['current_subscript'] == self.scripts['ESR']: self.scripts['ESR']._plot(axes_list) elif self._current_subscript_stage['current_subscript'] == self.scripts['Correlate']: self.scripts['Correlate']._plot(axes_list) #must be passed figure with galvo plot on first axis def _update_plot(self, axes_list): if self._current_subscript_stage['current_subscript'] == self.scripts['FindNV']: self.scripts['FindNV']._update_plot(axes_list) elif self._current_subscript_stage['current_subscript'] == self.scripts['ESR']: self.scripts['ESR']._update_plot(axes_list) elif self._current_subscript_stage['current_subscript'] == self.scripts['Correlate']: self.scripts['Correlate']._update_plot(axes_list) if __name__ == '__main__': script, failed, instruments = Script.load_and_append(script_dict={'AlignFieldToNV':'AlignFieldToNV'}) print(script) print(failed) # print(instruments)
if self.settings['track_laser_power_photodiode1']['on/off'] == True: array_to_plot = np.delete(np.divide(np.multiply(self.data['counts'], np.mean(self.data['laser_power'])), self.data['laser_power']),0) else: array_to_plot = np.delete(data['counts'], 0) plot_counts(axes_list[0], array_to_plot) def _update_plot(self, axes_list, data = None): if data is None: data = self.data if data: if self.settings['track_laser_power_photodiode1']['on/off'] == True: array_to_plot = np.delete(np.divide(np.multiply(self.data['counts'], np.mean(self.data['laser_power'])), self.data['laser_power']), 0) else: array_to_plot = np.delete(data['counts'], 0) update_counts_vs_pos(axes_list[0], array_to_plot, np.linspace(0, len(array_to_plot), len(array_to_plot))) class Daq_Read_Counter_NI6259(Daq_Read_Counter): _INSTRUMENTS = {'daq': NI6259} if __name__ == '__main__': script = {} instr = {} script, failed, instr = Script.load_and_append({'Daq_Read_Cntr': 'Daq_Read_Cntr'}, script, instr) print(script) print(failed) print(instr)
elif self.settings['type'] == 'ring' and len( self.data['nv_locations']) > 1: # here we create a circular grid, where pts a and be define the center and the outermost ring Nx, Ny = self.settings['Nx'], self.settings['Ny'] pta = self.data['nv_locations'][0] # center ptb = self.data['nv_locations'][1] # outermost ring # radius of outermost ring: rmax = np.sqrt((pta[0] - ptb[0])**2 + (pta[1] - ptb[1])**2) # create points on rings tmp = [] for r in np.linspace(rmax, 0, Ny + 1)[0:-1]: for theta in np.linspace(0, 2 * np.pi, Nx + 1)[0:-1]: tmp += [[ r * np.sin(theta) + pta[0], r * np.cos(theta) + pta[1] ]] self.data['nv_locations'] = np.array(tmp) self.stop() if __name__ == '__main__': script, failed, instr = Script.load_and_append( {'SelectPoints': 'SelectPoints'}) print(script) print(failed) print(instr)
axes_list[1].set_title('correlation image') # plot new image if not self.data['new_image'] == []: if not self.settings['display_processed_images']: plot_fluorescence_new(self.data['new_image'], self.data['new_image_extent'], axes_list[2]) else: plot_fluorescence_new(self.new_processed_image, self.data['new_image_extent'], axes_list[2]) axes_list[2].set_title('new image shifted by dx={:0.3f} dy={:0.3f}'.format(self.data['shift'][0], self.data['shift'][1])) def _update_plot(self, axes_list): ''' Plots the newly taken galvo scan to axis 2, and the correlation image to axis 1 Args: axes_list: list of axes to plot to. Uses two axes. ''' if self.scripts['take_baseline_image'].is_running: self.scripts['take_baseline_image']._update_plot(axes_list) elif self.scripts['take_new_image'].is_running: self.scripts['take_new_image']._update_plot(axes_list) else: self._plot(axes_list) if __name__ == '__main__': script, failed, instr = Script.load_and_append({'Correlate_Images': Take_And_Correlate_Images}) print(script) print(failed) print(instr)