def example(resource_name, options, voltage1, voltage2, delay):
    timeout = hightime.timedelta(seconds=(delay + 1.0))

    with nidcpower.Session(resource_name=resource_name,
                           options=options) as session:

        # Configure the session.
        session.source_mode = nidcpower.SourceMode.SINGLE_POINT
        session.output_function = nidcpower.OutputFunction.DC_VOLTAGE
        session.current_limit = .06
        session.voltage_level_range = 5.0
        session.current_limit_range = .06
        session.source_delay = hightime.timedelta(seconds=delay)
        session.measure_when = nidcpower.MeasureWhen.AUTOMATICALLY_AFTER_SOURCE_COMPLETE
        session.voltage_level = voltage1

        with session.initiate():
            channel_indices = '0-{0}'.format(session.channel_count - 1)
            channels = session.get_channel_names(channel_indices)
            for channel_name in channels:
                print('Channel: {0}'.format(channel_name))
                print('---------------------------------')
                print('Voltage 1:')
                print_fetched_measurements(
                    session.channels[channel_name].fetch_multiple(
                        count=1, timeout=timeout))
                session.voltage_level = voltage2  # on-the-fly set
                print('Voltage 2:')
                print_fetched_measurements(
                    session.channels[channel_name].fetch_multiple(
                        count=1, timeout=timeout))
                session.output_enabled = False
                print('')
def test_reset_with_defaults(session):
    deault_meas_time_histogram_high_time = session.meas_time_histogram_high_time
    assert deault_meas_time_histogram_high_time == hightime.timedelta(microseconds=500)
    session.meas_time_histogram_high_time = hightime.timedelta(microseconds=1000)
    non_default_meas_time_histogram_high_time = session.meas_time_histogram_high_time
    assert non_default_meas_time_histogram_high_time == hightime.timedelta(microseconds=1000)
    session.reset_device()
    assert session.meas_time_histogram_high_time == hightime.timedelta(microseconds=500)
示例#3
0
def test_datetime_utcoffset():
    assert datetime().utcoffset() is None
    assert (datetime(tzinfo=std_datetime.timezone.utc).utcoffset() ==
            std_datetime.timedelta())
    assert datetime(tzinfo=tzinfo(
        hours=1)).utcoffset() == std_datetime.timedelta(hours=1)
    assert datetime(tzinfo=std_datetime.timezone(hightime.timedelta(
        hours=1))).utcoffset() == hightime.timedelta(hours=1)
示例#4
0
def test_convert_timedeltas_to_seconds_real64():
    time_values = [10.5, -5e-10]
    test_result = convert_timedeltas_to_seconds_real64(time_values)
    assert all([actual.value == pytest.approx(expected) for actual, expected in zip(test_result, time_values)])
    assert all([isinstance(i, _visatype.ViReal64) for i in test_result])
    test_input = [hightime.timedelta(seconds=10.5), hightime.timedelta(nanoseconds=-0.5)]
    test_result = convert_timedeltas_to_seconds_real64(test_input)
    assert all([actual.value == pytest.approx(expected) for actual, expected in zip(test_result, time_values)])
    assert all([isinstance(i, _visatype.ViReal64) for i in test_result])
