dls-dodal 1.68.0__py3-none-any.whl → 1.69.0__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 (57) hide show
  1. {dls_dodal-1.68.0.dist-info → dls_dodal-1.69.0.dist-info}/METADATA +1 -31
  2. {dls_dodal-1.68.0.dist-info → dls_dodal-1.69.0.dist-info}/RECORD +57 -49
  3. dodal/_version.py +2 -2
  4. dodal/beamlines/adsim.py +30 -23
  5. dodal/beamlines/i02_1.py +14 -42
  6. dodal/beamlines/i02_2.py +5 -11
  7. dodal/beamlines/i03.py +4 -1
  8. dodal/beamlines/i03_supervisor.py +19 -0
  9. dodal/beamlines/i04.py +74 -179
  10. dodal/beamlines/i05.py +8 -0
  11. dodal/beamlines/i06_1.py +24 -0
  12. dodal/beamlines/i09.py +53 -9
  13. dodal/beamlines/i09_1.py +8 -0
  14. dodal/beamlines/i09_2.py +4 -4
  15. dodal/beamlines/i16.py +11 -0
  16. dodal/beamlines/i20_1.py +14 -0
  17. dodal/beamlines/i21.py +12 -4
  18. dodal/beamlines/i23.py +19 -25
  19. dodal/beamlines/i24.py +55 -105
  20. dodal/beamlines/p60.py +11 -1
  21. dodal/common/__init__.py +2 -1
  22. dodal/common/maths.py +80 -0
  23. dodal/devices/eiger.py +29 -14
  24. dodal/devices/electron_analyser/base/__init__.py +3 -3
  25. dodal/devices/electron_analyser/base/base_controller.py +19 -8
  26. dodal/devices/electron_analyser/base/base_enums.py +0 -5
  27. dodal/devices/electron_analyser/base/base_region.py +2 -1
  28. dodal/devices/electron_analyser/base/energy_sources.py +27 -26
  29. dodal/devices/electron_analyser/specs/specs_detector.py +7 -6
  30. dodal/devices/electron_analyser/vgscienta/vgscienta_detector.py +7 -6
  31. dodal/devices/fast_shutter.py +108 -25
  32. dodal/devices/i04/beam_centre.py +84 -0
  33. dodal/devices/i04/max_pixel.py +4 -17
  34. dodal/devices/i04/murko_results.py +18 -3
  35. dodal/devices/i10/i10_apple2.py +6 -6
  36. dodal/devices/i17/i17_apple2.py +6 -6
  37. dodal/devices/i24/commissioning_jungfrau.py +9 -10
  38. dodal/devices/insertion_device/__init__.py +12 -8
  39. dodal/devices/insertion_device/apple2_controller.py +380 -0
  40. dodal/devices/insertion_device/apple2_undulator.py +152 -531
  41. dodal/devices/insertion_device/energy.py +88 -0
  42. dodal/devices/insertion_device/energy_motor_lookup.py +1 -1
  43. dodal/devices/insertion_device/lookup_table_models.py +2 -2
  44. dodal/devices/insertion_device/polarisation.py +36 -0
  45. dodal/devices/oav/oav_detector.py +66 -1
  46. dodal/devices/oav/utils.py +17 -0
  47. dodal/devices/robot.py +35 -18
  48. dodal/devices/selectable_source.py +38 -0
  49. dodal/devices/zebra/zebra.py +15 -0
  50. dodal/devices/zebra/zebra_constants_mapping.py +1 -0
  51. dodal/plans/configure_arm_trigger_and_disarm_detector.py +0 -1
  52. dodal/testing/__init__.py +0 -0
  53. {dls_dodal-1.68.0.dist-info → dls_dodal-1.69.0.dist-info}/WHEEL +0 -0
  54. {dls_dodal-1.68.0.dist-info → dls_dodal-1.69.0.dist-info}/entry_points.txt +0 -0
  55. {dls_dodal-1.68.0.dist-info → dls_dodal-1.69.0.dist-info}/licenses/LICENSE +0 -0
  56. {dls_dodal-1.68.0.dist-info → dls_dodal-1.69.0.dist-info}/top_level.txt +0 -0
  57. /dodal/devices/insertion_device/{id_enum.py → enum.py} +0 -0
@@ -1,64 +1,58 @@
1
1
  import abc
2
2
  import asyncio
3
3
  from dataclasses import dataclass
4
- from math import isclose
5
- from typing import Generic, Protocol, TypeVar
4
+ from typing import Generic, TypeVar
6
5
 
7
6
  import numpy as np
8
- from bluesky.protocols import Locatable, Location, Movable
7
+ from bluesky.protocols import Movable
9
8
  from ophyd_async.core import (
9
+ DEFAULT_TIMEOUT,
10
10
  AsyncStatus,
11
+ Device,
12
+ FlyMotorInfo,
11
13
  Reference,
12
14
  SignalR,
13
- SignalRW,
14
15
  SignalW,
15
16
  StandardReadable,
16
17
  StandardReadableFormat,
17
- derived_signal_rw,
18
- soft_signal_r_and_setter,
19
- soft_signal_rw,
18
+ WatchableAsyncStatus,
19
+ WatcherUpdate,
20
+ observe_value,
20
21
  wait_for_value,
21
22
  )
22
- from ophyd_async.epics.core import epics_signal_r, epics_signal_rw, epics_signal_w
23
+ from ophyd_async.epics.core import epics_signal_r, epics_signal_rw
23
24
  from ophyd_async.epics.motor import Motor
24
25
 
25
26
  from dodal.common.enums import EnabledDisabledUpper
