dls-dodal 1.36.0__py3-none-any.whl → 1.36.2__py3-none-any.whl

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (44) hide show
  1. {dls_dodal-1.36.0.dist-info → dls_dodal-1.36.2.dist-info}/METADATA +33 -33
  2. {dls_dodal-1.36.0.dist-info → dls_dodal-1.36.2.dist-info}/RECORD +39 -39
  3. {dls_dodal-1.36.0.dist-info → dls_dodal-1.36.2.dist-info}/WHEEL +1 -1
  4. dodal/_version.py +2 -2
  5. dodal/beamlines/__init__.py +1 -0
  6. dodal/beamlines/adsim.py +75 -0
  7. dodal/beamlines/b01_1.py +16 -31
  8. dodal/beamlines/i22.py +124 -265
  9. dodal/beamlines/i24.py +72 -7
  10. dodal/beamlines/p38.py +16 -1
  11. dodal/beamlines/p99.py +22 -53
  12. dodal/beamlines/training_rig.py +16 -26
  13. dodal/cli.py +54 -8
  14. dodal/common/beamlines/beamline_utils.py +32 -2
  15. dodal/common/beamlines/device_helpers.py +2 -0
  16. dodal/devices/adsim.py +10 -10
  17. dodal/devices/attenuator.py +15 -5
  18. dodal/devices/dcm.py +5 -4
  19. dodal/devices/fast_grid_scan.py +21 -46
  20. dodal/devices/focusing_mirror.py +20 -6
  21. dodal/devices/i24/beam_center.py +12 -0
  22. dodal/devices/i24/focus_mirrors.py +60 -0
  23. dodal/devices/i24/pilatus_metadata.py +44 -0
  24. dodal/devices/linkam3.py +1 -1
  25. dodal/devices/motors.py +14 -10
  26. dodal/devices/oav/oav_detector.py +2 -2
  27. dodal/devices/oav/pin_image_recognition/__init__.py +4 -7
  28. dodal/devices/oav/utils.py +1 -0
  29. dodal/devices/p99/sample_stage.py +12 -16
  30. dodal/devices/pressure_jump_cell.py +299 -0
  31. dodal/devices/robot.py +1 -1
  32. dodal/devices/tetramm.py +1 -1
  33. dodal/devices/undulator.py +4 -1
  34. dodal/devices/undulator_dcm.py +7 -19
  35. dodal/devices/zocalo/zocalo_results.py +7 -7
  36. dodal/utils.py +151 -2
  37. dodal/adsim.py +0 -17
  38. dodal/devices/areadetector/__init__.py +0 -10
  39. dodal/devices/areadetector/adaravis.py +0 -101
  40. dodal/devices/areadetector/adsim.py +0 -47
  41. dodal/devices/areadetector/adutils.py +0 -81
  42. {dls_dodal-1.36.0.dist-info → dls_dodal-1.36.2.dist-info}/LICENSE +0 -0
  43. {dls_dodal-1.36.0.dist-info → dls_dodal-1.36.2.dist-info}/entry_points.txt +0 -0
  44. {dls_dodal-1.36.0.dist-info → dls_dodal-1.36.2.dist-info}/top_level.txt +0 -0
dodal/utils.py CHANGED
@@ -1,3 +1,4 @@
1
+ import functools
1
2
  import importlib
2
3
  import inspect
3
4
  import os
@@ -6,13 +7,14 @@ import socket
6
7
  import string
7
8
  from collections.abc import Callable, Iterable, Mapping
8
9
  from dataclasses import dataclass
9
- from functools import wraps
10
+ from functools import update_wrapper, wraps
10
11
  from importlib import import_module
11
12
  from inspect import signature
12
13
  from os import environ
13
14
  from types import ModuleType
