예제 #1
0
def do1d(param_set: _BaseParameter, start: number, stop: number,
         num_points: int, delay: number,
         *param_meas: Union[_BaseParameter, Callable[[], None]],
         enter_actions: Sequence[Callable[[], None]] = (),
         exit_actions: Sequence[Callable[[], None]] = (),
         do_plot: bool = True,
         do2dbuf: str = '',
         conDuct: Instrument = None) \
        -> AxesTupleListWithRunId:
    """
	adapted for logging settings by felix 17.04.2020
		-added argument do2buf
		-added _export_settings functionality

	adapted for live plotting of conductance by felix 17.04.2020
		-added argument conDuct
		-conDuct is a virtual parameter who has to be called as an optional argument in do1D.
		 conDuct has a function calcG() which allows to calculate the division of two given 
		 parameters or one parameter and a float number. See init file for more info.

    Perform a 1D scan of ``param_set`` from ``start`` to ``stop`` in
    ``num_points`` measuring param_meas at each step. In case param_meas is
    an ArrayParameter this is effectively a 2d scan.

    Args:
        param_set: The QCoDeS parameter to sweep over
        start: Starting point of sweep
        stop: End point of sweep
        num_points: Number of points in sweep
        delay: Delay after setting paramter before measurement is performed
        *param_meas: Parameter(s) to measure at each step or functions that
          will be called at each step. The function should take no arguments.
          The parameters and functions are called in the order they are
          supplied.
        enter_actions: A list of functions taking no arguments that will be
            called before the measurements start
        exit_actions: A list of functions taking no arguments that will be
            called after the measurements ends
        do_plot: should png and pdf versions of the images be saved after the
            run.

    Returns:
        The run_id of the DataSet created
    """
    meas = Measurement()
    meas.register_parameter(
        param_set)  # register the first independent parameter
    output = []
    param_set.post_delay = delay
    interrupted = False

    for action in enter_actions:
        # this omits the posibility of passing
        # argument to enter and exit actions.
        # Do we want that?
        meas.add_before_run(action, ())
    for action in exit_actions:
        meas.add_after_run(action, ())

    # do1D enforces a simple relationship between measured parameters
    # and set parameters. For anything more complicated this should be
    # reimplemented from scratch
    for parameter in param_meas:
        if isinstance(parameter, _BaseParameter):
            meas.register_parameter(parameter, setpoints=(param_set, ))
            output.append([parameter, None])
        if conDuct != None:
            meas.register_parameter(conDuct.G, setpoints=(param_set, ))
            output.append([conDuct.G, None])
    try:
        with meas.run() as datasaver:
            start_time = time.perf_counter()
            os.makedirs(datapath + '{}'.format(datasaver.run_id))
            for set_point in np.linspace(start, stop, num_points):
                param_set.set(set_point)
                output = []
                for parameter in param_meas:
                    if isinstance(parameter, _BaseParameter):
                        output.append((parameter, parameter.get()))
                    elif callable(parameter):
                        parameter()
                if conDuct != None:
                    output.append((conDuct.G, conDuct.calcG(output)))

                datasaver.add_result((param_set, set_point), *output)
    except KeyboardInterrupt:
        interrupted = True

    stop_time = time.perf_counter()

    dataid = datasaver.run_id  # convenient to have for plotting

    if interrupted:
        inst = list(meas.parameters.values())
        exportpath = datapath + '{}'.format(
            datasaver.run_id) + '/{}_set_{}_set.dat'.format(
                inst[0].name, inst[1].name)
        exportsnapshot = datapath + '{}'.format(
            datasaver.run_id) + '/snapshot.txt'
        #export_by_id(dataid,exportpath)
        export_by_id_pd(dataid, exportpath)
        export_snapshot_by_id(dataid, exportsnapshot)
        _export_settings(datasaver.run_id, inst, do2dbuf)
        stop_time = time.perf_counter()
        print("Acquisition took:  %s seconds " % (stop_time - start_time))
        raise KeyboardInterrupt

    print("Acquisition took:  %s seconds " % (stop_time - start_time))
    inst = list(meas.parameters.values())
    exportpath = datapath + '{}'.format(
        datasaver.run_id) + '/{}_set_{}_set.dat'.format(
            inst[0].name, inst[1].name)
    exportsnapshot = datapath + '{}'.format(datasaver.run_id) + '/snapshot.txt'
    #export_by_id(dataid,exportpath)
    export_by_id_pd(dataid, exportpath)
    export_snapshot_by_id(dataid, exportsnapshot)
    #added by felix 05.03.2020
    _export_settings(datasaver.run_id, inst, do2dbuf)

    if do_plot is True:
        ax, cbs = _save_image(datasaver, inst)
    else:
        ax = None,
        cbs = None

    return dataid, ax, cbs
예제 #2
0
class FollowPlotParams(object):
    def __init__(self, params, inter_delay=0.01, save_data=False):
        self._params = []
        self.save_data = save_data
        self.inter_delay = inter_delay
        self.pause = False

        for p in params:
            self._params.append(p)

        if self.save_data:
            self._create_measurement()

        self.create_figs()
        self.t0 = time.monotonic()

    def _create_measurement(self):
        """
        Creates a QCoDeS Measurement object. This controls the saving of data by registering
        QCoDeS Parameter objects, which this function does. Registers all 'tracked' parameters, 
        Returns the measurement object.
        """

        self.meas = Measurement()
        self.meas.register_custom_parameter('time', label='Time', unit='s')
        for p in self._params:
            self.meas.register_parameter(p)

        return self.meas

    def create_figs(self):
        """
        Creates default figures for each of the parameters. Plots them in a new, separate window.
        """

        self.fig = plt.figure(figsize=(4 * (2 + len(self._params)), 4))
        self.grid = plt.GridSpec(4, 1 + len(self._params), hspace=0)
        self.setax = []
        self.setaxline = []

        for i, p in enumerate(self._params):
            self.setax.append(self.fig.add_subplot(self.grid[:, i]))
            # First, create a plot of the sweeping parameters value against time
            self.setax[i].set_xlabel('Time (s)')
            self.setax[i].set_ylabel(f'{p.label} ({p.unit})')
            self.setaxline.append(self.setax[i].plot([], [])[0])

    def pause_run(self):
        self.pause = not self.pause

    def is_paused(self):
        return self.pause

    def autorun(self):
        if self.save_data:
            with self.meas.run() as datasaver:

                while self.pause is False:
                    t = time.monotonic() - self.t0

                    data = []
                    data.append(('time', t))

                    for i, p in enumerate(self._params):
                        v = p.get()
                        data.append((p, v))

                        self.setaxline[i].set_xdata(
                            np.append(self.setaxline[i].get_xdata(), t))
                        self.setaxline[i].set_ydata(
                            np.append(self.setaxline[i].get_ydata(), v))
                        self.setax[i].relim()
                        self.setax[i].autoscale_view()

                    if self.save_data:
                        datasaver.add_result(*data)

                    plt.pause(self.inter_delay)

    def iterate(self):
        t = time.monotonic() - self.t0

        data = []
        data.append(('time', t))

        for i, p in enumerate(self._params):
            v = p.get()
            data.append((p, v))

            self.setaxline[i].set_xdata(
                np.append(self.setaxline[i].get_xdata(), t))
            self.setaxline[i].set_ydata(
                np.append(self.setaxline[i].get_ydata(), v))
            self.setax[i].relim()
            self.setax[i].autoscale_view()

        if self.save_data:
            datasaver.add_result(*data)

        plt.pause(self.inter_delay)
예제 #3
0
파일: conftest.py 프로젝트: H6O3/Qcodes
def meas_with_registered_param(experiment, DAC, DMM):
    meas = Measurement()
    meas.register_parameter(DAC.ch1)
    meas.register_parameter(DMM.v1, setpoints=[DAC.ch1])
    yield meas
def generate_DB_file_with_runs_but_no_snapshots():
    """
    Generate a .db-file with a handful of runs without snapshots
    """

    # This function will run often on CI and re-generate the .db-files
    # That should ideally be a deterministic action
    # (although this hopefully plays no role)
    np.random.seed(0)

    v4fixturepath = os.path.join(utils.fixturepath, 'version4')
    os.makedirs(v4fixturepath, exist_ok=True)
    path = os.path.join(v4fixturepath, 'with_runs_but_no_snapshots.db')

    if os.path.exists(path):
        os.remove(path)

    from qcodes.dataset.sqlite_base import connect, is_column_in_table
    from qcodes.dataset.measurements import Measurement
    from qcodes.dataset.experiment_container import Experiment
    from qcodes import Parameter, Station

    connect(path)

    exp = Experiment(path_to_db=path,
                     name='experiment_1',
                     sample_name='no_sample_1')
    conn = exp.conn

    assert not is_column_in_table(conn, 'runs', 'snapshot')

    # Now make some parameters to use in measurements
    params = []
    for n in range(4):
        params.append(Parameter(f'p{n}', label=f'Parameter {n}',
                                unit=f'unit {n}', set_cmd=None, get_cmd=None))

    assert Station.default is None

    # Set up an experiment

    meas = Measurement(exp)
    meas.register_parameter(params[0])
    meas.register_parameter(params[1])
    meas.register_parameter(params[2], basis=(params[1],))
    meas.register_parameter(params[3], setpoints=(params[1], params[2]))

    # Make a number of identical runs

    for _ in range(4):

        with meas.run() as datasaver:

            for x in np.random.rand(4):
                for y in np.random.rand(4):
                    z = np.random.rand()
                    datasaver.add_result((params[1], x),
                                         (params[2], y),
                                         (params[3], z))

    assert not is_column_in_table(conn, 'runs', 'snapshot')
