dls-dodal 1.35.0__py3-none-any.whl → 1.36.1a0__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 (46) hide show
  1. {dls_dodal-1.35.0.dist-info → dls_dodal-1.36.1a0.dist-info}/METADATA +33 -31
  2. {dls_dodal-1.35.0.dist-info → dls_dodal-1.36.1a0.dist-info}/RECORD +46 -37
  3. {dls_dodal-1.35.0.dist-info → dls_dodal-1.36.1a0.dist-info}/WHEEL +1 -1
  4. dodal/_version.py +2 -2
  5. dodal/beamlines/b01_1.py +16 -31
  6. dodal/beamlines/i22.py +124 -265
  7. dodal/beamlines/i24.py +56 -7
  8. dodal/beamlines/p38.py +16 -1
  9. dodal/beamlines/p99.py +22 -53
  10. dodal/beamlines/training_rig.py +16 -26
  11. dodal/cli.py +54 -8
  12. dodal/common/beamlines/beamline_utils.py +32 -2
  13. dodal/common/beamlines/device_helpers.py +2 -0
  14. dodal/devices/aperture.py +7 -0
  15. dodal/devices/aperturescatterguard.py +195 -79
  16. dodal/devices/dcm.py +5 -4
  17. dodal/devices/eiger.py +88 -49
  18. dodal/devices/fast_grid_scan.py +21 -46
  19. dodal/devices/focusing_mirror.py +8 -3
  20. dodal/devices/i24/beam_center.py +12 -0
  21. dodal/devices/i24/focus_mirrors.py +60 -0
  22. dodal/devices/i24/pilatus_metadata.py +44 -0
  23. dodal/devices/linkam3.py +1 -1
  24. dodal/devices/motors.py +14 -10
  25. dodal/devices/oav/oav_detector.py +2 -2
  26. dodal/devices/oav/pin_image_recognition/__init__.py +4 -5
  27. dodal/devices/oav/utils.py +1 -0
  28. dodal/devices/p99/sample_stage.py +12 -16
  29. dodal/devices/pressure_jump_cell.py +299 -0
  30. dodal/devices/robot.py +1 -1
  31. dodal/devices/tetramm.py +1 -1
  32. dodal/devices/undulator.py +4 -1
  33. dodal/devices/undulator_dcm.py +3 -19
  34. dodal/devices/zocalo/zocalo_results.py +7 -7
  35. dodal/plan_stubs/__init__.py +0 -0
  36. dodal/{plans/data_session_metadata.py → plan_stubs/data_session.py} +2 -2
  37. dodal/{plans/motor_util_plans.py → plan_stubs/motor_utils.py} +2 -2
  38. dodal/plan_stubs/wrapped.py +150 -0
  39. dodal/plans/__init__.py +4 -0
  40. dodal/plans/scanspec.py +66 -0
  41. dodal/plans/wrapped.py +57 -0
  42. dodal/utils.py +151 -2
  43. {dls_dodal-1.35.0.dist-info → dls_dodal-1.36.1a0.dist-info}/LICENSE +0 -0
  44. {dls_dodal-1.35.0.dist-info → dls_dodal-1.36.1a0.dist-info}/entry_points.txt +0 -0
  45. {dls_dodal-1.35.0.dist-info → dls_dodal-1.36.1a0.dist-info}/top_level.txt +0 -0
  46. /dodal/{plans → plan_stubs}/check_topup.py +0 -0
