Ejemplo n.º 1
0
    def test_tasks_waits(self):
        delay0 = 0.01
        delay1 = 0.03
        loop = Loop(self.p1[1:3:1], delay0).each(Task(self.p2.set, -1),
                                                 Wait(delay1), self.p2,
                                                 Task(self.p2.set, 1), self.p2)
        delay_array = []
        loop._monitor = FakeMonitor(delay_array)

        # give it a "process" as if it was run in the bg before,
        # check that this gets cleared
        loop.process = 'TDD'

        data = loop.run_temp()

        self.assertFalse(hasattr(loop, 'process'))

        self.assertEqual(data.p1_set.tolist(), [1, 2])
        self.assertEqual(data.p2_2.tolist(), [-1, -1])
        self.assertEqual(data.p2_4.tolist(), [1, 1])

        self.assertEqual(len(delay_array), 4)
        for i, delay in enumerate(delay_array):
            target = delay1 if i % 2 else delay0
            self.assertLessEqual(delay, target)
            self.assertGreater(delay, target - 0.001)
Ejemplo n.º 2
0
    def testLoopCombinedParameterPrintTask(self, npoints, x_start_stop,
                                           y_start_stop, z_start_stop):

        x_set = np.linspace(x_start_stop[0], x_start_stop[1], npoints)
        y_set = np.linspace(y_start_stop[0], y_start_stop[1], npoints)
        z_set = np.linspace(z_start_stop[0], z_start_stop[1], npoints)
        setpoints = np.hstack(
            (x_set.reshape(npoints,
                           1), y_set.reshape(npoints,
                                             1), z_set.reshape(npoints, 1)))

        parameters = [
            Parameter(name, get_cmd=None, set_cmd=None)
            for name in ["X", "Y", "Z"]
        ]

        sweep_values = combine(*parameters, name="combined").sweep(setpoints)

        def ataskfunc():
            a = 1 + 1

        def btaskfunc():
            b = 1 + 2

        atask = Task(ataskfunc)
        btask = Task(btaskfunc)

        loop = Loop(sweep_values).each(atask, btask)
        data = loop.run(quiet=True)
        np.testing.assert_array_equal(data.arrays['X'].ndarray, x_set)
        np.testing.assert_array_equal(data.arrays['Y'].ndarray, y_set)
        np.testing.assert_array_equal(data.arrays['Z'].ndarray, z_set)
Ejemplo n.º 3
0
    def testLoopCombinedParameterPrintTask(self, npoints, x_start_stop,
                                           y_start_stop, z_start_stop):

        x_set = np.linspace(x_start_stop[0], x_start_stop[1], npoints)
        y_set = np.linspace(y_start_stop[0], y_start_stop[1], npoints)
        z_set = np.linspace(z_start_stop[0], z_start_stop[1], npoints)
        setpoints = np.hstack((x_set.reshape(npoints, 1),
                               y_set.reshape(npoints, 1),
                               z_set.reshape(npoints, 1)))

        parameters = [Parameter(name, get_cmd=None, set_cmd=None)
                      for name in ["X", "Y", "Z"]]

        sweep_values = combine(*parameters,
                               name="combined").sweep(setpoints)

        def ataskfunc():
            a = 1+1

        def btaskfunc():
            b = 1+2

        atask = Task(ataskfunc)
        btask = Task(btaskfunc)

        loc_fmt = 'data/{date}/#{counter}_{name}_{date}_{time}'
        rcd = {'name': 'printTask'}
        loc_provider = FormatLocation(fmt=loc_fmt, record=rcd)
        loop = Loop(sweep_values).each(atask, btask)
        data = loop.run(location=loc_provider, quiet=True)
        np.testing.assert_array_equal(data.arrays['X'].ndarray, x_set)
        np.testing.assert_array_equal(data.arrays['Y'].ndarray, y_set)
        np.testing.assert_array_equal(data.arrays['Z'].ndarray, z_set)