예제 #5
0
class Sweep1D(object):
    """
    Class to control sweeping along 1 parameter, while tracking multiple other parameters.
    It has functionality to live plot, or not, and one can create their own figures (e.g. in a GUI)
    or have the class create its own matplotlib figues. Follows QCoDeS data-taking methods.
    Adapted from Joe Finney's code.
    
    SR830s are not currently implemented.
    """
    def __init__(self,
                 set_param,
                 start,
                 stop,
                 step,
                 freq,
                 bidirectional=False,
                 meas=None,
                 plot=False,
                 auto_figs=False):
        """
        Initializes the Sweep object. Takes in the parameter to be swept (set_param), the 
        value to start and stop sweeping at (start/stop, respectively), the step spacing (step),
        and the frequency of measurements. Can turn plotting off through 'plot', also tells 
        system whether to create it's own plots or use given ones through 'auto_figs'.
        """
        # Save our input variables
        self.set_param = set_param
        self.start = start
        self.stop = stop
        self.step = step

        if (self.stop - self.start) > 0:
            self.step = abs(self.step)
        else:
            self.step = (-1) * abs(self.step)

        self.inter_delay = 1 / freq
        self.t0 = time.monotonic()
        self.setpoint = self.start - self.step
        self.bidirectional = bidirectional
        self.direction = 0  #Forward

        d = (stop - start) / step * self.inter_delay
        h, m, s = int(d / 3600), int(d / 60) % 60, int(d) % 60
        print(f'Minimum duration: {h}h {m}m {s}s')

        # Either mark or save the measurement object
        if meas is not None:
            self.meas = meas

        # Saves our plotting flags
        self.plot = plot
        self.auto_figs = auto_figs
        # Sets a flag to ensure that the figures have been created before trying to plot
        self.figs_set = False
        self.pause = False
        self._sr830s = []
        self._params = []

    def follow_param(self, p):
        """
        This function takes in a QCoDeS Parameter p, and tracks it through each sweep.
        """
        self._params.append(p)

    def follow_sr830(self, l, name, gain=1.0):
        """
        This function adds an SR830, but (as of now) does not do anything with it.
        """
        self._sr830s.append((l, name, gain))

    def _create_measurement(self, *set_params):
        """
        Creates a QCoDeS Measurement object. This controls the saving of data by registering
        QCoDeS Parameter objects, which this function does. Registers all 'sweeping' parameters
        (set_params), and all 'tracked' parameters, 'self._params'. Returns the measurement
        object.
        """
        self.meas = Measurement()
        for p in set_params:
            self.meas.register_parameter(p)
        self.meas.register_custom_parameter('time', label='Time', unit='s')
        for p in self._params:
            self.meas.register_parameter(p, setpoints=(
                *set_params,
                'time',
            ))
        for l, _, _ in self._sr830s:
            self.meas.register_parameter(l.X,
                                         setpoints=(
                                             *set_params,
                                             'time',
                                         ))
            self.meas.register_parameter(l.Y,
                                         setpoints=(
                                             *set_params,
                                             'time',
                                         ))

        return self.meas

    def create_figs(self):
        """
        Creates default figures for each of the parameters. Plots them in a new, separate window.
        """
        self.fig = plt.figure(
            figsize=(4 * (2 + len(self._params) + len(self._sr830s)), 4))
        self.grid = plt.GridSpec(4,
                                 1 + len(self._params) + len(self._sr830s),
                                 hspace=0)
        self.setax = self.fig.add_subplot(self.grid[:, 0])
        # First, create a plot of the sweeping parameters value against time
        self.setax.set_xlabel('Time (s)')
        self.setax.set_ylabel(
            f'{self.set_param.label} ({self.set_param.unit})')
        self.setaxline = self.setax.plot([], [])[0]

        self.plines = []
        self.axes = []
        # Now create a plot for every tracked parameter as a function of sweeping parameter
        for i, p in enumerate(self._params):
            self.axes.append(self.fig.add_subplot(self.grid[:, 1 + i]))
            self.axes[i].set_xlabel(
                f'{self.set_param.label} ({self.set_param.unit})')
            self.axes[i].set_ylabel(f'{p.label} ({p.unit})')

            forward_line = matplotlib.lines.Line2D([], [])
            forward_line.set_color('b')
            backward_line = matplotlib.lines.Line2D([], [])
            backward_line.set_color('r')
            self.axes[i].add_line(forward_line)
            self.axes[i].add_line(backward_line)
            self.plines.append((forward_line, backward_line))

        self.figs_set = True

    def set_figs(self, fig, setax, axes):
        """
        Give a figure and plots for both the sweeping parameter and the tracked parameters
        for the program to update. fig is of type matplotlib Figure, setax is a (sub)plot, 
        and axes is an array of subplots.
        """
        self.figs_set = True
        self.fig = fig
        self.setax = setax
        self.axes = axes

        # Initializes sweeping plot
        self.setax.set_xlabel('Time (s)')
        self.setax.set_ylabel(
            f'{self.set_param.label} ({self.set_param.unit})')
        self.setaxline = setax.plot([], [])[0]

        self.plines = []
        # Initializes tracking plots
        for i, p in enumerate(self._params):
            self.axes[i].set_xlabel(
                f'{self.set_param.label} ({self.set_param.unit})')
            self.axes[i].set_ylabel(f'{p.label} ({p.unit})')

            forward_line = matplotlib.lines.Line2D([], [])
            forward_line.set_color('b')
            backward_line = matplotlib.lines.Line2D([], [])
            backward_line.set_color('r')
            self.axes[i].add_line(forward_line)
            self.axes[i].add_line(backward_line)
            self.plines.append((forward_line, backward_line))

    def autorun(self, datasaver=None, persist_data=None):
        """
        Run a sweep through this class. Makes call to create_figs if needed.
        Calls self.iterate to move through each data point.
        """
        # Checks to see if it needs to generate its own figures
        if self.plot and self.auto_figs and not self.figs_set:
            self.create_figs()

        # If plots should have been set but are not, return 0
        if self.plot is True and self.figs_set is False:
            return 0

        # Run the loop
        if datasaver is None:
            with self.meas.run() as datasaver:
                # Check if we are within the stopping condition
                while abs(self.setpoint - self.stop) > abs(self.step / 2):
                    self.iterate(datasaver)

                # If we want to go both ways, we flip the start and stop, and run again
                if self.bidirectional:
                    self.flip_direction()
                    while abs(self.setpoint - self.stop) > abs(self.step / 2):
                        self.iterate(datasaver)
                    self.flip_direction()
        else:
            # Check if we are within the stopping condition
            while abs(self.setpoint - self.stop) > abs(self.step / 2):
                self.iterate(datasaver, persist_data)

            # If we want to go both ways, we flip the start and stop, and run again
            if self.bidirectional:
                self.flip_direction()
                while abs(self.setpoint - self.stop) > abs(self.step / 2):
                    self.iterate(datasaver, persist_data)
                self.flip_direction()

        return 1

    def iterate(self, datasaver=None, persist_data=None):
        """
        Runs one 'step' in the sweep. Takes in only the datasaver object, which is always
        a Measurement object's run() function (see autorun()). Iterate will update the 
        sweeping parameter, read each of the tracking parameters, and update the plots
        if plotting is enabled. Returns all values as a list of tuples, in the form of
        (parameter_name, parameter_value).
        """
        t = time.monotonic() - self.t0
        # Step the setpoint, and update the value
        self.setpoint = self.step + self.setpoint
        self.set_param.set(self.setpoint)

        # Update the sweeping parameter plot
        if self.plot is True:
            self.setaxline.set_xdata(np.append(self.setaxline.get_xdata(), t))
            self.setaxline.set_ydata(
                np.append(self.setaxline.get_ydata(), self.setpoint))
            self.setax.relim()
            self.setax.autoscale_view()

        # Pause if desired
        if self.inter_delay is not None:
            time.sleep(self.inter_delay)

        # Create our data storage object, which is a list of tuples of the parameter
        # and its value
        data = []
        if persist_data is not None:
            data.append(persist_data)
        data.append((self.set_param, self.setpoint))
        data.append(('time', t))

        # Loop through each of the tracking parameters
        for i, p in enumerate(self._params):
            # Update their values, and add them to the data object
            v = p.get()
            data.append((p, v))
            # Update each of the plots for the tracking parameters
            if self.plot is True:
                self.plines[i][self.direction].set_xdata(
                    np.append(self.plines[i][self.direction].get_xdata(),
                              self.setpoint))
                self.plines[i][self.direction].set_ydata(
                    np.append(self.plines[i][self.direction].get_ydata(), v))
                self.axes[i].relim()
                self.axes[i].autoscale_view()

        # Add this point to the dataset
        if datasaver is not None:
            datasaver.add_result(*data)

        # Set the plots
        if self.plot is True:
            self.fig.tight_layout()
            self.fig.canvas.draw()
            plt.pause(0.001)

        # Finally return all data
        return data

    def pause_run(self):
        self.pause = not self.pause

    def is_paused(self):
        return self.pause

    def ramp_to_zero(self):
        self.stop = 0
        if self.setpoint - self.step > 0:
            self.step = (-1) * abs(self.step)
        else:
            self.step = abs(self.step)

        print(f'Ramping {self.set_param.label} to 0 . . . ')
        while abs(self.setpoint - self.stop) > abs(self.step / 2):
            self.iterate()

        self.set_param.set(0)
        print(f'Done ramping {self.set_param.label} to 0!')

    def flip_direction(self):
        """
        Flips the direction of the sweep, to do bidirectional sweeping.
        """
        temp = self.start
        self.start = self.stop
        self.stop = temp
        self.step = -1 * self.step
        self.setpoint -= self.step

        # If backwards, go forwards, and vice versa
        if self.direction:
            self.direction = 0
        else:
            self.direction = 1

    def reset(self, new_params=None):
        """
        Resets the Sweep1D to reuse the same object with the same plots.
        
        Arguments:
            new_params - list of 4 values to determine how we sweep. In order, 
                         must be [ start value, stop value, step, frequency ]
        """
        # Set our new values if desired
        if new_params is not None:
            self.start = new_params[0]
            self.stop = new_params[1]
            self.step = new_params[2]
            self.inter_delay = 1 / new_params[3]

        # Reset our setpoint
        self.setpoint = self.start - self.step

        # Reset our plots
        if self.plot is True:
            self.setaxline.set_xdata(np.array([]))
            self.setaxline.set_ydata(np.array([]))
            self.setax.relim()
            self.setax.autoscale_view()

            for i, p in enumerate(self._params):
                self.plines[i][0].set_xdata(np.array([]))
                self.plines[i][0].set_ydata(np.array([]))
                self.plines[i][1].set_xdata(np.array([]))
                self.plines[i][1].set_ydata(np.array([]))
                self.axes[i].relim()
                self.axes[i].autoscale_view()

    def get_measurement(self):
        """
        Returns the measurement object.
        """
        return self.meas

    def save(self):
        """
        Saves the plots as a png
        (may not work? untested)
        """
        b = io.BytesIO()
        self.fig.savefig(b, format='png')
