def export_default_scripts(target_folder,
                           source_folder=None,
                           raise_errors=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
    """
    loaded_instruments = {}
    loaded_scripts = {}

    scripts_to_load = get_classes_in_folder(source_folder, Script)

    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.iteritems():
        filename = os.path.join(target_folder, '{:s}.b26'.format(name))
        value.save_b26(filename)

    print('\n================================================')
    print('================================================')
    print('saved {:d} scripts, {:d} failed'.format(len(loaded_scripts),
                                                   len(failed)))
    if failed != {}:
        for error_name, error in failed.iteritems():
            print('failed to create script: ', error_name, error)
Ejemplo n.º 2
0
    def test_loading_and_saving(self):
        from src.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)
Ejemplo n.º 3
0
        '''
        if not self.data[
                'nv_locations']:  #if self.data is empty so this is the first point
            self.data['nv_locations'].append(pt)
            self.data['image_data'] = None  # clear image data

        else:
            # use KDTree to find NV closest to mouse click
            tree = scipy.spatial.KDTree(self.data['nv_locations'])
            #does a search with k=1, that is a search for the nearest neighbor, within distance_upper_bound
            d, i = tree.query(pt,
                              k=1,
                              distance_upper_bound=self.settings['patch_size'])

            # removes NV if previously selected
            if d is not np.inf:
                self.data['nv_locations'].pop(i)
            # adds NV if not previously selected
            else:
                self.data['nv_locations'].append(pt)


if __name__ == '__main__':

    script, failed, instr = Script.load_and_append(
        {'SelectPoints': 'SelectPoints'})

    print(script)
    print(failed)
    print(instr)
Ejemplo n.º 4
0
    #
    # self.scripts, failed, self.instruments = Script.load_and_append(
    #     script_dict=scripts,
    #     instruments=self.instruments,
    #     log_function=self.log,
    #     data_path=self.gui_settings['data_folder'])



    # ========================= test explicitely loading for DAQ ========================================
    # scripts, loaded_failed, instruments = Script.load_and_append({'take_image': 'GalvoScanDAQ'})
    # print('===++++++===========++++++===========++++++========')
    # print(scripts)
    # print('===++++++===========++++++===========++++++========')

    # af = AutoFocusNIFPGA(scripts=scripts)
    # print(af)
    #
    # # ========================= test explicitely loading for DAQ ========================================
    # scripts, loaded_failed, instruments = Script.load_and_append({'take_image': 'GalvoScanDAQ'})
    # print('===++++++===========++++++===========++++++========')
    # print(scripts)
    # print('===++++++===========++++++===========++++++========')
    #
    # af = AutoFocusNIFPGA(scripts=scripts)
    # print(af)

    scripts, loaded_failed, instruments = Script.load_and_append({'test': AutoFocusTwoPoints})
    print('===++++++===========++++++===========++++++========')
    print(scripts)
    print('===++++++===========++++++===========++++++========')
Ejemplo n.º 5
0
                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.src.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)
Ejemplo n.º 6
0
        if self.data['maximum_point'] and self.data['max_fluor']:
            axes_list[0].hold(True)
            axes_list[0].plot(self.data['maximum_point'],
                              self.data['max_fluor'], 'ro')
            axes_list[0].hold(False)

    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

        """

        # only pick the first figure from the figure list, this avoids that get_axes_layout clears all the figures
        return super(optimizeZ, self).get_axes_layout([figure_list[1]])


if __name__ == '__main__':
    script, failed, instruments = Script.load_and_append(
        script_dict={'ConfocalScan': 'ConfocalScan'})

    print(script)
    print(failed)
    # print(instruments)
Ejemplo n.º 7
0
        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.src.core import Instrument
    # from b26_toolkit.src.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)
Ejemplo n.º 8
0
                                          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)
Ejemplo n.º 9
0
        attocube_voltage = self.instruments['attocube']['settings'][
            self.settings['axis']]['voltage']
        attocube.update({self.settings['axis']: {'voltage': attocube_voltage}})
        attocube_freq = self.instruments['attocube']['settings'][
            self.settings['axis']]['freq']
        attocube.update({self.settings['axis']: {'freq': attocube_freq}})
        if self.settings['direction'] == 'Up':
            dir = 0
        elif self.settings['direction'] == 'Down':
            dir = 1
        self.instruments['attocube']['instance'].step(self.settings['axis'],
                                                      dir)


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')
Ejemplo n.º 10
0
        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 = self.instruments['daq_out']['instance']
        # 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 = daq.setup_AO([
            self.settings['DAQ_channels']['x_ao_channel'],
            self.settings['DAQ_channels']['y_ao_channel']
        ], pt)
        daq.run(task)
        daq.waitToFinish(task)
        daq.stop(task)


if __name__ == '__main__':
    script, failed, instruments = Script.load_and_append(
        script_dict={'GalvoScan': 'GalvoScan'})

    print(script)
    print(failed)
    # print(instruments)
Ejemplo n.º 11
0
                'rabi'] and self.scripts['rabi'].is_running:
            self.scripts['rabi']._update_plot(axes_list)
        elif self.scripts['deer'].is_running:
            self.scripts['deer']._update_plot(axes_list)

    # 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
    #
    #     """
    #
    #     # create a new figure list that contains only figure 1, this assures that the super.get_axes_layout doesn't
    #     # empty the plot contained on figure 2
    #     # return super(EsrRabiDeer, self).get_axes_layout([figure_list[0]])
    #
    #     return super(EsrRabiDeer, self).get_axes_layout(figure_list)