26
- from dodal.devices.insertion_device.energy_motor_lookup import EnergyMotorLookup
27
- from dodal.devices.insertion_device.id_enum import Pol, UndulatorGateStatus
27
+ from dodal.devices.insertion_device.enum import UndulatorGateStatus
28
28
  from dodal.log import LOGGER
29
29
 
30
30
  T = TypeVar("T")
31
31
 
32
32
  DEFAULT_MOTOR_MIN_TIMEOUT = 10
33
- MAXIMUM_MOVE_TIME = 550 # There is no useful movements take longer than this.
34
33
 
35
34
 
36
35
  @dataclass
37
36
  class Apple2LockedPhasesVal:
38
- top_outer: str
39
- btm_inner: str
37
+ top_outer: float
38
+ btm_inner: float
40
39
 
41
40
 
42
41
  @dataclass
43
42
  class Apple2PhasesVal(Apple2LockedPhasesVal):
44
- top_inner: str
45
- btm_outer: str
43
+ top_inner: float
44
+ btm_outer: float
46
45
 
47
46
 
48
47
  @dataclass
49
48
  class Apple2Val:
50
- gap: str
49
+ gap: float
51
50
  phase: Apple2LockedPhasesVal | Apple2PhasesVal
52
51
 
53
52
  def extract_phase_val(self):
54
53
  return self.phase
55
54
 
56
55
 
57
- ROW_PHASE_MOTOR_TOLERANCE = 0.004
58
- MAXIMUM_ROW_PHASE_MOTOR_POSITION = 24.0
59
- MAXIMUM_GAP_MOTOR_POSITION = 100
60
-
61
-
62
56
  async def estimate_motor_timeout(
63
57
  setpoint: SignalR, curr_pos: SignalR, velocity: SignalR
64
58
  ):