Ejemplo n.º 4
0
    def test_basic(self):
        p1 = AbortingGetter('p1', count=2, vals=Numbers(-10, 10), set_cmd=None)
        sv = p1[1:3:1]
        loop = Loop(sv)

        # not sure why you'd do it, but you *can* snapshot a Loop
        expected = {
            '__class__': 'qcodes.loops.Loop',
            'sweep_values': sv.snapshot(),
            'delay': 0,
            'then_actions': []
        }
        self.assertEqual(loop.snapshot(), expected)
        loop = loop.then(Task(p1.set, 0), Wait(0.123))
        expected['then_actions'] = [{
            'type': 'Task',
            'func': repr(p1.set)
        }, {
            'type': 'Wait',
            'delay': 0.123
        }]

        # then test snapshot on an ActiveLoop
        breaker = BreakIf(lambda: p1.get_latest() > 3)
        self.assertEqual(breaker.snapshot()['type'], 'BreakIf')
        loop = loop.each(p1, breaker)
        expected['__class__'] = 'qcodes.loops.ActiveLoop'
        expected['actions'] = [p1.snapshot(), breaker.snapshot()]

        self.assertEqual(loop.snapshot(), expected)
Ejemplo n.º 5
0
    def test_then_construction(self):
        loop = Loop(self.p1[1:6:1])
        task1 = Task(self.p1.set, 2)
        task2 = Wait(0.02)
        loop2 = loop.then(task1)
        loop3 = loop2.then(task2, task1)
        loop4 = loop3.then(task2, overwrite=True)
        loop5 = loop4.each(self.p1, BreakIf(lambda: self.p1.get() >= 3))
        loop6 = loop5.then(task1)
        loop7 = loop6.then(task1, overwrite=True)

        # original loop is untouched, same as .each and .loop
        self.assertEqual(loop.then_actions, ())

        # but loop2 has the task we asked for
        self.assertEqual(loop2.then_actions, (task1, ))

        # loop3 gets the other tasks appended
        self.assertEqual(loop3.then_actions, (task1, task2, task1))

        # loop4 gets only the new one
        self.assertEqual(loop4.then_actions, (task2, ))

        # tasks survive .each
        self.assertEqual(loop5.then_actions, (task2, ))

        # and ActiveLoop.then works the same way as Loop.then
        self.assertEqual(loop6.then_actions, (task2, task1))
        self.assertEqual(loop7.then_actions, (task1, ))

        # .then rejects Loops and others that are valid loop actions
        for action in (loop2, loop7, BreakIf(lambda: self.p1() >= 3), self.p1,
                       True, 42):
            with self.assertRaises(TypeError):
                loop.then(action)
Ejemplo n.º 6
0
    def test_basic(self):
        p1 = AbortingGetter('p1', count=2, vals=Numbers(-10, 10))
        sv = p1[1:3:1]
        loop = Loop(sv)

        # not sure why you'd do it, but you *can* snapshot a Loop
        expected = {
            '__class__': 'qcodes.loops.Loop',
            'sweep_values': sv.snapshot(),
            'delay': 0,
            'then_actions': []
        }
        self.assertEqual(loop.snapshot(), expected)
        loop = loop.then(Task(p1.set, 0), Wait(0.123))
        expected['then_actions'] = [{
            'type': 'Task',
            'func': repr(p1.set)
        }, {
            'type': 'Wait',
            'delay': 0.123
        }]

        # then test snapshot on an ActiveLoop
        breaker = BreakIf(p1.get_latest > 3)
        self.assertEqual(breaker.snapshot()['type'], 'BreakIf')
        # TODO: once we have reprs for DeferredOperations, test that
        # the right thing shows up in breaker.snapshot()['condition']
        loop = loop.each(p1, breaker)
        expected['__class__'] = 'qcodes.loops.ActiveLoop'
        expected['actions'] = [p1.snapshot(), breaker.snapshot()]

        self.assertEqual(loop.snapshot(), expected)