def example(resource_name, options, voltage_max, current_max,
            points_per_output_function, delay_in_seconds):
    timeout = hightime.timedelta(seconds=(delay_in_seconds + 1.0))

    with nidcpower.Session(resource_name=resource_name,
                           options=options) as session:

        # Configure the session.
        session.source_mode = nidcpower.SourceMode.SEQUENCE
        session.voltage_level_autorange = True
        session.current_limit_autorange = True
        session.source_delay = hightime.timedelta(seconds=delay_in_seconds)
        properties_used = ['output_function', 'voltage_level', 'current_level']
        session.create_advanced_sequence(sequence_name='my_sequence',
                                         property_names=properties_used,
                                         set_as_active_sequence=True)

        voltage_per_step = voltage_max / points_per_output_function
        for i in range(points_per_output_function):
            session.create_advanced_sequence_step(set_as_active_step=False)
            session.output_function = nidcpower.OutputFunction.DC_VOLTAGE
            session.voltage_level = voltage_per_step * i

        current_per_step = current_max / points_per_output_function
        for i in range(points_per_output_function):
            session.create_advanced_sequence_step(set_as_active_step=False)
            session.output_function = nidcpower.OutputFunction.DC_CURRENT
            session.current_level = current_per_step * i

        with session.initiate():
            session.wait_for_event(nidcpower.Event.SEQUENCE_ENGINE_DONE)
            channel_indices = '0-{0}'.format(session.channel_count - 1)
            channels = session.get_channel_names(channel_indices)
            measurement_group = [
                session.channels[name].fetch_multiple(
                    points_per_output_function * 2, timeout=timeout)
                for name in channels
            ]

        session.delete_advanced_sequence(sequence_name='my_sequence')
        line_format = '{:<15} {:<4} {:<10} {:<10} {:<6}'
        print(
            line_format.format('Channel', 'Num', 'Voltage', 'Current',
                               'In Compliance'))
        for i, measurements in enumerate(measurement_group):
            num = 0
            channel_name = channels[i].strip()
            for measurement in measurements:
                print(
                    line_format.format(channel_name, num, measurement.voltage,
                                       measurement.current,
                                       str(measurement.in_compliance)))
                num += 1
def test_reset_with_defaults(multi_instrument_session):
    deault_meas_time_histogram_high_time = multi_instrument_session.meas_time_histogram_high_time
    assert deault_meas_time_histogram_high_time == hightime.timedelta(
        microseconds=500)
    multi_instrument_session.meas_time_histogram_high_time = hightime.timedelta(
        microseconds=1000)
    non_default_meas_time_histogram_high_time = multi_instrument_session.meas_time_histogram_high_time
    assert non_default_meas_time_histogram_high_time == hightime.timedelta(
        microseconds=1000)
    multi_instrument_session.reset_device()
    assert multi_instrument_session.meas_time_histogram_high_time == hightime.timedelta(
        microseconds=500)
示例#7
0
def test_convert_timedelta_to_seconds_double():
    test_result = convert_timedelta_to_seconds_real64(hightime.timedelta(seconds=10))
    assert test_result.value == 10.0
    assert isinstance(test_result, _visatype.ViReal64)
    test_result = convert_timedelta_to_seconds_real64(hightime.timedelta(nanoseconds=-0.5))
    assert test_result.value == pytest.approx(-5e-10)
    assert isinstance(test_result, _visatype.ViReal64)
    test_result = convert_timedelta_to_seconds_real64(10.5)
    assert test_result.value == 10.5
    assert isinstance(test_result, _visatype.ViReal64)
    test_result = convert_timedelta_to_seconds_real64(-1)
    assert test_result.value == -1
    assert isinstance(test_result, _visatype.ViReal64)
示例#8
0
def test_convert_timedelta_to_milliseconds_int32():
    test_result = convert_timedelta_to_milliseconds_int32(hightime.timedelta(seconds=10))
    assert test_result.value == 10000
    assert isinstance(test_result, _visatype.ViInt32)
    test_result = convert_timedelta_to_milliseconds_int32(hightime.timedelta(seconds=-5))
    assert test_result.value == -5000
    assert isinstance(test_result, _visatype.ViInt32)
    test_result = convert_timedelta_to_milliseconds_int32(10.5)
    assert test_result.value == 10500
    assert isinstance(test_result, _visatype.ViInt32)
    test_result = convert_timedelta_to_milliseconds_int32(-1)
    assert test_result.value == -1000
    assert isinstance(test_result, _visatype.ViInt32)
示例#9
0
 def test_set_timedelta_as_timedelta(self):
     session = nitclk.SessionReference(SESSION_NUM_FOR_TEST)
     self.patched_library.niTClk_SetAttributeViReal64.side_effect = self.side_effects_helper.niTClk_SetAttributeViReal64
     attribute_id = 11
     test_number = 4.2
     session.sample_clock_delay = hightime.timedelta(seconds=test_number)
     self.patched_library.niTClk_SetAttributeViReal64.assert_called_once_with(_matchers.ViSessionMatcher(SESSION_NUM_FOR_TEST), _matchers.ViStringMatcher(''), _matchers.ViAttrMatcher(attribute_id), _matchers.ViReal64Matcher(test_number))
