def initialize(self, deviceName, triggerMode): self.booting = True try: if(deviceName != ''): self.session = None self.wfm_handles = list() self.reportTime = ms() with niscope.Session(deviceName) as session: # Would get more session data here self.source0 = self.Add_AISource('0', -10, 10, 0.1) self.source1 = self.Add_AISource('1', -10, 10, 0.1) self.source2 = self.Add_AISource('2', -10, 10, 0.1) self.source3 = self.Add_AISource('3', -10, 10, 0.1) self.source4 = self.Add_AISource('4', -10, 10, 0.1) self.source5 = self.Add_AISource('5', -10, 10, 0.1) self.source6 = self.Add_AISource('6', -10, 10, 0.1) self.source7 = self.Add_AISource('7', -10, 10, 0.1) self.session = niscope.Session(deviceName) if(triggerMode == 'Front Digital Trigger'): self.Add_Digital_Trigger('PFI1') except: pass self.initialized.emit()
def multiple_niscope_sessions(): with niscope.Session( '', False, False, 'Simulate=1, DriverSetup=Model:5164;BoardType:PXIe' ) as simulated_session_1, niscope.Session( '', False, False, 'Simulate=1, DriverSetup=Model:5164;BoardType:PXIe' ) as simulated_session_2: yield [simulated_session_1, simulated_session_2]
def acquire_data(self): DAQ = self.DAQ # 1. Initialize DAQ with niscope.Session(resource_name=DAQ.resource_name,options=DAQ.options) as session: # 2. Configure settings for data acquisition: #Configure timing settings session.configure_horizontal_timing(min_sample_rate=DAQ.sample_rate, min_num_pts = DAQ.n_samples, ref_position = 0.0, num_records = 1, enforce_realtime = True) # Configure vertical (data) settings: session.channels[DAQ.channel_list].configure_vertical(DAQ.vertical_range, DAQ.coupling) # 3. Allocate numpy arrays for data DAQ.waveforms = [np.ndarray(DAQ.n_samples, dtype=np.float64) for c in DAQ.channel_list] # 4. Configure trigger session.configure_trigger_immediate() # 5. Collect data using fetch_into() #Initiate data collection with session.initiate(): for channel, waveform in zip(DAQ.channel_list, DAQ.waveforms): session.channels[channel].fetch_into(waveform) DAQ.waveforms[channel] = waveform
def update_config(self): try: self.config_channels = int(self.curr_channel.get()) except: self.config_channels = self.curr_channel.get() self.cached_absolute_initial_x = 0.0 self.cached_x_increment = 0.0 try: if self.dev_name != self.curr_device.get(): if self.session is not None: self.session.close() self.session = niscope.Session(self.curr_device.get()) self.dev_name = self.curr_device.get() self.session.configure_vertical( range=float(self.curr_vertical_range.get()), coupling=niscope.VerticalCoupling[ self.curr_vertical_coupling.get()], offset=float(self.curr_vertical_offset.get()), probe_attenuation=float(self.curr_probe_attenuation.get())) self.session.configure_horizontal_timing( min_sample_rate=float(self.curr_min_sample_rate.get()), min_num_pts=int(self.curr_min_record_length.get()), ref_position=50.0, num_records=1, enforce_realtime=True) except Exception as e: self._set_message(str(e)) else: self._set_message("Successfully updated configuration!")
def test_error_message(): try: # We pass in an invalid model name to force going to error_message with niscope.Session('FakeDevice', False, True, 'Simulate=1, DriverSetup=Model:invalid_model; BoardType:PXIe'): assert False except niscope.Error as e: assert e.code == -1074118609 assert e.description.find('Simulation does not support the selected model and board type.') != -1
def example(resource_name, channels, options, length, voltage): with niscope.Session(resource_name=resource_name, options=options) as session: session.configure_vertical(range=voltage, coupling=niscope.VerticalCoupling.AC) session.configure_horizontal_timing(min_sample_rate=50000000, min_num_pts=length, ref_position=50.0, num_records=1, enforce_realtime=True) waveforms = session.channels[channels].read(num_samples=length) for i in range(len(waveforms)): print('Waveform {0} information:'.format(i)) print(str(waveforms[i]) + '\n\n')
def get_wav_trig(self, fs, npts, channel='0', trigger_level=0, trigger_coupling=niscope.TriggerCoupling.DC, trigger_slope=niscope.TriggerSlope.POSITIVE): ''' Get triggered (edge type) readings from the PXI-5922 digitizer. Parameters ---------- fs : Int The sampling frequency in Hz. npts : Int The number of points that should be returned. channel : Str The channel to trigger on ('0', '1', 'TRIG') trigger_level : Float The voltage threshold for the trigger. trigger_coupling : niscope.TriggerCoupling type The trigger coupling. Normally set to niscope.TriggerCoupling.DC trigger_slope : niscope.TriggerSlope type Specifies whether a rising or falling edge should be used. Normally set to niscope.TriggerSlope.POSITIVE Returns ------- CH0 : TYPE Array of float64 voltage values, corresponding to Channel 0 of the module. CH1 : TYPE Array of float64 voltage values, corresponding to Channel 1 of the module. ''' # Inputs must be integers fs = int(fs) npts = int(npts) # Open session only in function definition, so that scope is only 'locked' during acquisition (afterwards, NI InstrumentStudio / Soft Front Panel can take over) with niscope.Session(self.PXIaddr) as session: # Configure channels session.channels[0].configure_vertical( range=1.0, coupling=niscope.VerticalCoupling.DC) session.channels[1].configure_vertical( range=1.0, coupling=niscope.VerticalCoupling.DC) # Configure horizontal session.configure_horizontal_timing(min_sample_rate=fs, min_num_pts=npts, ref_position=0, num_records=1, enforce_realtime=True) # Set up trigger session.configure_trigger_edge(channel, trigger_level, trigger_coupling, trigger_slope) with session.initiate(): waveform = np.ndarray(npts * 2, dtype=np.float64) session.channels[0, 1].fetch_into(waveform, timeout=5.0) CH0 = waveform[:npts] CH1 = waveform[npts:] return CH0, CH1
def OnConfigUpdate(self, event): # noqa: N802 current_dev_name = self._devices.GetStringSelection() try: if current_dev_name != self._dev_name: if self._session is not None: self._running = False self._session.close() self._session = niscope.Session(current_dev_name) # Get and validate parameters for configure vertical try: vert_range = float(self._vertical_range.GetValue()) coupling = get_vertical_coupling_enum(self._vertical_coupling.GetStringSelection()) # noqa: E501 vert_offset = float(self._vertical_offset.GetValue()) probe_atten = float(self._probe_attenuation.GetValue()) except TypeError as e: self._status.SetLabel('Error getting vertical configuration: {0}'.format(str(e))) # noqa: E501 self._status.Wrap(500) self._session.configure_vertical(vert_range, coupling, vert_offset, probe_atten) # noqa: E501 # Get and validate parameters for configure horizontal timing try: min_sample_rate = float(self._min_sample_rate.GetValue()) min_record_length = int(self._min_record_length.GetValue()) except TypeError as e: self._status.SetLabel('Error getting horizontal configuration: {0}'.format(str(e))) # noqa: E501 self._status.Wrap(500) self._session.configure_horizontal_timing(min_sample_rate, min_record_length, 0.50, 1, True) # noqa: E501 # Set Auto trigger to true self._session.trigger_modifier = niscope.TriggerModifier.AUTO # Determine trigger type and call configuration function trigger_type = self._trigger_type.GetPageText(self._trigger_type.GetSelection()) # noqa: E501 if trigger_type == 'Immediate': self.configure_trigger_immediate() elif trigger_type == 'Edge': self.configure_trigger_edge() elif trigger_type == 'Digital': self.configure_trigger_digital() elif trigger_type == 'Window': self.configure_trigger_window() elif trigger_type == 'Hysteresis': self.configure_trigger_hysteresis() else: raise TypeError('Invalid trigger type: {0}'.format(trigger_type)) # noqa: E501 self._session._initiate_acquisition() self._running = True self._cached_absolute_initial_x = 0.0 self._cached_x_increment = 0.0 except niscope.Error as e: self._status.SetLabel(str(e)) self._status.Wrap(500) self._dev_name = current_dev_name
def initialize(self, deviceName, triggerMode): try: if(deviceName != ''): self.session = None self.wfm_handles = list() self.reportTime = ms() with niscope.Session(deviceName) as session: # Would get more session data here self.source0 = self.Add_AISource('0', -10, 10, 0.1) self.source1 = self.Add_AISource('1', -10, 10, 0.1) self.session = niscope.Session(deviceName) if(triggerMode == 'Front Digital Trigger'): self.Add_Digital_Trigger('PXIe-5122 Trigger') except: pass self.initialized.emit()
def test_nitclk_session_reference(single_niscope_session): test_session = niscope.Session( 'FakeDevice', False, True, 'Simulate=1, DriverSetup=Model:5164; BoardType:PXIe') single_niscope_session.tclk.ref_trigger_master_session = test_session # We need to look at the actual session number inside the class # we know the type returned from session.tclk.pause_trigger_master_session will be nitclk.SessionReference # This test assumes knowledge of the class internals assert single_niscope_session.tclk.ref_trigger_master_session._session_number == test_session.tclk._get_tclk_session_reference( ) assert single_niscope_session.tclk.ref_trigger_master_session._session_number == test_session._vi
def example(resource_name1, resource_name2, options): with niscope.Session(resource_name=resource_name1, options=options) as session1, niscope.Session( resource_name=resource_name2, options=options) as session2: session_list = [session1, session2] for session in session_list: session.configure_vertical(range=1.0, coupling=niscope.VerticalCoupling.DC) session.configure_horizontal_timing(min_sample_rate=50000000, min_num_pts=1000, ref_position=50.0, num_records=1, enforce_realtime=True) session1.trigger_type = niscope.TriggerType.SOFTWARE nitclk.configure_for_homogeneous_triggers(session_list) nitclk.synchronize(session_list, 200e-9) nitclk.initiate(session_list) time.sleep(100) session1.send_software_trigger_edge(niscope.WhichTrigger.START) waveforms = session2.channels[0].fetch(num_samples=1000) for i in range(len(waveforms)): print('Waveform {0} information:'.format(i)) print(str(waveforms[i]) + '\n\n')
def example(resource_name, channels, options, length, voltage): with niscope.Session(resource_name=resource_name, options=options) as session: session.configure_vertical(range=voltage, coupling=niscope.VerticalCoupling.AC) session.configure_horizontal_timing(min_sample_rate=50000000, min_num_pts=length, ref_position=50.0, num_records=1, enforce_realtime=True) with session.initiate(): wfm, wfm_infos = session.channels[channels].fetch( num_samples=length) print('Number of samples acquired: {:,}\n'.format(len(wfm))) for i in range(len(wfm_infos)): print('Waveform {0} information:'.format(i)) print(str(wfm_infos[i]) + '\n\n')
def get_wav_now(self, fs, npts): ''' Get immediate readings from the PXI-5922 digitizer without triggering. Parameters ---------- fs : Int The sampling frequency in Hz. npts : Int The number of points that should be returned. Returns ------- CH0 : Array of float64 Voltages corresponding to Channel 0 of the module. CH1 : Array of float64 Voltages corresponding to Channel 1 of the module. ''' # Inputs must be integers fs = int(fs) npts = int(npts) # Open session only in function definition, so that scope is only 'locked' during acquisition (afterwards, NI InstrumentStudio / Soft Front Panel can take over) with niscope.Session(self.PXIaddr) as session: # Configure channels session.channels[0].configure_vertical( range=1.0, coupling=niscope.VerticalCoupling.DC) session.channels[1].configure_vertical( range=1.0, coupling=niscope.VerticalCoupling.DC) # Configure horizontal session.configure_horizontal_timing(min_sample_rate=fs, min_num_pts=npts, ref_position=0, num_records=1, enforce_realtime=True) # Set up trigger session.configure_trigger_edge('0', 0, niscope.TriggerCoupling.DC, niscope.TriggerSlope.POSITIVE) with session.initiate(): waveform = np.ndarray(npts * 2, dtype=np.float64) session.channels[0, 1].fetch_into(waveform, timeout=5.0) CH0 = waveform[:npts] CH1 = waveform[npts:] return CH0, CH1
def initialize_sessions(tsm: SMContext, options: dict = {}): """ Open sessions for all NI-SCOPE instrument channels that are defined in pinmap associated with the tsm context Args: tsm (SMContext): TestStand semiconductor module context options: Dictionary containing options for driver initialisation. """ instrument_names = tsm.get_all_niscope_instrument_names() for instrument_name in instrument_names: session = niscope.Session(instrument_name, reset_device=True, options=options) try: session.commit() except Exception: session.reset_device() session.configure_chan_characteristics(1e6, -1) session.commit() tsm.set_niscope_session(instrument_name, session)
def example(resource_name, options, total_acquisition_time_in_seconds, voltage, sample_rate_in_hz, samples_per_fetch): total_samples = int(total_acquisition_time_in_seconds * sample_rate_in_hz) # 1. Opening session with niscope.Session(resource_name=resource_name, options=options) as session: # We will acquire on all channels of the device channel_list = [c for c in range(session.channel_count) ] # Need an actual list and not a range # 2. Creating numpy arrays waveforms = [ np.ndarray(total_samples, dtype=np.float64) for c in channel_list ] # 3. Configuring session.configure_horizontal_timing(min_sample_rate=sample_rate_in_hz, min_num_pts=1, ref_position=0.0, num_records=1, enforce_realtime=True) session.channels[channel_list].configure_vertical( voltage, coupling=niscope.VerticalCoupling.DC, enabled=True) # Configure software trigger, but never send the trigger. # This starts an infinite acquisition, until you call session.abort() or session.close() session.configure_trigger_software() current_pos = 0 # 4. initiating with session.initiate(): while current_pos < total_samples: # We fetch each channel at a time so we don't have to de-interleave afterwards # We do not keep the wfm_info returned from fetch_into for channel, waveform in zip(channel_list, waveforms): # 5. fetching - we return the slice of the waveform array that we want to "fetch into" session.channels[channel].fetch_into( waveform[current_pos:current_pos + samples_per_fetch], relative_to=niscope.FetchRelativeTo.READ_POINTER, offset=0, record_number=0, num_records=1, timeout=hightime.timedelta(seconds=5.0)) current_pos += samples_per_fetch
def simulate_DAQ(resource_name, options, n_samples, sample_rate, vertical_range, coupling): # 1. Initialize DAQ with niscope.Session(resource_name=resource_name, options=options) as session: # List channels to be used: channel_list = [0] # 2. Configure settings for data acquisition: #Configure timing settings session.configure_horizontal_timing(min_sample_rate=sample_rate, min_num_pts=n_samples, ref_position=0.0, num_records=1, enforce_realtime=True) # Configure vertical (data) settings: session.channels[channel_list].configure_vertical( vertical_range, coupling) # 3. Allocate numpy arrays for data waveforms = [ np.ndarray(n_samples, dtype=np.float64) for c in channel_list ] # 4. Configure trigger session.configure_trigger_immediate() # 5. Collect data using fetch_into() #Initiate data collection with session.initiate(): for channel, waveform in zip(channel_list, waveforms): session.channels[channel].fetch_into(waveform) return waveforms
def multi_instrument_session(): with niscope.Session(','.join(instruments), False, True, 'Simulate=1, DriverSetup=Model:5164; BoardType:PXIe' ) as simulated_session: yield simulated_session
def session(): with niscope.Session('FakeDevice', False, True, 'Simulate=1, DriverSetup=Model:5164; BoardType:PXIe' ) as simulated_session: yield simulated_session
def session_5124(): with daqmx_sim_5124_lock: with niscope.Session('5124') as simulated_session: # 5124 is needed for video triggering yield simulated_session
def session_5142(): with daqmx_sim_5142_lock: with niscope.Session('5142') as simulated_session: # 5142 is needed for OSP yield simulated_session
#!/usr/bin/python import argparse import niscope parser = argparse.ArgumentParser(description='Outputs the specified voltage, then takes the specified number of voltage and current readings.', formatter_class=argparse.ArgumentDefaultsHelpFormatter) parser.add_argument('-n', '--name', default='PXI1Slot2', help='Resource name of a National Instruments SMU') parser.add_argument('-c', '--channels', default='0', help='Channel(s) to use') parser.add_argument('-l', '--length', default='20', type=int, help='Measure record length') parser.add_argument('-v', '--voltage', default=5.0, type=float, help='Voltage level') args = parser.parse_args() with niscope.Session(args.name, channels=args.channels) as session: pass
def __init__(self, time_offset, COM_port, record, sample, trigger, edge, channels): try: self.session = niscope.Session(COM_port) except niscope.errors.DriverError as err: logging.error("PXIe5171 error in __init__(): " + str(err)) self.verification_string = "cannot open session" self.instr = False return self.time_offset = time_offset # verify operation self.verification_string = "not implemented" # set record parameters try: self.session.max_input_frequency = 1e6 * float( record["bandwidth_MHz"]) except (niscope.errors.DriverError, ValueError): logging.warning( "Warning in PXIe5171: invalid max_input_frequency selected: " + str(err)) self.session.max_input_frequency = 100e6 try: samplingRate_kSs = float(sample["sample_rate"]) except ValueError: logging.warning( "Warning in PXIe5171: invalid sample rate selected: " + str(err)) samplingRate_kSs = 20.0 if samplingRate_kSs > 250e3: samplingRate_kSs = 20.0 try: self.num_samples = int(float(record["record_length"])) except ValueError: logging.warning( "Warning in PXIe5171: invalid record_length selected: " + str(err)) self.num_samples = 2000 try: self.session.binary_sample_width = int(sample["sample_width"]) except (niscope.errors.DriverError, ValueError): logging.warning( "Warning in PXIe5171: invalid binary_sample_width selected: " + str(err)) self.session.binary_sample_width = 16 try: self.num_records = int(float(record["nr_records"])) except ValueError: logging.warning( "Warning in PXIe5171: invalid nr_records selected: " + str(err)) self.num_records = 1 self.session.allow_more_records_than_memory = True self.session.configure_horizontal_timing(min_sample_rate=1000 * int(samplingRate_kSs), min_num_pts=self.num_samples, ref_position=0.0, num_records=2147483647, enforce_realtime=True) # set trigger configuration if trigger["trigger_type"] == "Edge": self.session.trigger_type = niscope.TriggerType.EDGE if trigger["trigger_type"] == "Immediate": self.session.trigger_type = niscope.TriggerType.IMMEDIATE if trigger['trigger_type'] == "Digital": self.session.trigger_type = niscope.TriggerType.DIGITAL self.session.trigger_source = edge["trigger_src"] if edge["trigger_slope"] == "Falling": self.session.trigger_slope = niscope.TriggerSlope.NEGATIVE elif edge["trigger_slope"] == "Rising": self.session.trigger_slope = niscope.TriggerSlope.POSITIVE try: self.session.trigger_level = float(edge["trigger_level"]) except (niscope.errors.DriverError, ValueError) as err: logging.warning( "Warning in PXIe5171: invalid trigger level selected: " + str(err)) self.session.trigger_level = 0.0 try: self.session.trigger_delay_time = float(trigger["trigger_delay"]) except (niscope.errors.DriverError, ValueError): logging.warning( "Warning in PXIe5171: invalid trigger delay selected: " + str(err)) self.session.trigger_delay_time = 0.0 # set channel configuration self.active_channels = [] for ch in [0, 1, 2, 3, 4, 5, 6, 7]: if bool(int(channels["enable"][ch])): self.active_channels.append(ch) try: range_V = float(channels["range"][ch][0:-2]) except ValueError as err: logging.warning( "Warning in PXIe5171: invalid range selected: " + str(err)) range_V = 5.0 if channels["coupling"][ch] == "AC": coupling_setting = niscope.VerticalCoupling.AC elif channels["coupling"][ch] == "DC": coupling_setting = niscope.VerticalCoupling.DC else: coupling_setting = niscope.VerticalCoupling.GND self.session.channels[ch].configure_vertical( range=range_V, coupling=coupling_setting) # specify active channels as attributes for HDF, etc. self.new_attributes = [ ("column_names", ", ".join(["ch" + str(x) for x in self.active_channels])), ("units", ", ".join(["binary" for x in self.active_channels])), ("sampling", str(1000 * samplingRate_kSs) + " [S/s]") ] # shape and type of the array of returned data self.shape = (self.num_records, len(self.active_channels), self.num_samples) self.dtype = np.int16 # index of which waveform to acquire self.rec_num = 0 self.trace_attrs = {} # start acquisition self.session.initiate()
def single_niscope_session(): with niscope.Session('', False, False, 'Simulate=1, DriverSetup=Model:5164;BoardType:PXIe' ) as simulated_session: yield simulated_session