14
15
  from typing import (
15
16
  Any,
17
+ Generic,
16
18
  Protocol,
17
19
  TypeGuard,
18
20
  TypeVar,
@@ -35,6 +37,7 @@ from bluesky.protocols import (
35
37
  Triggerable,
36
38
  WritesExternalAssets,
37
39
  )
40
+ from bluesky.run_engine import call_in_bluesky_event_loop
38
41
  from ophyd.device import Device as OphydV1Device
39
42
  from ophyd_async.core import Device as OphydV2Device
40
43
 
@@ -99,6 +102,8 @@ class BeamlinePrefix:
99
102
 
100
103
 
101
104
  T = TypeVar("T", bound=AnyDevice)
105
+ D = TypeVar("D", bound=OphydV2Device)
106
+ SkipType = bool | Callable[[], bool]
102
107
 
103
108
 
104
109
  def skip_device(precondition=lambda: True):
@@ -114,6 +119,91 @@ def skip_device(precondition=lambda: True):
114
119
  return decorator
115
120
 
116
121
 
122
+ class DeviceInitializationController(Generic[D]):
123
+ def __init__(
124
+ self,
125
+ factory: Callable[[], D],
126
+ use_factory_name: bool,
127
+ timeout: float,
128
+ mock: bool,
129
+ skip: SkipType,
130
+ ):
131
+ self._factory: Callable[[], D] = functools.cache(factory)
132
+ self._use_factory_name = use_factory_name
133
+ self._timeout = timeout
134
+ self._mock = mock
135
+ self._skip = skip
136
+ update_wrapper(self, factory)
137
+
138
+ @property
139
+ def skip(self) -> bool:
140
+ return self._skip() if callable(self._skip) else self._skip
141
+
142
+ def cache_clear(self) -> None:
143
+ """Clears the controller's internal cached instance of the device, if present.
144
+ Noop if not."""
145
+
146
+ # Functools adds the cache_clear function via setattr so the type checker
147
+ # does not pick it up.
148
+ self._factory.cache_clear() # type: ignore
149
+
150
+ def __call__(
151
+ self,
152
+ connect_immediately: bool = False,
153
+ name: str | None = None,
154
+ connection_timeout: float | None = None,
155
+ mock: bool | None = None,
156
+ ) -> D:
157
+ """Returns an instance of the Device the wrapped factory produces: the same
158
+ instance will be returned if this method is called multiple times, and arguments
159
+ may be passed to override this Controller's configuration.
160
+ Once the device is connected, the value of mock must be consistent, or connect
161
+ must be False.
162
+
163
+
164
+ Args:
165
+ connect_immediately (bool, default False): whether to call connect on the
166
+ device before returning it- connect is idempotent for ophyd-async devices.
167
+ Not connecting to the device allows for the instance to be created prior
168
+ to the RunEngine event loop being configured or for connect to be called
169
+ lazily e.g. by the `ensure_connected` stub.
170
+ name (str | None, optional): an override name to give the device, which is
171
+ also used to name its children. Defaults to None, which does not name the
172
+ device unless the device has no name and this Controller is configured to
173
+ use_factory_name, which propagates the name of the wrapped factory
174
+ function to the device instance.
175
+ connection_timeout (float | None, optional): an override timeout length in
176
+ seconds for the connect method, if it is called. Defaults to None, which
177
+ defers to the timeout configured for this Controller: the default uses
178
+ ophyd_async's DEFAULT_TIMEOUT.
179
+ mock (bool | None, optional): overrides whether to connect to Mock signal
180
+ backends, if connect is called. Defaults to None, which uses the mock
181
+ parameter of this Controller. This value must be used consistently when
182
+ connect is called on the Device.
183
+
184
+ Returns:
185
+ D: a singleton instance of the Device class returned by the wrapped factory.
186
+ """
187
+ device = self._factory()
188
+
189
+ if connect_immediately:
190
+ call_in_bluesky_event_loop(
191
+ device.connect(
192
+ timeout=connection_timeout
193
+ if connection_timeout is not None
194
+ else self._timeout,
195
+ mock=mock if mock is not None else self._mock,
196
+ )
197
+ )
198
+
199
+ if name:
200
+ device.set_name(name)
201
+ elif not device.name and self._use_factory_name:
202
+ device.set_name(self._factory.__name__)
203
+
204
+ return device
205
+
206
+
117
207
  def make_device(
118
208
  module: str | ModuleType,
119
209
  device_name: str,
@@ -206,7 +296,33 @@ def invoke_factories(
206
296
  dependent_name = leaves.pop()
207
297
  params = {name: devices[name] for name in dependencies[dependent_name]}
208
298
  try:
209
- devices[dependent_name] = factories[dependent_name](**params, **kwargs)
299
+ factory = factories[dependent_name]
300
+ if isinstance(factory, DeviceInitializationController):
301
+ # For now we translate the old-style parameters that
302
+ # device_instantiation expects. Once device_instantiation is gone and
303
+ # replaced with DeviceInitializationController we can formalise the
304
+ # API of make_all_devices and make these parameters explicit.
305
+ # https://github.com/DiamondLightSource/dodal/issues/844
306
+ mock = kwargs.get(
307
+ "mock",
308
+ kwargs.get(
309
+ "fake_with_ophyd_sim",
310
+ False,
311
+ ),
312
+ )
313
+ connect_immediately = kwargs.get(
314
+ "connect_immediately",
315
+ kwargs.get(
316
+ "wait_for_connection",
317
+ False,
318
+ ),
319
+ )
320
+ devices[dependent_name] = factory(
321
+ mock=mock,
322
+ connect_immediately=connect_immediately,
323
+ )
324
+ else:
325
+ devices[dependent_name] = factory(**params, **kwargs)
210
326
  except Exception as e:
211
327
  exceptions[dependent_name] = e
212
328
 
@@ -268,6 +384,8 @@ def collect_factories(
268
384
 
269
385
 
270
386
  def _is_device_skipped(func: AnyDeviceFactory) -> bool:
387
+ if isinstance(func, DeviceInitializationController):
388
+ return func.skip
271
389
  return getattr(func, "__skip__", False)
272
390
 
273
391
 
@@ -301,6 +419,37 @@ def is_v1_device_type(obj: type[Any]) -> bool:
301
419
  return is_class and follows_protocols and not is_v2_device_type(obj)
302
420
 
303
421
 
422
+ def filter_ophyd_devices(
423
+ devices: Mapping[str, AnyDevice],
424
+ ) -> tuple[Mapping[str, OphydV1Device], Mapping[str, OphydV2Device]]:
425
+ """
426
+ Split a dictionary of ophyd and ophyd-async devices
427
+ (i.e. the output of make_all_devices) into 2 separate dictionaries of the
428
+ different types. Useful when special handling is needed for each type of device.
429
+
430
+ Args:
431
+ devices: Dictionary of device name to ophyd or ophyd-async device.
432
+
433
+ Raises:
434
+ ValueError: If anything in the dictionary doesn't come from either library.
435
+
436
+ Returns:
437
+ Tuple of two dictionaries, one mapping names to ophyd devices and one mapping
438
+ names to ophyd-async devices.
439
+ """
440
+
441
+ ophyd_devices = {}
442
+ ophyd_async_devices = {}
443
+ for name, device in devices.items():
444
+ if isinstance(device, OphydV1Device):
445
+ ophyd_devices[name] = device
446
+ elif isinstance(device, OphydV2Device):
447
+ ophyd_async_devices[name] = device
448
+ else:
449
+ raise ValueError(f"{name}: {device} is not an ophyd or ophyd-async device")
450
+ return ophyd_devices, ophyd_async_devices
451
+
452
+
304
453
  def get_beamline_based_on_environment_variable() -> ModuleType:
305
454
  """
306
455
  Gets the dodal module for the current beamline, as specified by the
dodal/adsim.py DELETED
@@ -1,17 +0,0 @@
1
- import os
2
-
3
- from dodal.devices.adsim import SimStage
4
- from dodal.devices.areadetector import AdSimDetector
5
-
6
- from .utils import get_hostname
7
-
8
- # Default prefix to hostname unless overriden with export PREFIX=<prefix>
9
- PREFIX: str = os.environ.get("PREFIX", get_hostname())
10
-
11
-
12
- def stage(name: str = "sim_motors") -> SimStage:
13
- return SimStage(name=name, prefix=f"{PREFIX}-MO-SIM-01:")
14
-
15
-
16
- def det(name: str = "adsim") -> AdSimDetector:
17
- return AdSimDetector(name=name, prefix=f"{PREFIX}-AD-SIM-01:")
@@ -1,10 +0,0 @@
1
- from .adaravis import AdAravisDetector
2
- from .adsim import AdSimDetector
3
- from .adutils import Hdf5Writer, SynchronisedAdDriverBase
4
-
5
- __all__ = [
6
- "AdSimDetector",
7
- "SynchronisedAdDriverBase",
8
- "Hdf5Writer",
9
- "AdAravisDetector",
10
- ]
@@ -1,101 +0,0 @@
1
- from collections.abc import Mapping
2
- from typing import Any
3
-
4
- from ophyd import EpicsSignal, Signal
5
- from ophyd.areadetector.base import ADComponent as Cpt
6
- from ophyd.areadetector.detectors import DetectorBase
7
-
8
- from .adutils import Hdf5Writer, SingleTriggerV33, SynchronisedAdDriverBase
9
-
10
- _ACQUIRE_BUFFER_PERIOD = 0.2
11
-
12
-
13
- class AdAravisDetector(SingleTriggerV33, DetectorBase):
14
- cam = Cpt(SynchronisedAdDriverBase, suffix="DET:")
15
- hdf = Cpt(
16
- Hdf5Writer,
17
- suffix="HDF5:",
18
- root="",
19
- write_path_template="",
20
- )
21
- _priming_settings: Mapping[Signal, Any]
22
-
23
- def __init__(self, *args, **kwargs) -> None:
24
- super().__init__(*args, **kwargs)
25
- self.hdf.kind = "normal"
26
-
27
- # Values for staging
28
- self.stage_sigs = {
29
- # Get stage to wire up the plugins
30
- self.hdf.nd_array_port: self.cam.port_name.get(),
31
- # Reset array counter on stage
32
- self.cam.array_counter: 0,
33
- # Set image mode to multiple on stage so we have the option, can still
34
- # set num_images to 1
35
- self.cam.image_mode: "Multiple",
36
- # For now, this Ophyd device does not support hardware
37
- # triggered scanning, disable on stage
38
- self.cam.trigger_mode: "Off",
39
- **self.stage_sigs, # type: ignore
40
- }
41
-
42
- # Settings to apply when priming plugins during pre-stage
43
- self._priming_settings = {
44
- self.hdf.enable: 1,
45
- self.hdf.nd_array_port: self.cam.port_name.get(),
46
- self.cam.array_callbacks: 1,
47
- self.cam.image_mode: "Single",
48
- self.cam.trigger_mode: "Off",
49
- # Take the quickest possible frame
50
- self.cam.acquire_time: 6.3e-05,
51
- self.cam.acquire_period: 0.003,
52
- }
53
-
54
- # Signals that control driver and hdf writer should be put_complete to
55
- # avoid race conditions during priming
56
- for signal in set(self.stage_sigs.keys()).union(
57
- set(self._priming_settings.keys())
58
- ):
59
- if isinstance(signal, EpicsSignal):
60
- signal.put_complete = True
61
- self.cam.acquire.put_complete = True
62
-
63
- def stage(self, *args, **kwargs) -> list[object]:
64
- # We have to manually set the acquire period bcause the EPICS driver
65
- # doesn't do it for us. If acquire time is a staged signal, we use the
66
- # stage value to calculate the acquire period, otherwise we perform
67
- # a caget and use the current acquire time.
68
- if self.cam.acquire_time in self.stage_sigs:
69
- acquire_time = self.stage_sigs[self.cam.acquire_time]
70
- else:
71
- acquire_time = self.cam.acquire_time.get()
72
- self.stage_sigs[self.cam.acquire_period] = (
73
- float(acquire_time) + _ACQUIRE_BUFFER_PERIOD
74
- )
75
-
76
- # Ensure detector warmed up
77
- self._prime_hdf()
78
-
79
- # Now calling the super method should set the acquire period
80
- return super().stage(*args, **kwargs)
81
-
82
- def _prime_hdf(self) -> None:
83
- """
84
- Take a single frame and pipe it through the HDF5 writer plugin
85
- """
86
-
87
- # Backup state and ensure we are not acquiring
88
- reset_to = {signal: signal.get() for signal in self._priming_settings.keys()}
89
- self.cam.acquire.set(0).wait(timeout=10)
90
-
91
- # Apply all settings for acquisition
92
- for signal, value in self._priming_settings.items():
93
- # Ensure that .wait really will wait until the PV is set including its RBV
94
- signal.set(value).wait(timeout=10)
95
-
96
- # Acquire a frame
97
- self.cam.acquire.set(1).wait(timeout=10)
98
-
99
- # Revert settings to previous values
100
- for signal, value in reversed(reset_to.items()):
101
- signal.set(value).wait(timeout=10)
@@ -1,47 +0,0 @@
1
- from ophyd.areadetector.base import ADComponent as Cpt
2
- from ophyd.areadetector.detectors import DetectorBase
3
-
4
- from .adutils import Hdf5Writer, SingleTriggerV33, SynchronisedAdDriverBase
5
-
6
-
7
- class AdSimDetector(SingleTriggerV33, DetectorBase):
8
- cam = Cpt(SynchronisedAdDriverBase, suffix="CAM:", lazy=True)
9
- hdf = Cpt(
10
- Hdf5Writer,
11
- suffix="HDF5:",
12
- root="",
13
- write_path_template="",
14
- lazy=True,
15
- )
16
-
17
- def __init__(self, *args, **kwargs) -> None:
18
- super().__init__(*args, **kwargs)
19
- self.hdf.kind = "normal"
20
-
21
- self.stage_sigs = {
22
- # Get stage to wire up the plugins
23
- self.hdf.nd_array_port: self.cam.port_name.get(),
24
- # Reset array counter on stage
25
- self.cam.array_counter: 0,
26
- # Set image mode to multiple on stage so we have the option, can still
27
- # set num_images to 1
28
- self.cam.image_mode: "Multiple",
29
- # For now, this Ophyd device does not support hardware
30
- # triggered scanning, disable on stage
31
- self.cam.trigger_mode: "Internal",
32
- **self.stage_sigs, # type: ignore
33
- }
34
-
35
- def stage(self, *args, **kwargs) -> list[object]:
36
- # We have to manually set the acquire period bcause the EPICS driver
37
- # doesn't do it for us. If acquire time is a staged signal, we use the
38
- # stage value to calculate the acquire period, otherwise we perform
39
- # a caget and use the current acquire time.
40
- if self.cam.acquire_time in self.stage_sigs:
41
- acquire_time = self.stage_sigs[self.cam.acquire_time]
42
- else:
43
- acquire_time = self.cam.acquire_time.get()
44
- self.stage_sigs[self.cam.acquire_period] = acquire_time
45
-
46
- # Now calling the super method should set the acquire period
47
- return super().stage(*args, **kwargs)
@@ -1,81 +0,0 @@
1
- import time as ttime
2
-
3
- from ophyd import Component as Cpt
4
- from ophyd import DetectorBase, Device, EpicsSignal, EpicsSignalRO, Staged
5
- from ophyd.areadetector import ADTriggerStatus, TriggerBase
6
- from ophyd.areadetector.cam import AreaDetectorCam
7
- from ophyd.areadetector.filestore_mixins import FileStoreHDF5, FileStoreIterativeWrite
8
- from ophyd.areadetector.plugins import HDF5Plugin
9
-
10
-
11
- class SingleTriggerV33(TriggerBase):
12
- _status_type = ADTriggerStatus
13
-
14
- def __init__(self, *args, image_name=None, **kwargs):
15
- super().__init__(*args, **kwargs)
16
- if image_name is None:
17
- # Ensure that this mixin is part of valid device with name
18
- assert isinstance(self, Device)
19
- image_name = "_".join([self.name, "image"])
20
- self._image_name = image_name
21
-
22
- def trigger(self):
23
- "Trigger one acquisition."
24
- if self._staged != Staged.yes:
25
- raise RuntimeError(
26
- "This detector is not ready to trigger."
27
- "Call the stage() method before triggering."
28
- )
29
-
30
- self._status = self._status_type(self)
31
-
32
- def _acq_done(*args, **kwargs):
33
- # TODO sort out if anything useful in here
34
- self._status._finished() # noqa: SLF001
35
-
36
- self._acquisition_signal.put(1, use_complete=True, callback=_acq_done)
37
- # Ensure that this mixin is part of valid Detector with generate_datum
38
- assert isinstance(self, DetectorBase)
39
- self.generate_datum(self._image_name, ttime.time())
40
- return self._status
41
-
42
-
43
- class SynchronisedAdDriverBase(AreaDetectorCam):
44
- """
45
- Base Ophyd device to control an AreaDetector driver and
46
- syncrhonise it on other AreaDetector plugins, even non-blocking ones.
47
- """
48
-
49
- adcore_version = Cpt(EpicsSignalRO, "ADCoreVersion_RBV", string=True, kind="config")
50
- driver_version = Cpt(EpicsSignalRO, "DriverVersion_RBV", string=True, kind="config")
51
- wait_for_plugins = Cpt(EpicsSignal, "WaitForPlugins", string=True, kind="config")
52
-
53
- def stage(self, *args, **kwargs):
54
- # Makes the detector allow non-blocking AD plugins but makes Ophyd use
55
- # the AcquireBusy PV to determine when an acquisition is complete
56
- self.ensure_nonblocking()
57
- return super().stage(*args, **kwargs)
58
-
59
- def ensure_nonblocking(self):
60
- self.stage_sigs["wait_for_plugins"] = "Yes"
61
- if self.parent is not None:
62
- for c in self.parent.component_names:
63
- cpt = getattr(self.parent, c)
64
- if cpt is self:
65
- continue
66
- if hasattr(cpt, "ensure_nonblocking"):
67
- cpt.ensure_nonblocking()
68
-
69
-
70
- # ophyd code to be removed, only used for adim
71
- # https://github.com/DiamondLightSource/dodal/issues/404
72
- class Hdf5Writer(HDF5Plugin, FileStoreHDF5, FileStoreIterativeWrite): # type: ignore
73
- """ """
74
-
75
- pool_max_buffers = None
76
- file_number_sync = None
77
- file_number_write = None
78
-
79
- def get_frames_per_point(self):
80
- assert isinstance(self.parent, DetectorBase)
81
- return self.parent.cam.num_images.get()