@@ -68,7 +62,35 @@ async def estimate_motor_timeout(
68
62
  return abs((target_pos - cur_pos) * 2.0 / vel) + DEFAULT_MOTOR_MIN_TIMEOUT
69
63
 
70
64
 
71
- class SafeUndulatorMover(StandardReadable, Movable[T], Generic[T]):
65
+ class UndulatorBase(abc.ABC, Device, Generic[T]):
66
+ """Abstract base class for Apple2 undulator devices.
67
+ This class provides common functionality for undulator devices, including
68
+ gate and status signal management, safety checks before motion, and abstract
69
+ methods for setting demand positions and estimating move timeouts.
70
+ """
71
+
72
+ def __init__(self, name: str = ""):
73
+ # Gate keeper open when move is requested, closed when move is completed
74
+ self.gate: SignalR[UndulatorGateStatus]
75
+ self.status: SignalR[EnabledDisabledUpper]
76
+ super().__init__(name=name)
77
+
78
+ @abc.abstractmethod
79
+ async def set_demand_positions(self, value: T) -> None:
80
+ """Set the demand positions on the device without actually hitting move."""
81
+
82
+ @abc.abstractmethod
83
+ async def get_timeout(self) -> float:
84
+ """Get the timeout for the move based on an estimate of how long it will take."""
85
+
86
+ async def raise_if_cannot_move(self) -> None:
87
+ if await self.status.get_value() is EnabledDisabledUpper.DISABLED:
88
+ raise RuntimeError(f"{self.name} is DISABLED and cannot move.")
89
+ if await self.gate.get_value() is UndulatorGateStatus.OPEN:
90
+ raise RuntimeError(f"{self.name} is already in motion.")
91
+
92
+
93
+ class SafeUndulatorMover(StandardReadable, UndulatorBase, Generic[T]):
72
94
  """A device that will check it's safe to move the undulator before moving it and
73
95
  wait for the undulator to be safe again before calling the move complete.
74
96
  """
@@ -90,27 +112,65 @@ class SafeUndulatorMover(StandardReadable, Movable[T], Generic[T]):
90
112
  await self.set_move.set(value=1, timeout=timeout)
91
113
  await wait_for_value(self.gate, UndulatorGateStatus.CLOSE, timeout=timeout)
92
114
 
93
- @abc.abstractmethod
94
- async def set_demand_positions(self, value: T) -> None:
95
- """Set the demand positions on the device without actually hitting move."""
96
115
 
97
- @abc.abstractmethod
98
- async def get_timeout(self) -> float:
99
- """Get the timeout for the move based on an estimate of how long it will take."""
116
+ class UnstoppableMotor(Motor):
117
+ """A motor that does not support stop."""
100
118
 
101
- async def raise_if_cannot_move(self) -> None:
102
- if await self.status.get_value() is not EnabledDisabledUpper.ENABLED:
103
- raise RuntimeError(f"{self.name} is DISABLED and cannot move.")
104
- if await self.gate.get_value() == UndulatorGateStatus.OPEN:
105
- raise RuntimeError(f"{self.name} is already in motion.")
119
+ def __init__(self, prefix: str, name: str = ""):
120
+ super().__init__(prefix=prefix, name=name)
121
+ del self.motor_stop # Remove motor_stop from the public interface
106
122
 
123
+ async def stop(self, success=False):
124
+ LOGGER.warning(f"Stopping {self.name} is not supported.")
125
+
126
+
127
+ class GapSafeMotorNoStop(UnstoppableMotor, UndulatorBase[float]):
128
+ """Update gap safe motor that checks it's safe to move before moving."""
129
+
130
+ def __init__(self, set_move: SignalW[int], prefix: str, name: str = ""):
131
+ # Gate keeper open when move is requested, closed when move is completed
132
+ self.gate = epics_signal_r(UndulatorGateStatus, prefix + "BLGATE")
133
+ self.status = epics_signal_r(EnabledDisabledUpper, prefix + "IDBLENA")
134
+ self.set_move = set_move
135
+ super().__init__(prefix=prefix + "BLGAPMTR", name=name)
136
+
137
+ @WatchableAsyncStatus.wrap
138
+ async def set(self, new_position: float, timeout=DEFAULT_TIMEOUT):
139
+ (
140
+ old_position,
141
+ units,
142
+ precision,
143
+ ) = await asyncio.gather(
144
+ self.user_setpoint.get_value(),
145
+ self.motor_egu.get_value(),
146
+ self.precision.get_value(),
147
+ )
148
+ LOGGER.info(f"Setting {self.name} to {new_position}")
149
+ await self.raise_if_cannot_move()
150
+ await self.set_demand_positions(new_position)
151
+ timeout = await self.get_timeout()
152
+ LOGGER.info(f"Moving {self.name} to {new_position} with timeout = {timeout}")
153
+
154
+ await self.set_move.set(value=1, wait=True, timeout=timeout)
155
+ move_status = AsyncStatus(
156
+ wait_for_value(self.gate, UndulatorGateStatus.CLOSE, timeout=timeout)
157
+ )
158
+
159
+ async for current_position in observe_value(
160
+ self.user_readback, done_status=move_status
161
+ ):
162
+ yield WatcherUpdate(
163
+ current=current_position,
164
+ initial=old_position,
165
+ target=new_position,
166
+ name=self.name,
167
+ unit=units,
168
+ precision=precision,
169
+ )
107
170
 
108
- class UndulatorGap(SafeUndulatorMover[float]):
109
- """A device with a collection of epics signals to set Apple 2 undulator gap motion.
110
- Only PV used by beamline are added the full list is here:
111
- /dls_sw/work/R3.14.12.7/support/insertionDevice/db/IDGapVelocityControl.template
112
- /dls_sw/work/R3.14.12.7/support/insertionDevice/db/IDPhaseSoftMotor.template
113
- """
171
+
172
+ class UndulatorGap(GapSafeMotorNoStop):
173
+ """Apple 2 undulator gap motor device. With PV corrections."""
114
174
 
115
175
  def __init__(self, prefix: str, name: str = ""):
116
176
  """
@@ -123,80 +183,67 @@ class UndulatorGap(SafeUndulatorMover[float]):
123
183
  Name of the Id device
124
184
 
125
185
  """
126
-
127
- # Gap demand set point and readback
128
- self.user_setpoint = epics_signal_rw(
129
- str, prefix + "GAPSET.B", prefix + "BLGSET"
130
- )
131
- # Nothing move until this is set to 1 and it will return to 0 when done
132
186
  self.set_move = epics_signal_rw(int, prefix + "BLGSETP")
187
+ # Nothing move until this is set to 1 and it will return to 0 when done.
188
+ super().__init__(self.set_move, prefix, name)
133
189
 
134
- # These are gap velocity limit.
135
190
  self.max_velocity = epics_signal_r(float, prefix + "BLGSETVEL.HOPR")
136
191
  self.min_velocity = epics_signal_r(float, prefix + "BLGSETVEL.LOPR")
137
- # These are gap limit.
138
- self.high_limit_travel = epics_signal_r(float, prefix + "BLGAPMTR.HLM")
139
- self.low_limit_travel = epics_signal_r(float, prefix + "BLGAPMTR.LLM")
140
-
141
- # This is calculated acceleration from speed
142
- self.acceleration_time = epics_signal_r(float, prefix + "IDGSETACC")
143
-
144
- with self.add_children_as_readables(StandardReadableFormat.CONFIG_SIGNAL):
145
- # Unit
146
- self.motor_egu = epics_signal_r(str, prefix + "BLGAPMTR.EGU")
147
- # Gap velocity
148
- self.velocity = epics_signal_rw(float, prefix + "BLGSETVEL")
149
- with self.add_children_as_readables(StandardReadableFormat.HINTED_SIGNAL):
150
- # Gap readback value
151
- self.user_readback = epics_signal_r(float, prefix + "CURRGAPD")
152
- super().__init__(self.set_move, prefix, name)
192
+ self.user_setpoint = epics_signal_rw(str, prefix + "BLGSET")
193
+ """ Clear the motor config_signal as we need new PV for velocity."""
194
+ self._describe_config_funcs = ()
195
+ self._read_config_funcs = ()
196
+ self.velocity = epics_signal_rw(float, prefix + "BLGSETVEL")
197
+ self.add_readables(
198
+ [self.velocity, self.motor_egu, self.offset],
199
+ format=StandardReadableFormat.CONFIG_SIGNAL,
200
+ )
153
201
 
154
- async def set_demand_positions(self, value: float) -> None:
155
- await self.user_setpoint.set(str(value))
202
+ @AsyncStatus.wrap
203
+ async def prepare(self, value: FlyMotorInfo) -> None:
204
+ """
205
+ Prepare for a fly scan by moving to the run-up position at max velocity.
206
+ Stores fly info for later use in kickoff.
207
+ """
208
+ max_velocity, min_velocity, egu = await asyncio.gather(
209
+ self.max_velocity.get_value(),
210
+ self.min_velocity.get_value(),
211
+ self.motor_egu.get_value(),
212
+ )
213
+ velocity = abs(value.velocity)
214
+ if not (min_velocity <= velocity <= max_velocity):
215
+ raise ValueError(
216
+ f"Requested velocity {velocity} {egu}/s is out of bounds: "
217
+ f"must be between {min_velocity} and {max_velocity} {egu}/s."
218
+ )
219
+ await super().prepare(value)
156
220
 
157
221
  async def get_timeout(self) -> float:
158
222
  return await estimate_motor_timeout(
159
223
  self.user_setpoint, self.user_readback, self.velocity
160
224
  )
161
225
 
226
+ async def set_demand_positions(self, value: float) -> None:
227
+ await self.user_setpoint.set(str(value))
228
+
162
229
 
163
- class UndulatorPhaseMotor(StandardReadable):
164
- """A collection of epics signals for ID phase motion.
165
- Only PV used by beamline are added the full list is here:
166
- /dls_sw/work/R3.14.12.7/support/insertionDevice/db/IDPhaseSoftMotor.template
167
- """
230
+ class UndulatorPhaseMotor(UnstoppableMotor):
231
+ """Phase motor that will not stop."""
168
232
 
169
- def __init__(self, prefix: str, infix: str, name: str = ""):
233
+ def __init__(self, prefix: str, name: str = ""):
170
234
  """
171
235
  Parameters
172
236
  ----------
173
237
 
174
238
  prefix : str
175
239
  The setting prefix PV.
176
- infix: str
177
- Collection of pv that are different between beamlines
178
240
  name : str
179
241
  Name of the Id phase device
180
242
  """
181
- full_pv = f"{prefix}BL{infix}"
182
- self.user_setpoint = epics_signal_w(str, full_pv + "SET")
183
- self.user_setpoint_readback = epics_signal_r(float, full_pv + "DMD")
184
- full_pv = full_pv + "MTR"
185
- with self.add_children_as_readables(StandardReadableFormat.HINTED_SIGNAL):
186
- self.user_readback = epics_signal_r(float, full_pv + ".RBV")
187
-
188
- with self.add_children_as_readables(StandardReadableFormat.CONFIG_SIGNAL):
189
- self.motor_egu = epics_signal_r(str, full_pv + ".EGU")
190
- self.velocity = epics_signal_rw(float, full_pv + ".VELO")
191
-
192
- self.max_velocity = epics_signal_r(float, full_pv + ".VMAX")
193
- self.acceleration_time = epics_signal_rw(float, full_pv + ".ACCL")
194
- self.precision = epics_signal_r(int, full_pv + ".PREC")
195
- self.deadband = epics_signal_r(float, full_pv + ".RDBD")
196
- self.motor_done_move = epics_signal_r(int, full_pv + ".DMOV")
197
- self.low_limit_travel = epics_signal_rw(float, full_pv + ".LLM")
198
- self.high_limit_travel = epics_signal_rw(float, full_pv + ".HLM")
199
- super().__init__(name=name)
243
+ motor_pv = f"{prefix}MTR"
244
+ super().__init__(prefix=motor_pv, name=name)
245
+ self.user_setpoint = epics_signal_rw(str, prefix + "SET")
246
+ self.user_setpoint_readback = epics_signal_r(float, prefix + "DMD")
200
247
 
201
248
 
202
249
  Apple2PhaseValType = TypeVar("Apple2PhaseValType", bound=Apple2LockedPhasesVal)
@@ -214,8 +261,8 @@ class UndulatorLockedPhaseAxes(SafeUndulatorMover[Apple2PhaseValType]):
214
261
  ):
