def virt_imag(self, value): if self.virt_energysave_mode == 4: self.virt_sync_currents = 'start' self._wait_for_sweep() self.persistent_switch_heater = 'on' self.virt_iout = Quantity(value,self._units) self.persistent_switch_heater = 'off' self.sweep = 'zero' elif self.virt_energysave_mode == 3: self.virt_sync_currents = 'start' self._wait_for_sweep() self.device.virt_both_persistent_switch_heaters = 'on' self.virt_iout = Quantity(value,self._units) self.device.virt_both_persistent_switch_heaters = 'off' self.sweep = 'zero' elif self.virt_energysave_mode == 2: self.persistent_switch_heater = 'on' self.virt_iout = Quantity(value,self._units) self.persistent_switch_heater = 'off' elif self.virt_energysave_mode == 1: self.device.virt_both_persistent_switch_heaters = 'on' self.virt_iout = Quantity(value,self._units) self.device.virt_both_persistent_switch_heaters = 'off' elif self.virt_energysave_mode == 0: if self.persistent_switch_heater != 'on': raise ValueError('Heater switch is not on in channel {0}.'.format(self.channel)) self.virt_iout = Quantity(value, self._units)
def testMarkerValues(self): """ Set the various marker values. """ awg = self.obtain_device() awg.reset() awg.channels[1].markers[1].delay = Quantity(1, 'ns') awg.channels[1].markers[1].high = Quantity(0.5, 'V') awg.channels[1].markers[2].delay = Quantity(0.1, 'ns') awg.channels[2].markers[1].low = Quantity(-100, 'mV') eq_(awg.channels[1].markers[1].delay.value, 1e-9) eq_(awg.channels[1].markers[2].delay.value, 0.1e-9) eq_(awg.channels[2].markers[1].delay.value, 0) eq_(awg.channels[2].markers[2].delay.value, 0) eq_(awg.channels[1].markers[1].high.value, 0.5) eq_(awg.channels[1].markers[2].high.value, 1) eq_(awg.channels[2].markers[1].high.value, 1) eq_(awg.channels[2].markers[2].high.value, 1) eq_(awg.channels[1].markers[1].low.value, 0) eq_(awg.channels[1].markers[2].low.value, 0) eq_(awg.channels[2].markers[1].low.value, -0.1) eq_(awg.channels[2].markers[2].low.value, 0)
def ok_callback(dlg): self.plot_settings = dlg.GetValue() if self.plot_settings.units_from and self.plot_settings.units_to: try: quantity_from = Quantity(1, self.plot_settings.units_from) quantity_to = Quantity(1, self.plot_settings.units_to) except ValueError as e: self.unit_conversion = 0 MessageDialog(self, str(e), 'Invalid unit').Show() else: # We don't actually care about the units; just the prefix values. self.unit_conversion = math.log(quantity_from.value, 10) - math.log(quantity_to.value, 10) else: self.unit_conversion = 0 self.acq_thread.delay = self.plot_settings.delay if self.plot_settings.time_value == 0: self.plot.x_label = 'Time (s)' elif self.plot_settings.time_value == 1: self.plot.x_label = 'Points' if self.plot_settings.y_scale != 0: self.plot.y_label = '/ 10 ^ {0}'.format(self.plot_settings.y_scale) else: self.plot.y_label = '' if self.plot_settings.units_to: self.plot.y_label += ' ({0})'.format(self.plot_settings.units_to) self.update_plot()
def autotune(self, voltage_resource, min_value=None, max_value=None, final_value=0, set_result=True): """ Take some measured data and solve for the gain and offset. voltage_resource: A resource which provides the realtime measured data for this port. min_value: Smallest value to take into account. max_value: Largest value to take into account. final_value: Value to set port to after all measurements are taken. set_result: Whether to apply the resulting gain and offset. """ self.device.status.append('Autotuning port {0}'.format(self.num)) try: if min_value is None: min_value = self.min_value if max_value is None: max_value = self.max_value # Test with raw values. old_gain, old_offset = self.gain, self.offset self.gain, self.offset = 1, 0 if max_value < min_value: raise ValueError('{0} > {1}'.format(min_value, max_value)) elif max_value == min_value: num_points = 1 else: num_points = 21 # Obtain data. real = numpy.linspace(min_value, max_value, num_points) measured = [] for x in real: self.voltage = Quantity(x, 'V') time.sleep(0.2) measured.append(voltage_resource.value.value) # Solve. A = numpy.vstack([measured, numpy.ones(len(measured))]).T gain, offset = numpy.linalg.lstsq(A, real)[0] if set_result: self.gain, self.offset = gain, offset else: self.gain, self.offset = old_gain, old_offset # Set the voltage after the gain and offset, so that it is potentially more correct. self.voltage = Quantity(final_value, 'V') return (gain, offset) finally: self.device.status.pop()
def wrapped(self, value): value.assert_dimensions(units) # Perform conversion. Note that this is a bit of a trick. We must use a value of 1.0 because # normalization messes up for Quantities with 0 magnitude. new_value = Quantity(1.0, units) new_value += value new_value -= Quantity(1.0, units) return f(self, new_value.original_value * multiplier)
def quantity_converter(x, symbols='s', dimensions='time', non_negative=True): try: q = Quantity(x) q.assert_dimensions(symbols) except (IncompatibleDimensions, ValueError): raise ValueError('Expected {0} quantity'.format(dimensions)) if non_negative and q.value < 0: raise ValueError('Expected non-negative quantity') return q
def testRounding(self): """ The model4g rounds to a nearest gaussian, and amp (??). Test this since the code relies on this with the sweep_to higher order functions. """ magctrler = self.obtain_device() magctrler.reset() chanctrler = magctrler.channels[self.channel_to_test] chanctrler.virt_iout = Quantity('20.19 G') eq_(chanctrler.virt_iout, Quantity('20 G'))
def testWaitForSweep(self): """ Tests the function _wait_for_sweep() """ magctrler = self.obtain_device() magctrler.reset() chanctrler = magctrler.channels[self.channel_to_test] chanctrler.virt_iout_sweep_to = Quantity('20 G') chanctrler._wait_for_sweep() # Check if sweep is actually done several times. for _ in range(1, 10): eq_(chanctrler.power_supply_current, Quantity('20 G'))
def power_supply_current(self): """ The power supply output current """ response = self.device.ask('iout?') stripped_response = Quantity.from_string(response)[0] return stripped_response
def magnet_current(self): """ This is the persistent magnet current setting """ response = self.device.ask('imag?') stripped_response = Quantity.from_string(response)[0] return stripped_response
def low_limit(self): """ The lower limit on the magnetic current """ response = self.device.ask('llim?') stripped_response = Quantity.from_string(response)[0] return stripped_response
def __init__(self, order, config=None, wait='100 ms', const=0.0, use_const=False, resource_name='', *args, **kwargs): Variable.__init__(self, *args, **kwargs) self.resource_name = resource_name self.order = order if config is not None: self.config = config else: self.config = LinSpaceConfig(0.0, 0.0, 1) # Iteration parameters. self._wait = Quantity(wait) self.const = const self.use_const = use_const # Smooth set. self.smooth_steps = 10 self.smooth_from = False self.smooth_to = False self.smooth_transition = False self.type = 'float' self.units = None
def GetValue(self): cond_args = [] arg_types = [] for i, type in enumerate(self.arg_type_setters): # We ensure values are sane along the way. if type['float'].Value: arg_types.append('float') cond_args.append(float(self.args[i].Value)) elif type['integer'].Value: arg_types.append('integer') cond_args.append(int(self.args[i].Value)) elif type['resource name'].Value: arg_types.append('resource name') cond_args.append(self.args[i].Value) elif type['quantity'].Value: arg_types.append('quantity') cond_args.append(Quantity(self.args[i].Value)) elif type['string'].Value: arg_types.append('string') cond_args.append(self.args[i].Value) condition = Condition(arg_types[0], arg_types[1], cond_args[0], self.op_menu.Value, cond_args[1]) return condition
def set_waveform(self, waveform, markers=None, name=None): """ Set the waveform on this channel. The waveform data should be in V. """ if name is None: name = 'Channel {0}'.format(self.channel) # Clear existing. if name in self.device.waveform_names: self.device.delete_waveform(name) # Normalize waveform. max_amp = max(abs(x) for x in waveform) if max_amp > self.max_amplitude: raise ValueError('Amplitude {0} V exceeds maximum of {1} V'.format( max_amp, self.max_amplitude)) elif max_amp > 0: if max_amp < self.min_amplitude: max_amp = self.min_amplitude waveform = [x / max_amp for x in waveform] self.amplitude = Quantity(max_amp, 'V') # Create new. self.device.create_waveform(name, waveform, markers) self.waveform_name = name
def testVirtIout(self): """ Test the resource virt_iout. """ magctrler = self.obtain_device() magctrler.reset() chanctrler = magctrler.channels[self.channel_to_test] chanctrler.virt_iout = Quantity('20 G') eq_(chanctrler.virt_iout, Quantity('20 G')) try: chanctrler.virt_iout = 55 except AttributeError: pass else: assert False, 'Expected AttributeError.'
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 virt_imag_sweep_to(self, value): if self.persistent_switch_heater != 'on': self.persistent_switch_heater = 'on' self.virt_iout_sweep_to = Quantity(value, self._units) if self._units == 'kG': self._imag_target = round(value,3) #round to the nearest Gaussian. else: self._imag_target = value #TODO: need to support rounding on amps.
def __init__(self): self.enabled = plot_available self.num_points = 500 self.delay = Quantity(0.2, 's') self.update_x = True self.time_value = 0 self.time_mode = 0 self.update_y = True self.y_scale = 0 self.units_from = '' self.units_to = ''
def transform(self, x): """ Perform a transform according to the scaling. """ if self.offset == 0: return self.linear_scale * x * (10 ** self.exponential_scale) elif isinstance(x, Quantity): return self.linear_scale * x * (10 ** self.exponential_scale) + Quantity(self.offset, x.original_units) else: return self.linear_scale * x * (10 ** self.exponential_scale) + self.offset
def testUnits(self): """ Test the units. """ magctrler = self.obtain_device() magctrler.reset() chanctrler = magctrler.channels[self.channel_to_test] # Test turning a heater on and off. chanctrler.units = 'A' eq_(chanctrler.units, 'A') chanctrler.units = 'kG' eq_(chanctrler.units, 'kG') try: chanctrler.units = 'T' except ValueError: pass else: assert False, 'Expected ValueError.' # Test both heaters option. magctrler.virt_both_units = 'A' eq_(magctrler.virt_both_units, 'A') chanctrler.units = 'kG' eq_(magctrler.virt_both_units, 'unequal') # Try setting hilim with something not in the right units, and something that is in related units. try: chanctrler.high_limit = Quantity('5 A') except IncompatibleDimensions: pass else: assert False, 'Expected IncompatibleDimensions.' chanctrler.high_limit = Quantity('0.5 T') eq_(chanctrler.high_limit, Quantity('5 kG'))
def virt_iout_sweep_to(self, value): # determine whether to set the hilim or lolim for increment, then sweep if value == 0: self.sweep = 'zero' elif self.power_supply_current.value < value: if self.low_limit > Quantity(value, self._units): self.low_limit = Quantity(value, self._units) #we put the low limit to zero self.high_limit = Quantity(value, self._units) self.sweep = 'up' elif self.power_supply_current.value > value: if self.high_limit < Quantity(value, self._units): self.high_limit = Quantity(value, self._units) self.low_limit = Quantity(value, self._units) self.sweep = 'down' if self._units == 'kG': self._iout_target = round(value,3) else: self._iout_target = value #TODO: need to support rounding on amps.
def testAcquire(self): """ Obtain some waveforms. """ dpo = self.obtain_device() dpo.reset() dpo.autoset() eq_(dpo.stopafter, 'runstop') assert dpo.acquiring ws = [] # 1 is enabled by default. # 2 and 3 are disabled by default. dpo.channels[4].enabled = True dpo.channels[1].scale = dpo.channels[4].scale = Quantity(500, 'mV') dpo.channels[1].offset = dpo.channels[4].offset = Quantity(1, 'V') # Many records. dpo.time_scale = Quantity(100, 'ns') dpo.sample_rate = Quantity(40, 'GHz') eq_(dpo.record_length, 4e3) dpo.acquire() ws.append(dpo.channels[1].waveform) ws.append(dpo.channels[4].waveform) eq_(dpo.time_scale.value, 1e-7) eq_(dpo.sample_rate.value, 4e10) eq_(len(ws[0]), 4e3) eq_(len(ws[1]), 4e3) # Long sample. dpo.acquisition_mode = 'sample' dpo.time_scale = Quantity(10, 's') dpo.sample_rate = Quantity(0.1, 'kHz') eq_(dpo.record_length, 1e3) dpo.acquire() ws.append(dpo.channels[1].waveform) ws.append(dpo.channels[4].waveform) eq_(dpo.time_scale.value, 1e1) eq_(dpo.sample_rate.value, 1e2) eq_(len(ws[2]), 1e3) eq_(len(ws[3]), 1e3) # Check the channels. assert dpo.channels[1].enabled assert not dpo.channels[2].enabled assert not dpo.channels[3].enabled assert dpo.channels[4].enabled # Check the data. assert all(x >= -1.5 and x <= 3.5 for w in ws for _, x in w)
def OnSetLowLimit(self, evt=None): try: Quantity(self.lolim_input.GetValue()) except ValueError as e: MessageDialog(self, str(e), 'Invalid value').Show() return False new_value = self.lolim_input.GetValue() resource = self.channel_subdevice.resources['low_limit'] try: resource.value = resource.convert(new_value) except IncompatibleDimensions: MessageDialog(self, ValueError('Expected dimensions to match "{0}"'.format(resource.units))).Show()
def testIllegal(self): """ These values aren't allowed. """ sg = self.obtain_device() sg.write('unit:power v') try: sg.power = Quantity(9.001, 'V') except ValueError: pass else: assert False, 'Expected ValueError' try: sg.frequency = Quantity(0, 'Hz') except ValueError: pass else: assert False, 'Expected ValueError'
def testSetVoltages(self): """ Set voltages on all the ports. Note: Verification should also be done manually based on the voltage source output. """ vsrc = self.obtain_device() test_voltages = list(range(-10, 10 + 1, 2)) + list(range(5, 0, -1)) for port, voltage in zip(range(6), test_voltages): vsrc.ports[port].voltage = Quantity(voltage, 'V')
def __init__(self, order, resource_names=None, conditions=[], wait='100 ms', *args, **kwargs): Variable.__init__(self, *args, **kwargs) self.order = order self.conditions = conditions self._wait = Quantity(wait) self.resource_names = resource_names
def testCurrentSync(self): """ Test to see if the current syncing works in a variety of circumstances. """ magctrler = self.obtain_device() magctrler.reset() chanctrler = magctrler.channels[self.channel_to_test] # set the curs different. # check to see if not synced. chanctrler.virt_iout = Quantity('20 G') chanctrler.virt_sync_currents = 'start' chanctrler._wait_for_sweep() eq_(chanctrler.virt_iout, chanctrler.virt_imag)
def GetValue(self): plot_settings = PlotSettings() plot_settings.enabled = self.enabled_checkbox.Value plot_settings.num_points = self.points_input.Value plot_settings.delay = Quantity(self.delay_input.GetValue(), 's') plot_settings.update_x = self.update_x_axis.Value plot_settings.time_value = self.time_value.Selection plot_settings.time_mode = self.time_mode.Selection plot_settings.update_y = self.update_y_axis.Value plot_settings.y_scale = self.y_scale.GetValue() plot_settings.units_from = self.units_from_input.Value plot_settings.units_to = self.units_to_input.Value return plot_settings
def OnSetRate(self, evt=None): try: Quantity(self.rate_input.GetValue()) except ValueError as e: MessageDialog(self, str(e), 'Invalid value').Show() return False range_id = self.rates_menu.GetCurrentSelection() resource = self.channel_subdevice.resources['rate_{0}'.format(range_id)] new_value = self.rate_input.GetValue() try: resource.value = resource.convert(new_value) except IncompatibleDimensions: MessageDialog(self, ValueError('Expected dimensions to match "{0}"'.format(resource.units))).Show()
def with_type(self, value): """ Set to the correct type, and wrap with the correct units. """ if self.type == 'integer': return int(value) elif self.type == 'float': return value elif self.type == 'quantity' and self.units is not None: return Quantity(value, self.units) else: raise ValueError( 'Invalid variable setup; type: {0}, units: {1}'.format( self.type, self.units))
def wait(self, value): wait = Quantity(value) wait.assert_dimensions("s") self._wait = wait