def TestT1Fit(self): #def testT1Fit(self): # Added try/except trap with alternate syntax -- TJR """Test the fit_t1 experiment """ # Set parameters and generate synthetic data in natural units T1 = 40 * 1e3 # 40 us xdata = np.arange(20,120020,1000) synth_data = fits.t1_model(xdata, 1, T1, 0) synth_data = [np.random.normal(scale=0.1) + i for i in synth_data] # fit the T1 data result, result_err = fits.fit_t1(xdata,synth_data) # ----- # EEE Original logic routinely raising IndexError to include: # self.assertAlmostEqual(T1, result[1], delta=result_err[1]) # IndexError: invalid index to scalar variable. # # Wrapped in a temporary try/except block for experimentation. try: self.assertAlmostEqual(T1, result[1], delta=result_err[1]) # # EEE This routinely producing IndexError to include the following: # self.assertAlmostEqual(T1, result[1], delta=result_err[1]) # IndexError: invalid index to scalar variable. # except Exception as e: logger.warning( "Original ~array centric assertAlmostEqual call failed!" \ "\n\r << assertAlmostEqual(T1, result[1], delta=result_err[1])" "\n\r << EEE %s Exception %s" \ "\n\r $$ type( result):%s, type( result_err):%s" \ "\n\r -- repeating assertAlmostEqual call with simple value references..." \ "\n\r << assertAlmostEqual(T1, result, delta=result_err)", type( e), e, type( result), type( result_err)) self.assertAlmostEqual(T1, result, delta=result_err)
def __init__(self, resource_name=None, name="Unlabeled APS2"): self.name = name self.resource_name = resource_name if aps2_missing: logger.warning("Could not load aps2 library") if fake_aps2: self.wrapper = MagicMock() else: self.wrapper = aps2.APS2() self.set_enabled = self.wrapper.set_channel_enabled self.set_mixer_phase_skew = self.wrapper.set_mixer_phase_skew self.set_mixer_amplitude_imbalance = self.wrapper.set_mixer_amplitude_imbalance self.get_amplitude = self.wrapper.get_channel_scale self.get_offset = self.wrapper.get_channel_offset self.get_enabled = self.wrapper.get_channel_enabled self.get_mixer_phase_skew = self.wrapper.get_mixer_phase_skew self.get_mixer_amplitude_imbalance = self.wrapper.get_mixer_amplitude_imbalance self.run = self.wrapper.run self.stop = self.wrapper.stop self.connected = False self._sequence_filename = None self._mode = "RUN_SEQUENCE" if not fake_aps2: self._mode_dict = aps2.run_mode_dict self._mode_inv_dict = {v: k for k, v in aps2.run_mode_dict.items()}
def connect(self, resource_name=None, interface_type="VISA"): """Connect to the RF source via a specified physical interface. Defaults to the IP address given at instatiation and the VISA interface if these arguments are not given. Args: resource_name: IP address of BNC. Defaults to None. interface_type: Physical interface for communication. Default is None, indicating use of PyVISA. Returns: None. """ if resource_name is not None: if is_valid_ipv4(resource_name): resource_name = resource_name + "::inst0::INSTR" else: logger.error("Invalid IP address for BNC845: {}.".format(resource_name)) super(BNC845, self).connect(resource_name, interface_type) self.interface._resource.read_termination = '\n' self.interface._resource.write_termination = '\n' # Setup the reference every time # Output 10MHz for daisy-chaining and lock to 10MHz external # reference self.output = True self.interface.write('SOURCE:ROSC:EXT:FREQ 10E6') self.interface.write('SOUR:ROSC:SOUR EXT') # Check that it locked -- it does not lock. for ct in range(10): locked = self.interface.query('SOURCE:ROSC:LOCKED?') logger.debug("Lock attempt {}: {}".format(ct, locked)) if locked == '1': break time.sleep(0.5) if locked != '1': logger.warning('BNC845 at %s is unlocked.', self.resource_name.split("::")[1]);
def init_instruments(self): for name, instr in self._instruments.items(): instr_par = self.settings['instruments'][name] logger.debug("Setting instr %s with params %s.", name, instr_par) instr.set_all(instr_par) self.digitizers = [ v for _, v in self._instruments.items() if "Digitizer" in v.instrument_type ] self.awgs = [ v for _, v in self._instruments.items() if "AWG" in v.instrument_type ] # Swap the master AWG so it is last in the list try: master_awg_idx = next( ct for ct, awg in enumerate(self.awgs) if 'master' in self.settings['instruments'][awg.name] and self.settings['instruments'][awg.name]['master']) self.awgs[-1], self.awgs[master_awg_idx] = self.awgs[ master_awg_idx], self.awgs[-1] except: logger.warning("No AWG is specified as the master.") # attach digitizer stream sockets to output connectors for chan, dig in self.chan_to_dig.items(): socket = dig.get_socket(chan) oc = self.chan_to_oc[chan] self.loop.add_reader(socket, dig.receive_data, chan, oc) if self.cw_mode: for awg in self.awgs: awg.run()
def connect(self, resource_name=None): if resource_name is not None: self.resource_name = resource_name # pass thru functions self.acquire = self._lib.acquire self.stop = self._lib.stop self.disconnect = self._lib.disconnect if self.gen_fake_data or fake_x6: self._lib = MagicMock() #logger.warning("Could not load x6 library") # szMockLabel = "" if self.gen_fake_data: szMockLabel += "gen_fake_data:{}".format( self.gen_fake_data) if len( szMockLabel) > 0: szMockLabel += " && " if fake_x6: szMockLabel += "fake_x6:{}".format( fake_x6) logger.warning("MagicMock X6 library assigned" \ " << %s...", szMockLabel) # logger.warning("X6 GENERATING FAKE DATA\n\r") self._lib.connect(int(self.resource_name))
def disconnect(self): if self._resource is not None: self._resource.close() logger.info("Disconnected %s from %s" % (self.name, self.resource_name)) else: logger.warning("No connection is established. Do nothing.")
def __init__(self, resource_name=None, name="Unlabled APS"): self.name = name self.resource_name = resource_name if aps1_missing: logger.warning("Could not load aps1 library!") if fake_aps1: self.wrapper = MagicMock() else: self.wrapper = libaps.APS() self.run = self.wrapper.run self.stop = self.wrapper.stop self.connected = False self.read_register = self.wrapper.read_register self._sequence_filename = None self._run_mode = "RUN_SEQUENCE" self._repeat_mode = "TRIGGERED" self._sampling_rate = 1200 self._run_mode_dict = {1: 'RUN_SEQUENCE', 0: 'RUN_WAVEFORM'} self._run_mode_inv_dict = { v: k for k, v in self._run_mode_dict.items() } self._repeat_mode_dict = {1: "CONTINUOUS", 0: "TRIGGERED"} self._repeat_mode_inv_dict = { v: k for k, v in self._repeat_mode_dict.items() }
def shutdown(self): logger.debug("Shutting down instruments") # This includes stopping the flow of data, and must be done before terminating nodes self.shutdown_instruments() try: ct_max = 5 #arbitrary waiting 10 s before giving up for ct in range(ct_max): if any([n.is_alive() for n in self.other_nodes]): logger.warning( "Filter pipeline appears stuck. Use keyboard interrupt to terminate." ) time.sleep(2.0) else: break for n in self.other_nodes: n.terminate() raise Exception('Filter pipeline stuck!') except KeyboardInterrupt as e: for n in self.other_nodes: n.terminate() if not self.keep_instruments_connected: logger.debug("Disconnecting instruments") self.disconnect_instruments() for n in self.other_nodes: n.done.set() import gc gc.collect()
def reset(self, stream=None): """ Reset the progress bar(s) """ logger.debug("Update stream descriptor for progress bars.") if stream is not None: self.stream = stream if self.stream is None: logger.warning("No stream is associated with the progress bars!") self.axes = [] else: self.axes = self.stream.descriptor.axes self.num = min(self.num, len(self.axes)) self.totals = [ self.stream.descriptor.num_points_through_axis(axis) for axis in range(self.num) ] self.chunk_sizes = [ max(1, self.stream.descriptor.num_points_through_axis(axis + 1)) for axis in range(self.num) ] logger.debug("Reset the progress bars to initial states.") self.bars = [] for i in range(self.num): if self.notebook: self.bars.append( tqdm_notebook(total=self.totals[i] / self.chunk_sizes[i])) else: self.bars.append( tqdm(total=self.totals[i] / self.chunk_sizes[i]))
async def run(self): """ Generic run method which waits on a single stream and calls `process_data` on any new_data """ logger.debug('Running "%s" run loop', self.name) self.finished_processing = False input_stream = getattr(self, self._input_connectors[0]).input_streams[0] while True: message = await input_stream.queue.get() message_type = message['type'] message_data = message['data'] message_comp = message['compression'] if message_comp == 'zlib': message_data = pickle.loads(zlib.decompress(message_data)) # If we receive a message if message['type'] == 'event': logger.debug('%s "%s" received event "%s"', self.__class__.__name__, self.name, message_data) # Propagate along the graph for oc in self.output_connectors.values(): for os in oc.output_streams: logger.debug('%s "%s" pushed event "%s" to %s, %s', self.__class__.__name__, self.name, message_data, oc, os) await os.queue.put(message) # Check to see if we're done if message['event_type'] == 'done': if not self.finished_processing: logger.warning( "Filter {} being asked to finish before being done processing." .format(self.name)) await self.on_done() break elif message['event_type'] == 'refined': await self.refine(message_data) elif message['type'] == 'data': if not hasattr(message_data, 'size'): message_data = np.array([message_data]) logger.debug('%s "%s" received %d points.', self.__class__.__name__, self.name, message_data.size) logger.debug("Now has %d of %d points.", input_stream.points_taken, input_stream.num_points()) await self.process_data(message_data.flatten()) elif message['type'] == 'data_direct': await self.process_direct(message_data) # If we have gotten all our data and process_data has returned, then we are done! if all([v.done() for v in self.input_connectors.values()]): self.finished_processing = True
def run_sweeps(self): #For now, only update histograms if we don't have a parameter sweep. if not self.sweeper.axes: self.init_plots() self.add_manual_plotter(self.re_plot) self.add_manual_plotter(self.im_plot) else: if any([ x.save_kernel.value for x in self.filters.values() if type(x) is SingleShotMeasurement ]): logger.warning( "Kernel saving is not supported if you have parameter sweeps!" ) super(SingleShotFidelityExperiment, self).run_sweeps() if not self.sweeper.axes: self._update_histogram_plots() if hasattr(self, 'extra_plot_server'): try: self.extra_plot_server.stop() except: pass if self.sweeper.axes and self.optimize: #select the buffers/writers whose sources are singleshot filters fid_buffers = [ buff for buff in self.buffers if self.settings['filters'][ buff.name]['source'].strip().split()[1] == 'fidelity' ] if not fid_buffers: raise NameError( "Please connect a buffer to the single-shot filter output in order to optimize fidelity." ) #set sweep parameters to the values that maximize fidelity. Then update the saved_settings with the new values for buff in fid_buffers: dataset, descriptor = buff.get_data(), buff.get_descriptor() opt_ind = np.argmax(dataset['Data']) for k, axis in enumerate(self.sweeper.axes): instr_tree = axis.parameter.instr_tree param_key = self.saved_settings['instruments'] for key in instr_tree[:-1]: # go through the tree param_key = param_key[key] opt_value = float(dataset[axis.name][opt_ind]) # special case to set APS ch12 amplitudes if instr_tree[-1] == 'amplitude' and instr_tree[ -2] in self.saved_settings['instruments'].keys(): param_key['tx_channels']['12']['1'][ 'amplitude'] = round(float(opt_value), 5) param_key['tx_channels']['12']['2'][ 'amplitude'] = round(float(opt_value), 5) else: param_key[instr_tree[-1]] = opt_value logger.info("Set{} to {}.".format( " ".join(str(x) for x in instr_tree), opt_value)) config.yaml_dump(self.saved_settings, config.configFile)
def last_data_axis(self): # Return the outer most data axis but not sweep axis data_axes_idx = [i for i, a in enumerate(self.axes) if not isinstance(a,SweepAxis)] if len(data_axes_idx)>0: return data_axes_idx[0] else: logger.warning("DataStreamDescriptor has no pure DataAxis. Return None.") return None
def shutdown_instruments(self): self.awg.output = False # self.awg.auto_range = True try: self.analog_input.StopTask() self.analog_input.ClearTask() except Exception as e: logger.warning("Failed to clear DAQ task!")
def num_points(self): if self.descriptor is not None: return self.descriptor.num_points() else: logger.warning( "Stream '{}' has no descriptor. Function num_points() returns 0." .format(self.name)) return 0
def power(self, value): if value > self.max_power: value = self.max_power logger.warning('Lab Brick power out of range') elif value < self.min_power: value = self.min_power logger.warning('Lab Brick power out of range') self._lib.fnLMS_SetPowerLevel(self.device_id, int(value * 4)) # Convert to 0.25 dB
def connect(self, resource_name=None): if fake_alazar: logger.warning("Could not load Alazar library") if resource_name: self.resource_name = resource_name self._lib.connect("{}/{}".format(self.name, int(self.resource_name))) for channel in self.channels: self.get_socket(channel)
def shutdown_instruments(self): try: self.analog_input.StopTask() except Exception as e: logger.warning("Warning failed to stop task. This is typical.") pass self.arb.stop() self.keith.current = 0.0 self.mag.disconnect()
def stop(self): if self.do_plotting: try: self.socket.close() self.context.term() except: logger.warning( f"Exception occured while closing socket and context for {self}" )
def shutdown_instruments(self): try: self.analog_input.StopTask() except Exception as e: logger.warning("Warning failed to stop task. This is typical.") pass self.arb.stop() self.lock.amp = 0
def shutdown_instruments(self): try: self.analog_input.StopTask() except Exception as e: logger.warning("Warning failed to stop task, which is quite typical (!)") self.arb.stop() # self.keith.current = 0.0 # self.mag.zero() self.pspl.output = False
def shutdown_instruments(self): try: self.analog_input.StopTask() except Exception as e: logger.warning( "Warning failed to stop task, which is quite typical (!)") self.arb.stop() self.pspl.output = False self.lock.amp = 0
def use_internal_ref(self, value): if value != 1 and value != 0: using_internal_ref = self._lib.fnLMS_SetUseInternalRef( self.device_id, 1) logger.warning( 'Lab Brick internal reference use must be 0 or 1. Set to: 1') else: using_internal_ref = self._lib.fnLMS_SetUseInternalRef( self.device_id, value) return using_internal_ref
def __init__(self, resource_name=None, name="Unlabeled Holzworth HS9000"): self.name = name self.resource_name = resource_name try: self._lib = ctypes.CDLL("HolzworthMulti.dll") except: logger.warning("Could not find the Holzworth driver.") self._lib = MagicMock() self._lib.usbCommWrite.restype = ctypes.c_char_p self._lib.openDevice.restype = ctypes.c_int
def get_voltage(self): volt = None for ct in range(10): try: volt = float(self.interface.query("READ ")) except ValueError: pass if volt is None: logger.warning("Failed to get data from BBN Spectrum Analyzer " + " at {}.".format(self.resource_name)) return volt
def init_progressbar(self, num=0, notebook=False): """ initialize the progress bars.""" oc = list(self.output_connectors.values()) if len(oc) > 0: self.progressbar = ExpProgressBar(oc[0].output_streams[0], num=num, notebook=notebook) else: logger.warning( "No stream is found for progress bars. Create a dummy bar.") self.progressbar = ExpProgressBar(None, num=num, notebook=notebook)
def load_waveforms(self, wfA, wfB): wfA_32 = [((wfA[2 * i + 1] << 16) | wfA[2 * i]) for i in range(len(wfA) // 2)] wfB_32 = [((wfB[2 * i + 1] << 16) | wfB[2 * i]) for i in range(len(wfB) // 2)] if len(wfA_32) > 0 and len(wfB_32) > 0: self.write_dram(self.WFA_OFFSET(), wfA_32) # I self.write_dram(self.WFB_OFFSET(), wfB_32) # Q else: logger.warning('Discarding zero-length waveform.')
def update_descriptors(self): logger.debug( "Updating Plotter %s descriptors based on input descriptor %s", self.name, self.sink.descriptor) self.stream = self.sink.input_streams[0] self.descriptor = self.sink.descriptor for axis in self.descriptor.axes: if axis.name == 'round_robins' and len(axis.points) == 1: self.descriptor.pop_axis('round_robins') logger.warning( "Popping singleton axis 'round_robins' axis from '%s'", self.name)
def execute_on_run(self): # Connect to the plot server if self.do_plotting: try: self.context = zmq.Context() self.socket = self.context.socket(zmq.DEALER) self.socket.identity = "Auspex_Experiment".encode() self.socket.connect("tcp://localhost:7762") except: logger.warning( "Exception occured while contacting the plot server. Is it running?" )
def is_valid_ipv4(ipv4_address): try: socket.inet_aton(ipv4_address) if ipv4_address.count(".") != 3: logger.warning("User-provided IP {} is a valid IP address but does" + " not appear to be in human-readable format.".format(ipv4_address)) return False return True except socket.error: return False except: raise
def receive_data(self, channel, oc, exit, ready, run): try: sock = self._chan_to_rsocket[channel] sock.settimeout(2) self.last_timestamp.value = datetime.datetime.now().timestamp() total = 0 ready.value += 1 logger.debug( f"{self} receiver launched with pid {os.getpid()}. ppid {os.getppid()}" ) while not exit.is_set(): # push data from a socket into an OutputConnector (oc) # wire format is just: [size, buffer...] # TODO receive 4 or 8 bytes depending on sizeof(size_t) run.wait() # Block until we are running again try: msg = sock.recv(8) self.last_timestamp.value = datetime.datetime.now( ).timestamp() except: continue # reinterpret as int (size_t) msg_size = struct.unpack('n', msg)[0] buf = sock_recvall(sock, msg_size) if len(buf) != msg_size: logger.error( "Channel %s socket msg shorter than expected" % channel.channel) logger.error("Expected %s bytes, received %s bytes" % (msg_size, len(buf))) return data = np.frombuffer(buf, dtype=channel.dtype) # logger.info(f"X6 {msg_size} got {len(data)}") total += len(data) oc.push(data) # logger.info('RECEIVED %d %d', total, oc.points_taken.value) # TODO: this is suspeicious for stream in oc.output_streams: abc = 0 while True: try: dat = stream.queue.get(False) abc += 1 time.sleep(0.005) except queue.Empty as e: # logger.info(f"All my data {oc} has been consumed {abc}") break # logger.info("X6 receive data exiting") except Exception as e: logger.warning(f"{self} receiver raised exception {e}. Bailing.")