예제 #6
0
    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'))
예제 #7
0
def test_subscriptions(experiment, DAC, DMM):
    """
    Test that subscribers are called at the moment that data is flushed to database

    Note that for the purpose of this test, flush_data_to_database method is called explicitly instead of waiting for
    the data to be flushed automatically after the write_period passes after a add_result call.

    Args:
        experiment (qcodes.dataset.experiment_container.Experiment) : qcodes experiment object
        DAC (qcodes.instrument.base.Instrument) : dummy instrument object
        DMM (qcodes.instrument.base.Instrument) : another dummy instrument object
    """
    def subscriber1(results, length, state):
        """
        A dict of all results
        """
        state[length] = results

    def subscriber2(results, length, state):
        """
        A list of all parameter values larger than 7
        """
        for res in results:
            state += [pres for pres in res if pres > 7]

    meas = Measurement(exp=experiment)
    meas.register_parameter(DAC.ch1)
    meas.register_parameter(DMM.v1, setpoints=(DAC.ch1, ))

    res_dict = {}
    lt7s = []

    meas.add_subscriber(subscriber1, state=res_dict)
    assert len(meas.subscribers) == 1
    meas.add_subscriber(subscriber2, state=lt7s)
    assert len(meas.subscribers) == 2

    meas.write_period = 0.2

    expected_list = []

    with meas.run() as datasaver:

        assert len(datasaver._dataset.subscribers) == 2
        assert res_dict == {}
        assert lt7s == []

        as_and_bs = list(zip(range(5), range(3, 8)))

        for num in range(5):

            (a, b) = as_and_bs[num]
            expected_list += [c for c in (a, b) if c > 7]

            datasaver.add_result((DAC.ch1, a), (DMM.v1, b))
            datasaver.flush_data_to_database()

            assert lt7s == expected_list
            assert list(res_dict.keys()) == [n for n in range(1, num + 2)]

    assert len(datasaver._dataset.subscribers) == 0
def test_subscriptions(experiment, DAC, DMM):
    """
    Test that subscribers are called at the moment the data is flushed to database

    Note that for the purpose of this test, flush_data_to_database method is
    called explicitly instead of waiting for the data to be flushed
    automatically after the write_period passes after a add_result call.
    """
    def collect_all_results(results, length, state):
        """
        Updates the *state* to contain all the *results* acquired
        during the experiment run
        """
        # Due to the fact that by default subscribers only hold 1 data value
        # in their internal queue, this assignment should work (i.e. not
        # overwrite values in the "state" object) assuming that at the start
        # of the experiment both the dataset and the *state* objects have
        # the same length.
        state[length] = results

    def collect_values_larger_than_7(results, length, state):
        """
        Appends to the *state* only the values from *results*
        that are larger than 7
        """
        for result_tuple in results:
            state += [value for value in result_tuple if value > 7]

    meas = Measurement(exp=experiment)
    meas.register_parameter(DAC.ch1)
    meas.register_parameter(DMM.v1, setpoints=(DAC.ch1, ))

    # key is the number of the result tuple,
    # value is the result tuple itself
    all_results_dict = {}
    values_larger_than_7 = []

    meas.add_subscriber(collect_all_results, state=all_results_dict)
    assert len(meas.subscribers) == 1
    meas.add_subscriber(collect_values_larger_than_7,
                        state=values_larger_than_7)
    assert len(meas.subscribers) == 2

    meas.write_period = 0.2

    with meas.run() as datasaver:

        # Assert that the measurement, runner, and datasaver
        # have added subscribers to the dataset
        assert len(datasaver._dataset.subscribers) == 2

        assert all_results_dict == {}
        assert values_larger_than_7 == []

        dac_vals_and_dmm_vals = list(zip(range(5), range(3, 8)))
        values_larger_than_7__expected = []

        for num in range(5):
            (dac_val, dmm_val) = dac_vals_and_dmm_vals[num]
            values_larger_than_7__expected += \
                [val for val in (dac_val, dmm_val) if val > 7]

            datasaver.add_result((DAC.ch1, dac_val), (DMM.v1, dmm_val))

            # Ensure that data is flushed to the database despite the write
            # period, so that the database triggers are executed, which in turn
            # add data to the queues within the subscribers
            datasaver.flush_data_to_database()

            # In order to make this test deterministic, we need to ensure that
            # just enough time has passed between the moment the data is flushed
            # to database and the "state" object (that is passed to subscriber
            # constructor) has been updated by the corresponding subscriber's
            # callback function. At the moment, there is no robust way to ensure
            # this. The reason is that the subscribers have internal queue which
            # is populated via a trigger call from the SQL database, hence from
            # this "main" thread it is difficult to say whether the queue is
            # empty because the subscriber callbacks have already been executed
            # or because the triggers of the SQL database has not been executed
            # yet.
            #
            # In order to overcome this problem, a special decorator is used
            # to wrap the assertions. This is going to ensure that some time
            # is given to the Subscriber threads to finish exhausting the queue.
            @retry_until_does_not_throw(
                exception_class_to_expect=AssertionError, delay=0.5, tries=10)
            def assert_states_updated_from_callbacks():
                assert values_larger_than_7 == values_larger_than_7__expected
                assert list(all_results_dict.keys()) == \
                    [result_index for result_index in range(1, num + 1 + 1)]

            assert_states_updated_from_callbacks()

    # Ensure that after exiting the "run()" context,
    # all subscribers get unsubscribed from the dataset
    assert len(datasaver._dataset.subscribers) == 0

    # Ensure that the triggers for each subscriber
    # have been removed from the database
    get_triggers_sql = "SELECT * FROM sqlite_master WHERE TYPE = 'trigger';"
    triggers = atomic_transaction(datasaver._dataset.conn,
                                  get_triggers_sql).fetchall()
    assert len(triggers) == 0
예제 #9
0
from pytopo.qctools import instruments as instools

from qcodes.instrument_drivers.QuTech.IVVI import IVVI
ivvi = instools.create_inst(IVVI, "ivvi", "ASRL5::INSTR")

from qcodes.instrument_drivers.Keysight.Keysight_34465A import Keysight_34465A
key1 = instools.create_inst(Keysight_34465A, "key1",
                            "USB0::0x2A8D::0x0101::MY57503556::INSTR")
key2 = instools.create_inst(Keysight_34465A, "key2",
                            "USB0::0x2A8D::0x0101::MY57503135::INSTR")

station = qc.Station(ivvi, key1, key2)

meas = Measurement()
meas.register_parameter(ivvi.dac1)
meas.register_parameter(key1.volt, setpoints=(ivvi.dac1, ))
meas.register_parameter(key2.volt, setpoints=(ivvi.dac1, ))

fig, ax = plt.subplots(1, 1)

with meas.run() as datasaver:
    for bias_v in np.linspace(-100, 100, 11):
        ivvi.dac1(bias_v)
        current = key1.volt()
        voltage = key2.volt()

        datasaver.add_result((ivvi.dac1, bias_v), (key1.volt, current),
                             (key2.volt, voltage))

        bias_vals = datasaver.dataset.get_data('ivvi_dac1')