@@ -0,0 +1,150 @@
1
+ import itertools
2
+ from collections.abc import Mapping
3
+ from typing import Annotated, Any
4
+
5
+ import bluesky.plan_stubs as bps
6
+ from bluesky.protocols import Movable
7
+ from bluesky.utils import MsgGenerator
8
+
9
+ """
10
+ Wrappers for Bluesky built-in plan stubs with type hinting
11
+ """
12
+
13
+ Group = Annotated[str, "String identifier used by 'wait' or stubs that await"]
14
+
15
+
16
+ # After bluesky 1.14, bounds for stubs that move can be narrowed
17
+ # https://github.com/bluesky/bluesky/issues/1821
18
+ def set_absolute(
19
+ movable: Movable, value: Any, group: Group | None = None, wait: bool = False
20
+ ) -> MsgGenerator:
21
+ """
22
+ Set a device, wrapper for `bp.abs_set`.
23
+
24
+ Args:
25
+ movable (Movable): The device to set
26
+ value (T): The new value
27
+ group (Group | None, optional): The message group to associate with the
28
+ setting, for sequencing. Defaults to None.
29
+ wait (bool, optional): The group should wait until all setting is complete
30
+ (e.g. a motor has finished moving). Defaults to False.
31
+
32
+ Returns:
33
+ MsgGenerator: Plan
34
+
35
+ Yields:
36
+ Iterator[MsgGenerator]: Bluesky messages
37
+ """
38
+ return (yield from bps.abs_set(movable, value, group=group, wait=wait))
39
+
40
+
41
+ def set_relative(
42
+ movable: Movable, value: Any, group: Group | None = None, wait: bool = False
43
+ ) -> MsgGenerator:
44
+ """
45
+ Change a device, wrapper for `bp.rel_set`.
46
+
47
+ Args:
48
+ movable (Movable): The device to set
49
+ value (T): The new value
50
+ group (Group | None, optional): The message group to associate with the
51
+ setting, for sequencing. Defaults to None.
52
+ wait (bool, optional): The group should wait until all setting is complete
53
+ (e.g. a motor has finished moving). Defaults to False.
54
+
55
+ Returns:
56
+ MsgGenerator: Plan
57
+
58
+ Yields:
59
+ Iterator[MsgGenerator]: Bluesky messages
60
+ """
61
+
62
+ return (yield from bps.rel_set(movable, value, group=group, wait=wait))
63
+
64
+
65
+ def move(moves: Mapping[Movable, Any], group: Group | None = None) -> MsgGenerator:
66
+ """
67
+ Move a device, wrapper for `bp.mv`.
68
+
69
+ Args:
70
+ moves (Mapping[Movable, T]): Mapping of Movables to target positions
71
+ group (Group | None, optional): The message group to associate with the
72
+ setting, for sequencing. Defaults to None.
73
+
74
+ Returns:
75
+ MsgGenerator: Plan
76
+
77
+ Yields:
78
+ Iterator[MsgGenerator]: Bluesky messages
79
+ """
80
+
81
+ return (
82
+ # type ignore until https://github.com/bluesky/bluesky/issues/1809
83
+ yield from bps.mv(*itertools.chain.from_iterable(moves.items()), group=group) # type: ignore
84
+ )
85
+
86
+
87
+ def move_relative(
88
+ moves: Mapping[Movable, Any], group: Group | None = None
89
+ ) -> MsgGenerator:
90
+ """
91
+ Move a device relative to its current position, wrapper for `bp.mvr`.
92
+
93
+ Args:
94
+ moves (Mapping[Movable, T]): Mapping of Movables to target deltas
95
+ group (Group | None, optional): The message group to associate with the
96
+ setting, for sequencing. Defaults to None.
97
+
98
+ Returns:
99
+ MsgGenerator: Plan
100
+
101
+ Yields:
102
+ Iterator[MsgGenerator]: Bluesky messages
103
+ """
104
+
105
+ return (
106
+ # type ignore until https://github.com/bluesky/bluesky/issues/1809
107
+ yield from bps.mvr(*itertools.chain.from_iterable(moves.items()), group=group) # type: ignore
108
+ )
109
+
110
+
111
+ def sleep(time: float) -> MsgGenerator:
112
+ """
113
+ Suspend all action for a given time, wrapper for `bp.sleep`
114
+
115
+ Args:
116
+ time (float): Time to wait in seconds
117
+
118
+ Returns:
119
+ MsgGenerator: Plan
120
+
121
+ Yields:
122
+ Iterator[MsgGenerator]: Bluesky messages
123
+ """
124
+
125
+ return (yield from bps.sleep(time))
126
+
127
+
128
+ def wait(
129
+ group: Group | None = None,
130
+ timeout: float | None = None,
131
+ ) -> MsgGenerator:
132
+ """
133
+ Wait for a group status to complete, wrapper for `bp.wait`.
134
+ Does not expose move_on, as when used as a stub will not fail on Timeout.
135
+
136
+ Args:
137
+ group (Group | None, optional): The name of the group to wait for, defaults
138
+ to None, in which case waits for all
139
+ groups that have not yet been awaited.
140
+ timeout (float | None, default=None): a timeout in seconds
141
+
142
+
143
+ Returns:
144
+ MsgGenerator: Plan
145
+
146
+ Yields:
147
+ Iterator[MsgGenerator]: Bluesky messages
148
+ """
149
+
150
+ return (yield from bps.wait(group, timeout=timeout))
@@ -0,0 +1,4 @@
1
+ from .scanspec import spec_scan
2
+ from .wrapped import count
3
+
4
+ __all__ = ["count", "spec_scan"]
@@ -0,0 +1,66 @@
1
+ import operator
2
+ from functools import reduce
3
+ from typing import Annotated, Any
4
+
5
+ import bluesky.plans as bp
6
+ from bluesky.protocols import Movable, Readable
7
+ from cycler import Cycler, cycler
8
+ from pydantic import Field, validate_call
9
+ from scanspec.specs import Spec
10
+
11
+ from dodal.common import MsgGenerator
12
+ from dodal.plan_stubs.data_session import attach_data_session_metadata_decorator
13
+
14
+
15
+ @attach_data_session_metadata_decorator()
16
+ @validate_call(config={"arbitrary_types_allowed": True})
17
+ def spec_scan(
18
+ detectors: Annotated[
19
+ set[Readable],
20
+ Field(
21
+ description="Set of readable devices, will take a reading at each point, \
22
+ in addition to any Movables in the Spec",
23
+ ),
24
+ ],
25
+ spec: Annotated[
26
+ Spec[Movable],
27
+ Field(description="ScanSpec modelling the path of the scan"),
28
+ ],
29
+ metadata: dict[str, Any] | None = None,
30
+ ) -> MsgGenerator:
31
+ """Generic plan for reading `detectors` at every point of a ScanSpec `Spec`.
32
+ A `Spec` is an N-dimensional path.
33
+ """
34
+ # TODO: https://github.com/bluesky/scanspec/issues/154
35
+ # support Static.duration: Spec[Literal["DURATION"]]
36
+
37
+ _md = {
38
+ "plan_args": {
39
+ "detectors": {det.name for det in detectors},
40
+ "spec": repr(spec),
41
+ },
42
+ "plan_name": "spec_scan",
43
+ "shape": spec.shape(),
44
+ **(metadata or {}),
45
+ }
46
+
47
+ yield from bp.scan_nd(tuple(detectors), _as_cycler(spec), md=_md)
48
+
49
+
50
+ def _as_cycler(spec: Spec[Movable]) -> Cycler:
51
+ """
52
+ Convert a scanspec to a cycler for compatibility with legacy Bluesky plans such as
53
+ `bp.scan_nd`. Use the midpoints of the scanspec since cyclers are normally used
54
+ for software triggered scans.
55
+
56
+ Args:
57
+ spec: A scanspec
58
+
59
+ Returns:
60
+ Cycler: A new cycler
61
+ """
62
+
63
+ midpoints = spec.frames().midpoints
64
+ # Need to "add" the cyclers for all the axes together. The code below is
65
+ # effectively: cycler(motor1, [...]) + cycler(motor2, [...]) + ...
66
+ return reduce(operator.add, (cycler(*args) for args in midpoints.items()))
dodal/plans/wrapped.py ADDED
@@ -0,0 +1,57 @@
1
+ from collections.abc import Sequence
2
+ from typing import Annotated, Any
3
+
4
+ import bluesky.plans as bp
5
+ from bluesky.protocols import Readable
6
+ from pydantic import Field, NonNegativeFloat, validate_call
7
+
8
+ from dodal.common import MsgGenerator
9
+ from dodal.plan_stubs.data_session import attach_data_session_metadata_decorator
10
+
11
+ """This module wraps plan(s) from bluesky.plans until required handling for them is
12
+ moved into bluesky or better handled in downstream services.
13
+
14
+ Required decorators are installed on plan import
15
+ https://github.com/DiamondLightSource/blueapi/issues/474
16
+
17
+ Non-serialisable fields are ignored when they are optional
18
+ https://github.com/DiamondLightSource/blueapi/issues/711
19
+
20
+ We may also need other adjustments for UI purposes, e.g.
21
+ Forcing uniqueness or orderedness of Readables
22
+ Limits and metadata (e.g. units)
23
+ """
24
+
25
+
26
+ @attach_data_session_metadata_decorator()
27
+ @validate_call(config={"arbitrary_types_allowed": True})
28
+ def count(
29
+ detectors: Annotated[
30
+ set[Readable],
31
+ Field(
32
+ description="Set of readable devices, will take a reading at each point",
33
+ min_length=1,
34
+ ),
35
+ ],
36
+ num: Annotated[int, Field(description="Number of frames to collect", ge=1)] = 1,
37
+ delay: Annotated[
38
+ NonNegativeFloat | Sequence[NonNegativeFloat],
39
+ Field(
40
+ description="Delay between readings: if tuple, len(delay) == num - 1 and \
41
+ the delays are between each point, if value or None is the delay for every \
42
+ gap",
43
+ json_schema_extra={"units": "s"},
44
+ ),
45
+ ] = 0.0,
46
+ metadata: dict[str, Any] | None = None,
47
+ ) -> MsgGenerator:
48
+ """Reads from a number of devices.
49
+ Wraps bluesky.plans.count(det, num, delay, md=metadata) exposing only serializable
50
+ parameters and metadata."""
51
+ if isinstance(delay, Sequence):
52
+ assert (
53
+ len(delay) == num - 1
54
+ ), f"Number of delays given must be {num - 1}: was given {len(delay)}"
55
+ metadata = metadata or {}
56
+ metadata["shape"] = (num,)
57
+ yield from bp.count(tuple(detectors), num, delay=delay, md=metadata)
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
File without changes