def _setup(self):
        AbstractDevice._setup(self)

        # Resources.
        #read_only = ['reading']
        #for name in read_only:
        #	self.resources[name] = Resource(self, name)

        read_write = [
            'reference_freq', 'reference_amplitude', 'reference_phase'
        ]
        for name in read_write:
            self.resources[name] = Resource(self, name, name)

        read_only = [
            'amplitude_x', 'amplitude_y', 'amplitude_R', 'angle_theta'
        ]
        for name in read_only:
            self.resources[name] = Resource(self, name, name, name, name)

        self.resources['reference_amplitude'].units = 'V'
        self.resources['reference_freq'].units = 'Hz'
        self.resources['amplitude_x'].units = 'V'
        self.resources['amplitude_y'].units = 'V'
        self.resources['amplitude_R'].units = 'V'
示例#2
0
    def _setup(self):
        AbstractSubdevice._setup(self)
        
        # Resources.
        
        read_only = ['magnet_current','power_supply_current']
        for name in read_only:
            self.resources[name] = Resource(self, name)
            
        read_write = ['persistent_switch_heater', 'high_limit','low_limit','sweep',
                        'rate_0','rate_1','rate_2','rate_3','rate_4', 'virt_sync_currents', 'virt_imag', 'virt_iout',
                        'virt_imag_sweep_to','virt_iout_sweep_to','virt_energysave_mode', 'virt_heater_wait_mode'
                        ,'virt_sweep_sleep', 'units']
        for name in read_write:
            self.resources[name] = Resource(self, name, name)
            
        # Resources with their units controlled by self._units.        
        self.dynamic_unit_resources = ['virt_imag_sweep_to','virt_iout_sweep_to','virt_imag','virt_iout','magnet_current',
                                  'power_supply_current','high_limit','low_limit' ]
        for name in self.dynamic_unit_resources:
            self.resources[name].units = self._units

        self.resources['virt_sweep_sleep'].units = 's'
        for x in range(5):
            self.resources['rate_{0}'.format(x)].units = 'A.s-1'
        
        self.resources['virt_heater_wait_mode'].allowed_values = self.allowed_heater_wait_mode
        self.resources['virt_energysave_mode'].allowed_values = self.allowed_energysave_mode
        self.resources['virt_energysave_mode'].converter = int
        self.resources['persistent_switch_heater'].allowed_values = self.allowed_switch_heater
        self.resources['sweep'].allowed_values = self.allowed_sweep
        self.resources['virt_sync_currents'].allowed_values = self.allowed_sync
        self.resources['units'].allowed_values = self.allowed_units
    def testReadException(self):
        """
		Fail to write.
		"""

        exceptions = []
        e = ValueError()

        def getter():
            raise e

        res = Resource(setter=lambda x: x)
        var = OutputVariable(name='Var', order=1, enabled=True)
        var.config = LinSpaceConfig(1.0, 4.0, 4)

        meas_res = Resource(getter=getter)
        meas_var = InputVariable(name='Meas var')

        vars, num_items = sort_output_variables([var])
        ctrl = sweep.SweepController([(('Res', res), )], vars, num_items,
                                     [('Meas res', meas_res)], [meas_var])

        def resource_exception_handler(name, e, write):
            exceptions.append((name, e))
            assert not write

        ctrl.resource_exception_handler = resource_exception_handler

        ctrl.run()

        eq_(exceptions, [('Meas res', e)] * 4)
    def testPulseProgram(self):
        """
		Iterate with a pulse program.
		"""

        res_buf = []

        def setter(value):
            res_buf.append(value)

        res = Resource(setter=setter)
        var1 = OutputVariable(name='Var 1', order=1, enabled=True)
        var1.config = LinSpaceConfig(1.0, 4.0, 4)

        p = Program.from_file(path.join(resource_dir, '01.pulse'))
        p.frequency = Quantity(1, 'GHz')
        p.set_value(('_acq_marker', 'marker_num'), 1)
        p.set_value(('_acq_marker', 'output'), 'f1')

        eq_(
            p.all_values,
            set([('_acq_marker', 'marker_num'), ('_acq_marker', 'output'),
                 ('d', ), ('i', ), ('p', 'amplitude'), ('p', 'length'),
                 ('p', 'shape')]))

        parameters = [('i', ), ('d', ), ('p', 'amplitude'), ('p', 'length')]
        for parameter in parameters:
            p.resource_labels[parameter] = 'res_' + '.'.join(parameter)
            p.resources[parameter] = Resource()

        var2 = OutputVariable(name='Var 2', order=1, enabled=True)
        var2.config = LinSpaceConfig(1, 4, 4)
        var2.type = 'integer'

        awg_cfg = DeviceConfig('awg')
        awg_cfg.address_mode = awg_cfg.address_modes.gpib
        awg_cfg.manufacturer, awg_cfg.model = 'Tektronix', 'AWG5014B'
        awg_cfg.mock = True
        awg_cfg.connect()

        osc_cfg = DeviceConfig('osc')
        osc_cfg.address_mode = awg_cfg.address_modes.gpib
        osc_cfg.manufacturer, osc_cfg.model = 'Tektronix', 'DPO7104'
        osc_cfg.mock = True
        osc_cfg.connect()

        pulse_config = sweep.PulseConfiguration(p.with_resources, {'f1': 1},
                                                awg_cfg.device, osc_cfg.device)

        vars, num_items = sort_output_variables([var1, var2])
        ress = [(('Res 1', res), ('Res 2', p.resources[('i', )]))]
        ctrl = sweep.SweepController(ress, vars, num_items, [], [], [], [],
                                     pulse_config)

        ctrl.run()

        eq_(res_buf, [1.0, 2.0, 3.0, 4.0])
	def _setup(self):
		AbstractDevice._setup(self)

		# Resources.
		read_only = ['reading']
		for name in read_only:
			self.resources[name] = Resource(self, name)

		read_write = ['setting']
		for name in read_write:
			self.resources[name] = Resource(self, name, name)

		self.resources['reading'].units = 'A'
		self.resources['setting'].allowed_values = self.allowed_settings
示例#6
0
	def _setup(self):
		AbstractSubdevice._setup(self)

		# Resources.
		read_only = ['waveform']
		for name in read_only:
			self.resources[name] = Resource(self, name)

		read_write = ['enabled']
		for name in read_write:
			self.resources[name] = Resource(self, name, name)

		self.resources['waveform'].slow = True
		self.resources['waveform'].display_units = 'V'
		self.resources['enabled'].converter = str_to_bool