예제 #10
0
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)
예제 #11
0
    def _take_data(self, qc_measurement_parameters: List[qc.Parameter]) -> int:
        """
        It will always sweep the same gates and measure the same parameter
        TO DO: Implement smart way of sampling measurement points
        """
        meas = QC_Measurement()
        output = []
        output_dict: Dict[str, Optional[float]] = {}
        gate_parameters = []
        n_points_true = [0, 0]
        gates_to_sweep = self.setpoint_settings['gates_to_sweep']

        nt.set_database(self.data_settings['db_name'],
                        db_folder=self.data_settings['db_folder'])

        nt_meta = self._prepare_nt_metadata()

        with self.set_up_gates_for_measurement():
            for gate in gates_to_sweep:
                meas.register_parameter(gate.dc_voltage)
                gate_parameters.append(gate.dc_voltage)

            for m_param in qc_measurement_parameters:
                _flush_buffers(m_param)
                meas.register_parameter(m_param, setpoints=gate_parameters)
                output.append([m_param, None])
                output_dict[m_param.full_name] = None

            start_time = time.time()
            done = False

            with meas.run() as datasaver:
                # Save some important metadata before we start measuring
                datasaver.dataset.add_metadata(nt.meta_tag, json.dumps(nt_meta))

                for set_point0 in self.current_setpoints[0]:
                    gates_to_sweep[0].dc_voltage(set_point0)
                    self.do_at_outer_setpoint(set_point0)
                    n_points_true[0] += 1

                    if len(gates_to_sweep) == 2:
                        gates_to_sweep[1].use_ramp(True)
                        start_voltage = self.current_setpoints[1][0]

                        gates_to_sweep[1].dc_voltage(start_voltage)
                        gates_to_sweep[1].use_ramp(False)

                        for set_point1 in self.current_setpoints[1]:
                            gates_to_sweep[1].dc_voltage(set_point1)
                            n_points_true[1] += 1
                            m_params = qc_measurement_parameters
                            for p, parameter in enumerate(m_params):
                                value = parameter.get()
                                output[p][1] = value
                                output_dict[parameter.full_name] = value

                            paramx = gates_to_sweep[0].dc_voltage.full_name
                            paramy = gates_to_sweep[1].dc_voltage.full_name
                            datasaver.add_result(
                                (paramx, set_point0),
                                (paramy, set_point1),
                                *output, # type: ignore
                            )
                            done = self.finish_early(output_dict)  # type: ignore
                            if done:
                                break
                    else:
                        m_params = qc_measurement_parameters
                        for p, parameter in enumerate(m_params):
                            value = parameter.get()
                            output[p][1] = value
                            output_dict[parameter.full_name] = value

                        paramx = gates_to_sweep[0].dc_voltage.full_name
                        datasaver.add_result(
                            (paramx, set_point0), *output # type: ignore
                        )
                        done = self.finish_early(output_dict)  # type: ignore
                    if done:
                        break

                elapsed_time = time.time() - start_time
                minutes, seconds = divmod(elapsed_time, 60)
                msg = "Elapsed time to take data: {:.0f} min, {:.2f} sec."
                logger.info(msg.format(minutes, seconds))

                # Add last bits of info to metadata
                nt_meta["n_points"] = n_points_true
                nt_meta["elapsed_time"] = round(float(elapsed_time), 2)

                datasaver.dataset.add_metadata(nt.meta_tag, json.dumps(nt_meta))

        return datasaver.run_id
예제 #12
0
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')
예제 #13
0
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)
예제 #14
0
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)
예제 #15
0
# Criar um database
initialise_or_create_database_at("~/teste.db")

exp = load_or_create_experiment(experiment_name='osc realtime intro 2',
                                sample_name="osc realtime 1")


def calculateGain():
    Y = osc.ch3.wavesample()
    n_mean = int(len(Y) / 2)
    value = 2 * np.mean(Y[n_mean:])
    value = 10 * np.log(np.power(value, 2))
    return value


gain = Parameter('gain', label='gain', unit='dB', get_cmd=calculateGain)

# Medida de fato
meas = Measurement(exp=exp, station=station)

meas.register_parameter(PSG1.freq)
meas.register_parameter(gain, setpoints=[PSG1.freq])

with meas.run(write_in_background=True) as datasaver:
    for aFreq in np.linspace(1, 500, 500):
        time.sleep(1)
        PSG1.freq(aFreq)
        PSG2.freq(aFreq)
        datasaver.add_result((gain, gain()), (PSG1.freq, PSG1.freq()))
예제 #16
0
def test_cache_1d_shape(experiment, DAC, DMM, n_points, bg_writing,
                        channel_array_instrument, setpoints_type):

    setpoints_param, setpoints_values = _prepare_setpoints_1d(
        DAC, channel_array_instrument, n_points, setpoints_type)

    meas = Measurement()

    meas.register_parameter(setpoints_param)

    meas_parameters = (
        DMM.v1,
        channel_array_instrument.A.dummy_multi_parameter,
        channel_array_instrument.A.dummy_scalar_multi_parameter,
        channel_array_instrument.A.dummy_2d_multi_parameter,
        channel_array_instrument.A.dummy_2d_multi_parameter_2,
        channel_array_instrument.A.dummy_array_parameter,
        channel_array_instrument.A.dummy_complex_array_parameter,
        channel_array_instrument.A.dummy_complex,
        channel_array_instrument.A.dummy_parameter_with_setpoints,
        channel_array_instrument.A.dummy_parameter_with_setpoints_complex,
    )
    pws_n_points = 10
    channel_array_instrument.A.dummy_start(0)
    channel_array_instrument.A.dummy_stop(10)
    channel_array_instrument.A.dummy_n_points(pws_n_points)

    expected_shapes = {
        'dummy_dmm_v1': (n_points, ),
        'dummy_channel_inst_ChanA_multi_setpoint_param_this': (n_points, 5),
        'dummy_channel_inst_ChanA_multi_setpoint_param_that': (n_points, 5),
        'dummy_channel_inst_ChanA_thisparam': (n_points, ),
        'dummy_channel_inst_ChanA_thatparam': (n_points, ),
        'dummy_channel_inst_ChanA_this': (n_points, 5, 3),
        'dummy_channel_inst_ChanA_that': (n_points, 5, 3),
        'dummy_channel_inst_ChanA_this_5_3': (n_points, 5, 3),
        'dummy_channel_inst_ChanA_this_2_7': (n_points, 2, 7),
        'dummy_channel_inst_ChanA_dummy_array_parameter': (n_points, 5),
        'dummy_channel_inst_ChanA_dummy_complex_array_parameter':
        (n_points, 5),
        'dummy_channel_inst_ChanA_dummy_complex': (n_points, ),
        'dummy_channel_inst_ChanA_dummy_parameter_with_setpoints':
        (n_points, pws_n_points),
        'dummy_channel_inst_ChanA_dummy_parameter_with_setpoints_complex':
        (n_points, pws_n_points)
    }

    for param in meas_parameters:
        meas.register_parameter(param, setpoints=(setpoints_param, ))
    meas.set_shapes(detect_shape_of_measurement(meas_parameters, (n_points, )))
    n_points_measured = 0
    with meas.run(write_in_background=bg_writing) as datasaver:
        dataset = datasaver.dataset
        _assert_parameter_data_is_identical(dataset.get_parameter_data(),
                                            dataset.cache.data())
        for i, v in enumerate(setpoints_values):
            n_points_measured += 1
            setpoints_param.set(v)

            meas_vals = [(param, param.get())
                         for param in meas_parameters[:-2]]
            meas_vals += expand_setpoints_helper(meas_parameters[-2])
            meas_vals += expand_setpoints_helper(meas_parameters[-1])

            datasaver.add_result((setpoints_param, v), *meas_vals)
            datasaver.flush_data_to_database(block=True)
            cache_data_trees = dataset.cache.data()
            param_data_trees = dataset.get_parameter_data()
            _assert_partial_cache_is_as_expected(cache_data_trees,
                                                 expected_shapes,
                                                 n_points_measured,
                                                 param_data_trees,
                                                 cache_correct=True)
    cache_data_trees = dataset.cache.data()
    param_data_trees = dataset.get_parameter_data()

    _assert_completed_cache_is_as_expected(cache_data_trees,
                                           param_data_trees,
                                           flatten=False)
예제 #17
0
    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)