if __name__ == '__main__':
    script, failed, instr = Script.load_and_append(
        {'EsrRabiDeer': EsrRabiDeer})

    print(script)
    print(failed)
    print(instr)
Ejemplo n.º 12
0
        freq = data['frequency']
        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 (??)')

        # plot phase
        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'})
Ejemplo n.º 13
0
    PulseBlasterBaseScript plot leads to errors
    Plot 1: self.data['tau'], the list of times specified for a given experiment, verses self.data['counts'], the data
    received for each time
    Plot 2: the pulse sequence performed at the current time (or if plotted statically, the last pulse sequence
    performed

    Args:
        axes_list: list of axes to write plots to (uses first 2)
        data (optional) dataset to plot (dictionary that contains keys counts, tau), if not provided use self.data
    """
    if data is None:
        data = self.data

    counts = data['counts']
    x_data = data['tau']
    axis1 = axes_list[0]
    plot_1d_simple_timetrace_ns(axis1, x_data, [counts])
    axis2 = axes_list[1]
    plot_pulses(axis2, self.pulse_sequences[self.sequence_index])


if __name__ == '__main__':
    script = {}
    instr = {}
    script, failed, instr = Script.load_and_append(
        {'PulseDelays': 'PulseDelays'}, script, instr)

    print(script)
    print('failed', failed)
    print(instr)
        # clean up APD tasks
        self.instruments['daq']['instance'].stop(task)

        # turn laser off
        self.instruments['PB']['instance'].update({'laser': {'status': False}})
        self.log('Laser is off.')

    def plot(self, figure_list):
        # COMMENT_ME
        super(Daq_Read_Counter_Single, self).plot([figure_list[1]])

    def _plot(self, axes_list, data=None):
        # COMMENT_ME

        if data is None:
            data = self.data

        if data:
            plot_counts(axes_list[0], data['counts'], data['time'],
                        'time [sec]')


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)
Ejemplo n.º 15
0
        """
        new_figure_list = [figure_list[1]]
        return super(ESR, self).get_axes_layout(new_figure_list)

        # # fit ESR curve to lorentzian and return fit parameters. If initial guess known, put in fit_start_params, otherwise
        # # guesses reasonable initial values.
        # def fit_esr(self, freq_values, esr_data, fit_start_params=None):
        #     if (fit_start_params is None):
        #         offset = np.mean(esr_data)
        #         amplitude = np.max(esr_data) - np.min(esr_data)
        #         center = freq_values[esr_data.argmin()]
        #         width = 10000000  # 10 MHz arbitrarily chosen as reasonable
        #         fit_start_params = [amplitude, width, center, offset]
        #     try:
        #         return opt.curve_fit(self.lorentzian, freq_values, esr_data, fit_start_params)
        #     except RuntimeError:
        #         self.log('Lorentzian fit failed')
        #         return [-1, -1, -1, -1], 'Ignore'
        #
        # # defines a lorentzian with some amplitude, width, center, and offset to use with opt.curve_fit
        # def lorentzian(self, x, amplitude, width, center, offset):
        #     return (-(amplitude*(.5*width)**2)/((x-center)**2+(.5*width)**2))+offset

if __name__ == '__main__':
    script = {}
    instr = {}
    script, failed, instr = Script.load_and_append({'ESR': 'ESR'}, script, instr)

    print(script)
    print(failed)
    print(instr)
Ejemplo n.º 16
0
        elif self.scripts['deer_pwr'].is_running:
            self.scripts['deer_pwr']._update_plot(axes_list)
        elif self.scripts['deer_RFpitime'].is_running:
            self.scripts['deer_RFpitime']._update_plot(axes_list)

    # 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
    #
    #     """
    #
    #     # create a new figure list that contains only figure 1, this assures that the super.get_axes_layout doesn't
    #     # empty the plot contained on figure 2
    #     # return super(EsrRabiDeer, self).get_axes_layout([figure_list[0]])
    #
    #     return super(EsrRabiDeer, self).get_axes_layout(figure_list)


if __name__ == '__main__':
    script, failed, instr = Script.load_and_append(
        {'EsrRabiDeerXYnSpectrumAdvanced': EsrRabiDeerXYnSpectrumAdvanced})

    print(script)
    print(failed)
    print(instr)
Ejemplo n.º 17
0
        elif self.scripts['deer_pwr'].is_running:
            self.scripts['deer_pwr']._update_plot(axes_list)
        elif self.scripts['deer_RFpitime'].is_running:
            self.scripts['deer_RFpitime']._update_plot(axes_list)

    # 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
    #
    #     """
    #
    #     # create a new figure list that contains only figure 1, this assures that the super.get_axes_layout doesn't
    #     # empty the plot contained on figure 2
    #     # return super(EsrRabiDeer, self).get_axes_layout([figure_list[0]])
    #
    #     return super(EsrRabiDeer, self).get_axes_layout(figure_list)


if __name__ == '__main__':
    script, failed, instr = Script.load_and_append(
        {'EsrRabiDeerXYnSpectrum': EsrRabiDeerXYnSpectrum})

    print(script)
    print(failed)
    print(instr)