215
262
  # Gap demand set point and readback
216
263
  with self.add_children_as_readables():
217
- self.top_outer = UndulatorPhaseMotor(prefix=prefix, infix=top_outer)
218
- self.btm_inner = UndulatorPhaseMotor(prefix=prefix, infix=btm_inner)
264
+ self.top_outer = UndulatorPhaseMotor(prefix=f"{prefix}BL{top_outer}")
265
+ self.btm_inner = UndulatorPhaseMotor(prefix=f"{prefix}BL{btm_inner}")
219
266
  # Nothing move until this is set to 1 and it will return to 0 when done.
220
267
  self.set_move = epics_signal_rw(int, f"{prefix}BL{top_outer}" + "MOVE")
221
268
  self.axes = [self.top_outer, self.btm_inner]
@@ -223,13 +270,13 @@ class UndulatorLockedPhaseAxes(SafeUndulatorMover[Apple2PhaseValType]):
223
270
 
224
271
  async def set_demand_positions(self, value: Apple2PhaseValType) -> None:
225
272
  await asyncio.gather(
226
- self.top_outer.user_setpoint.set(value=value.top_outer),
227
- self.btm_inner.user_setpoint.set(value=value.btm_inner),
273
+ self.top_outer.user_setpoint.set(value=str(value.top_outer)),
274
+ self.btm_inner.user_setpoint.set(value=str(value.btm_inner)),
228
275
  )
229
276
 
230
277
  async def get_timeout(self) -> float:
231
278
  """
232
- Get all four motor speed, current positions and target positions to calculate required timeout.
279
+ Get all motor speed, current positions and target positions to calculate required timeout.
233
280
  """
234
281
 
235
282
  timeouts = await asyncio.gather(
@@ -270,18 +317,18 @@ class UndulatorPhaseAxes(UndulatorLockedPhaseAxes[Apple2PhasesVal]):
270
317
  ):
271
318
  # Gap demand set point and readback
272
319
  with self.add_children_as_readables():