示例#7
0
    def testFindResource(self):
        """
		Attempt to find a resource.
		"""

        dev = abstract_device.AbstractDevice(ip_address='192.0.2.123',
                                             autoconnect=False)
        subdev1 = abstract_device.AbstractSubdevice(dev)
        subdev2 = abstract_device.AbstractSubdevice(dev)
        subdev3 = abstract_device.AbstractSubdevice(subdev1)
        res1 = Resource(object(), '__class__')
        res2 = Resource(object(), '__str__')
        res3 = Resource(object(), '__doc__')

        dev.subdevices['subdev1'] = subdev1
        dev.resources['res1'] = res1
        dev.subdevices['subdev2'] = subdev2
        subdev1.subdevices['subdev3'] = subdev3
        subdev3.resources['res2'] = res2
        subdev3.resources['res3'] = res3

        # Success.
        found = dev.find_resource(('subdev1', 'subdev3', 'res3'))
        eq_(found.value, object.__doc__)

        # No such resource.
        try:
            dev.find_resource(('subdev1', 'res3'))
        except ValueError:
            pass
        else:
            assert False, 'Expected ValueError.'

        # No such subdevice.
        try:
            dev.find_resource(('subdev1', 'subdev2', 'res3'))
        except ValueError:
            pass
        else:
            assert False, 'Expected ValueError.'

        # Nothing to even try.
        try:
            dev.find_resource(())
        except ValueError:
            pass
        else:
            assert False, 'Expected ValueError.'
示例#8
0
    def _setup(self):
        AbstractDevice._setup(self)

        # Resources.

        read_write = [
            'frequency', 'phase', 'BNCAmplitude', 'typeNAmplitude',
            'modulationType', 'modulationEnabled', 'BNCEnable', 'typeNEnable',
            'modulationFunction', 'FMDeviation', 'AMDepth'
        ]
        for name in read_write:
            self.resources[name] = Resource(self, name, name)

        #write_only = ['BNCEnable','typeNEnable']
        #for name in write_only:
        #	self.resources[name] = Resource(self, None, name)

        self.resources['frequency'].units = 'Hz'
        self.resources['BNCAmplitude'].units = 'V'
        self.resources['typeNAmplitude'].units = 'V'
        self.resources['FMDeviation'].units = 'Hz'
        self.resources['BNCEnable'].allowed_values = self.allowedEnable
        self.resources['typeNEnable'].allowed_values = self.allowedEnable
        self.resources['modulationEnabled'].allowed_values = self.allowedEnable
        self.resources['modulationType'].allowed_values = self.allowedModType
        self.resources[
            'modulationFunction'].allowed_values = self.allowedModFunc
    def testWriteException(self):
        """
		Fail to read.
		"""

        exceptions = []
        e = ValueError()

        def setter(value):
            raise e

        res = Resource(setter=setter)
        var = OutputVariable(name='Var', order=1, enabled=True, const=0.0)
        var.config = LinSpaceConfig(1.0, 4.0, 4)

        vars, num_items = sort_output_variables([var])
        ctrl = sweep.SweepController([(('Res', res), )], vars, num_items, [],
                                     [])

        def resource_exception_handler(name, e, write):
            exceptions.append((name, e))
            ctrl.abort(fatal=True)
            assert write

        ctrl.resource_exception_handler = resource_exception_handler

        ctrl.run()

        eq_(exceptions, [('Res', e)])
示例#10
0
    def _setup(self):
        AbstractDevice._setup(self)
        
        # Channel subdevices.
        self.channels = [None] # There is no channel 0.
        for chan_num in xrange(1, 3):
            channel = Channel(self,chan_num)
            self.subdevices['channel{0}'.format(chan_num)] = channel
            # this list is useful as it is actually ordered, as opposed to the dict above.
            self.channels.append(channel)
            
        #This saves the last channel set to the device for programming purposes...its a way of minimizing
        #calls to the device.
        self.active_channel_store = None

        # Resources.
        
        read_write = ['active_channel', 'virt_both_persistent_switch_heaters', 'virt_both_units']
        for name in read_write:
            self.resources[name] = Resource(self, name, name)
        
        self.resources['active_channel'].allowed_values = self.allowed_active_channel
        self.resources['active_channel'].converter = int
        self.resources['virt_both_persistent_switch_heaters'].allowed_values = self.allowed_both_heaters
        self.resources['virt_both_units'].allowed_values = self.allowed_both_units
示例#11
0
	def _setup(self):
		AbstractDevice._setup(self)

		# Resources.
		read_only = ['reading']
		for name in read_only:
			self.resources[name] = Resource(self, name)

		read_write = ['integration_time', 'auto_zero']
		for name in read_write:
			self.resources[name] = Resource(self, name, name)

		self.resources['reading'].units = 'V'
		self.resources['integration_time'].converter = float
		self.resources['integration_time'].allowed_values = self.allowed_nplc
		self.resources['auto_zero'].allowed_values = self.allowed_auto_zero
    def _setup(self):
        AbstractDevice._setup(self)

        # Resources.
        read_only = ['marker']
        for name in read_only:
            self.resources[name] = Resource(self, name)

        read_write = ['cwFreq', 'power', 'markFreq']
        for name in read_write:
            self.resources[name] = Resource(self, name, name, name)

        self.resources['marker'].converter = float
        self.resources['cwFreq'].units = 'Hz'
        self.resources['power'].converter = float
        self.resources['markFreq'].units = 'Hz'
	def _setup(self):
		AbstractDevice._setup(self)

		# Resources.
		self.read_only = ['temperature1','temperature2','temperature3','temperature4','temperature5','temperature6','temperature7','temperature8']
		for name in self.read_only:
			self.resources[name] = Resource(self, name)
			self.resources[name].units = 'K'
    def testSingle(self):
        """
		Iterate over a single thing without any measurements.
		"""

        res_buf = []

        def setter(value):
            res_buf.append(value)

        res = Resource(setter=setter)
        var = OutputVariable(name='Var', order=1, enabled=True, const=-1.0)
        var.config = LinSpaceConfig(1.0, 4.0, 4)
        var.smooth_steps = 3
        var.smooth_from, var.smooth_to = [True] * 2

        vars, num_items = sort_output_variables([var])
        ctrl = sweep.SweepController([(('Res', res), )], vars, num_items, [],
                                     [])

        # Callback verification buffers.
        actual_values = []
        actual_measurement_values = []
        actual_writes = []
        actual_reads = []
        closed = [0]

        # Callbacks.
        def data_callback(cur_time, values, measurement_values):
            actual_values.append(values)
            actual_measurement_values.append(measurement_values)

        ctrl.data_callback = data_callback

        def close_callback():
            closed[0] += 1

        ctrl.close_callback = close_callback

        def write_callback(pos, i, value):
            actual_writes.append((pos, i, value))

        ctrl.write_callback = write_callback

        def read_callback(i, value):
            actual_reads.append((i, value))

        ctrl.read_callback = read_callback

        # Let it run.
        ctrl.run()

        eq_(res_buf, [-1.0, 0.0, 1.0, 1.0, 2.0, 3.0, 4.0, 4.0, 1.5, -1.0])
        eq_(actual_values, [(1.0, ), (2.0, ), (3.0, ), (4.0, )])
        eq_(actual_measurement_values, [()] * 4)
        eq_(actual_writes, [(0, 0, x) for x in [1.0, 2.0, 3.0, 4.0]])
        eq_(actual_reads, [])
        eq_(closed, [1])