示例#10
0
    def wait_for_debounce(self,
                          maximum_time_ms=hightime.timedelta(milliseconds=-1)):
        r'''wait_for_debounce

        Waits for all of the switches in the NI Switch Executive virtual device
        to debounce. This method does not return until either the switching
        system is completely debounced and settled or the maximum time has
        elapsed and the system is not yet debounced. In the event that the
        maximum time elapses, the method returns an error indicating that a
        timeout has occurred. To ensure that all of the switches have settled,
        NI recommends calling wait_for_debounce after a series of connection
        or disconnection operations and before taking any measurements of the
        signals connected to the switching system.

        Args:
            maximum_time_ms (hightime.timedelta, datetime.timedelta, or int in milliseconds): The amount of time to wait (in milliseconds) for the debounce to
                complete. A value of 0 checks for debouncing once and returns an error
                if the system is not debounced at that time. A value of -1 means to
                block for an infinite period of time until the system is debounced.

        '''
        vi_ctype = _visatype.ViSession(self._vi)  # case S110
        maximum_time_ms_ctype = _converters.convert_timedelta_to_milliseconds_int32(
            maximum_time_ms)  # case S140
        error_code = self._library.niSE_WaitForDebounce(
            vi_ctype, maximum_time_ms_ctype)
        errors.handle_error(self,
                            error_code,
                            ignore_warnings=False,
                            is_error_handling=False)
        return
def test_fetch_array_measurement(multi_instrument_session,
                                 measurement_wfm_length):
    test_voltage = 1.0
    test_record_length = 1000
    test_num_channels = 2
    test_meas_wfm_length = measurement_wfm_length.passed_in
    test_array_meas_function = niscope.ArrayMeasurement.ARRAY_GAIN
    test_starting_record_number = 2
    test_num_records_to_acquire = 5
    test_num_records_to_fetch = test_num_records_to_acquire - test_starting_record_number
    multi_instrument_session.configure_vertical(test_voltage,
                                                niscope.VerticalCoupling.AC)
    multi_instrument_session.configure_horizontal_timing(
        50000000, test_record_length, 50.0, test_num_records_to_acquire, True)

    with multi_instrument_session.initiate():
        waveforms = multi_instrument_session.channels[
            test_channels].fetch_array_measurement(
                array_meas_function=test_array_meas_function,
                meas_wfm_size=test_meas_wfm_length,
                relative_to=niscope.FetchRelativeTo.PRETRIGGER,
                offset=5,
                record_number=test_starting_record_number,
                num_records=test_num_records_to_fetch,
                meas_num_samples=2000,
                timeout=hightime.timedelta(seconds=4))

    assert len(waveforms) == test_num_channels * test_num_records_to_fetch
    expected_channels = test_channels.split(',') * test_num_records_to_fetch
    expected_records = [2, 2, 3, 3, 4, 4]
    for i in range(len(waveforms)):
        assert len(waveforms[i].samples) == measurement_wfm_length.expected
        assert waveforms[i].channel == expected_channels[i]
        assert waveforms[i].record == expected_records[i]
示例#12
0
 def __hash__(self):
     t = self.replace(fold=0) if getattr(self, "fold", 0) else self
     offset = t.utcoffset()
     if offset is None:
         return hash((
             self.year,
             self.month,
             self.day,
             self.hour,
             self.minute,
             self.second,
             self.microsecond,
             self.femtosecond,
             self.yoctosecond,
         ))
     else:
         return hash(
             hightime.timedelta(
                 days=self.toordinal(),
                 hours=self.hour,
                 minutes=self.minute,
                 seconds=self.second,
                 microseconds=self.microsecond,
                 femtoseconds=self.femtosecond,
                 yoctoseconds=self.yoctosecond,
             ) - offset)