예제 #18
0
def test_cache_2d_shape(experiment, DAC, DMM, n_points_outer, n_points_inner,
                        pws_n_points, bg_writing, channel_array_instrument,
                        cache_size):
    meas = Measurement()

    meas.register_parameter(DAC.ch1)
    meas.register_parameter(DAC.ch2)

    meas_parameters = (
        DMM.v1,
        channel_array_instrument.A.dummy_multi_parameter,
        channel_array_instrument.A.dummy_scalar_multi_parameter,
        channel_array_instrument.A.dummy_2d_multi_parameter,
        channel_array_instrument.A.dummy_2d_multi_parameter_2,
        channel_array_instrument.A.dummy_array_parameter,
        channel_array_instrument.A.dummy_complex_array_parameter,
        channel_array_instrument.A.dummy_complex,
        channel_array_instrument.A.dummy_parameter_with_setpoints,
        channel_array_instrument.A.dummy_parameter_with_setpoints_complex,
    )

    channel_array_instrument.A.dummy_start(0)
    channel_array_instrument.A.dummy_stop(10)
    channel_array_instrument.A.dummy_n_points(pws_n_points)
    for param in meas_parameters:
        meas.register_parameter(param, setpoints=(DAC.ch1, DAC.ch2))

    if cache_size == "too_small":
        meas.set_shapes(
            detect_shape_of_measurement(
                meas_parameters,
                (int(ceil(n_points_outer / 2)), n_points_inner)))
    elif cache_size == "too_large":
        meas.set_shapes(
            detect_shape_of_measurement(meas_parameters,
                                        (n_points_outer * 2, n_points_inner)))
    else:
        meas.set_shapes(
            detect_shape_of_measurement(meas_parameters,
                                        (n_points_outer, n_points_inner)))

    expected_shapes = {
        'dummy_dmm_v1': (n_points_outer, n_points_inner),
        'dummy_channel_inst_ChanA_multi_setpoint_param_this':
        (n_points_outer, n_points_inner, 5),
        'dummy_channel_inst_ChanA_multi_setpoint_param_that':
        (n_points_outer, n_points_inner, 5),
        'dummy_channel_inst_ChanA_thisparam': (n_points_outer, n_points_inner),
        'dummy_channel_inst_ChanA_thatparam': (n_points_outer, n_points_inner),
        'dummy_channel_inst_ChanA_this': (n_points_outer, n_points_inner, 5,
                                          3),
        'dummy_channel_inst_ChanA_that': (n_points_outer, n_points_inner, 5,
                                          3),
        'dummy_channel_inst_ChanA_this_5_3': (n_points_outer, n_points_inner,
                                              5, 3),
        'dummy_channel_inst_ChanA_this_2_7': (n_points_outer, n_points_inner,
                                              2, 7),
        'dummy_channel_inst_ChanA_dummy_array_parameter': (n_points_outer,
                                                           n_points_inner, 5),
        'dummy_channel_inst_ChanA_dummy_complex_array_parameter':
        (n_points_outer, n_points_inner, 5),
        'dummy_channel_inst_ChanA_dummy_complex': (n_points_outer,
                                                   n_points_inner),
        'dummy_channel_inst_ChanA_dummy_parameter_with_setpoints':
        (n_points_outer, n_points_inner, pws_n_points),
        'dummy_channel_inst_ChanA_dummy_parameter_with_setpoints_complex':
        (n_points_outer, n_points_inner, pws_n_points)
    }

    if cache_size == "correct":
        assert meas._shapes == expected_shapes

    with meas.run(write_in_background=bg_writing) as datasaver:
        dataset = datasaver.dataset
        # Check that parameter data and cache data are indential for empty datasets
        _assert_parameter_data_is_identical(dataset.get_parameter_data(),
                                            dataset.cache.data())
        n_points_measured = 0
        for v1 in np.linspace(-1, 1, n_points_outer):
            for v2 in np.linspace(-1, 1, n_points_inner):
                n_points_measured += 1
                DAC.ch1.set(v1)
                DAC.ch2.set(v2)
                meas_vals = [(param, param.get()) for param in meas_parameters]

                datasaver.add_result((DAC.ch1, v1), (DAC.ch2, v2), *meas_vals)
                datasaver.flush_data_to_database(block=True)
                param_data_trees = dataset.get_parameter_data()
                cache_data_trees = dataset.cache.data()

                _assert_partial_cache_is_as_expected(cache_data_trees,
                                                     expected_shapes,
                                                     n_points_measured,
                                                     param_data_trees,
                                                     cache_size == "correct")
    cache_data_trees = dataset.cache.data()
    param_data_trees = dataset.get_parameter_data()
    _assert_completed_cache_is_as_expected(cache_data_trees,
                                           param_data_trees,
                                           flatten=cache_size == "too_small",
                                           clip=cache_size == "too_large")
예제 #19
0
def test_register_parameter_numbers(DAC, DMM):
    """
    Test the registration of scalar QCoDeS parameters
    """

    parameters = [DAC.ch1, DAC.ch2, DMM.v1, DMM.v2]
    not_parameters = ['', 'Parameter', 0, 1.1, Measurement]

    meas = Measurement()

    for not_a_parameter in not_parameters:
        with pytest.raises(ValueError):
            meas.register_parameter(not_a_parameter)

    my_param = DAC.ch1
    meas.register_parameter(my_param)
    assert len(meas.parameters) == 1
    paramspec = meas.parameters[str(my_param)]
    assert paramspec.name == str(my_param)
    assert paramspec.label == my_param.label
    assert paramspec.unit == my_param.unit
    assert paramspec.type == 'numeric'

    # registering the same parameter twice should lead
    # to a replacement/update, but also change the
    # parameter order behind the scenes
    # (to allow us to re-register a parameter with new
    # setpoints)

    my_param.unit = my_param.unit + '/s'
    meas.register_parameter(my_param)
    assert len(meas.parameters) == 1
    paramspec = meas.parameters[str(my_param)]
    assert paramspec.name == str(my_param)
    assert paramspec.label == my_param.label
    assert paramspec.unit == my_param.unit
    assert paramspec.type == 'numeric'

    for parameter in parameters:
        with pytest.raises(ValueError):
            meas.register_parameter(my_param, setpoints=(parameter, ))
        with pytest.raises(ValueError):
            meas.register_parameter(my_param, basis=(parameter, ))

    meas.register_parameter(DAC.ch2)
    meas.register_parameter(DMM.v1)
    meas.register_parameter(DMM.v2)
    meas.register_parameter(my_param,
                            basis=(DAC.ch2, ),
                            setpoints=(DMM.v1, DMM.v2))

    assert list(meas.parameters.keys()) == [
        str(DAC.ch2), str(DMM.v1),
        str(DMM.v2), str(my_param)
    ]
    paramspec = meas.parameters[str(my_param)]
    assert paramspec.name == str(my_param)
    assert paramspec.inferred_from == ', '.join([str(DAC.ch2)])
    assert paramspec.depends_on == ', '.join([str(DMM.v1), str(DMM.v2)])

    meas = Measurement()

    meas.register_parameter(DAC.ch1)
    meas.register_parameter(DAC.ch2, setpoints=(DAC.ch1, ))
    with pytest.raises(ValueError):
        meas.register_parameter(DMM.v1, setpoints=(DAC.ch2, ))
예제 #20
0
 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)
예제 #21
0
def test_plot_dataset_2d_shaped(experiment, request, nan_setpoints, shifted):
    """
    Test plotting of preshaped data on a grid that may or may not be shifted
    with and without nans in the set points.
    """
    inst = DummyInstrument("dummy", gates=["s1", "m1", "s2"])
    request.addfinalizer(inst.close)

    inst.m1.get = np.random.randn

    meas = Measurement()
    meas.register_parameter(inst.s1)
    meas.register_parameter(inst.s2)
    meas.register_parameter(inst.m1, setpoints=(inst.s1, inst.s2))

    outer_shape = 10
    inner_shape = 20

    meas.set_shapes(
        detect_shape_of_measurement((inst.m1, ), (outer_shape, inner_shape)))

    shift = 0

    with meas.run() as datasaver:
        try:
            for outer in np.linspace(0, 9, outer_shape):
                for inner in np.linspace(0 + shift, 10 + shift, inner_shape):
                    datasaver.add_result((inst.s1, outer), (inst.s2, inner),
                                         (inst.m1, inst.m1()))
                    if inner > 7 and outer > 6 and nan_setpoints:
                        raise TerminateLoopException
                if shifted:
                    shift += 1
        except TerminateLoopException:
            pass

    axes, cbs = plot_dataset(datasaver.dataset)
    xlims = axes[0].get_xlim()
    ylims = axes[0].get_ylim()

    # check that this generates a QuadMesh which is the expected output of pcolormesh
    assert any(
        isinstance(mplobj, QuadMesh) for mplobj in axes[0].get_children())

    if nan_setpoints and shifted:
        assert xlims[0] == -0.5
        assert xlims[1] == 7.5
        assert ylims[0] < 0
        assert ylims[0] > -1.0
        assert ylims[1] > 16
        assert ylims[1] < 17
    elif not nan_setpoints and shifted:
        assert xlims[0] == -0.5
        assert xlims[1] == 9.5
        assert ylims[0] < 0
        assert ylims[0] > -1.0
        assert ylims[1] > 19
        assert ylims[1] < 20
    elif nan_setpoints and not shifted:
        assert xlims[0] == -0.5
        assert xlims[1] == 7.5
        assert ylims[0] < 0
        assert ylims[0] > -1.0
        assert ylims[1] > 10
        assert ylims[1] < 11
    else:
        assert xlims[0] == -0.5
        assert xlims[1] == 9.5
        assert ylims[0] < 0
        assert ylims[0] > -1.0
        assert ylims[1] > 10
        assert ylims[1] < 11