273
- self.top_inner = UndulatorPhaseMotor(prefix=prefix, infix=top_inner)
274
- self.btm_outer = UndulatorPhaseMotor(prefix=prefix, infix=btm_outer)
320
+ self.top_inner = UndulatorPhaseMotor(prefix=f"{prefix}BL{top_inner}")
321
+ self.btm_outer = UndulatorPhaseMotor(prefix=f"{prefix}BL{btm_outer}")
275
322
 
276
323
  super().__init__(prefix, top_outer=top_outer, btm_inner=btm_inner, name=name)
277
324
  self.axes.extend([self.top_inner, self.btm_outer])
278
325
 
279
326
  async def set_demand_positions(self, value: Apple2PhasesVal) -> None:
280
327
  await asyncio.gather(
281
- self.top_outer.user_setpoint.set(value=value.top_outer),
282
- self.top_inner.user_setpoint.set(value=value.top_inner),
283
- self.btm_inner.user_setpoint.set(value=value.btm_inner),
284
- self.btm_outer.user_setpoint.set(value=value.btm_outer),
328
+ self.top_outer.user_setpoint.set(value=str(value.top_outer)),
329
+ self.top_inner.user_setpoint.set(value=str(value.top_inner)),
330
+ self.btm_inner.user_setpoint.set(value=str(value.btm_inner)),
331
+ self.btm_outer.user_setpoint.set(value=str(value.btm_outer)),
285
332
  )
286
333
 
287
334
 
@@ -300,7 +347,7 @@ class UndulatorJawPhase(SafeUndulatorMover[float]):
300
347
  ):
301
348
  # Gap demand set point and readback
302
349
  with self.add_children_as_readables():
303
- self.jaw_phase = UndulatorPhaseMotor(prefix=prefix, infix=jaw_phase)
350
+ self.jaw_phase = UndulatorPhaseMotor(prefix=f"{prefix}BL{jaw_phase}")
304
351
  # Nothing move until this is set to 1 and it will return to 0 when done
305
352
  self.set_move = epics_signal_rw(int, f"{prefix}BL{move_pv}" + "MOVE")
306
353
 
@@ -359,7 +406,7 @@ class Apple2(StandardReadable, Movable[Apple2Val], Generic[PhaseAxesType]):
359
406
  all at the same time.