def test_fetch_measurement_stats(multi_instrument_session):
    test_voltage = 1.0
    test_record_length = 1000
    test_num_channels = 2
    test_num_records = 3
    test_starting_record_number = 2
    test_num_records_to_acquire = 5
    test_num_records_to_fetch = test_num_records_to_acquire - test_starting_record_number
    multi_instrument_session.configure_vertical(test_voltage,
                                                niscope.VerticalCoupling.AC)
    multi_instrument_session.configure_horizontal_timing(
        50000000, test_record_length, 50.0, test_num_records_to_acquire, True)
    with multi_instrument_session.initiate():
        measurement_stats = multi_instrument_session.channels[
            test_channels].fetch_measurement_stats(
                scalar_meas_function=niscope.enums.ScalarMeasurement.
                NO_MEASUREMENT,
                relative_to=niscope.FetchRelativeTo.PRETRIGGER,
                offset=5,
                record_number=test_starting_record_number,
                num_records=test_num_records_to_fetch,
                timeout=hightime.timedelta(seconds=4))

    assert len(measurement_stats) == test_num_channels * test_num_records
    expected_channels = test_channels.split(',') * test_num_records_to_fetch
    expected_records = [2, 2, 3, 3, 4, 4]
    for i in range(len(measurement_stats)):
        assert measurement_stats[i].result == 0.0
        assert measurement_stats[i].channel == expected_channels[i]
        assert measurement_stats[i].record == expected_records[i]
示例#14
0
    def __add__(self, other):
        "Add a datetime and a timedelta."
        if not isinstance(other, std_datetime.timedelta):
            return NotImplemented

        delta = hightime.timedelta(
            self.toordinal(),
            hours=self.hour,
            minutes=self.minute,
            seconds=self.second,
            microseconds=self.microsecond,
            femtoseconds=self.femtosecond,
            yoctoseconds=self.yoctosecond,
        )
        delta += other
        if 0 < delta.days <= datetime.max.toordinal():
            date = std_datetime.date.fromordinal(delta.days)
            hour, minute = divmod(delta.seconds, 3600)
            minute, second = divmod(minute, 60)

            return datetime(
                date.year,
                date.month,
                date.day,
                hour,
                minute,
                second,
                delta.microseconds,
                delta.femtoseconds,
                delta.yoctoseconds,
                tzinfo=self.tzinfo,
            )

        raise OverflowError("result out of range")
示例#15
0
    def __sub__(self, other):
        "Subtract two datetimes, or a datetime and a timedelta."
        if not isinstance(other, std_datetime.datetime):
            if isinstance(other, std_datetime.timedelta):
                return self + -other
            return NotImplemented

        base = hightime.timedelta(
            days=self.toordinal() - other.toordinal(),
            hours=self.hour - other.hour,
            minutes=self.minute - other.minute,
            seconds=self.second - other.second,
            microseconds=self.microsecond - other.microsecond,
            femtoseconds=self.femtosecond - getattr(other, "femtosecond", 0),
            yoctoseconds=self.yoctosecond - getattr(other, "yoctosecond", 0),
        )
        if self.tzinfo is other.tzinfo:
            return base

        my_offset = self.utcoffset()
        other_offset = other.utcoffset()

        if my_offset == other_offset:
            return base

        if my_offset is None or other_offset is None:
            raise TypeError("cannot mix naive and timezone-aware time")

        return base + other_offset - my_offset
示例#16
0
 def test_synchronize_timedelta(self):
     min_time = hightime.timedelta(seconds=0.042)
     self.patched_library.niTClk_Synchronize.side_effect = self.side_effects_helper.niTClk_Synchronize
     nitclk.synchronize(multiple_session_references, min_time)
     self.patched_library.niTClk_Synchronize.assert_called_once_with(
         _matchers.ViUInt32Matcher(len(multiple_sessions)),
         _matchers.ViSessionBufferMatcher(multiple_sessions),
         _matchers.ViReal64Matcher(min_time.total_seconds()))
     return
示例#17
0
def test_fetch_waveform_error(session):
    number_of_points_to_read = 100
    try:
        session.configure_waveform_acquisition(nidmm.Function.WAVEFORM_VOLTAGE, 10, 1800000, number_of_points_to_read)
        with session.initiate():
            session.fetch_waveform(number_of_points_to_read * 2, maximum_time=hightime.timedelta(milliseconds=1))   # trying to fetch points more than configured
            assert False
    except nidmm.Error as e:
        assert e.code == -1074126845  # Max Time exceeded before operation completed