示例#15
0
    def _setup(self):
        AbstractSubdevice._setup(self)

        # Resources.
        read_write = ['voltage']
        for name in read_write:
            self.resources[name] = Resource(self, name, name)

        self.resources['voltage'].units = 'V'
示例#16
0
	def _setup(self):
		AbstractDevice._setup(self)

		# Resources.
		self.read_only = ['temperature']
		for name in self.read_only:
			self.resources[name] = Resource(self, name)

		self.resources['temperature'].units = 'K'
    def _setup(self):
        AbstractSubdevice._setup(self)

        # Resources.
        read_write = ['delay', 'high', 'low']
        for name in read_write:
            self.resources[name] = Resource(self, name, name)

        self.resources['delay'].units = 's'
        self.resources['high'].units = 'V'
        self.resources['low'].units = 'V'
示例#18
0
    def _setup(self):
        AbstractDevice._setup(self)

        # Resources.
        read_write = ['enabled', 'power', 'frequency']
        for name in read_write:
            self.resources[name] = Resource(self, name, name)

        self.resources['enabled'].converter = str_to_bool
        self.resources['power'].units = 'V'
        self.resources['frequency'].units = 'Hz'
	def _setup(self):
		AbstractDevice._setup(self)

		# Resources.
		read_only = ['voltageIn', 'currentIn']
		for name in read_only:
			self.resources[name] = Resource(self, name)

		#read_write = ['voltageOut', 'currentOut','sourceType','senseType']
		read_write = ['voltageOut', 'currentOut','output']
		for name in read_write:
			self.resources[name] = Resource(self, name, name)

		self.resources['voltageIn'].units = 'V'
		self.resources['voltageOut'].units = 'V'
		self.resources['currentIn'].units = 'A'
		self.resources['currentOut'].units = 'A'
		self.resources['output'].allowed_values = self.allowedOutput
		self.currOutputState = -1
		self.currentOutputCurrent = -88
		self.currentOutputVoltage = -88
    def _setup(self):
        AbstractDevice._setup(self)

        self._perma_hot = True

        # Resources.
        read_write = ['perma_hot', 'sweep_rate', 'field']
        for name in read_write:
            self.resources[name] = Resource(self, name, name)

        self.resources['perma_hot'].converter = str_to_bool
        self.resources['sweep_rate'].units = 'T.s-1'
        self.resources['field'].units = 'T'
示例#21
0
	def _setup(self):
		AbstractSubdevice._setup(self)

		# These values are used to tune the input values according to empirical error.
		self.gain = 1.0
		self.offset = 0.0

		# Resources.
		read_write = ['voltage']
		for name in read_write:
			self.resources[name] = Resource(self, name, name)

		self.resources['voltage'].units = 'V'
    def _setup(self):
        AbstractDevice._setup(self)

        # These values are used to tune the input values according to empirical error.
        self.gain = 1.0
        self.offset = 0.0

        # Test
        self.default_Ilim = 2.0
        self.default_dwelltime = 0.01

        # Resources.
        write_only = ['voltage']
        for name in write_only:
            self.resources[name] = Resource(self, None, name)

        read_write = ['I_limit', 'dwell_time']
        for name in read_write:
            self.resources[name] = Resource(self, name, name)

        self.resources['voltage'].units = 'V'
        self.resources['I_limit'].converter = float
        self.resources['I_limit'].allowed_values = self.allowed_I_limit
        self.resources['dwell_time'].converter = float
示例#23
0
	def _setup(self):
		AbstractDevice._setup(self)

		self.channels = [None] # There is no channel 0.
		for chan in xrange(1, 5):
			channel = Channel(self, chan)
			self.channels.append(channel)
			self.subdevices['channel{0}'.format(chan)] = channel

		# Resources.
		read_write = ['sample_rate', 'time_scale']
		for name in read_write:
			self.resources[name] = Resource(self, name, name)

		self.resources['sample_rate'].units = 'Hz'
		self.resources['time_scale'].units = 's'
    def _setup(self):
        AbstractSubdevice._setup(self)

        self.markers = [None]  # There is no marker 0.
        for mark in xrange(1, 3):
            marker = Marker(self.device, self.channel, mark)
            self.markers.append(marker)
            self.subdevices['marker{0}'.format(mark)] = marker

        # Resources.
        read_write = ['waveform_name', 'enabled', 'amplitude']
        for name in read_write:
            self.resources[name] = Resource(self, name, name)

        self.resources['enabled'].converter = str_to_bool
        self.resources['amplitude'].units = 'V'
    def _setup(self):
        AbstractDevice._setup(self)

        self.channels = [None]  # There is no channel 0.
        for chan in xrange(1, 5):
            channel = Channel(self, chan)
            self.channels.append(channel)
            self.subdevices['channel{0}'.format(chan)] = channel

        # Resources.
        read_write = ['sampling_rate', 'run_mode', 'enabled']
        for name in read_write:
            self.resources[name] = Resource(self, name, name)

        self.resources['sampling_rate'].units = 'Hz'
        self.resources['run_mode'].allowed_values = self.allowed_run_modes
        self.resources['enabled'].converter = str_to_bool