Ejemplo n.º 7
0
    def save_changes(self):
        name = self.name

        if name in self.loops:
            # Create a task that checks if loop stop has been request on each measure point of the loop
            task = Task(self.parent.check_stop_request)
            # grab data for creating a loop from elements of the widget
            try:
                lower = float(self.textbox_lower_limit.text())
                upper = float(self.textbox_upper_limit.text())
                num = float(self.textbox_num.text())
                delay = float(self.textbox_step.text())
                sweep_division = float(self.sweep_parameter_divider.text())
            except Exception as e:
                warning_string = "Errm, looks like something went wrong ! \nHINT: Measurement parameters not set. \n" \
                                 + str(e)
                show_error_message("Warning", warning_string)
            else:
                # Create dividres and add them to a dict of dividers (shared with main window)
                sweep_parameter = self.sweep_parameter_cb.currentData()
                if sweep_division != 1:
                    full_name = str(sweep_parameter)
                    sweep_parameter = VoltageDivider(sweep_parameter,
                                                     sweep_division)
                    self.dividers[full_name] = sweep_parameter
                # create a list and fill it with actions created by user (dividers if they are attached)
                actions = []
                for i in range(len(self.current_loop_actions_dictionary)):
                    action_array = self.current_loop_actions_dictionary[
                        "action" + str(i)]
                    if action_array is not None:
                        action_parameter = action_array[1].currentData()
                        try:
                            division = float(action_array[2].text())
                        except Exception as e:
                            show_error_message("Warning", str(e))
                        else:
                            if division != 1:
                                action_parameter = VoltageDivider(
                                    action_parameter, division)
                            actions.append(action_parameter)
                # append a task that checks for loop stop request
                actions.append(task)

                self.loops[name].sweep_values = sweep_parameter.sweep(lower,
                                                                      upper,
                                                                      num=num)
                self.loops[name].delay = delay
                self.loops[name].actions = list(actions)

            self.parent.update_loops_preview(edit=name)
        else:
            show_error_message(
                "Warning",
                "The loop does not exist. \nNew loop will be created")
            self.name = ""
            self.create_loop()
            self.close()
Ejemplo n.º 8
0
    def test_tasks_callable_arguments(self):
        data = Loop(self.p1[1:3:1], 0.01).each(Task(self.p2.set, self.p1),
                                               Task(self.p3.set, self.p1.get),
                                               self.p2, self.p3).run_temp()

        self.assertEqual(data.p2.tolist(), [1, 2])
        self.assertEqual(data.p3.tolist(), [1, 2])

        def test_func(*args, **kwargs):
            self.assertEqual(args, (1, 2))
            self.assertEqual(kwargs, {'a_kwarg': 4})

        data = Loop(self.p1[1:2:1], 0.01).each(
            Task(self.p2.set, self.p1 * 2),
            Task(test_func, self.p1, self.p1 * 2, a_kwarg=self.p1 * 4),
            self.p2, self.p3).run_temp()

        self.assertEqual(data.p2.tolist(), [2])
def qc_run(name, seq, *params):
    loop = None
    for sp in seq.params:
        if loop is None:
            loop = Loop(sp[sp.values])
        else:
            loop = loop.loop((sp[sp.values]))

    play_task = Task(upload_play, seq)

    if loop is not None:
        m = loop.each(play_task, *params)
    else:
        m = Measure(play_task, *params)

    ds = m.run(loc_record={'name':name})
    return ds
Ejemplo n.º 10
0
    def run_with_livedata(self):
        """
        ################################################################################################################
        LEGACY METHOD. Was used when i had no idea that each parameter hold the data of its last value so i dont need to
        get it everytime from the physical instrument, i can just get it from tha parameter object.
        ################################################################################################################

        This function appends a task to a loop. Task updates value of instruments parameter every iteration of the loop.
        After appending the task the loop gets started with plot option turned on.

        :return: NoneType
        """
        loop_name = self.select_loop_cb.currentText()
        loop = self.loops[loop_name]
        tsk = Task(self.update_opened_instruments)
        loop.actions.append(tsk)
        loop_index = self.actions.index(loop)
        self.actions[loop_index], self.actions[-1] = self.actions[
            -1], self.actions[loop_index]
        self.run_with_plot()