예제 #22
0
    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 generate_DB_file_with_runs_and_snapshots():
    """
    Generate a .db-file with a handful of runs some of which have snapshots.

    Generated runs:
        #1: run with a snapshot that has some content
        #2: run with a snapshot of an empty station
        #3: run without a snapshot
    """
    v4fixturepath = os.path.join(utils.fixturepath, 'version4')
    os.makedirs(v4fixturepath, exist_ok=True)
    path = os.path.join(v4fixturepath, 'with_runs_and_snapshots.db')

    if os.path.exists(path):
        os.remove(path)

    from qcodes.dataset.sqlite_base import is_column_in_table
    from qcodes.dataset.measurements import Measurement
    from qcodes.dataset.experiment_container import Experiment
    from qcodes import Parameter, Station
    from qcodes.dataset.descriptions import RunDescriber
    from qcodes.dataset.dependencies import InterDependencies

    exp = Experiment(path_to_db=path,
                     name='experiment_1',
                     sample_name='no_sample_1')
    conn = exp.conn

    # Now make some parameters to use in measurements
    params = []
    for n in range(4):
        params.append(Parameter(f'p{n}', label=f'Parameter {n}',
                                unit=f'unit {n}', set_cmd=None, get_cmd=None))

    # We are going to make 3 runs
    run_ids = []

    # Make a run with a snapshot with some content

    full_station = Station(*params[0:1], default=False)
    assert Station.default is None

    meas = Measurement(exp, full_station)
    meas.register_parameter(params[0])
    meas.register_parameter(params[1])
    meas.register_parameter(params[2], basis=(params[1],))
    meas.register_parameter(params[3], setpoints=(params[1], params[2]))

    with meas.run() as datasaver:

        for x in np.random.rand(4):
            for y in np.random.rand(4):
                z = np.random.rand()
                datasaver.add_result((params[1], x),
                                     (params[2], y),
                                     (params[3], z))

    run_ids.append(datasaver.run_id)

    # Make a run with a snapshot of empty station

    empty_station = Station(default=False)
    assert Station.default is None

    meas = Measurement(exp, empty_station)
    meas.register_parameter(params[0])
    meas.register_parameter(params[1])
    meas.register_parameter(params[2])
    meas.register_parameter(params[3], setpoints=(params[1], params[2]))

    with meas.run() as datasaver:

        for x in np.random.rand(4):
            for y in np.random.rand(4):
                z = np.random.rand()
                datasaver.add_result((params[1], x),
                                     (params[2], y),
                                     (params[3], z))

    run_ids.append(datasaver.run_id)

    # Make a run without a snapshot (i.e. station is None)

    assert Station.default is None

    meas = Measurement(exp)
    meas.register_parameter(params[0])
    meas.register_parameter(params[1])
    meas.register_parameter(params[2], basis=(params[1],))
    meas.register_parameter(params[3], setpoints=(params[1], params[2]))

    with meas.run() as datasaver:

        for x in np.random.rand(4):
            for y in np.random.rand(4):
                z = np.random.rand()
                datasaver.add_result((params[1], x),
                                     (params[2], y),
                                     (params[3], z))

    run_ids.append(datasaver.run_id)

    # Check correctness of run_id's

    assert [1, 2, 3] == run_ids, 'Run ids of generated runs are not as ' \
                                 'expected after generating runs #1-3'

    # Ensure snapshot column

    assert is_column_in_table(conn, 'runs', 'snapshot')
예제 #24
0
    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()
예제 #25
0
class Sweep2D(object):
    def __init__(self, inner_sweep_parameters, outer_sweep_parameters, freq,
                 follow_param):
        """
        We initialize our 2D sweep by taking in the parameters for each sweep, and the frequency.
        The inner_sweep_parameters and outer_sweep_parameters MUST be a list, conforming to the 
        following standard:
        
            [ <QCoDeS Parameter>, <start value>, <stop value>, <step size> ]
            
        Arguments: 
            inner_sweep_parameters - list conforming to above standard for the inner sweep
            outer_sweep_parameters - list conforming to above standard for the inner sweep
            freq - the frequency of measurement
            follow_param - the parameter to be tracked while other two are swept
        """

        # Ensure that the inputs were passed (at least somewhat) correctly
        if len(inner_sweep_parameters) != 4 or len(
                outer_sweep_parameters) != 4:
            raise TypeError(
                'For 2D Sweep, must pass list of 4 object for each sweep parameter, \
                             in order: [ <QCoDeS Parameter>, <start value>, <stop value>, <step size> ]'
            )

        # Save our input variables
        self.in_param = inner_sweep_parameters[0]
        self.in_start = inner_sweep_parameters[1]
        self.in_stop = inner_sweep_parameters[2]
        self.in_step = inner_sweep_parameters[3]

        if (self.in_stop - self.in_start) > 0:
            self.in_step = abs(self.in_step)
        else:
            self.in_step = (-1) * abs(self.in_step)

        self.out_param = outer_sweep_parameters[0]
        self.out_start = outer_sweep_parameters[1]
        self.out_stop = outer_sweep_parameters[2]
        self.out_step = outer_sweep_parameters[3]

        if (self.out_stop - self.out_start) > 0:
            self.out_step = abs(self.out_step)
        else:
            self.out_step = (-1) * abs(self.out_step)

        self.out_setpoint = self.out_start - self.out_step

        self.inter_delay = 1 / freq

        # Sets a flag to ensure that the figures have been created before trying to plot
        self.figs_set = False
        self._params = []
        self._sr830s = []

        # Add the tracking parameter, and create the measurement
        self.follow_param(follow_param)
        self.meas = self._create_measurement(self.out_param, self.in_param)

        # Create the inner sweep
        self.inner_sweep = Sweep1D(self.in_param,
                                   self.in_start,
                                   self.in_stop,
                                   self.in_step,
                                   freq,
                                   meas=self.meas,
                                   bidirectional=True,
                                   plot=True,
                                   auto_figs=False)
        # Make sure the inner sweep knows what parameter it should be reading
        self.inner_sweep._params.append(follow_param)

        # Deal with creating the figures
        self.create_figs()
        self.inner_sweep.set_figs(self.fig, self.setax, self.axes)

        self.t0 = time.monotonic()
        # The origin of the plot is top left, we want it to be bottom left,
        # so we keep count of what number sweep we are at to put it into the
        # matrix backwards
        self.count = 0

        # We want to track the max and min values seen to autorange the heatmap
        self.max_datapt = float("-inf")
        self.min_datapt = float("inf")

        self.pause = False

    def autorun(self, update_rule=None):
        """
        Run the 2D Sweep. Creates the datasaver and passes it to the iterate function.
        Updates the plots, and then updates the inner sweep if desired.
        
        Arguments:
            update_rule - function to call, accepting the Sweep1D object as an argument,
                          to determine how the next inner sweep should behave
        """
        # If there is not an update_rule passed, then call our own no_change function
        # to run the same sweep again
        if update_rule is None:
            update_rule = self.no_change

        with self.meas.run() as datasaver:
            # Loop until we are done
            while abs(self.out_setpoint - self.out_stop) > abs(
                    self.out_step / 2) and self.pause is False:
                self.iterate(datasaver)

                self.update_heatmap(self.count)

                update_rule(self.inner_sweep)
                self.count += 1

            datasaver.flush_data_to_database()
            # Make the plots persist after finishing plotting
            plt.show()

    def iterate(self, datasaver):
        """
        This function is one iteration of the outer sweep, which steps the outer parameter,
        and then runs the inner sweep.
        
        Arguments:
            datasaver - the Runner object created from calling Measurement.run()
        """
        # Step the setpoint, and update the value
        self.out_setpoint = self.out_step + self.out_setpoint
        self.out_param.set(self.out_setpoint)

        # Pause if desired
        if self.inter_delay is not None:
            time.sleep(self.inter_delay)

        # Create our data storage object, which is a list of tuples of the parameter
        # and its value
        data = (self.out_param, self.out_setpoint)

        # We pass to the inner sweep the datasaver, and pass it the information about
        # the outer sweep parameter
        self.inner_sweep.autorun(datasaver, data)

    def ramp_to_zero(self):
        """
        Ramps the parameter down to 0.
        """
        self.out_stop = 0
        if self.out_setpoint - self.out_stop > 0:
            self.out_step = (-1) * abs(self.out_step)
        else:
            self.out_step = abs(self.out_step)

        self.inner_sweep.ramp_to_zero()

        print(f'Ramping {self.out_param.label} to 0 . . . ')

        while abs(self.out_setpoint - self.out_stop) > abs(self.out_step / 2):
            # Step the setpoint, and update the value
            self.out_setpoint = self.out_step + self.out_setpoint
            self.out_param.set(self.out_setpoint)

            # Pause if desired
            if self.inter_delay is not None:
                time.sleep(self.inter_delay)

        print(f'Done ramping {self.out_param.label} to 0!')

    def pause_run(self):
        if self.pause is False:
            self.pause = True
        else:
            self.pause = False

    def create_figs(self):
        """
        Creates default figures for each of the parameters. Plots them in a new, separate window.
        Also creates a 2D heatmap of the data.
        """
        self.fig = plt.figure(
            figsize=(4 * (2 + len(self._params) + len(self._sr830s)), 4))
        self.grid = plt.GridSpec(4,
                                 1 + len(self._params) + len(self._sr830s),
                                 hspace=0)
        self.setax = self.fig.add_subplot(self.grid[:, 0])
        # First, create a plot of the sweeping parameters value against time
        self.setax.set_xlabel('Time (s)')
        self.setax.set_ylabel(f'{self.in_param.label} ({self.in_param.unit})')
        self.setaxline = self.setax.plot([], [])[0]

        self.axes = []
        # Now create a plot for every tracked parameter as a function of sweeping parameter
        for i, p in enumerate(self._params):
            self.axes.append(self.fig.add_subplot(self.grid[:, 1 + i]))
            self.axes[i].set_xlabel(
                f'{self.in_param.label} ({self.in_param.unit})')
            self.axes[i].set_ylabel(f'{p.label} ({p.unit})')

        # Create the heatmap
        # First, determine the resolution on each axis
        self.res_in = math.ceil(
            abs((self.in_stop - self.in_start) / self.in_step)) + 1
        self.res_out = math.ceil(
            abs((self.out_stop - self.out_start) / self.out_step)) + 1

        self.heatmap_data = np.zeros((self.res_out, self.res_in))
        self.heat_fig = plt.figure(2)
        self.heatmap = plt.imshow(self.heatmap_data)
        ax = plt.gca()
        self.heat_ax = ax

        plt.ylabel(f'{self.out_param.label} ({self.out_param.unit})')
        plt.xlabel(f'{self.in_param.label} ({self.in_param.unit})')
        inner_tick_lbls = np.linspace(self.in_start, self.in_stop, 5)
        outer_tick_lbls = np.linspace(self.out_stop, self.out_start, 5)

        ax.set_xticks(np.linspace(0, self.res_in - 1, 5))
        ax.set_yticks(np.linspace(0, self.res_out - 1, 5))
        ax.set_xticklabels(inner_tick_lbls)
        ax.set_yticklabels(outer_tick_lbls)

        divider = make_axes_locatable(ax)
        cax = divider.append_axes("right", size="5%", pad=0.05)

        cbar = plt.colorbar(self.heatmap, cax=cax)
        cbar.set_label(f'{self._params[0].label} ({self._params[0].unit})')

        self.figs_set = True

    def update_heatmap(self, count):
        # GRAB THE X AND Y DATA HERE
        forward_line = self.axes[0].get_lines()[0]
        backward_line = self.axes[0].get_lines()[1]

        x_data_forward = forward_line.get_xdata()
        y_data_forward = forward_line.get_ydata()

        x_data_backward = backward_line.get_xdata()
        y_data_backward = backward_line.get_ydata()

        # ADD THE DATA TO THE HEATMAP
        for i, x in enumerate(x_data_forward):
            self.heatmap_data[self.res_out - count - 1, i] = y_data_forward[i]
            if y_data_forward[i] > self.max_datapt:
                self.max_datapt = y_data_forward[i]
            if y_data_forward[i] < self.min_datapt:
                self.min_datapt = y_data_forward[i]

        self.heatmap.set_data(self.heatmap_data)
        self.heatmap.set_clim(self.min_datapt, self.max_datapt)
        self.heat_fig.canvas.draw()
        self.heat_fig.canvas.flush_events()

    def no_change(self, sweep):
        """
        This function is the default update_rule function. It simply runs the same sweep over again.
        """
        sweep.reset()

    def follow_param(self, p):
        """
        This function takes in a QCoDeS Parameter p, and tracks it through each sweep.
        """
        self._params.append(p)

    def follow_sr830(self, l, name, gain=1.0):
        """
        This function adds an SR830, but (as of now) does not do anything with it.
        """
        self._sr830s.append((l, name, gain))

    def _create_measurement(self, *set_params):
        """
        Creates a QCoDeS Measurement object. This controls the saving of data by registering
        QCoDeS Parameter objects, which this function does. Registers all 'sweeping' parameters
        (set_params), and all 'tracked' parameters, 'self._params'. Returns the measurement
        object.
        """
        self.meas = Measurement()
        for p in set_params:
            self.meas.register_parameter(p)
        self.meas.register_custom_parameter('time', label='Time', unit='s')
        for p in self._params:
            self.meas.register_parameter(p, setpoints=(
                *set_params,
                'time',
            ))
        for l, _, _ in self._sr830s:
            self.meas.register_parameter(l.X,
                                         setpoints=(
                                             *set_params,
                                             'time',
                                         ))
            self.meas.register_parameter(l.Y,
                                         setpoints=(
                                             *set_params,
                                             'time',
                                         ))

        return self.meas