示例#26
0
    def OnResourceInput(self, parameter, evt):
        label = evt.String

        try:
            # Do nothing if there has not been a change.
            if label == self.resource_labels[parameter]:
                return
        except KeyError:
            pass

        # The actual setter is generated when the program is cloned.
        resource = Resource(setter=lambda x: None)

        try:
            self.global_store.resources[label] = resource
        except KeyError as e:
            MessageDialog(self, str(e[0]), 'Resource label conflicts').Show()

            return

        # Validated.
        self.set_resource_label(parameter, label, resource)

        evt.EventObject.BackgroundColour = OK_BACKGROUND_COLOR
    def testContinuous(self):
        """
		Keep going, and then eventually stop.
		"""

        res_buf = []

        def setter(value):
            res_buf.append(value)

        res = Resource(setter=setter)
        var = OutputVariable(name='Var', order=1, wait='0 ms', enabled=True)
        var.config = LinSpaceConfig(1.0, 4.0, 4)

        vars, num_items = sort_output_variables([var])
        ctrl = sweep.SweepController([(('Res', res), )],
                                     vars,
                                     num_items, [], [], [], [],
                                     continuous=True)

        thr = Thread(target=ctrl.run)
        thr.daemon = True
        thr.start()

        sleep(0.5)
        ctrl.pause()
        sleep(0.5)
        ctrl.unpause()
        sleep(0.5)

        ctrl.last_continuous = True
        thr.join()

        expected_buf = [1.0, 2.0, 3.0, 4.0]

        eq_(res_buf[:len(expected_buf) * 50], expected_buf * 50)
	def testProper(self):
		"""
		Testing everything that there is to test along the happy path:
			nested and parallel variables
			measurements
			dwell time
		"""

		res_bufs = [[], [], [], []]
		measurement_counts = [0] * 2

		def setter(i, value):
			res_bufs[i].append(value)

		def getter(i):
			measurement_counts[i] += (-1) ** i

			return measurement_counts[i]

		dwell_time = Quantity(50, 'ms')

		# Output.
		res0 = Resource(setter=partial(setter, 0))
		res0.units = 'cm-1'
		res1 = Resource(setter=partial(setter, 1))
		res2 = Resource(setter=partial(setter, 2))
		res3 = Resource(setter=partial(setter, 3))

		var0 = OutputVariable(name='Var 0', order=2, enabled=True, const=0.0)
		var0.config = LinSpaceConfig(-1.0, -2.0, 2)
		var0.smooth_steps = 2
		var0.smooth_from, var0.smooth_to, var0.smooth_transition = [True] * 3
		var0.type = 'quantity'
		var0.units = 'cm-1'

		var1 = OutputVariable(name='Var 1', order=1, enabled=True, const=-1.0)
		var1.config = LinSpaceConfig(1.0, 4.0, 4)
		var1.smooth_steps = 3
		var1.smooth_from, var1.smooth_to, var1.smooth_transition = [True] * 3

		var2 = OutputVariable(name='Var 2', order=1, enabled=True, const=1.23, use_const=True)

		var3 = OutputVariable(name='Var 3', order=1, enabled=True, const=-9.0, wait=str(dwell_time))
		var3.config = LinSpaceConfig(-1.0, 2.0, 4)
		var3.smooth_steps = 2
		var3.smooth_from, var3.smooth_to, var3.smooth_transition = True, True, False

		var4 = OutputVariable(name='Var 4', order=3, enabled=True, const=-20.0)
		var4.config = LinSpaceConfig(-10.0, 20, 1)
		var4.smooth_steps = 2
		var4.smooth_from = True

		# Input.
		meas_res0 = Resource(getter=partial(getter, 0))
		meas_res1 = Resource(getter=partial(getter, 1))

		meas0 = InputVariable(name='Meas 0')
		meas1 = InputVariable(name='Meas 1')

		vars, num_items = sort_output_variables([var0, var1, var2, var3, var4])
		ctrl = sweep.SweepController([(('Res 2', res2),), (('Something', None),), (('Res 0', res0),),
				(('Res 1', res1), ('Res 3', res3))], vars, num_items,
				[('Meas res 0', meas_res0), ('Meas res 1', meas_res1)], [meas0, meas1])

		# Callback verification buffers.
		actual_values = []
		actual_measurement_values = []
		actual_writes = []
		actual_reads = []
		closed = [0]

		# Callbacks.
		def data_callback(cur_time, values, measurement_values):
			actual_values.append(values)
			actual_measurement_values.append(measurement_values)
		ctrl.data_callback = data_callback

		def close_callback():
			closed[0] += 1
		ctrl.close_callback = close_callback

		def write_callback(pos, i, value):
			actual_writes.append((pos, i, value))
		ctrl.write_callback = write_callback

		def read_callback(i, value):
			actual_reads.append((i, value))
		ctrl.read_callback = read_callback

		# Let it run.
		start_time = time()
		ctrl.run()
		elapsed_time = time() - start_time

		expected_time = num_items * dwell_time.value
		assert expected_time < elapsed_time, 'Took {0} s, expected at least {1} s.'.format(elapsed_time, expected_time)

		expected_res1 = [1.0, 2.0, 3.0, 4.0]
		expected_res2 = [-1.0, 0.0, 1.0, 2.0]

		expected_inner_writes = list(flatten(((3, 0, x), (3, 1, x - 2.0)) for x in [1.0, 2.0, 3.0, 4.0]))
		expected_writes = [(0, 0, 1.23), (1, 0, -10.0)] + list(flatten([(2, 0, x)] + expected_inner_writes
				for x in [Quantity(x, 'cm-1') for x in [-1.0, -2.0]]))

		eq_(res_bufs, [
			[Quantity(x, 'cm-1') for x in [0.0, -1.0, -1.0, -2.0, -2.0, 0.0]],
			[-1.0, 0.0, 1.0] + expected_res1 + [4.0, 2.5, 1.0] + expected_res1 + [4.0, 1.5, -1.0],
			[1.23],
			[-9.0, -1.0] + expected_res2 + expected_res2 + [2.0, -9.0],
		])
		eq_(measurement_counts, [8, -8])
		eq_(actual_values, [(1.23, -10.0, x, y, y - 2.0)
				for x in [Quantity(x, 'cm-1') for x in [-1.0, -2.0]]
				for y in [1.0, 2.0, 3.0, 4.0]])
		eq_(actual_measurement_values, [(x, -x) for x in xrange(1, 9)])
		eq_(actual_writes, expected_writes)
		eq_(actual_reads, list(flatten(((0, x), (1, -x)) for x in xrange(1, 9))))
		eq_(closed, [1])
	def testConditionsSweep(self):
		"""
		Tests a setup with condition variables and output variables.  Similar to testProper, but with
		conditions mixed in.
		"""

		res_bufs = [[], [], [], []]
		measurement_counts = [0] * 2

		def setter(i, value):
			res_bufs[i].append(value)

		def getter(i):
			measurement_counts[i] += (-1) ** i

			return measurement_counts[i]

		dwell_time = Quantity(50, 'ms')

		# Output.
		res0 = Resource(setter=partial(setter, 0))
		res0.units = 'cm-1'
		res1 = Resource(setter=partial(setter, 1))
		res2 = Resource(setter=partial(setter, 2))
		res3 = Resource(setter=partial(setter, 3))

		var0 = OutputVariable(name='Var 0', order=2, enabled=True, const=0.0)
		var0.config = LinSpaceConfig(-1.0, -2.0, 2)
		var0.smooth_steps = 2
		var0.smooth_from, var0.smooth_to, var0.smooth_transition = [True] * 3
		var0.type = 'quantity'
		var0.units = 'cm-1'

		var1 = OutputVariable(name='Var 1', order=1, enabled=True, const=-1.0)
		var1.config = LinSpaceConfig(1.0, 4.0, 4)
		var1.smooth_steps = 3
		var1.smooth_from, var1.smooth_to, var1.smooth_transition = [True] * 3

		var2 = OutputVariable(name='Var 2', order=1, enabled=True, const=1.23, use_const=True)

		var3 = OutputVariable(name='Var 3', order=1, enabled=True, const=-9.0, wait=str(dwell_time))
		var3.config = LinSpaceConfig(-1.0, 2.0, 4)
		var3.smooth_steps = 2
		var3.smooth_from, var3.smooth_to, var3.smooth_transition = True, True, False

		var4 = OutputVariable(name='Var 4', order=3, enabled=True, const=-20.0)
		var4.config = LinSpaceConfig(-10.0, 20, 1)
		var4.smooth_steps = 2
		var4.smooth_from = True
		
		# Condition variables.
		
		## Resources used for checking the conditions.
		
		iters = [cycle([0,1]), cycle([0,1,2]), cycle([0,-1,-2])]
		def cres_getter(i):
			return iters[i].next()
				
		cres0 = Resource('cres0', getter=partial(cres_getter,0))
		cres1 = Resource('cres1', getter=partial(cres_getter,1))
		cres2 = Resource('cres2', getter=partial(cres_getter,2))
		
		condition_resources = [(('cres0',cres0),),(('cres1',cres1),('cres2',cres2),)]
		
		
		cond0 = Condition('resource name','integer','cres0','==',1)
		cond1 = Condition('resource name','integer','cres1','==',2)
		cond2 = Condition('resource name','integer','cres2','==',-2)

		cvar0 = ConditionVariable(name='cvar0',order=0,enabled=True,wait=str(dwell_time),
								resource_names=['cres0',],conditions=[cond0])
		cvar1 = ConditionVariable(name='cvar1',order=1,enabled=True,wait=str(dwell_time),
								resource_names=['cres1',],conditions=[cond1])
		cvar2 = ConditionVariable(name='cvar2',order=1,enabled=True,wait=str(dwell_time),
								resource_names=['cres2',],conditions=[cond2])

		# Input.
		meas_res0 = Resource(getter=partial(getter, 0))
		meas_res1 = Resource(getter=partial(getter, 1))

		meas0 = InputVariable(name='Meas 0')
		meas1 = InputVariable(name='Meas 1')

		vars, num_items = sort_output_variables([var0, var1, var2, var3, var4])
		cvars = sort_condition_variables([cvar0,cvar1,cvar2])
		ctrl = sweep.SweepController([(('Res 2', res2),), (('Something', None),), (('Res 0', res0),),
				(('Res 1', res1), ('Res 3', res3))], vars, num_items,
				[('Meas res 0', meas_res0), ('Meas res 1', meas_res1)], [meas0, meas1],
				condition_resources, cvars)

		# Callback verification buffers.
		actual_values = []
		actual_measurement_values = []
		actual_writes = []
		actual_reads = []
		closed = [0]

		# Callbacks.
		def data_callback(cur_time, values, measurement_values):
			actual_values.append(values)
			actual_measurement_values.append(measurement_values)
		ctrl.data_callback = data_callback

		def close_callback():
			closed[0] += 1
		ctrl.close_callback = close_callback

		def write_callback(pos, i, value):
			actual_writes.append((pos, i, value))
		ctrl.write_callback = write_callback

		def read_callback(i, value):
			actual_reads.append((i, value))
		ctrl.read_callback = read_callback

		# Let it run.
		start_time = time()
		ctrl.run()
		elapsed_time = time() - start_time

		expected_time = num_items * dwell_time.value
		assert expected_time < elapsed_time, 'Took {0} s, expected at least {1} s.'.format(elapsed_time, expected_time)

		expected_res1 = [1.0, 2.0, 3.0, 4.0]
		expected_res2 = [-1.0, 0.0, 1.0, 2.0]

		expected_inner_writes = list(flatten(((3, 0, x), (3, 1, x - 2.0)) for x in [1.0, 2.0, 3.0, 4.0]))
		expected_writes = [(0, 0, 1.23), (1, 0, -10.0)] + list(flatten([(2, 0, x)] + expected_inner_writes
				for x in [Quantity(x, 'cm-1') for x in [-1.0, -2.0]]))

		eq_(res_bufs, [
			[Quantity(x, 'cm-1') for x in [0.0, -1.0, -1.0, -2.0, -2.0, 0.0]],
			[-1.0, 0.0, 1.0] + expected_res1 + [4.0, 2.5, 1.0] + expected_res1 + [4.0, 1.5, -1.0],
			[1.23],
			[-9.0, -1.0] + expected_res2 + expected_res2 + [2.0, -9.0],
		])
		
		eq_(measurement_counts, [24, -24])
		
	
		# Construct predicted actual values. 
		expected_actual_values = []
		for x in [Quantity(x, 'cm-1') for x in [-1.0, -2.0]]:
			for y in [1.0, 2.0, 3.0, 4.0]:
				
				# We append twice since the 0th order condition will create an extra measurement
				# for every non_conditionally based measurement
				expected_actual_values.append((1.23, -10.0, x, y, y - 2.0))
				expected_actual_values.append((1.23, -10.0, x, y, y - 2.0))
				
				# If were at the end of order 1, we append 4 more times to have a total of 6
				# This is because in the condition checking stage, we require the 0th order condition
				# and the 1st order conditions to all be true. So, cycling through entries in [0,1]
				# and [0,1,2], it will take a total of 6 condition checks to get 1 in [0,1], and 2 in
				# [0,1,2].
				if y == 4:
					expected_actual_values.append((1.23, -10.0, x, y, y - 2.0))
					expected_actual_values.append((1.23, -10.0, x, y, y - 2.0))
					expected_actual_values.append((1.23, -10.0, x, y, y - 2.0))
					expected_actual_values.append((1.23, -10.0, x, y, y - 2.0))
				

		eq_(actual_values, expected_actual_values)

		eq_(actual_measurement_values, [(x, -x) for x in xrange(1, 25)])
		eq_(actual_writes, expected_writes)
		eq_(actual_reads, list(flatten(((0, x), (1, -x)) for x in xrange(1, 25))))
		eq_(closed, [1])
    def testEvaluateCondition(self):
        """
		Test if evaluating conditions works properly
		for different combinations of types.
		"""
        # Some variables to use for tests.

        res_bufs = [[], [], [], []]

        def setter(i, value):
            res_bufs[i].append(value)

        def getter(i):
            return res_bufs[i][0]

        a = Quantity('5 T')
        b = Quantity('50 kG')
        c = 'on'

        res0 = Resource(getter=partial(getter, 0), setter=partial(setter, 0))
        res0.units = 'T'
        res1 = Resource(getter=partial(getter, 1), setter=partial(setter, 1))
        res1.units = 'kG'
        res2 = Resource(getter=partial(getter, 2), setter=partial(setter, 2))
        res2.allowed_values = ['on', 'off']

        res0.value = a
        res1.value = b
        res2.value = c

        # Check 2 quantities of equivalent units.
        c1 = variables.Condition('quantity', 'quantity', a, '==', b)
        eq_(c1.evaluate(), True)

        # Check a resource against a quantity.
        c2 = variables.Condition('resource', 'quantity', res0, '==', a)
        eq_(c2.evaluate(), True)

        # Check a resource with a resource.
        c3 = variables.Condition('resource', 'resource', res0, '==', res1)
        eq_(c3.evaluate(), True)

        # Check a resource that has an allowed value with a string.
        c4 = variables.Condition('resource', 'string', res2, '==', c)
        eq_(c4.evaluate(), True)

        # Test evaluating resource names.
        resources = [('res0', res0), ('res1', res1), ('res2', res2)]
        c3 = variables.Condition('resource name', 'resource name', 'res0',
                                 '==', 'res1')
        eq_(c3.evaluate(resources), True)

        # Check some things that should mess up.

        ## string instead of quantity.
        try:
            c5 = variables.Condition('resource', 'string', res0, '==', '5 T')
            eq_(c5.evaluate(), True)
        except TypeError:
            pass
        else:
            assert False, 'Expected TypeError.'

        ## not matching units.
        try:
            c6 = variables.Condition('quantity', 'quantity', Quantity('5 A'),
                                     '==', Quantity('5 T'))
            eq_(c6.evaluate(), True)
        except IncompatibleDimensions:
            pass
        else:
            assert False, 'Expected IncompatibleDimensions error.'
	def testEvaluateCondition(self):
		"""
		Test if evaluating conditions works properly
		for different combinations of types.
		"""
		# Some variables to use for tests.
		
		res_bufs = [[], [], [], []]

		def setter(i, value):
			res_bufs[i].append(value)
			
		def getter(i):
			return res_bufs[i][0]
			
			
		a = Quantity('5 T')
		b = Quantity('50 kG')
		c = 'on'

		res0 = Resource(getter=partial(getter,0), setter=partial(setter, 0))
		res0.units = 'T'
		res1 = Resource(getter=partial(getter,1), setter=partial(setter, 1))
		res1.units = 'kG'
		res2 = Resource(getter=partial(getter,2), setter=partial(setter, 2))
		res2.allowed_values = ['on','off']
		
		res0.value = a
		res1.value = b
		res2.value = c

		# Check 2 quantities of equivalent units.
		c1 = variables.Condition('quantity','quantity',a,'==',b)
		eq_(c1.evaluate(), True)
		
		# Check a resource against a quantity.
		c2 = variables.Condition('resource','quantity',res0,'==',a)
		eq_(c2.evaluate(), True)
		
		# Check a resource with a resource.
		c3 = variables.Condition('resource','resource',res0,'==',res1)
		eq_(c3.evaluate(), True)
		
		# Check a resource that has an allowed value with a string.
		c4 = variables.Condition('resource','string',res2,'==',c)
		eq_(c4.evaluate(), True)
		
		# Test evaluating resource names.
		resources = [('res0',res0),('res1',res1),('res2',res2)]
		c3 = variables.Condition('resource name','resource name','res0','==','res1')
		eq_(c3.evaluate(resources), True)
		
		# Check some things that should mess up.
		
		## string instead of quantity.
		try:
			c5 = variables.Condition('resource','string',res0,'==','5 T')
			eq_(c5.evaluate(), True)
		except TypeError:
			pass
		else:
			assert False, 'Expected TypeError.'
		
		## not matching units.
		try:
			c6 = variables.Condition('quantity','quantity',Quantity('5 A'),'==',Quantity('5 T'))
			eq_(c6.evaluate(), True)
		except IncompatibleDimensions:
			pass
		else:
			assert False, 'Expected IncompatibleDimensions error.'
    def testProper(self):
        """
		Testing everything that there is to test along the happy path:
			nested and parallel variables
			measurements
			dwell time
		"""

        res_bufs = [[], [], [], []]
        measurement_counts = [0] * 2

        def setter(i, value):
            res_bufs[i].append(value)

        def getter(i):
            measurement_counts[i] += (-1)**i

            return measurement_counts[i]

        dwell_time = Quantity(50, 'ms')

        # Output.
        res0 = Resource(setter=partial(setter, 0))
        res0.units = 'cm-1'
        res1 = Resource(setter=partial(setter, 1))
        res2 = Resource(setter=partial(setter, 2))
        res3 = Resource(setter=partial(setter, 3))

        var0 = OutputVariable(name='Var 0', order=2, enabled=True, const=0.0)
        var0.config = LinSpaceConfig(-1.0, -2.0, 2)
        var0.smooth_steps = 2
        var0.smooth_from, var0.smooth_to, var0.smooth_transition = [True] * 3
        var0.type = 'quantity'
        var0.units = 'cm-1'

        var1 = OutputVariable(name='Var 1', order=1, enabled=True, const=-1.0)
        var1.config = LinSpaceConfig(1.0, 4.0, 4)
        var1.smooth_steps = 3
        var1.smooth_from, var1.smooth_to, var1.smooth_transition = [True] * 3

        var2 = OutputVariable(name='Var 2',
                              order=1,
                              enabled=True,
                              const=1.23,
                              use_const=True)

        var3 = OutputVariable(name='Var 3',
                              order=1,
                              enabled=True,
                              const=-9.0,
                              wait=str(dwell_time))
        var3.config = LinSpaceConfig(-1.0, 2.0, 4)
        var3.smooth_steps = 2
        var3.smooth_from, var3.smooth_to, var3.smooth_transition = True, True, False

        var4 = OutputVariable(name='Var 4', order=3, enabled=True, const=-20.0)
        var4.config = LinSpaceConfig(-10.0, 20, 1)
        var4.smooth_steps = 2
        var4.smooth_from = True

        # Input.
        meas_res0 = Resource(getter=partial(getter, 0))
        meas_res1 = Resource(getter=partial(getter, 1))

        meas0 = InputVariable(name='Meas 0')
        meas1 = InputVariable(name='Meas 1')

        vars, num_items = sort_output_variables([var0, var1, var2, var3, var4])
        ctrl = sweep.SweepController([(('Res 2', res2), ),
                                      (('Something', None), ),
                                      (('Res 0', res0), ),
                                      (('Res 1', res1), ('Res 3', res3))],
                                     vars, num_items,
                                     [('Meas res 0', meas_res0),
                                      ('Meas res 1', meas_res1)],
                                     [meas0, meas1])

        # Callback verification buffers.
        actual_values = []
        actual_measurement_values = []
        actual_writes = []
        actual_reads = []
        closed = [0]

        # Callbacks.
        def data_callback(cur_time, values, measurement_values):
            actual_values.append(values)
            actual_measurement_values.append(measurement_values)

        ctrl.data_callback = data_callback

        def close_callback():
            closed[0] += 1

        ctrl.close_callback = close_callback

        def write_callback(pos, i, value):
            actual_writes.append((pos, i, value))

        ctrl.write_callback = write_callback

        def read_callback(i, value):
            actual_reads.append((i, value))

        ctrl.read_callback = read_callback

        # Let it run.
        start_time = time()
        ctrl.run()
        elapsed_time = time() - start_time

        expected_time = num_items * dwell_time.value
        assert expected_time < elapsed_time, 'Took {0} s, expected at least {1} s.'.format(
            elapsed_time, expected_time)

        expected_res1 = [1.0, 2.0, 3.0, 4.0]
        expected_res2 = [-1.0, 0.0, 1.0, 2.0]

        expected_inner_writes = list(
            flatten(
                ((3, 0, x), (3, 1, x - 2.0)) for x in [1.0, 2.0, 3.0, 4.0]))
        expected_writes = [(0, 0, 1.23), (1, 0, -10.0)] + list(
            flatten([(2, 0, x)] + expected_inner_writes
                    for x in [Quantity(x, 'cm-1') for x in [-1.0, -2.0]]))

        eq_(res_bufs, [
            [Quantity(x, 'cm-1') for x in [0.0, -1.0, -1.0, -2.0, -2.0, 0.0]],
            [-1.0, 0.0, 1.0] + expected_res1 + [4.0, 2.5, 1.0] +
            expected_res1 + [4.0, 1.5, -1.0],
            [1.23],
            [-9.0, -1.0] + expected_res2 + expected_res2 + [2.0, -9.0],
        ])
        eq_(measurement_counts, [8, -8])
        eq_(actual_values,
            [(1.23, -10.0, x, y, y - 2.0)
             for x in [Quantity(x, 'cm-1') for x in [-1.0, -2.0]]
             for y in [1.0, 2.0, 3.0, 4.0]])
        eq_(actual_measurement_values, [(x, -x) for x in xrange(1, 9)])
        eq_(actual_writes, expected_writes)
        eq_(actual_reads, list(flatten(
            ((0, x), (1, -x)) for x in xrange(1, 9))))
        eq_(closed, [1])
    def testConditionsSweep(self):
        """
		Tests a setup with condition variables and output variables.  Similar to testProper, but with
		conditions mixed in.
		"""

        res_bufs = [[], [], [], []]
        measurement_counts = [0] * 2

        def setter(i, value):
            res_bufs[i].append(value)

        def getter(i):
            measurement_counts[i] += (-1)**i

            return measurement_counts[i]

        dwell_time = Quantity(50, 'ms')

        # Output.
        res0 = Resource(setter=partial(setter, 0))
        res0.units = 'cm-1'
        res1 = Resource(setter=partial(setter, 1))
        res2 = Resource(setter=partial(setter, 2))
        res3 = Resource(setter=partial(setter, 3))

        var0 = OutputVariable(name='Var 0', order=2, enabled=True, const=0.0)
        var0.config = LinSpaceConfig(-1.0, -2.0, 2)
        var0.smooth_steps = 2
        var0.smooth_from, var0.smooth_to, var0.smooth_transition = [True] * 3
        var0.type = 'quantity'
        var0.units = 'cm-1'

        var1 = OutputVariable(name='Var 1', order=1, enabled=True, const=-1.0)
        var1.config = LinSpaceConfig(1.0, 4.0, 4)
        var1.smooth_steps = 3
        var1.smooth_from, var1.smooth_to, var1.smooth_transition = [True] * 3

        var2 = OutputVariable(name='Var 2',
                              order=1,
                              enabled=True,
                              const=1.23,
                              use_const=True)

        var3 = OutputVariable(name='Var 3',
                              order=1,
                              enabled=True,
                              const=-9.0,
                              wait=str(dwell_time))
        var3.config = LinSpaceConfig(-1.0, 2.0, 4)
        var3.smooth_steps = 2
        var3.smooth_from, var3.smooth_to, var3.smooth_transition = True, True, False

        var4 = OutputVariable(name='Var 4', order=3, enabled=True, const=-20.0)
        var4.config = LinSpaceConfig(-10.0, 20, 1)
        var4.smooth_steps = 2
        var4.smooth_from = True

        # Condition variables.

        ## Resources used for checking the conditions.

        iters = [cycle([0, 1]), cycle([0, 1, 2]), cycle([0, -1, -2])]

        def cres_getter(i):
            return iters[i].next()

        cres0 = Resource('cres0', getter=partial(cres_getter, 0))
        cres1 = Resource('cres1', getter=partial(cres_getter, 1))
        cres2 = Resource('cres2', getter=partial(cres_getter, 2))

        condition_resources = [(('cres0', cres0), ),
                               (
                                   ('cres1', cres1),
                                   ('cres2', cres2),
                               )]

        cond0 = Condition('resource name', 'integer', 'cres0', '==', 1)
        cond1 = Condition('resource name', 'integer', 'cres1', '==', 2)
        cond2 = Condition('resource name', 'integer', 'cres2', '==', -2)

        cvar0 = ConditionVariable(name='cvar0',
                                  order=0,
                                  enabled=True,
                                  wait=str(dwell_time),
                                  resource_names=[
                                      'cres0',
                                  ],
                                  conditions=[cond0])
        cvar1 = ConditionVariable(name='cvar1',
                                  order=1,
                                  enabled=True,
                                  wait=str(dwell_time),
                                  resource_names=[
                                      'cres1',
                                  ],
                                  conditions=[cond1])
        cvar2 = ConditionVariable(name='cvar2',
                                  order=1,
                                  enabled=True,
                                  wait=str(dwell_time),
                                  resource_names=[
                                      'cres2',
                                  ],
                                  conditions=[cond2])

        # Input.
        meas_res0 = Resource(getter=partial(getter, 0))
        meas_res1 = Resource(getter=partial(getter, 1))

        meas0 = InputVariable(name='Meas 0')
        meas1 = InputVariable(name='Meas 1')

        vars, num_items = sort_output_variables([var0, var1, var2, var3, var4])
        cvars = sort_condition_variables([cvar0, cvar1, cvar2])
        ctrl = sweep.SweepController([(('Res 2', res2), ),
                                      (('Something', None), ),
                                      (('Res 0', res0), ),
                                      (('Res 1', res1), ('Res 3', res3))],
                                     vars, num_items,
                                     [('Meas res 0', meas_res0),
                                      ('Meas res 1', meas_res1)],
                                     [meas0, meas1], condition_resources,
                                     cvars)

        # Callback verification buffers.
        actual_values = []
        actual_measurement_values = []
        actual_writes = []
        actual_reads = []
        closed = [0]

        # Callbacks.
        def data_callback(cur_time, values, measurement_values):
            actual_values.append(values)
            actual_measurement_values.append(measurement_values)

        ctrl.data_callback = data_callback

        def close_callback():
            closed[0] += 1

        ctrl.close_callback = close_callback

        def write_callback(pos, i, value):
            actual_writes.append((pos, i, value))

        ctrl.write_callback = write_callback

        def read_callback(i, value):
            actual_reads.append((i, value))

        ctrl.read_callback = read_callback

        # Let it run.
        start_time = time()
        ctrl.run()
        elapsed_time = time() - start_time

        expected_time = num_items * dwell_time.value
        assert expected_time < elapsed_time, 'Took {0} s, expected at least {1} s.'.format(
            elapsed_time, expected_time)

        expected_res1 = [1.0, 2.0, 3.0, 4.0]
        expected_res2 = [-1.0, 0.0, 1.0, 2.0]

        expected_inner_writes = list(
            flatten(
                ((3, 0, x), (3, 1, x - 2.0)) for x in [1.0, 2.0, 3.0, 4.0]))
        expected_writes = [(0, 0, 1.23), (1, 0, -10.0)] + list(
            flatten([(2, 0, x)] + expected_inner_writes
                    for x in [Quantity(x, 'cm-1') for x in [-1.0, -2.0]]))

        eq_(res_bufs, [
            [Quantity(x, 'cm-1') for x in [0.0, -1.0, -1.0, -2.0, -2.0, 0.0]],
            [-1.0, 0.0, 1.0] + expected_res1 + [4.0, 2.5, 1.0] +
            expected_res1 + [4.0, 1.5, -1.0],
            [1.23],
            [-9.0, -1.0] + expected_res2 + expected_res2 + [2.0, -9.0],
        ])

        eq_(measurement_counts, [24, -24])

        # Construct predicted actual values.
        expected_actual_values = []
        for x in [Quantity(x, 'cm-1') for x in [-1.0, -2.0]]:
            for y in [1.0, 2.0, 3.0, 4.0]:

                # We append twice since the 0th order condition will create an extra measurement
                # for every non_conditionally based measurement
                expected_actual_values.append((1.23, -10.0, x, y, y - 2.0))
                expected_actual_values.append((1.23, -10.0, x, y, y - 2.0))

                # If were at the end of order 1, we append 4 more times to have a total of 6
                # This is because in the condition checking stage, we require the 0th order condition
                # and the 1st order conditions to all be true. So, cycling through entries in [0,1]
                # and [0,1,2], it will take a total of 6 condition checks to get 1 in [0,1], and 2 in
                # [0,1,2].
                if y == 4:
                    expected_actual_values.append((1.23, -10.0, x, y, y - 2.0))
                    expected_actual_values.append((1.23, -10.0, x, y, y - 2.0))
                    expected_actual_values.append((1.23, -10.0, x, y, y - 2.0))
                    expected_actual_values.append((1.23, -10.0, x, y, y - 2.0))

        eq_(actual_values, expected_actual_values)

        eq_(actual_measurement_values, [(x, -x) for x in xrange(1, 25)])
        eq_(actual_writes, expected_writes)
        eq_(actual_reads,
            list(flatten(((0, x), (1, -x)) for x in xrange(1, 25))))
        eq_(closed, [1])