diff --git a/pslab/instrument/buffer.py b/pslab/instrument/buffer.py index a2a5cdb..a2aa331 100644 --- a/pslab/instrument/buffer.py +++ b/pslab/instrument/buffer.py @@ -6,6 +6,12 @@ class ADCBufferMixin: """Mixin for classes that need to read or write to the ADC buffer.""" + def _get_buffer_generation(self) -> int: + return getattr(self._device, "_adc_buffer_generation", 0) + + def _mark_buffer_write(self): + self._device._adc_buffer_generation = self._get_buffer_generation() + 1 + def fetch_buffer(self, samples: int, starting_position: int = 0): """Fetch a section of the ADC buffer. @@ -51,6 +57,8 @@ def clear_buffer(self, samples: int, starting_position: int = 0): Location in the ADC buffer to start from. By default samples will be cleared from the beginning of the buffer. """ + if samples: + self._mark_buffer_write() self._device.send_byte(CP.COMMON) self._device.send_byte(CP.CLEAR_BUFFER) self._device.send_int(starting_position) @@ -71,6 +79,8 @@ def fill_buffer(self, data: list[int], starting_position: int = 0): buf_size = 128 idx = starting_position remaining = len(data) + if remaining: + self._mark_buffer_write() while remaining > 0: self._device.send_byte(CP.COMMON) diff --git a/pslab/instrument/logic_analyzer.py b/pslab/instrument/logic_analyzer.py index 8888034..553dc1c 100644 --- a/pslab/instrument/logic_analyzer.py +++ b/pslab/instrument/logic_analyzer.py @@ -58,6 +58,7 @@ def __init__(self, device: ConnectionHandler | None = None): self._channel_one_map = "LA1" self._channel_two_map = "LA2" self._trimmed = 0 + self._pulse_count_capture = None def measure_frequency( self, channel: str, simultaneous_oscilloscope: bool = False, timeout: float = 1 @@ -713,12 +714,22 @@ def get_states(self) -> Dict[str, bool]: } def count_pulses( - self, channel: str = "FRQ", interval: float = 1, block: bool = True + self, + channel: str = "FRQ", + interval: float = 1, + timeout: float = 1, + *, + block: bool = True, ) -> Union[int, None]: """Count pulses on a digital input. - The counter is 16 bits, so it will roll over after 65535 pulses. This - method can be used at the same time as the oscilloscope. + The number of pulses is calculated from the period of the signal, which + is measured by capturing logic events. This method cannot be used at the + same time as the oscilloscope. The signal must be slow enough for the + capture to resolve the time between two events, and fast enough for two + events to be captured within the timeout. Captures lasting a full + 32-bit counter cycle (about 67 seconds) return 0 because the number of + wraps between events cannot be determined. Parameters ---------- @@ -727,46 +738,118 @@ def count_pulses( interval : float, optional Time in seconds during which to count pulses. The default value is 1 second. + timeout : float, optional + Timeout in seconds before cancelling a blocking capture. The default + value is 1 second. It does not delay a nonblocking call. A boolean + in this position is treated as the original API's blocking flag. block : bool, optional - Whether to block while counting pulses or not. If False, this - method will return None, and the pulses must be manually fetched - using :meth:`fetch_pulse_count`. Additionally, the interval - argument has no meaning if block is False; the counter will keep - counting even after the interval time has expired. The default - value is True. + If False, return None without waiting for capture. Use + :meth:`fetch_pulse_count` to estimate pulses since this call; the + interval argument is ignored in that case. The default is True. Returns ------- Union[int, None] - Number of pulses counted during the interval, or None if block is - False. + Estimated number of pulses, or 0 if the signal cannot be measured. + Return None if block is False. + + Raises + ------ + ValueError if the interval is negative. """ - self._reset_prescaler() - self._device.send_byte(CP.COMMON) - self._device.send_byte(CP.START_COUNTING) - self._device.send_byte(self._channels[channel].number) - self._device.get_ack() + if isinstance(timeout, bool): + # The original API used the third argument as the blocking flag. + block, timeout = timeout, 1 + if interval < 0: + raise ValueError("Interval cannot be negative.") + + self._pulse_count_capture = None + started = time.monotonic() + tmp = self._channel_one_map + self._channel_one_map = channel + try: + timestamps = self.capture( + channel, 2, modes=["sixteen rising"], block=block, timeout=timeout + ) + finally: + self._channel_one_map = tmp - if block: - time.sleep(interval) - else: - return + if not block: + self._pulse_count_capture = ( + channel, + started, + self._get_buffer_generation(), + ) + return None - return self.fetch_pulse_count() + return self._count_pulses_from_timestamps( + timestamps[0], interval, time.monotonic() - started + ) def fetch_pulse_count(self) -> int: - """Return the number of pulses counted since calling :meth:`count_pulses`. + """Estimate pulses since starting a nonblocking pulse count. + + The estimate uses the measured period and elapsed time, not a firmware + counter. Fetching does not wait for another event or stop the capture. + The signal must remain periodic. A capture, buffer clear, or buffer fill + on any instrument sharing this connection invalidates the pending count. + This method cannot run alongside the oscilloscope. Fetch within one + 32-bit counter cycle (about 67 seconds) of starting the count; later + fetches return 0 because multiple counter wraps cannot be ruled out, + even if an earlier fetch succeeded. Returns ------- int - Number of pulses counted since calling :meth:`count_pulses`. + Estimated pulse count, or 0 if two distinct events are unavailable. + + Raises + ------ + RuntimeError + If no nonblocking pulse count is active. """ - self._device.send_byte(CP.COMMON) - self._device.send_byte(CP.FETCH_COUNT) - count = self._device.get_int() - self._device.get_ack() - return count + if self._pulse_count_capture is None: + raise RuntimeError("No nonblocking pulse count is active.") + + channel, started, generation = self._pulse_count_capture + if generation != self._get_buffer_generation(): + self._pulse_count_capture = None + raise RuntimeError("No nonblocking pulse count is active.") + + tmp = self._channel_one_map + self._channel_one_map = channel + try: + timestamps = self.fetch_data()[0] + finally: + self._channel_one_map = tmp + + elapsed = time.monotonic() - started + return self._count_pulses_from_timestamps(timestamps, elapsed, elapsed) + + @staticmethod + def _count_pulses_from_timestamps( + timestamps: np.ndarray, interval: float, capture_duration: float + ) -> int: + # After a full counter cycle, even an increasing pair may hide wraps. + if capture_duration >= 2**32 / CP.CLOCK_RATE: + return 0 + + try: + # Sixteen rising edges are captured, so the time between two + # captured events covers 16 periods of the signal. + delta = timestamps[1] - timestamps[0] + if delta < 0: + # The capture counter is 32 bits and wraps after 67 seconds, + # so the difference has to be taken modulo its range. + delta += 2**32 / CP.CLOCK_RATE * 1e6 + period = delta * 1e-6 / 16 + except IndexError: + return 0 + + if period <= 0: + return 0 + + return int(round(interval / period)) def _reset_prescaler(self): self._device.send_byte(CP.TIMING) @@ -780,6 +863,7 @@ def _reset_prescaler(self): self._prescaler = 0 def _invalidate_buffer(self): + self._pulse_count_capture = None for c in self._channels.values(): c.events_in_buffer = 0 c.buffer_idx = None diff --git a/pslab/instrument/oscilloscope.py b/pslab/instrument/oscilloscope.py index b8d3e30..32db95b 100644 --- a/pslab/instrument/oscilloscope.py +++ b/pslab/instrument/oscilloscope.py @@ -186,6 +186,7 @@ def _lookup_mininum_timegap(self, channels: int) -> float: return min_timegaps[channels_idx[channels]][self.trigger_enabled] def _capture(self, channels: int, samples: int, timegap: float): + self._mark_buffer_write() self._invalidate_buffer() chosa = self._channels[self._channel_one_map].chosa self._channels[self._channel_one_map].resolution = 10 diff --git a/tests/test_logic_analyzer.py b/tests/test_logic_analyzer.py index 550a929..8fb6b7c 100644 --- a/tests/test_logic_analyzer.py +++ b/tests/test_logic_analyzer.py @@ -16,9 +16,9 @@ import pslab.protocol as CP from pslab.instrument.logic_analyzer import LogicAnalyzer +from pslab.instrument.oscilloscope import Oscilloscope from pslab.instrument.waveform_generator import PWMGenerator - EVENTS = 2495 FREQUENCY = 1e5 DUTY_CYCLE = 0.5 @@ -280,3 +280,336 @@ def test_count_pulses(la): pulses = la.count_pulses("LA2", interval) expected_pulses = FREQUENCY * interval assert expected_pulses == pytest.approx(pulses, rel=0.1) # Pretty bad accuracy. + + +# The tests below use a stand-in transport and do not need a connected PSLab. + + +class FakeDevice: + """Stand-in for a SerialHandler, recording the commands it receives.""" + + def __init__(self): + self.commands = [] + + def send_byte(self, value): + self.commands.append(value) + + def send_int(self, value): + self.commands.append(value) + + def get_ack(self): + return True + + def get_byte(self): + return 0 + + def get_int(self): + return 0 + + +def test_count_pulses_from_the_measured_period(mocker): + la = LogicAnalyzer(FakeDevice()) + # A 100 kHz signal, sampled every 16th rising edge. + mocker.patch.object(la, "capture", return_value=[np.array([0, 160])]) + assert la.count_pulses("LA2", 0.2) == FREQUENCY * 0.2 + + +@pytest.mark.parametrize("timestamps", [np.array([]), np.array([500, 500])]) +def test_count_pulses_without_a_measurable_period(mocker, timestamps): + la = LogicAnalyzer(FakeDevice()) + mocker.patch.object(la, "capture", return_value=[timestamps]) + assert la.count_pulses("LA2", 0.2) == 0 + + +def test_count_pulses_does_not_use_the_firmware_counter(mocker): + device = FakeDevice() + la = LogicAnalyzer(device) + mocker.patch.object(la, "capture", return_value=[np.array([0, 160])]) + la.count_pulses("LA2", 0.2) + assert CP.START_COUNTING not in device.commands + assert CP.FETCH_COUNT not in device.commands + + +def capture_updating_the_channel_map(la, timestamps): + """Stand-in for capture(), which maps a channel name to channel one.""" + + def capture(channels, events, **kwargs): + la._check_arguments(channels, events) + return [timestamps] + + return capture + + +def test_count_pulses_restores_the_channel_map(mocker): + la = LogicAnalyzer(FakeDevice()) + mocker.patch.object( + la, + "capture", + side_effect=capture_updating_the_channel_map(la, np.array([0, 160])), + ) + assert la.count_pulses("LA2", 0.2) == FREQUENCY * 0.2 + assert la._channel_one_map == "LA1" + + +def test_count_pulses_restores_the_channel_map_when_capture_fails(mocker): + la = LogicAnalyzer(FakeDevice()) + + def capture(channels, events, **kwargs): + la._check_arguments(channels, events) + raise ValueError("capture failed") + + mocker.patch.object(la, "capture", side_effect=capture) + with pytest.raises(ValueError): + la.count_pulses("LA2", 0.2) + assert la._channel_one_map == "LA1" + + +def test_count_pulses_rejects_a_negative_interval(mocker): + la = LogicAnalyzer(FakeDevice()) + capture = mocker.patch.object(la, "capture", return_value=[np.array([0, 160])]) + with pytest.raises(ValueError): + la.count_pulses("LA2", -0.2) + assert not capture.called + + +@pytest.mark.parametrize("timeout", [0, 0.05, 1]) +def test_count_pulses_keeps_the_positional_timeout(mocker, timeout): + la = LogicAnalyzer(FakeDevice()) + capture = mocker.patch.object(la, "capture", return_value=[np.array([0, 160])]) + + assert la.count_pulses("LA2", 0.2, timeout) == 20000 + assert capture.call_args.kwargs["timeout"] == timeout + assert capture.call_args.kwargs["block"] is True + + +def test_count_pulses_keeps_the_nonblocking_api(mocker): + la = LogicAnalyzer(FakeDevice()) + capture = mocker.patch.object(la, "capture", return_value=None) + clock = mocker.patch( + "pslab.instrument.logic_analyzer.time.monotonic", return_value=10 + ) + + assert la.count_pulses("LA2", 0.1, False) is None + assert capture.call_args.kwargs["block"] is False + + fetch = mocker.patch.object(la, "fetch_data", return_value=[np.array([0, 160])]) + clock.return_value = 10.2 + assert la.fetch_pulse_count() == 20000 + fetch.assert_called_once_with() + assert la._channel_one_map == "LA1" + + +def test_nonblocking_pulse_capture_returns_before_fetching(mocker): + la = LogicAnalyzer(FakeDevice()) + clock = mocker.patch( + "pslab.instrument.logic_analyzer.time.monotonic", return_value=10 + ) + fetch = mocker.patch.object(la, "fetch_data", return_value=[np.array([0, 160])]) + + assert la.count_pulses("LA2", block=False) is None + fetch.assert_not_called() + assert la._channel_one_map == "LA1" + + def fetched_channel(): + assert la._channel_one_map == "LA2" + return [np.array([0, 160])] + + fetch.side_effect = fetched_channel + clock.return_value = 10.2 + assert la.fetch_pulse_count() == 20000 + clock.return_value = 10.4 + assert la.fetch_pulse_count() == 40000 + assert la._channel_one_map == "LA1" + + +@pytest.mark.parametrize( + "timestamps", [np.array([]), np.array([160]), np.array([160, 160])] +) +def test_nonblocking_pulse_fetch_waits_for_a_measurable_period(mocker, timestamps): + la = LogicAnalyzer(FakeDevice()) + mocker.patch.object(la, "capture", return_value=None) + la.count_pulses("LA2", block=False) + mocker.patch.object(la, "fetch_data", return_value=[timestamps]) + assert la.fetch_pulse_count() == 0 + + +def test_nonblocking_pulse_fetch_restores_channel_map_after_error(mocker): + la = LogicAnalyzer(FakeDevice()) + mocker.patch.object(la, "capture", return_value=None) + la.count_pulses("LA2", block=False) + mocker.patch.object(la, "fetch_data", side_effect=OSError("read failed")) + with pytest.raises(OSError, match="read failed"): + la.fetch_pulse_count() + assert la._channel_one_map == "LA1" + + +def test_nonblocking_pulse_capture_failure_leaves_no_pending_count(mocker): + la = LogicAnalyzer(FakeDevice()) + capture = mocker.patch.object(la, "capture", return_value=None) + la.count_pulses("LA2", block=False) + capture.side_effect = OSError("capture failed") + with pytest.raises(OSError, match="capture failed"): + la.count_pulses("LA3", block=False) + with pytest.raises(RuntimeError, match="No nonblocking pulse count is active"): + la.fetch_pulse_count() + assert la._channel_one_map == "LA1" + + +def test_another_capture_invalidates_the_pending_pulse_count(mocker): + la = LogicAnalyzer(FakeDevice()) + la.count_pulses("LA2", block=False) + + la.capture("LA3", events=2, block=False) + + with pytest.raises(RuntimeError, match="No nonblocking pulse count is active"): + la.fetch_pulse_count() + + +def test_count_pulses_across_a_counter_rollover(mocker): + la = LogicAnalyzer(FakeDevice()) + # Same 100 kHz signal, but the second event is seen after the 32-bit + # capture counter has wrapped. + wrap = 2**32 / CP.CLOCK_RATE * 1e6 + mocker.patch.object(la, "capture", return_value=[np.array([wrap - 80, 80])]) + assert la.count_pulses("LA2", 0.2) == FREQUENCY * 0.2 + + +@pytest.mark.parametrize("writer", ["same_analyzer", "other_analyzer", "scope"]) +@pytest.mark.parametrize("operation", ["fill", "clear", "capture"]) +def test_buffer_writers_invalidate_the_pending_pulse_count(mocker, writer, operation): + device = FakeDevice() + la = LogicAnalyzer(device) + la.count_pulses("LA2", block=False) + mocker.patch.object(la, "fetch_data", return_value=[np.array([0, 160])]) + if writer == "same_analyzer": + instrument = la + elif writer == "other_analyzer": + instrument = LogicAnalyzer(device) + else: + instrument = Oscilloscope(device) + + if operation == "fill": + instrument.fill_buffer([1, 2, 3, 4]) + elif operation == "clear": + instrument.clear_buffer(4) + elif writer == "scope": + instrument.capture(1, 4, 1, block=False) + else: + instrument.capture("LA3", events=2, block=False) + + with pytest.raises(RuntimeError, match="No nonblocking pulse count is active"): + la.fetch_pulse_count() + + +@pytest.mark.parametrize( + "operation", ["read", "empty_fill", "empty_clear", "other_device_write"] +) +def test_buffer_operations_preserve_an_unmodified_pulse_capture(mocker, operation): + device = FakeDevice() + la = LogicAnalyzer(device) + clock = mocker.patch( + "pslab.instrument.logic_analyzer.time.monotonic", return_value=10 + ) + la.count_pulses("LA2", block=False) + mocker.patch.object(la, "fetch_data", return_value=[np.array([0, 160])]) + other = LogicAnalyzer(device) + + if operation == "read": + other.fetch_buffer(4) + elif operation == "empty_fill": + other.fill_buffer([]) + elif operation == "empty_clear": + other.clear_buffer(0) + else: + LogicAnalyzer(FakeDevice()).fill_buffer([1, 2, 3, 4]) + + clock.return_value = 10.2 + assert la.fetch_pulse_count() == 20000 + + +@pytest.mark.parametrize("operation", ["fill", "clear", "capture"]) +def test_failed_buffer_writes_invalidate_the_pending_pulse_count(mocker, operation): + device = FakeDevice() + la = LogicAnalyzer(device) + la.count_pulses("LA2", block=False) + scope = Oscilloscope(device) + # Bypass PGA setup so the failed ACK belongs to the buffer-writing command. + mocker.patch.object(scope, "_set_gain") + mocker.patch.object(device, "get_ack", side_effect=OSError("ack failed")) + mocker.patch.object(la, "fetch_data", return_value=[np.array([0, 160])]) + + with pytest.raises(OSError, match="ack failed"): + if operation == "fill": + scope.fill_buffer([1, 2, 3, 4]) + elif operation == "clear": + scope.clear_buffer(4) + else: + scope.capture(1, 4, 1, block=False) + + with pytest.raises(RuntimeError, match="No nonblocking pulse count is active"): + la.fetch_pulse_count() + + +@pytest.mark.parametrize("block", [False, True]) +def test_pulse_count_rejects_ambiguous_long_gap(mocker, block): + la = LogicAnalyzer(FakeDevice()) + clock = mocker.patch( + "pslab.instrument.logic_analyzer.time.monotonic", return_value=10 + ) + wrap = 2**32 / CP.CLOCK_RATE + # A 0.1 Hz signal has 160 seconds between every 16th rising edge. + timestamps = np.array([1, (161 % wrap)]) * 1e6 + + def capture(*args, **kwargs): + clock.return_value = 171 + return [timestamps] if block else None + + mocker.patch.object(la, "capture", side_effect=capture) + mocker.patch.object(la, "fetch_data", return_value=[timestamps]) + result = la.count_pulses("LA2", interval=161, timeout=200, block=block) + if not block: + result = la.fetch_pulse_count() + assert result == 0 + + +@pytest.mark.parametrize("block", [False, True]) +@pytest.mark.parametrize("offset", [-1e-6, 0, 1e-6]) +def test_pulse_count_bounds_capture_duration_not_count_interval(mocker, block, offset): + la = LogicAnalyzer(FakeDevice()) + clock = mocker.patch( + "pslab.instrument.logic_analyzer.time.monotonic", return_value=0 + ) + elapsed = 2**32 / CP.CLOCK_RATE + offset + timestamps = np.array([100, 260]) + + def capture(*args, **kwargs): + if block: + clock.return_value = elapsed + return [timestamps] + + def fetch(): + # The duration check must include time spent retrieving timestamps. + clock.return_value = elapsed + return [timestamps] + + mocker.patch.object(la, "capture", side_effect=capture) + mocker.patch.object(la, "fetch_data", side_effect=fetch) + result = la.count_pulses("LA2", interval=1000, block=block) + if not block: + result = la.fetch_pulse_count() + expected = round((1000 if block else elapsed) * FREQUENCY) if offset < 0 else 0 + assert result == expected + assert la._channel_one_map == "LA1" + + +def test_repeated_pulse_fetch_rejects_a_later_ambiguous_capture(mocker): + la = LogicAnalyzer(FakeDevice()) + clock = mocker.patch( + "pslab.instrument.logic_analyzer.time.monotonic", return_value=0 + ) + la.count_pulses("LA2", block=False) + mocker.patch.object(la, "fetch_data", return_value=[np.array([100, 260])]) + clock.return_value = 0.2 + assert la.fetch_pulse_count() == 20000 + clock.return_value = 160 + assert la.fetch_pulse_count() == 0