예제 #26
0
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)
예제 #27
0
def test_perform_actual_upgrade_6_to_newest_add_new_data():
    """
    Insert new runs on top of existing runs upgraded and verify that they
    get the correct captured_run_id and captured_counter
    """
    from qcodes.dataset.measurements import Measurement
    from qcodes.instrument.parameter import Parameter
    import numpy as np

    fixpath = os.path.join(fixturepath, 'db_files', 'version6')

    db_file = 'some_runs.db'
    dbname_old = os.path.join(fixpath, db_file)

    if not os.path.exists(dbname_old):
        pytest.skip("No db-file fixtures found. You can generate test db-files"
                    " using the scripts in the "
                    "https://github.com/QCoDeS/qcodes_generate_test_db/ repo")

    with temporarily_copied_DB(dbname_old, debug=False, version=6) as conn:
        assert isinstance(conn, ConnectionPlus)
        perform_db_upgrade(conn)
        assert get_user_version(conn) >= 7
        no_of_runs_query = "SELECT max(run_id) FROM runs"
        no_of_runs = one(atomic_transaction(conn, no_of_runs_query),
                         'max(run_id)')

        # Now let's insert new runs and ensure that they also get
        # captured_run_id assigned.
        params = []
        for n in range(5):
            params.append(
                Parameter(f'p{n}',
                          label=f'Parameter {n}',
                          unit=f'unit {n}',
                          set_cmd=None,
                          get_cmd=None))

        # Set up an experiment
        exp = new_experiment('some-exp', 'some-sample', conn=conn)
        meas = Measurement(exp=exp)
        meas.register_parameter(params[0])
        meas.register_parameter(params[1])
        meas.register_parameter(params[2], basis=(params[0], ))
        meas.register_parameter(params[3], basis=(params[1], ))
        meas.register_parameter(params[4], setpoints=(params[2], params[3]))

        # Make a number of identical runs
        for _ in range(10):
            with meas.run() as datasaver:
                for x in np.random.rand(10):
                    for y in np.random.rand(10):
                        z = np.random.rand()
                        datasaver.add_result((params[0], 0), (params[1], 1),
                                             (params[2], x), (params[3], y),
                                             (params[4], z))

        no_of_runs_new = one(atomic_transaction(conn, no_of_runs_query),
                             'max(run_id)')
        assert no_of_runs_new == 20

        # check that run_id is equivalent to captured_run_id for new
        # runs
        for run_id in range(no_of_runs, no_of_runs_new + 1):
            ds1 = load_by_id(run_id, conn)
            ds2 = load_by_run_spec(captured_run_id=run_id, conn=conn)

            assert ds1.the_same_dataset_as(ds2)

            assert ds1.run_id == run_id
            assert ds1.run_id == ds1.captured_run_id
            assert ds2.run_id == run_id
            assert ds2.run_id == ds2.captured_run_id

        # we are creating a new experiment into a db with one exp so:
        exp_id = 2

        # check that counter is equivalent to captured_counter for new
        # runs
        for counter in range(1, no_of_runs_new - no_of_runs + 1):
            ds1 = load_by_counter(counter, exp_id, conn)
            # giving only the counter is not unique since we have 2 experiments
            with pytest.raises(NameError,
                               match="More than one"
                               " matching dataset"):
                load_by_run_spec(captured_counter=counter, conn=conn)
            # however we can supply counter and experiment
            ds2 = load_by_run_spec(captured_counter=counter,
                                   experiment_name='some-exp',
                                   conn=conn)

            assert ds1.the_same_dataset_as(ds2)
            assert ds1.counter == counter
            assert ds1.counter == ds1.captured_counter
            assert ds2.counter == counter
            assert ds2.counter == ds2.captured_counter
예제 #28
0
def test_datasaver_2d(experiment, DAC, DMM, caplog,
                      n_points_1, n_points_2):
    meas = Measurement()
    meas.register_parameter(DAC.ch1)
    meas.register_parameter(DAC.ch2)
    meas.register_parameter(DMM.v1, setpoints=(DAC.ch1,
                                               DAC.ch2))

    n_points_expected_1 = 5
    n_points_expected_2 = 10

    meas.set_shapes({DMM.v1.full_name: (n_points_expected_1,
                                        n_points_expected_2,)})

    with meas.run() as datasaver:

        for set_v_1 in np.linspace(0, 1, n_points_1):
            for set_v_2 in np.linspace(0, 1, n_points_2):
                datasaver.add_result((DAC.ch1, set_v_1),
                                     (DAC.ch2, set_v_2),
                                     (DMM.v1, DMM.v1()))

    ds = datasaver.dataset
    caplog.clear()
    data = ds.get_parameter_data()

    if n_points_1*n_points_2 == n_points_expected_1*n_points_expected_2:
        assert len(caplog.record_tuples) == 0
        for dataarray in data[DMM.v1.full_name].values():
            assert dataarray.shape == (n_points_expected_1, n_points_expected_2)
    elif n_points_1*n_points_2 > n_points_expected_1*n_points_expected_2:
        assert len(caplog.record_tuples) == 3
        exp_module = "qcodes.dataset.sqlite.queries"
        exp_level = logging.WARNING
        exp_msg = ("Tried to set data shape for {} in "
                   "dataset {} "
                   "from metadata when loading "
                   "but found inconsistent lengths {} and {}")
        assert caplog.record_tuples[0] == (
            exp_module,
            exp_level,
            exp_msg.format(
                DMM.v1.full_name,
                DMM.v1.full_name,
                n_points_1*n_points_2,
                n_points_expected_1*n_points_expected_2
            )
        )
        assert caplog.record_tuples[1] == (
            exp_module,
            exp_level,
            exp_msg.format(
                DAC.ch1.full_name,
                DMM.v1.full_name,
                n_points_1*n_points_2,
                n_points_expected_1*n_points_expected_2)
        )
        assert caplog.record_tuples[2] == (
            exp_module,
            exp_level,
            exp_msg.format(
                DAC.ch2.full_name,
                DMM.v1.full_name,
                n_points_1*n_points_2,
                n_points_expected_1*n_points_expected_2
            )
        )