Ejemplo n.º 11
0
    def test_then_action(self):
        self.maxDiff = None
        nan = float('nan')
        self.p1.set(5)
        f_calls, g_calls = [], []

        def f():
            f_calls.append(1)

        def g():
            g_calls.append(1)

        breaker = BreakIf(lambda: self.p1() >= 3)
        ts1 = datetime.now().strftime('%Y-%m-%d %H:%M:%S')
        # evaluate param snapshots now since later value will change
        p1snap = self.p1.snapshot()
        self.p2.set(2)
        p2snap = self.p2.snapshot()
        self.p3.set(3)
        p3snap = self.p3.snapshot()
        data = Loop(self.p1[1:6:1]).each(self.p1,
                                         breaker).then(Task(self.p1.set, 2),
                                                       Wait(0.01),
                                                       Task(f)).run_temp()
        ts2 = datetime.now().strftime('%Y-%m-%d %H:%M:%S')

        self.assertEqual(repr(data.p1.tolist()), repr([1., 2., 3., nan, nan]))
        self.assertEqual(self.p1.get(), 2)
        self.assertEqual(len(f_calls), 1)

        # this loop makes use of all the features, so use it to test
        # DataSet metadata
        loopmeta = data.metadata['loop']
        default_meas_meta = data.metadata['station']['default_measurement']
        # assuming the whole loop takes < 1 sec, all timestamps
        # should each be the same as one of the bounding times
        self.check_snap_ts(loopmeta, 'ts_start', (ts1, ts2))
        self.check_snap_ts(loopmeta, 'ts_end', (ts1, ts2))
        self.check_snap_ts(loopmeta['sweep_values']['parameter'], 'ts',
                           (ts1, ts2))
        self.check_snap_ts(loopmeta['actions'][0], 'ts', (ts1, ts2))
        self.check_snap_ts(default_meas_meta[0], 'ts', (ts1, ts2, None))
        self.check_snap_ts(default_meas_meta[1], 'ts', (ts1, ts2, None))
        del p1snap['ts'], p2snap['ts'], p3snap['ts']

        self.assertEqual(
            data.metadata, {
                'station': {
                    'instruments': {},
                    'parameters': {},
                    'components': {},
                    'default_measurement': [p2snap, p3snap]
                },
                'loop': {
                    'use_threads':
                    False,
                    '__class__':
                    'qcodes.loops.ActiveLoop',
                    'sweep_values': {
                        'parameter':
                        p1snap,
                        'values': [{
                            'first': 1,
                            'last': 5,
                            'num': 5,
                            'type': 'linear'
                        }]
                    },
                    'delay':
                    0,
                    'actions': [p1snap, breaker.snapshot()],
                    'then_actions': [{
                        'type': 'Task',
                        'func': repr(self.p1.set)
                    }, {
                        'type': 'Wait',
                        'delay': 0.01
                    }, {
                        'type': 'Task',
                        'func': repr(f)
                    }]
                }
            })

        # now test a nested loop with .then inside and outside
        f_calls[:] = []

        Loop(self.p1[1:3:1]).each(
            Loop(self.p2[1:3:1]).each(self.p2).then(Task(g))).then(
                Task(f)).run_temp()

        self.assertEqual(len(f_calls), 1)
        self.assertEqual(len(g_calls), 2)

        # Loop.loop nesting always just makes the .then actions run after
        # the outer loop
        f_calls[:] = []
        Loop(self.p1[1:3:1]).then(Task(f)).loop(self.p2[1:3:1]).each(
            self.p1).run_temp()
        self.assertEqual(len(f_calls), 1)

        f_calls[:] = []
        Loop(self.p1[1:3:1]).loop(self.p2[1:3:1]).then(Task(f)).each(
            self.p1).run_temp()
        self.assertEqual(len(f_calls), 1)

        f_calls[:] = []
        Loop(self.p1[1:3:1]).loop(self.p2[1:3:1]).each(self.p1).then(
            Task(f)).run_temp()
        self.assertEqual(len(f_calls), 1)