360
407
  """
361
408
 
362
- # Only need to check gap as the phase motors share both fault and gate with gap.
409
+ # Only need to check gap as the phase motors share both status and gate with gap.
363
410
  await self.gap().raise_if_cannot_move()
364
411
 
365
412
  await asyncio.gather(
@@ -372,7 +419,7 @@ class Apple2(StandardReadable, Movable[Apple2Val], Generic[PhaseAxesType]):
372
419
  await asyncio.gather(self.gap().get_timeout(), self.phase().get_timeout())
373
420
  )
374
421
  LOGGER.info(
375
- f"Moving f{self.name} apple2 motors to {id_motor_values}, timeout = {timeout}"
422
+ f"Moving {self.name} apple2 motors to {id_motor_values}, timeout = {timeout}"
376
423
  )
377
424
  await asyncio.gather(
378
425
  self.gap().set_move.set(value=1, wait=False, timeout=timeout),
@@ -381,429 +428,3 @@ class Apple2(StandardReadable, Movable[Apple2Val], Generic[PhaseAxesType]):
381
428
  await wait_for_value(
382
429
  self.gap().gate, UndulatorGateStatus.CLOSE, timeout=timeout
383
430
  )
384
-
385
-
386
- class EnergyMotorConvertor(Protocol):
387
- def __call__(self, energy: float, pol: Pol) -> float:
388
- """Protocol to provide energy to motor position conversion"""
389
- ...
390
-
391
-
392
- Apple2Type = TypeVar("Apple2Type", bound=Apple2)
393
-
394
-
395
- class Apple2Controller(abc.ABC, StandardReadable, Generic[Apple2Type]):
396
- """
397
-
398
- Abstract base class for controlling an Apple2 undulator device.
399
-
400
- This class manages the undulator's gap and phase motors, and provides an interface
401
- for controlling polarisation and energy settings. It exposes derived signals for
402
- energy and polarisation, and handles conversion between energy/polarisation and
403
- motor positions via a user-supplied conversion callable.
404
-
405
- Attributes
406
- ----------
407
- apple2 : Reference[Apple2Type]
408
- Reference to the Apple2 device containing gap and phase motors.
409
- energy : derived_signal_rw
410
- Derived signal for moving and reading back energy.
411
- polarisation_setpoint : SignalR
412
- Soft signal for the polarisation setpoint.
413
- polarisation : derived_signal_rw
414
- Hardware-backed signal for polarisation readback and control.
415
- gap_energy_to_motor_converter : EnergyMotorConvertor
416
- Callable that converts energy and polarisation to gap motor positions.
417
- phase_energy_to_motor_converter : EnergyMotorConvertor
418
- Callable that converts energy and polarisation to phase motor positions.
419
-
420
- Abstract Methods
421
- ----------------
422
- _get_apple2_value(gap: float, phase: float) -> Apple2Val
423
- Abstract method to return the Apple2Val used to set the apple2 with.
424
- Notes
425
- -----
426
- - Subclasses must implement `_get_apple2_value` for beamline-specific logic.
427
- - LH3 polarisation is indistinguishable from LH in hardware; special handling is provided.
428
- - Supports multiple polarisation modes, including linear horizontal (LH), linear vertical (LV),
429
- positive circular (PC), negative circular (NC), and linear arbitrary (LA).
430
-
431
- """
432
-
433
- def __init__(
434
- self,
435
- apple2: Apple2Type,
436
- gap_energy_motor_converter: EnergyMotorConvertor,
437
- phase_energy_motor_converter: EnergyMotorConvertor,
438
- units: str = "eV",
439
- name: str = "",
440
- ) -> None:
441
- """
442
-
443
- Parameters
444
- ----------
445
- apple2: Apple2
446
- An Apple2 device.
447
- name: str
448
- Name of the device.
449
- """
450
- self.apple2 = Reference(apple2)
451
- self.gap_energy_motor_converter = gap_energy_motor_converter
452
- self.phase_energy_motor_converter = phase_energy_motor_converter
453
-
454
- # Store the set energy for readback.
455
- self._energy, self._energy_set = soft_signal_r_and_setter(
456
- float, initial_value=None, units=units
457
- )
458
- with self.add_children_as_readables(StandardReadableFormat.HINTED_SIGNAL):
459
- self.energy = derived_signal_rw(
460
- raw_to_derived=self._read_energy,
461
- set_derived=self._set_energy,
462
- energy=self._energy,
463
- derived_units=units,
464
- )
465
-
466
- # Store the polarisation for setpoint. And provide readback for LH3.
467
- # LH3 is a special case as it is indistinguishable from LH in the hardware.
468
- self.polarisation_setpoint, self._polarisation_setpoint_set = (
469
- soft_signal_r_and_setter(Pol)
470
- )
471
- phase = self.apple2().phase()
472
- # check if undulator phase is unlocked.
473
- if isinstance(phase, UndulatorPhaseAxes):
474
- top_inner = phase.top_inner.user_readback
475
- btm_outer = phase.btm_outer.user_readback
476
- else:
477
- # If locked phase axes make the locked phase 0.
478
- top_inner = btm_outer = soft_signal_rw(float, initial_value=0.0)
479
-
480
- with self.add_children_as_readables(StandardReadableFormat.HINTED_SIGNAL):
481
- # Hardware backed read/write for polarisation.
482
-
483
- self.polarisation = derived_signal_rw(
484
- raw_to_derived=self._read_pol,
485
- set_derived=self._set_pol,
486
- pol=self.polarisation_setpoint,
487
- top_outer=phase.top_outer.user_readback,
488
- top_inner=top_inner,
489
- btm_inner=phase.btm_inner.user_readback,
490
- btm_outer=btm_outer,
491
- gap=self.apple2().gap().user_readback,
492
- )
493
- super().__init__(name)
494
-
495
- @abc.abstractmethod
496
- def _get_apple2_value(self, gap: float, phase: float, pol: Pol) -> Apple2Val:
497
- """
498
- This method should be implemented by the beamline specific ID class as the
499
- motor positions will be different for each beamline depending on the
500
- undulator design.
501
- """
502
-
503
- async def _set_motors_from_energy_and_polarisation(
504
- self, energy: float, pol: Pol
505
- ) -> None:
506
- """Set the undulator motors for a given energy and polarisation."""
507
- gap = self.gap_energy_motor_converter(energy=energy, pol=pol)
508
- phase = self.phase_energy_motor_converter(energy=energy, pol=pol)
509
- apple2_val = self._get_apple2_value(gap, phase, pol)
510
- LOGGER.info(f"Setting polarisation to {pol}, with values: {apple2_val}")
511
- await self.apple2().set(id_motor_values=apple2_val)
512
-
513
- async def _set_energy(self, energy: float) -> None:
514
- pol = await self._check_and_get_pol_setpoint()
515
- await self._set_motors_from_energy_and_polarisation(energy, pol)
516
- self._energy_set(energy)
517
-
518
- def _read_energy(self, energy: float) -> float:
519
- """Readback for energy is just the set value."""
520
- return energy
521
-
522
- async def _check_and_get_pol_setpoint(self) -> Pol:
523
- """
524
- Check the polarisation setpoint and if it is NONE try to read it from
525
- hardware.
526
- """
527
- pol = await self.polarisation_setpoint.get_value()
528
-
529
- if pol == Pol.NONE:
530
- LOGGER.warning(
531
- "Found no setpoint for polarisation. Attempting to"
532
- " determine polarisation from hardware..."
533
- )
534
- pol = await self.polarisation.get_value()
535
- if pol == Pol.NONE:
536
- raise ValueError(
537
- f"Polarisation cannot be determined from hardware for {self.name}"
538
- )
539
- self._polarisation_setpoint_set(pol)
540
- return pol
541
-
542
- async def _set_pol(
543
- self,
544
- value: Pol,
545
- ) -> None:
546
- # This changes the pol setpoint and then changes polarisation via set energy.
547
- self._polarisation_setpoint_set(value)
548
- await self.energy.set(await self.energy.get_value(), timeout=MAXIMUM_MOVE_TIME)
549
-
550
- def _read_pol(
551
- self,
552
- pol: Pol,
553
- top_outer: float,
554
- top_inner: float,
555
- btm_inner: float,
556
- btm_outer: float,
557
- gap: float,
558
- ) -> Pol:
559
- LOGGER.info(
560
- f"Reading polarisation setpoint from hardware: "
561
- f"top_outer={top_outer}, top_inner={top_inner}, "
562
- f"btm_inner={btm_inner}, btm_outer={btm_outer}, gap={gap}."
563
- )
564
-
565
- read_pol, _ = self.determine_phase_from_hardware(
566
- top_outer, top_inner, btm_inner, btm_outer, gap
567
- )
568
- # LH3 is indistinguishable from LH see determine_phase_from_hardware's docString
569
- # so we return LH3 if the setpoint is LH3 and the readback is LH.
570
- if pol == Pol.LH3 and read_pol == Pol.LH:
571
- LOGGER.info(
572
- "The hardware cannot distinguish between LH and LH3."
573
- " Returning the last commanded polarisation value"
574
- )
575
- return Pol.LH3
576
-
577
- return read_pol
578
-
579
- def determine_phase_from_hardware(
580
- self,
581
- top_outer: float,
582
- top_inner: float,
583
- btm_inner: float,
584
- btm_outer: float,
585
- gap: float,
586
- ) -> tuple[Pol, float]:
587
- """
588
- Determine polarisation and phase value using motor position patterns.
589
- However there is no way to return lh3 polarisation or higher harmonic setting.
590
- (May be for future one can use the inverse poly to work out the energy and try to match it with the current energy
591
- to workout the polarisation but during my test the inverse poly is too unstable for general use.)
592
- """
593
- if gap > MAXIMUM_GAP_MOTOR_POSITION:
594
- raise RuntimeError(
595
- f"{self.name} is not in use, close gap or set polarisation to use this ID"
596
- )
597
-
598
- if all(
599
- isclose(x, 0.0, abs_tol=ROW_PHASE_MOTOR_TOLERANCE)
600
- for x in [top_outer, top_inner, btm_inner, btm_outer]
601
- ):
602
- LOGGER.info("Determined polarisation: LH (Linear Horizontal).")
603
- return Pol.LH, 0.0
604
- if (
605
- isclose(
606
- top_outer,
607
- MAXIMUM_ROW_PHASE_MOTOR_POSITION,
608
- abs_tol=ROW_PHASE_MOTOR_TOLERANCE,
609
- )
610
- and isclose(top_inner, 0.0, abs_tol=ROW_PHASE_MOTOR_TOLERANCE)
611
- and isclose(
612
- btm_inner,
613
- MAXIMUM_ROW_PHASE_MOTOR_POSITION,
614
- abs_tol=ROW_PHASE_MOTOR_TOLERANCE,
615
- )
616
- and isclose(btm_outer, 0.0, abs_tol=ROW_PHASE_MOTOR_TOLERANCE)
617
- ):
618
- LOGGER.info("Determined polarisation: LV (Linear Vertical).")
619
- return Pol.LV, MAXIMUM_ROW_PHASE_MOTOR_POSITION
620
- if (
621
- isclose(top_outer, btm_inner, abs_tol=ROW_PHASE_MOTOR_TOLERANCE)
622
- and top_outer > 0.0
623
- and isclose(top_inner, 0.0, abs_tol=ROW_PHASE_MOTOR_TOLERANCE)
624
- and isclose(btm_outer, 0.0, abs_tol=ROW_PHASE_MOTOR_TOLERANCE)
625
- ):
626
- LOGGER.info("Determined polarisation: PC (Positive Circular).")
627
- return Pol.PC, top_outer
628
- if (
629
- isclose(top_outer, btm_inner, abs_tol=ROW_PHASE_MOTOR_TOLERANCE)
630
- and top_outer < 0.0
631
- and isclose(top_inner, 0.0, abs_tol=ROW_PHASE_MOTOR_TOLERANCE)
632
- and isclose(btm_outer, 0.0, abs_tol=ROW_PHASE_MOTOR_TOLERANCE)
633
- ):
634
- LOGGER.info("Determined polarisation: NC (Negative Circular).")
635
- return Pol.NC, top_outer
636
- if (
637
- isclose(top_outer, -btm_inner, abs_tol=ROW_PHASE_MOTOR_TOLERANCE)
638
- and isclose(top_inner, 0.0, abs_tol=ROW_PHASE_MOTOR_TOLERANCE)
639
- and isclose(btm_outer, 0.0, abs_tol=ROW_PHASE_MOTOR_TOLERANCE)
640
- ):
641
- LOGGER.info("Determined polarisation: LA (Positive Linear Arbitrary).")
642
- return Pol.LA, top_outer
643
- if (
644
- isclose(top_inner, -btm_outer, abs_tol=ROW_PHASE_MOTOR_TOLERANCE)
645
- and isclose(top_outer, 0.0, abs_tol=ROW_PHASE_MOTOR_TOLERANCE)
646
- and isclose(btm_inner, 0.0, abs_tol=ROW_PHASE_MOTOR_TOLERANCE)
647
- ):
648
- LOGGER.info("Determined polarisation: LA (Negative Linear Arbitrary).")
649
- return Pol.LA, top_inner
650
-
651
- LOGGER.warning("Unable to determine polarisation. Defaulting to NONE.")
652
- return Pol.NONE, 0.0
653
-
654
-
655
- class Apple2EnforceLHMoveController(Apple2Controller[Apple2]):
656
- """The latest Apple2 version allows unrestricted motor movement.
657
- However, because of the high forces involved in polarization changes,
658
- all movements must be performed using the Linear Horizontal (LH) mode.
659
- A look-up table must also be used to determine the highest energy that can
660
- be reached in LH mode."""
661
-
662
- def __init__(
663
- self,
664
- apple2: Apple2,
665
- gap_energy_motor_lut: EnergyMotorLookup,
666
- phase_energy_motor_lut: EnergyMotorLookup,
667
- units: str = "eV",
668
- name: str = "",
669
- ) -> None:
670
- self.gap_energy_motor_lu = gap_energy_motor_lut
671
- self.phase_energy_motor_lu = phase_energy_motor_lut
672
- super().__init__(
673
- apple2=apple2,
674
- gap_energy_motor_converter=gap_energy_motor_lut.find_value_in_lookup_table,
675
- phase_energy_motor_converter=phase_energy_motor_lut.find_value_in_lookup_table,
676
- units=units,
677
- name=name,
678
- )
679
-
680
- def _get_apple2_value(self, gap: float, phase: float, pol: Pol) -> Apple2Val:
681
- apple2_val = Apple2Val(
682
- gap=f"{gap:.6f}",
683
- phase=Apple2PhasesVal(
684
- top_outer=f"{phase:.6f}",
685
- top_inner=f"{0.0:.6f}",
686
- btm_inner=f"{phase:.6f}",
687
- btm_outer=f"{0.0:.6f}",
688
- ),
689
- )
690
- LOGGER.info(f"Getting apple2 value for pol={pol}, gap={gap}, phase={phase}.")
691
- LOGGER.info(f"Apple2 motor values: {apple2_val}.")
692
-
693
- return apple2_val
694
-
695
- async def _set_pol(
696
- self,
697
- value: Pol,
698
- ) -> None:
699
- # I09/I21 require all polarisation change to go via LH.
700
- current_pol = await self.polarisation.get_value()
701
- if current_pol == value:
702
- LOGGER.info(f"Polarisation already at {value}")
703
- else:
704
- target_energy = await self.energy.get_value()
705
- if (value is not Pol.LH) and (current_pol is not Pol.LH):
706
- self._polarisation_setpoint_set(Pol.LH)
707
- max_lh_energy = float(
708
- self.gap_energy_motor_lu.lut.root[Pol("lh")].max_energy
709
- )
710
- lh_setpoint = (
711
- max_lh_energy if target_energy > max_lh_energy else target_energy
712
- )
713
- LOGGER.info(f"Changing polarisation to {value} via {Pol.LH}")
714
- await self.energy.set(lh_setpoint, timeout=MAXIMUM_MOVE_TIME)
715
- self._polarisation_setpoint_set(value)
716
- await self.energy.set(target_energy, timeout=MAXIMUM_MOVE_TIME)
717
-
718
-
719
- class InsertionDeviceEnergyBase(abc.ABC, StandardReadable, Movable):
720
- """Base class for ID energy movable device."""
721
-
722
- def __init__(self, name: str = "") -> None:
723
- self.energy: Reference[SignalRW[float]]
724
- super().__init__(name=name)
725
-
726
- @abc.abstractmethod
727
- @AsyncStatus.wrap
728
- async def set(self, energy: float) -> None: ...
729
-
730
-
731
- class BeamEnergy(StandardReadable, Movable[float]):
732
- """
733
- Compound device to set both ID and energy motor at the same time with an option to add an offset.
734
- """
735
-
736
- def __init__(
737
- self, id_energy: InsertionDeviceEnergyBase, mono: Motor, name: str = ""
738
- ) -> None:
739
- """
740
- Parameters
741
- ----------
742
-
743
- id_energy: InsertionDeviceEnergy
744
- An InsertionDeviceEnergy device.
745
- mono: Motor
746
- A Motor(energy) device.
747
- name:
748
- New device name.
749
- """
750
- super().__init__(name=name)
751
- self._id_energy = Reference(id_energy)
752
- self._mono_energy = Reference(mono)
753
-
754
- self.add_readables(
755
- [
756
- self._id_energy().energy(),
757
- self._mono_energy().user_readback,
758
- ],
759
- StandardReadableFormat.HINTED_SIGNAL,
760
- )
761
-
762
- with self.add_children_as_readables(StandardReadableFormat.CONFIG_SIGNAL):
763
- self.id_energy_offset = soft_signal_rw(float, initial_value=0)
764
-
765
- @AsyncStatus.wrap
766
- async def set(self, energy: float) -> None:
767
- LOGGER.info(f"Moving f{self.name} energy to {energy}.")
768
- await asyncio.gather(
769
- self._id_energy().set(
770
- energy=energy + await self.id_energy_offset.get_value()
771
- ),
772
- self._mono_energy().set(energy),
773
- )
774
-
775
-
776
- class InsertionDeviceEnergy(InsertionDeviceEnergyBase):
777
- """Apple2 ID energy movable device."""
778
-
779
- def __init__(self, id_controller: Apple2Controller, name: str = "") -> None:
780
- self.energy = Reference(id_controller.energy)
781
- super().__init__(name=name)
782
-
783
- self.add_readables([self.energy()], StandardReadableFormat.HINTED_SIGNAL)
784
-
785
- @AsyncStatus.wrap
786
- async def set(self, energy: float) -> None:
787
- await self.energy().set(energy, timeout=MAXIMUM_MOVE_TIME)
788
-
789
-
790
- class InsertionDevicePolarisation(StandardReadable, Locatable[Pol]):
791
- """Apple2 ID polarisation movable device."""
792
-
793
- def __init__(self, id_controller: Apple2Controller, name: str = "") -> None:
794
- self.polarisation = Reference(id_controller.polarisation)
795
- self.polarisation_setpoint = Reference(id_controller.polarisation_setpoint)
796
- super().__init__(name=name)
797
-
798
- self.add_readables([self.polarisation()], StandardReadableFormat.HINTED_SIGNAL)
799
-
800
- @AsyncStatus.wrap
801
- async def set(self, pol: Pol) -> None:
802
- await self.polarisation().set(pol, timeout=MAXIMUM_MOVE_TIME)
803
-
804
- async def locate(self) -> Location[Pol]:
805
- """Return the current polarisation"""
806
- setpoint, readback = await asyncio.gather(
807
- self.polarisation_setpoint().get_value(), self.polarisation().get_value()
808
- )
809
- return Location(setpoint=setpoint, readback=readback)