diff --git a/ophyd_devices/sim/sim_monitor.py b/ophyd_devices/sim/sim_monitor.py index c034c0f..7bf64ad 100644 --- a/ophyd_devices/sim/sim_monitor.py +++ b/ophyd_devices/sim/sim_monitor.py @@ -9,7 +9,7 @@ from ophyd import Device, Kind, StatusBase from ophyd_devices.interfaces.base_classes.psi_device_base import PSIDeviceBase from ophyd_devices.sim.sim_data import SimulatedDataMonitor -from ophyd_devices.sim.sim_signals import ReadOnlySignal, SetableSignal +from ophyd_devices.sim.sim_signals import AsyncUpdateSignal, ReadOnlySignal, SetableSignal from ophyd_devices.utils import bec_utils from ophyd_devices.utils.bec_signals import AsyncSignal, ProgressSignal @@ -129,7 +129,7 @@ class SimMonitorAsyncControl(Device): readback = Cpt(ReadOnlySignal, value=BIT_DEPTH(0), kind=Kind.hinted, compute_readback=True) current_trigger = Cpt(SetableSignal, value=BIT_DEPTH(0), kind=Kind.config) - async_update = Cpt(SetableSignal, value="extend", kind=Kind.config) + async_update = Cpt(AsyncUpdateSignal, value="add", kind=Kind.config) data = Cpt(AsyncSignal, ndim=1, max_size=1000, doc="Buffered asynchronous readings") progress = Cpt(ProgressSignal, doc="Scan progress") @@ -168,7 +168,12 @@ class SimMonitorAsync(PSIDeviceBase, SimMonitorAsyncControl): A simulated device to mimic the behaviour of an asynchronous monitor. During a scan, this device will send data not in sync with the point ID to BEC, - but buffer data and send it in random intervals.s + but buffer data and send it at random intervals. + + ``async_update`` selects how buffered readings are stored: ``add`` extends a + flat stream, ``add_slice`` assembles the chunks into row zero of the scan's + dataset, and ``replace`` retains the latest chunk. All modes preserve the + timestamp of each reading. """ def __init__( @@ -213,13 +218,19 @@ class SimMonitorAsync(PSIDeviceBase, SimMonitorAsyncControl): def _send_data_to_bec(self) -> None: """Emit buffered readings through the asynchronous data signal.""" async_update = self.async_update.get() - if async_update not in ["extend", "append"]: + if async_update == "add": + update = {"type": "add", "max_shape": [None]} + elif async_update == "add_slice": + update = {"type": "add_slice", "max_shape": [None, None], "index": 0} + elif async_update == "replace": + update = {"type": "replace"} + else: raise ValueError(f"Invalid async_update value for device {self.name}: {async_update}") self.data.put( self.data_buffer["value"].copy(), - timestamp=self.data_buffer["timestamp"][-1], - async_update={"type": "add", "max_shape": [None]}, + timestamp=self.data_buffer["timestamp"].copy(), + async_update=update, ) self.clear_buffer() diff --git a/ophyd_devices/sim/sim_signals.py b/ophyd_devices/sim/sim_signals.py index a9c1b16..25d3fb6 100644 --- a/ophyd_devices/sim/sim_signals.py +++ b/ophyd_devices/sim/sim_signals.py @@ -139,6 +139,15 @@ class SetableSignal(Signal): self._active_callbacks.remove(sub_type) +class AsyncUpdateSignal(SetableSignal): + """Select how asynchronous simulator data updates the current dataset.""" + + def check_value(self, value, **kwargs) -> None: + """Accept the update modes supported by BEC asynchronous signals.""" + if value not in ["add", "add_slice", "replace"]: + raise ValueError(f"Invalid async_update type: {value} for signal {self.name}") + + class ReadOnlySignal(Signal): """Computed readback signal for simulated devices. diff --git a/ophyd_devices/sim/sim_waveform.py b/ophyd_devices/sim/sim_waveform.py index c1d6394..3beacf0 100644 --- a/ophyd_devices/sim/sim_waveform.py +++ b/ophyd_devices/sim/sim_waveform.py @@ -13,7 +13,7 @@ from ophyd import Device, DeviceStatus, Kind, Staged from typeguard import typechecked from ophyd_devices.sim.sim_data import SimulatedDataWaveform -from ophyd_devices.sim.sim_signals import SetableSignal +from ophyd_devices.sim.sim_signals import AsyncUpdateSignal, SetableSignal from ophyd_devices.utils import bec_utils from ophyd_devices.utils.bec_signals import AsyncMultiSignal, AsyncSignal, ProgressSignal from ophyd_devices.utils.errors import DeviceStopError @@ -21,31 +21,6 @@ from ophyd_devices.utils.errors import DeviceStopError logger = bec_logger.logger -class AsyncUpdateSignal(SetableSignal): - """Async updated signal, with check for async_update type.""" - - def check_value(self, value, **kwargs) -> None: - """Check the value of the async_update signal.""" - if value not in ["add_slice", "add"]: - raise ValueError(f"Invalid async_update type: {value} for signal {self.name}") - - # FIXME: BEC issue #443 remove this method once tests in BEC are updated. - def put(self, value: Any) -> None: - """Put the value of the async_update signal.""" - if value in ["append", "extend"]: - if value == "append": - logger.warning( - f"Deprecated async_update of type {value} for signal {self.name}, falling back to 'add_slice'" - ) - value = "add_slice" - elif value == "extend": - logger.warning( - f"Deprecated async_update of type {value} for signal {self.name}, falling back to 'add'" - ) - value = "add" - super().put(value) - - class SimWaveform(Device): """A simulated device mimic any 1D Waveform detector. @@ -87,7 +62,7 @@ class SimWaveform(Device): acquisition_group="monitored", ) data = Cpt(AsyncSignal, name="data", ndim=1, max_size=1000) - # Can be extend or append + # add extends the stream, add_slice assembles waveforms, replace keeps the latest waveform. async_update = Cpt(AsyncUpdateSignal, value="add", kind=Kind.config) progress = Cpt(ProgressSignal, name="progress") async_multi_data = Cpt( @@ -116,8 +91,6 @@ class SimWaveform(Device): else: self.device_manager = bec_utils.DMMock() - self.connector = self.device_manager.connector - self._stream_ttl = 1800 # 30 min max self.stopped = False self._staged = Staged.no self._trigger_thread = None @@ -178,7 +151,7 @@ class SimWaveform(Device): raise DeviceStopError(f"{self.name} was stopped") self._slice_index += 1 # option add - elif self.async_update.get() == "add": + elif self.async_update.get() in ["add", "replace"]: self._send_async_update(value=values) else: # This should never happen, but just in case @@ -224,6 +197,8 @@ class SimWaveform(Device): async_update = {"type": "add", "max_shape": [None, waveform_shape]} elif async_update_type == "add": async_update = {"type": "add", "max_shape": [None]} + elif async_update_type == "replace": + async_update = {"type": "replace"} else: raise ValueError( f"Invalid async_update type: {async_update_type} for device {self.name}" diff --git a/ophyd_devices/utils/bec_signals.py b/ophyd_devices/utils/bec_signals.py index dac61f8..0082c78 100644 --- a/ophyd_devices/utils/bec_signals.py +++ b/ophyd_devices/utils/bec_signals.py @@ -1084,7 +1084,7 @@ class AsyncSignal(DynamicSignal): def put( self, value: Any, - timestamp: float | None = None, + timestamp: float | list[float] | None = None, async_update: dict[Literal["type", "max_shape", "index"], Any] | None = None, acquisition_group: str | None = None, **kwargs, @@ -1094,11 +1094,11 @@ class AsyncSignal(DynamicSignal): Args: value (Any): The value to put. - timestamp (float | None): The timestamp of the value. If None, the current time is used. + timestamp (float | list[float] | None): A timestamp or per-reading timestamps. If None, the current time is used. async_update (dict[Literal["type", "max_shape", "index"], Any] | None): Additional metadata for asynchronous updates. Please refer to the class docstring for details. acquisition_group (Literal["baseline", "monitored"] | str | None): The acquisition group of the signal. """ - timestamp = timestamp or time.time() + timestamp = time.time() if timestamp is None else timestamp super().put( value={self.name: {"value": value, "timestamp": timestamp}}, async_update=async_update, @@ -1109,7 +1109,7 @@ class AsyncSignal(DynamicSignal): def set( self, value: Any, - timestamp: float | None = None, + timestamp: float | list[float] | None = None, async_update: dict[Literal["type", "max_shape", "index"], Any] | None = None, acquisition_group: str | None = None, **kwargs, @@ -1119,7 +1119,7 @@ class AsyncSignal(DynamicSignal): Args: value (Any): The value to put. - timestamp (float | None): The timestamp of the value. If None, the current time is used. + timestamp (float | list[float] | None): A timestamp or per-reading timestamps. If None, the current time is used. async_update (dict[Literal["type", "max_shape", "index"], Any] | None): Additional metadata for asynchronous updates. Please refer to the class docstring for details. acquisition_group (Literal["baseline", "monitored"] | str | None): The acquisition group of the signal. """ diff --git a/tests/test_simulation.py b/tests/test_simulation.py index 817603c..53245f0 100644 --- a/tests/test_simulation.py +++ b/tests/test_simulation.py @@ -786,8 +786,15 @@ def test_async_mon_on_trigger(async_monitor): assert mock_send.call_count == 1 -@pytest.mark.parametrize("mode", ["extend", "append"]) -def test_async_mon_send_data_to_bec(async_monitor, mode): +@pytest.mark.parametrize( + "mode, expected_update", + [ + ("add", {"type": "add", "max_shape": [None]}), + ("add_slice", {"type": "add_slice", "max_shape": [None, None], "index": 0}), + ("replace", {"type": "replace"}), + ], +) +def test_async_mon_send_data_to_bec(async_monitor, mode, expected_update): """Buffered readings are emitted through a BEC message signal.""" async_monitor.scan_info = get_mock_scan_info(device=async_monitor) async_monitor.async_update.put(mode) @@ -797,11 +804,25 @@ def test_async_mon_send_data_to_bec(async_monitor, mode): async_monitor._send_data_to_bec() assert updates == [ messages.DeviceMessage( - signals={async_monitor.data.name: {"value": [0, 5], "timestamp": 2}}, - metadata={"async_update": {"type": "add", "max_shape": [None]}}, + signals={async_monitor.data.name: {"value": [0, 5], "timestamp": [1, 2]}}, + metadata={"async_update": expected_update}, ) ] assert async_monitor.data_buffer == {"value": [], "timestamp": []} + async_monitor.data_buffer.update({"value": [7], "timestamp": [3]}) + async_monitor._send_data_to_bec() + assert updates[1].signals[async_monitor.data.name] == {"value": [7], "timestamp": [3]} + assert updates[1].metadata["async_update"] == expected_update + assert updates[0].signals[async_monitor.data.name] == {"value": [0, 5], "timestamp": [1, 2]} + + +@pytest.mark.parametrize("mode", ["append", "extend", "invalid_mode"]) +def test_sim_async_update_rejects_invalid_modes(async_monitor, waveform, mode): + """Both simulators reject legacy and unknown update modes before acquisition.""" + for device in [async_monitor, waveform]: + with pytest.raises(ValueError): + device.async_update.put(mode) + assert device.async_update.get() == "add" def test_async_monitor_progress_signal(async_monitor): @@ -864,10 +885,19 @@ def test_waveform(waveform): @pytest.mark.parametrize( - "mode, expected_chunks", [("add", [[0, 1, 2, 3, 4]]), ("add_slice", [[0, 1], [2, 3], [4]])] + "mode, expected_chunks, expected_update", + [ + ("add", [[0, 1, 2, 3, 4]], {"type": "add", "max_shape": [None]}), + ( + "add_slice", + [[0, 1], [2, 3], [4]], + {"type": "add_slice", "index": 0, "max_shape": [None, 5]}, + ), + ("replace", [[0, 1, 2, 3, 4]], {"type": "replace"}), + ], ) -def test_waveform_update_modes(waveform, mode, expected_chunks): - """Both update modes emit the expected asynchronous waveform chunks.""" +def test_waveform_update_modes(waveform, mode, expected_chunks, expected_update): + """All update modes emit the expected asynchronous waveform chunks.""" waveform.sim.select_model("GaussianModel") waveform.sim.params = {"amplitude": 500, "center": 500, "sigma": 10} with pytest.raises(ValueError): @@ -884,11 +914,6 @@ def test_waveform_update_modes(waveform, mode, expected_chunks): assert len(updates) == len(expected_chunks) for msg, chunk in zip(updates, expected_chunks): assert np.array_equal(msg.signals[waveform.data.name]["value"], np.asarray(chunk)) - expected_update = ( - {"type": "add", "max_shape": [None]} - if mode == "add" - else {"type": "add_slice", "index": 0, "max_shape": [None, 5]} - ) assert msg.metadata["async_update"] == expected_update @@ -902,11 +927,12 @@ def test_waveform_update_modes(waveform, mode, expected_chunks): ), ("add_slice", None, {"async_update": {"type": "add", "max_shape": [None, 200]}}), ("add", 0, {"async_update": {"type": "add", "max_shape": [None]}}), + ("replace", None, {"async_update": {"type": "replace"}}), ], ) def test_waveform_send_async_update(waveform, mode, index, expected_md): """Test the send_async_update method of SimWaveform.""" - max_shape = expected_md["async_update"]["max_shape"] + max_shape = expected_md["async_update"].get("max_shape", [None]) if len(max_shape) > 1: wv_shape = max_shape[1] else: diff --git a/tests/test_utils.py b/tests/test_utils.py index a25bb35..28c91c5 100644 --- a/tests/test_utils.py +++ b/tests/test_utils.py @@ -476,6 +476,17 @@ def test_utils_async_signal(): assert reading_value["metadata"]["acquisition_group"] == "scan" +@pytest.mark.parametrize("timestamp", [0.0, [1.0, 2.0]]) +@pytest.mark.parametrize("method", ["put", "set"]) +def test_utils_async_signal_preserves_timestamps(timestamp, method): + """Asynchronous signals preserve explicit and per-reading timestamps.""" + signal = AsyncSignal(name="data", ndim=1, max_size=1000) + getattr(signal, method)( + [0, 5], timestamp=timestamp, async_update={"type": "add", "max_shape": [None]} + ) + assert signal.get().signals[signal.name]["timestamp"] == timestamp + + def test_utils_file_event_signal(): """Test FileEventSignal""" dev = Device(name="device")