Ejemplo n.º 12
0
    b =3
    aa += a*b
    return aa

def QFunction():
    a = F.get_latest() - 15
    return a
def Print():
    global b
    print('b',b)
    print('123')
    print('345')
    b+=1
    return True

TP = Task(func = Print)

P = StandardParameter(name = 'Para1', set_cmd = Pfunction)

F = StandardParameter(name = 'Fixed1', get_cmd = Ffunction)

Q = StandardParameter(name = 'Para2', set_cmd = Pfunction, get_cmd = QFunction)

E = StandardParameter(name = 'Fixed2', get_cmd = QFunction)

Sweep_Value = P[1:5.5:0.5]

Sweep_2 = Q[2:10:1]
LP1 = Loop(sweep_values = Sweep_2).each(F)

#LP = Loop(sweep_values = Sweep_Value).each(LP1, TP,  E)
Ejemplo n.º 13
0
def do2d(inst_set, start, stop, num_points, delay,
         inst_set2, start2, stop2, num_points2, delay2,
         *inst_meas, do_plots=True, use_threads=False,
         set_before_sweep: Optional[bool]=False,
         innerloop_repetitions: Optional[int]=1,
         innerloop_pre_tasks: Optional[Sequence]=None,
         innerloop_post_tasks: Optional[Sequence]=None,
         auto_color_scale: Optional[bool]=None,
         cutoff_percentile: Optional[Union[Tuple[Number, Number], Number]]=None):
    """

    Args:
        inst_set:  Instrument to sweep over
        start:  Start of sweep
        stop:  End of sweep
        num_points:  Number of steps to perform
        delay:  Delay at every step
        inst_set2:  Second instrument to sweep over
        start2:  Start of sweep for second instrument
        stop2:  End of sweep for second instrument
        num_points2:  Number of steps to perform
        delay2:  Delay at every step for second instrument
        *inst_meas:
        do_plots: Default True: If False no plots are produced.
            Data is still saved and can be displayed with show_num.
        use_threads: If True and if multiple things are being measured,
            multiple threads will be used to parallelise the waiting.
        set_before_sweep: if True the outer parameter is set to its first value
            before the inner parameter is swept to its next value.
        innerloop_pre_tasks: Tasks to execute before each iteration of the
            outer loop
        innerloop_post_tasks: Tasks to execute after each iteration of the
            outer loop
        auto_color_scale: if True, the colorscale of heatmap plots will be
            automatically adjusted to disregard outliers.
        cutoff_percentile: percentile of data that may maximally be clipped
            on both sides of the distribution.
            If given a tuple (a,b) the percentile limits will be a and 100-b.
            See also the plotting tuorial notebook.

    Returns:
        plot, data : returns the plot and the dataset

    """

    for inst in inst_meas:
        if getattr(inst, "setpoints", False):
            setpoints = inst.setpoints
            if isinstance(setpoints, Iterable):
                if all(len(v) == 0 for v in setpoints):
                    continue
            raise ValueError("3d plotting is not supported")

    actions = []
    for i_rep in range(innerloop_repetitions):
        innerloop = qc.Loop(inst_set2.sweep(start2,
                                            stop2,
                                            num=num_points2),
                            delay2).each(*inst_meas)
        if set_before_sweep:
            ateach = [innerloop, Task(inst_set2, start2)]
        else:
            ateach = [innerloop]

        if innerloop_pre_tasks is not None:
            ateach = list(innerloop_pre_tasks) + ateach
        if innerloop_post_tasks is not None:
            ateach = ateach + list(innerloop_post_tasks)

        actions += ateach

    outerloop = qc.Loop(inst_set.sweep(start,
                                       stop,
                                       num=num_points),
                        delay).each(*actions)

    set_params = ((inst_set, start, stop),
                  (inst_set2, start2, stop2))
    meas_params = _select_plottables(inst_meas)

    plot, data = _do_measurement(outerloop, set_params, meas_params,
                                 do_plots=do_plots, use_threads=use_threads,
                                 auto_color_scale=auto_color_scale,
                                 cutoff_percentile=cutoff_percentile)

    return plot, data