示例#18
0
def example(resource_name, channels, options, steps, voltage_start,
            voltage_final, current_start, current_final):

    # The Python API should provide these values. But it doesn't. Issue #504. For now, put magic values here.
    attribute_ids = [
        1150008,  # output_function
        1250001,  # voltage_level
        1150009,  # current_level
    ]

    with nidcpower.Session(resource_name=resource_name,
                           channels=channels,
                           options=options) as session:

        session.source_mode = nidcpower.SourceMode.SEQUENCE
        session.source_delay = hightime.timedelta(seconds=0.1)
        session.voltage_level_autorange = True
        session.current_level_autorange = True
        session._create_advanced_sequence(sequence_name='my_sequence',
                                          attribute_ids=attribute_ids)
        voltages = create_sweep(voltage_start, voltage_final, steps)
        currents = create_sweep(current_start, current_final, steps)

        for v in voltages:
            session._create_advanced_sequence_step()
            session.output_function = nidcpower.OutputFunction.DC_VOLTAGE
            session.voltage_level = v

        for c in currents:
            session._create_advanced_sequence_step()
            session.output_function = nidcpower.OutputFunction.DC_CURRENT
            session.current_level = c

        with session.initiate():
            session.wait_for_event(nidcpower.Event.SEQUENCE_ENGINE_DONE)
            measurements = session.fetch_multiple(count=steps * 2)

        # Print a table with the measurements
        programmed_levels = voltages + currents
        units = ['V'] * steps + ['A'] * steps
        row_format = '{:<8} {:4} {:<25} {:<25} {}'
        print(
            row_format.format('Sourced', '', 'Measured voltage',
                              'Measured current', 'In-compliance'))
        for i in range(steps * 2):
            print(
                row_format.format(programmed_levels[i], units[i],
                                  measurements[i].voltage,
                                  measurements[i].current,
                                  measurements[i].in_compliance))
def example(resource_name, channels, options, voltage1, voltage2, delay):
    timeout = hightime.timedelta(seconds=(delay + 1.0))

    with nidcpower.Session(resource_name=resource_name,
                           channels=channels,
                           options=options) as session:
        while True:

            # Configure the session.
            session.source_mode = nidcpower.SourceMode.SINGLE_POINT
            session.output_function = nidcpower.OutputFunction.DC_VOLTAGE

            session.current_limit = .06
            session.voltage_level_range = 5.0
            session.current_limit_range = .9
            session.source_delay = hightime.timedelta(seconds=delay)
            session.measure_when = nidcpower.MeasureWhen.AUTOMATICALLY_AFTER_SOURCE_COMPLETE
            session.voltage_level = voltage1
            with session.initiate():
                session.output_enabled = True
                session.output_connected = True
                print("V1:")
                print_fetched_measurements(
                    session.fetch_multiple(count=1, timeout=timeout))
示例#20
0
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
示例#21
0
def convert_month_to_timedelta(months):
    return hightime.timedelta(days=(30.4167 * months))
示例#22
0
def convert_seconds_real64_to_timedelta(value):
    return hightime.timedelta(seconds=value)
示例#23
0
def timedelta(*args, **kwargs):
    """Instantiate a hightime.timedelta, allowing unit shorthand kwargs"""

    _replace(kwargs, plural=True)
    return hightime.timedelta(*args, **kwargs)
示例#24
0
def test_wait_until_done(session):
    session.wait_until_done(hightime.timedelta(milliseconds=20))
示例#25
0
 def __get__(self, session, session_type):
     return hightime.timedelta(seconds=session._get_attribute_vi_real64(self._attribute_id))
示例#26
0
 def __get__(self, session, session_type):
     return hightime.timedelta(milliseconds=session._get_attribute_vi_int32(self._attribute_id))
示例#27
0
def test_vi_real64_attribute(session):
    session.settling_time = hightime.timedelta(seconds=0.1)
    assert session.settling_time.total_seconds() == 0.1
def test_wait_for_event_with_timeout(session):
    with session.initiate():
        session.wait_for_event(nidcpower.Event.SOURCE_COMPLETE,
                               hightime.timedelta(seconds=0.5))