예제 #29
0
def RT_LT(station, voltage, stanford_gain_V, stanford_gain_I):
    R_I = 1e4

    station.dmm1.NPLC(10)
    station.dmm2.NPLC(10)

    station.yoko.output('off')
    station.yoko.source_mode("VOLT")
    station.yoko.output('on')

    station.yoko.voltage.step = 1e-3
    station.yoko.voltage.inter_delay = 0.0001

    meas = Measurement()

    meas.register_parameter(station.yoko.voltage)
    meas.register_parameter(station.BlueFors_LD.MC_temp)
    meas.register_custom_parameter("Counter")
    meas.register_custom_parameter("Current", unit = "A")
    meas.register_parameter(station.dmm1.volt)
    meas.register_parameter(station.dmm2.volt)
    meas.register_custom_parameter("Resistance", unit = "Ohms", setpoints=(station.BlueFors_LD.MC_temp,))
    
    win = qcm.pyplot.PlotWindow(title="R(T)")
    win.resize(750,500)

    num_points = 0
    array_size = 1
    temp_array = np.full((1,), np.nan)
    r_array = np.full((1,), np.nan)


    plot1 = win.addPlot(title="RT  4K - 8mK")
    plotdata = plot1.plot(setpoint_x=temp_array)

    plot1.left_axis.label = "Resistance"
    plot1.left_axis.units = "Ohms"
    plot1.bot_axis.label = "Temperature"
    plot1.bot_axis.units = "K"

    j=0

    T =  station.BlueFors_LD.MC_temp()

    with meas.run() as datasaver:
        
        while T > 0.008:
            T =  station.BlueFors_LD.MC_temp()    

            station.yoko.voltage(voltage)
            
            time.sleep(1)

            volt_p = station.dmm1.volt()/stanford_gain_V
            curr_p = station.dmm2.volt()/(R_I*stanford_gain_I) #10kOhm resistor for current meas.
            
            time.sleep(1)
            
            station.yoko.voltage(-voltage)
            
            time.sleep(1)
            
            volt_m = station.dmm1.volt()/stanford_gain_V
            curr_m = station.dmm2.volt()/(1e4*stanford_gain_I)
            
            V_av = (volt_p - volt_m)/2
            I_av = (curr_p - curr_m)/2
            R_av = V_av/I_av

            datasaver.add_result((station.yoko.voltage, voltage),
                                ( station.BlueFors_LD.MC_temp, T),
                                ("Counter", j),
                                 ("Resistance", R_av),
                                (station.dmm1.volt,V_av),
                                ("Current", I_av))

            temp_array[num_points] = T
            r_array[num_points] = R_av
            plotdata.xData = temp_array
            plotdata.update(r_array)
            num_points += 1

            if num_points == array_size:
                array_size *= 2
                temp_array.resize(array_size)
                temp_array[array_size//2:] = np.nan
                r_array.resize(array_size)
                r_array[array_size//2:] = np.nan
            
            
            #print((T,R_av))
            time.sleep(1)
            j = j+1
            
    station.yoko.voltage(0)
예제 #30
0
def do2d(param_set1: _BaseParameter,
         start1: number,
         stop1: number,
         num_points1: int,
         delay1: number,
         param_set2: _BaseParameter,
         start2: number,
         stop2: number,
         num_points2: int,
         delay2: number,
         *param_meas: Union[_BaseParameter, Callable[[], None]],
         set_before_sweep: Optional[bool] = False,
         enter_actions: Sequence[Callable[[], None]] = (),
         exit_actions: Sequence[Callable[[], None]] = (),
         before_inner_actions: Sequence[Callable[[], None]] = (),
         after_inner_actions: Sequence[Callable[[], None]] = (),
         write_period: Optional[float] = None,
         flush_columns: bool = False,
         do_plot: bool = True,
         conDuct: Instrument = None) -> AxesTupleListWithRunId:
    """
    adapted for logging settings by felix 17.04.2020
		-added argument do2buf
		-added _export_settings functionality

	adapted for live plotting of conductance by felix 17.04.2020
		-added argument conDuct
		-conDuct is a virtual parameter who has to be called as an optional argument in do1D.
		 conDuct has a function calcG() which allows to calculate the division of two given 
		 parameters or one parameter and a float number. See init file for more info.

    Perform a 1D scan of ``param_set1`` from ``start1`` to ``stop1`` in
    ``num_points1`` and ``param_set2`` from ``start2`` to ``stop2`` in
    ``num_points2`` measuring param_meas at each step.

    Args:
        param_set1: The QCoDeS parameter to sweep over in the outer loop
        start1: Starting point of sweep in outer loop
        stop1: End point of sweep in the outer loop
        num_points1: Number of points to measure in the outer loop
        delay1: Delay after setting parameter in the outer loop
        param_set2: The QCoDeS parameter to sweep over in the inner loop
        start2: Starting point of sweep in inner loop
        stop2: End point of sweep in the inner loop
        num_points2: Number of points to measure in the inner loop
        delay2: Delay after setting paramter before measurement is performed
        *param_meas: Parameter(s) to measure at each step or functions that
          will be called at each step. The function should take no arguments.
          The parameters and functions are called in the order they are
          supplied.
        set_before_sweep: if True the outer parameter is set to its first value
            before the inner parameter is swept to its next value.
        enter_actions: A list of functions taking no arguments that will be
            called before the measurements start
        exit_actions: A list of functions taking no arguments that will be
            called after the measurements ends
        before_inner_actions: Actions executed before each run of the inner loop
        after_inner_actions: Actions executed after each run of the inner loop
        do_plot: should png and pdf versions of the images be saved after the
            run.

    Returns:
        The run_id of the DataSet created
    """

    meas = Measurement()
    if write_period:
        meas.write_period = write_period
    meas.register_parameter(param_set1)
    param_set1.post_delay = delay1
    meas.register_parameter(param_set2)
    param_set2.post_delay = delay2
    interrupted = False
    for action in enter_actions:
        # this omits the possibility of passing
        # argument to enter and exit actions.
        # Do we want that?
        meas.add_before_run(action, ())

    for action in exit_actions:
        meas.add_after_run(action, ())

    for parameter in param_meas:
        if isinstance(parameter, _BaseParameter):
            meas.register_parameter(parameter,
                                    setpoints=(param_set1, param_set2))
        if conDuct != None:
            meas.register_parameter(conDuct.G,
                                    setpoints=(param_set1, param_set2))

    try:
        with meas.run() as datasaver:
            start_time = time.perf_counter()
            os.makedirs(datapath + '{}'.format(datasaver.run_id))
            for set_point1 in np.linspace(start1, stop1, num_points1):
                if set_before_sweep:
                    param_set2.set(start2)

                param_set1.set(set_point1)
                for action in before_inner_actions:
                    action()
                for set_point2 in np.linspace(start2, stop2, num_points2):
                    # skip first inner set point if `set_before_sweep`
                    if set_point2 == start2 and set_before_sweep:
                        pass
                    else:
                        param_set2.set(set_point2)
                    output = []
                    for parameter in param_meas:
                        if isinstance(parameter, _BaseParameter):
                            output.append((parameter, parameter.get()))
                        elif callable(parameter):
                            parameter()

                        if conDuct != None:
                            output.append((conDuct.G, conDuct.calcG(output)))

                    datasaver.add_result((param_set1, set_point1),
                                         (param_set2, set_point2), *output)
                for action in after_inner_actions:
                    action()
                if flush_columns:
                    datasaver.flush_data_to_database()

        stop_time = time.perf_counter()
    except KeyboardInterrupt:
        interrupted = True

    dataid = datasaver.run_id

    if interrupted:
        inst = list(meas.parameters.values())
        exportpath = datapath + '{}'.format(
            datasaver.run_id) + '/{}_set_{}_set.dat'.format(
                inst[0].name, inst[1].name)
        exportsnapshot = datapath + '{}'.format(
            datasaver.run_id) + '/snapshot.txt'
        #export_by_id(dataid,exportpath)
        export_by_id_pd(dataid, exportpath)
        export_snapshot_by_id(dataid, exportsnapshot)
        #added by felix 05.03.2020
        _export_settings(datasaver.run_id, inst)

        stop_time = time.perf_counter()
        print("Acquisition took:  %s seconds " % (stop_time - start_time))
        raise KeyboardInterrupt

    inst = list(meas.parameters.values())
    exportpath = datapath + '{}'.format(
        datasaver.run_id) + '/{}_set_{}_set.dat'.format(
            inst[0].name, inst[1].name)
    exportsnapshot = datapath + '{}'.format(datasaver.run_id) + '/snapshot.txt'
    #export_by_id(dataid,exportpath)
    export_by_id_pd(dataid, exportpath)
    export_snapshot_by_id(dataid, exportsnapshot)
    # _export_settings(datasaver.run_id,inst)

    if do_plot is True:
        ax, cbs = _save_image(datasaver, inst)
    else:
        ax = None,
        cbs = None

    print("Acquisition took:  %s seconds " % (stop_time - start_time))

    return dataid, ax, cbs