Ejemplo n.º 14
0
    def run_qcodes(self, with_plot=False):
        """
        Runs qcodes with specified instruments and parameters. Checks for errors in data prior to runing qcodes
        Adds all instruments to qc.Station and runs the last created loop (i think this is not good, but hey theres a
        button for each loop to run that specific loop)

        Loop is ran in a separate thread so that it does not block GUI thread (and the program)

        :param with_plot: if set to true, runs (and saves) live plot while measurement is running
        :return: NoneType
        """
        self.stop_loop_requested = False
        self.loop_started.emit()
        self.line_trace_count = 0

        # first create a station and add all instruments to it, to have the data available in the output files
        station = qc.Station()
        for name, instrument in self.instruments.items():
            station.add_component(instrument, name)

        # grab the last action added to the actions list. Set its data_set to None in case that loop has already been
        # ran. Create a new data set with the name and location provided by user input
        if len(self.actions):
            loop = self.actions[-1]
            loop.data_set = None

            # adjust save location of the file
            if self.save_location != "":
                loc_provider = qc.data.location.FormatLocation(
                    fmt=self.save_location +
                    '/{date}/#{counter}_{name}_{time}')
                qc.data.data_set.DataSet.location_provider = loc_provider
            data = loop.get_data_set(name=self.output_file_name.text())

            # Check if the function was called with plot in background, if it was, create a new plot, delete backgroud
            # action of the loop (if a loop has been ran before with a background action [loop cannot have more then
            # 1 background action]), attach a new background action and run a loop by calling a worker to run it in a
            # separate thread
            if with_plot:
                # if you are running loop in a loop then create one more graph that will display 10 most recent line
                # traces
                if isinstance(loop.actions[0], ActiveLoop):
                    line_traces_plot = qc.QtPlot(fig_x_position=0.05,
                                                 fig_y_position=0.4,
                                                 window_title="Line traces")
                    self.live_plots.append(line_traces_plot)
                    if len(loop.actions) < 3:
                        loop.actions.append(
                            Task(lambda: self.update_line_traces(
                                line_traces_plot, data, parameter_name)))
                    else:
                        loop.actions[-1] = Task(
                            lambda: self.update_line_traces(
                                line_traces_plot, data, parameter_name))
                    loop.actions[0].progress_interval = None
                else:
                    if loop.progress_interval is None:
                        loop.progress_interval = 20
                parameter = get_plot_parameter(loop)
                plot = qc.QtPlot(fig_x_position=0.05,
                                 fig_y_position=0.4,
                                 window_title=self.output_file_name.text())
                self.live_plots.append(plot)
                parameter_name = str(parameter)
                plot.add(getattr(data, parameter_name))
                # loop.with_bg_task(plot.update, plot.save).run(use_threads=True)
                loop.bg_task = None
                worker = Worker(
                    loop.with_bg_task(plot.update, plot.save).run, False)
            else:
                # loop.run(use_threads=True) -> this has something to do with multiple gets at the same time
                #                               i guess it would get them all at the same time instead of one by one

                # otherwise if plot was not requested, just run a loop (also in separate thread)
                worker = Worker(loop.run, False)
            self.workers.append(worker)

            # connect the signals of a worker
            worker.signals.result.connect(print_output)
            worker.signals.finished.connect(self.cleanup)
            worker.signals.progress.connect(progress_func)

            # start the worker
            del self.workers[:]
            # starting live mode of all opened instruments
            # commented cause it causes collision in the instrument when two different sources send commands to the
            # instrument. Sometimes this causes crashing of the loop.
            """for widget in self.active_isntruments:
                # only if that instrument has this parameter, then start its live mode
                if self.actions[-1].sweep_values.name in widget.textboxes.keys():
                    widget.toggle_live()"""
            self.disable_run_buttons()
            self.thread_pool.start(worker)

        # Just in case someone presses run with no loops created
        else:
            show_error_message("Oops !",
                               "Looks like there is no loop to be ran !")
Ejemplo n.º 15
0
    def create_loop(self):
        """
        Creates a new loop from data input by user. Adds newly created loop to "loops" dictionary in MainWindow.
        Creates action to be executed upon running qcodes and adds it to "actions" list in MainWindow

        :return: NoneType
        """
        if self.name != "":
            self.save_changes()
        else:
            # otherwise create a new loop and save it to the loops dictionary
            # Try to fetch user input data and cast it to floats
            # If it fails, throw an exception
            # Otherwise, create a loop, add it to the shared dict

            # Create a task that checks if loop stop has been request on each measure point of the loop
            task = Task(self.parent.check_stop_request)
            # grab data for creating a loop from elements of the widget
            try:
                lower = float(self.textbox_lower_limit.text())
                upper = float(self.textbox_upper_limit.text())
                num = float(self.textbox_num.text())
                delay = float(self.textbox_step.text())
                sweep_division = float(self.sweep_parameter_divider.text())
            except Exception as e:
                warning_string = "Errm, looks like something went wrong ! \nHINT: Measurement parameters not set. \n"\
                                 + str(e)
                show_error_message("Warning", warning_string)
            else:
                # Create dividres and add them to a dict of dividers (shared with main window)
                sweep_parameter = self.sweep_parameter_cb.currentData()
                if sweep_division != 1:
                    full_name = str(sweep_parameter)
                    sweep_parameter = VoltageDivider(sweep_parameter,
                                                     sweep_division)
                    self.dividers[full_name] = sweep_parameter

                # create a list and fill it with actions created by user (dividers if they are attached)
                actions = []
                for i in range(len(self.current_loop_actions_dictionary)):
                    action_array = self.current_loop_actions_dictionary[
                        "action" + str(i)]
                    if action_array is not None:
                        action_parameter = action_array[1].currentData()
                        try:
                            division = float(action_array[2].text())
                        except Exception as e:
                            show_error_message("Warning", str(e))
                        else:
                            if division != 1:
                                action_parameter = VoltageDivider(
                                    action_parameter, division)
                            actions.append(action_parameter)
                # append a task that checks for loop stop request
                actions.append(task)

                # pass dereferenced list of actions to a loops each method
                if len(self.instruments):
                    lp = qc.Loop(sweep_parameter.sweep(lower, upper, num=num),
                                 delay,
                                 progress_interval=20).each(*actions)
                else:
                    show_error_message(
                        "Warning", "U can't make a loop without instruments !")
                    return
                name = "loop" + str(len(self.parent.shown_loops) + 1)
                self.loops[name] = lp
                self.actions.append(lp)
                self.parent.update_loops_preview()
                """# if a loop name has been passed to this widget then overwrite that loop in the loops dictionary
Ejemplo n.º 16
0
def do2d(inst_set, start, stop, num_points, delay,
         inst_set2, start2, stop2, num_points2, delay2,
         *inst_meas, do_plots=True, use_threads=False,
         set_before_sweep: Optional[bool]=False,
         innerloop_repetitions: Optional[int]=1,
         innerloop_pre_tasks: Optional[Sequence]=None,
         innerloop_post_tasks: Optional[Sequence]=None):
    """

    Args:
        inst_set:  Instrument to sweep over
        start:  Start of sweep
        stop:  End of sweep
        num_points:  Number of steps to perform
        delay:  Delay at every step
        inst_set2:  Second instrument to sweep over
        start2:  Start of sweep for second instrument
        stop2:  End of sweep for second instrument
        num_points2:  Number of steps to perform
        delay2:  Delay at every step for second instrument
        *inst_meas:
        do_plots: Default True: If False no plots are produced.
            Data is still saved and can be displayed with show_num.
        use_threads: If True and if multiple things are being measured,
            multiple threads will be used to parallelise the waiting.
        set_before_sweep: if True the outer parameter is set to its first value
            before the inner parameter is swept to its next value.
        innerloop_pre_tasks: Tasks to execute before each iteration of the
            outer loop
        innerloop_post_tasks: Tasks to execute after each iteration of the
            outer loop

    Returns:
        plot, data : returns the plot and the dataset

    """

    for inst in inst_meas:
        if getattr(inst, "setpoints", False):
            setpoints = inst.setpoints
            if isinstance(setpoints, Iterable):
                if all(len(v) == 0 for v in setpoints):
                    continue
            raise ValueError("3d plotting is not supported")

    actions = []
    for i_rep in range(innerloop_repetitions):
        innerloop = qc.Loop(inst_set2.sweep(start2,
                                            stop2,
                                            num=num_points2),
                            delay2).each(*inst_meas)
        if set_before_sweep:
            ateach = [innerloop, Task(inst_set2, start2)]
        else:
            ateach = [innerloop]

        if innerloop_pre_tasks is not None:
            ateach = list(innerloop_pre_tasks) + ateach
        if innerloop_post_tasks is not None:
            ateach = ateach + list(innerloop_post_tasks)

        actions += ateach

    outerloop = qc.Loop(inst_set.sweep(start,
                                       stop,
                                       num=num_points),
                        delay).each(*actions)

    set_params = ((inst_set, start, stop),
                  (inst_set2, start2, stop2))
    meas_params = _select_plottables(inst_meas)

    plot, data = _do_measurement(outerloop, set_params, meas_params,
                                 do_plots=do_plots, use_threads=use_threads)

    return plot, data
Ejemplo n.º 17
0
    def create_loop(self):

        task = Task(self.parent.check_stop_request)

        self.submitted.emit()
Ejemplo n.º 18
0
    def testLoopCombinedParameterInside(self, npoints, npoints_outer,
                                        x_start_stop, y_start_stop,
                                        z_start_stop):
        x_set = np.linspace(x_start_stop[0], x_start_stop[1], npoints_outer)
        y_set = np.linspace(y_start_stop[0], y_start_stop[1], npoints)
        z_set = np.linspace(z_start_stop[0], z_start_stop[1], npoints)

        setpoints = np.hstack((y_set.reshape(npoints,
                                             1), z_set.reshape(npoints, 1)))

        parameters = [
            Parameter(name, get_cmd=None, set_cmd=None)
            for name in ["X", "Y", "Z"]
        ]
        sweep_values = combine(parameters[1], parameters[2],
                               name="combined").sweep(setpoints)

        def ataskfunc():
            a = 1 + 1

        def btaskfunc():
            b = 1 + 2

        atask = Task(ataskfunc)
        btask = Task(btaskfunc)

        def wrapper():
            counter = 0

            def inner():
                nonlocal counter
                counter += 1
                return counter

            return inner

        self.dmm.voltage.get = wrapper()
        loop = Loop(
            parameters[0].sweep(x_start_stop[0],
                                x_start_stop[1],
                                num=npoints_outer)).loop(sweep_values).each(
                                    self.dmm.voltage, atask,
                                    self.dmm.somethingelse, self.dmm.voltage,
                                    btask)
        data = loop.run(quiet=True)
        np.testing.assert_array_equal(data.arrays['X_set'].ndarray, x_set)
        np.testing.assert_array_equal(
            data.arrays['Y'].ndarray,
            np.repeat(y_set.reshape(1, npoints), npoints_outer, axis=0))
        np.testing.assert_array_equal(
            data.arrays['Z'].ndarray,
            np.repeat(z_set.reshape(1, npoints), npoints_outer, axis=0))

        np.testing.assert_array_equal(
            data.arrays['dmm_voltage_0'].ndarray,
            np.arange(1, npoints * npoints_outer * 2,
                      2).reshape(npoints_outer, npoints))
        np.testing.assert_array_equal(
            data.arrays['dmm_voltage_3'].ndarray,
            np.arange(2, npoints * npoints_outer * 2 + 1,
                      2).reshape(npoints_outer, npoints))
        np.testing.assert_array_equal(data.arrays['dmm_somethingelse'].ndarray,
                                      np.ones((npoints_outer, npoints)))