ionpulse_sequence_generator 2.4.1__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.

Potentially problematic release.


This version of ionpulse_sequence_generator might be problematic. Click here for more details.

Files changed (37) hide show
  1. ionpulse_sequence_generator/__init__.py +91 -0
  2. ionpulse_sequence_generator/base/__init__.py +0 -0
  3. ionpulse_sequence_generator/base/configuration.py +23 -0
  4. ionpulse_sequence_generator/base/header.py +90 -0
  5. ionpulse_sequence_generator/base/jsonexportable.py +264 -0
  6. ionpulse_sequence_generator/event/__init__.py +0 -0
  7. ionpulse_sequence_generator/event/ddspidstatechange.py +65 -0
  8. ionpulse_sequence_generator/event/dioevent.py +73 -0
  9. ionpulse_sequence_generator/event/event.py +84 -0
  10. ionpulse_sequence_generator/event/multitonerfevent.py +139 -0
  11. ionpulse_sequence_generator/event/qubitevent.py +66 -0
  12. ionpulse_sequence_generator/event/readout.py +239 -0
  13. ionpulse_sequence_generator/event/singletonerfevent.py +185 -0
  14. ionpulse_sequence_generator/event/wait.py +63 -0
  15. ionpulse_sequence_generator/event/waveform.py +54 -0
  16. ionpulse_sequence_generator/hardware/__init__.py +0 -0
  17. ionpulse_sequence_generator/hardware/channel.py +115 -0
  18. ionpulse_sequence_generator/hardware/device.py +184 -0
  19. ionpulse_sequence_generator/hardware/hardware.py +780 -0
  20. ionpulse_sequence_generator/hardware/readout.py +500 -0
  21. ionpulse_sequence_generator/hardware/system.py +213 -0
  22. ionpulse_sequence_generator/hardware/units.py +97 -0
  23. ionpulse_sequence_generator/parameter/__init__.py +0 -0
  24. ionpulse_sequence_generator/parameter/parameter.py +479 -0
  25. ionpulse_sequence_generator/parameter/pid_parameter.py +118 -0
  26. ionpulse_sequence_generator/parameter/spline_parameter.py +370 -0
  27. ionpulse_sequence_generator/py.typed +0 -0
  28. ionpulse_sequence_generator/sequence/__init__.py +0 -0
  29. ionpulse_sequence_generator/sequence/conditional.py +121 -0
  30. ionpulse_sequence_generator/sequence/loop.py +108 -0
  31. ionpulse_sequence_generator/sequence/sequence.py +882 -0
  32. ionpulse_sequence_generator/utils/__init__.py +0 -0
  33. ionpulse_sequence_generator/utils/logging.py +96 -0
  34. ionpulse_sequence_generator/utils/utils.py +38 -0
  35. ionpulse_sequence_generator-2.4.1.dist-info/METADATA +52 -0
  36. ionpulse_sequence_generator-2.4.1.dist-info/RECORD +37 -0
  37. ionpulse_sequence_generator-2.4.1.dist-info/WHEEL +4 -0
@@ -0,0 +1,370 @@
1
+ from __future__ import annotations
2
+
3
+ import hashlib
4
+ import logging
5
+ from typing import Any, ClassVar
6
+
7
+ import numpy as np
8
+ from scipy.interpolate import CubicSpline, PPoly
9
+
10
+ from ionpulse_sequence_generator.base.jsonexportable import JSONexportable
11
+ from ionpulse_sequence_generator.hardware.hardware import QuenchHardware, Units
12
+ from ionpulse_sequence_generator.parameter.parameter import Amp, Freq, Phase, Time
13
+
14
+ logger = logging.getLogger(__name__)
15
+
16
+
17
+ class SplineParameter(JSONexportable):
18
+ """
19
+ Parameter for Quench Interpolation engines
20
+ """
21
+
22
+ __slots__ = ("_coeff", "_order", "_ppoly", "_shaping_time", "_x")
23
+
24
+ # Cache for test_ppoly_coeff results
25
+ _test_ppoly_coeff_cache: ClassVar[dict[str, bool]] = {}
26
+
27
+ def __init__(self, ppoly: np.ndarray, name="", interpolator_max_order=3) -> None:
28
+ super().__init__(name)
29
+ shaping_time: list[float] = []
30
+ poly_order: list[int] = []
31
+ # find shape and poly order
32
+ for p in ppoly.reshape((-1,)):
33
+ poly_order.append(p.c.shape[0])
34
+ shaping_time.append(p.x[-1])
35
+ if max(poly_order) > interpolator_max_order + 1:
36
+ raise ValueError(
37
+ f"Provided polynomial order of {max(poly_order)} is larger"
38
+ f"than max permissible order of {interpolator_max_order}"
39
+ "provide a polynomial of lower order."
40
+ )
41
+ self._ppoly = ppoly
42
+ # Shaping time has to be calculated using time resolution because ppoly.x is given in
43
+ # native time resolution
44
+ self._shaping_time = Time(
45
+ QuenchHardware._time_min_shaping_ns
46
+ + np.array(shaping_time).reshape(ppoly.shape) * QuenchHardware._time_resolution_ns,
47
+ Units.ns,
48
+ )
49
+ self._order = np.array(poly_order).reshape(ppoly.shape)
50
+ # convert to coefficients only once for testing and exporting
51
+ self._coeff = [self.ppoly_to_coeff(p) for p in ppoly.reshape(-1)]
52
+ self._x = [p.x for p in ppoly.reshape(-1)]
53
+
54
+ def order(self):
55
+ return self._order
56
+
57
+ @classmethod
58
+ def check_min_shape_interval(cls, time: Time) -> None:
59
+ min_time = np.array(QuenchHardware._time_min_shaping_interval_ns)
60
+ intervals = np.diff(time._value)
61
+ if np.any(intervals < min_time):
62
+ raise ValueError(f"Given time intervals {intervals} are below minimum time interval {min_time}")
63
+
64
+ @classmethod
65
+ def ppoly_to_coeff(cls, ppoly: PPoly) -> np.ndarray:
66
+ scaling = 16 # 16 bit for each order
67
+ spl_coeffs = np.zeros((len(ppoly.c), len(ppoly.c[0])), dtype=np.int64)
68
+ # Note: ppoly is defined with the highest order at 0
69
+ match len(ppoly.c):
70
+ case 1:
71
+ spl_coeffs[0] = np.round(ppoly.c[0])
72
+ return spl_coeffs
73
+ case 2:
74
+ spl_coeffs[1] = np.round(ppoly.c[1])
75
+ spl_coeffs[0] = np.round(ppoly.c[0] * 2**scaling)
76
+ return spl_coeffs
77
+ case 4: # third order polynomial
78
+ spl_coeffs[0] = np.ceil(ppoly.c[0] * 6.0 * (2**scaling) ** 3)
79
+ spl_coeffs[1] = np.ceil(spl_coeffs[0] / 2**scaling + (2 * ppoly.c[1]) * (2**scaling) ** 2)
80
+ spl_coeffs[2] = np.ceil(
81
+ -1 / 3 * spl_coeffs[0] / 2 ** (2 * scaling)
82
+ + 1 / 2 * spl_coeffs[1] / 2**scaling
83
+ + (ppoly.c[2]) * 2**scaling
84
+ )
85
+ spl_coeffs[3] = np.ceil(ppoly.c[3])
86
+ return spl_coeffs
87
+ case _:
88
+ raise ValueError(f"PPoly with order {len(ppoly.c)} can not be converted!")
89
+
90
+ @classmethod
91
+ def coeff_to_ppoly(cls, coeff: np.ndarray, x: np.ndarray) -> PPoly:
92
+ c = np.zeros(coeff.shape)
93
+ scaling = 16 # 16 bit for each order
94
+ match len(coeff):
95
+ case 1:
96
+ c[0] = coeff[0]
97
+ case 2:
98
+ c[0] = coeff[0] / 2**scaling
99
+ c[1] = coeff[1]
100
+ case 4: # third order polynomial
101
+ c[0] = coeff[0] / 6.0 / (2**scaling) ** 3
102
+ c[1] = (coeff[1] / (2**scaling) ** 2 - coeff[0] / (2**scaling) ** 3) / 2
103
+ c[2] = (
104
+ coeff[2] / 2**scaling - 1 / 2 * coeff[1] / (2**scaling) ** 2 + 1 / 3 * coeff[0] / (2**scaling) ** 3
105
+ )
106
+ c[3] = coeff[3]
107
+ case _:
108
+ raise ValueError(f"Coefficients with order {len(coeff)} can not be converted!")
109
+ return PPoly(c, x)
110
+
111
+ def content_v(self) -> tuple:
112
+ """
113
+ Returns:
114
+ tuple of content values of the class for serialization.
115
+ """
116
+ spl_coeffs = []
117
+ segments = []
118
+ for coeff, x, ppoly in zip(self._coeff, self._x, self._ppoly.reshape(-1)):
119
+ spline_end = np.array([0 for i in range(coeff.shape[0] - 1)] + [ppoly(x[-1])])
120
+ # flip because ppoly 0th order is the last coefficient
121
+ spl_coeffs.append(np.flip(np.append(coeff, spline_end.reshape((spline_end.shape[0], -1)), 1), 0))
122
+ segments.append(np.append((x[1:] - x[:-1]), 0).astype(np.uint16))
123
+
124
+ # Check time. Could be done in constructor, but segment lengths are already calculated here
125
+ # which makes this check more efficient
126
+ if np.any(
127
+ np.array(segments)[:, :-1]
128
+ < QuenchHardware._time_min_shaping_interval_ns / QuenchHardware._time_resolution_ns
129
+ ):
130
+ raise ValueError(
131
+ f"Given time intervals {segments} are below minimum time interval"
132
+ f"{QuenchHardware._time_min_shaping_interval_ns / QuenchHardware._time_resolution_ns} for shaping!"
133
+ )
134
+ match len(ppoly.c):
135
+ case 4:
136
+ return (
137
+ tuple([tuple(segment) for segment in segments]),
138
+ tuple([tuple(spl_coeff[0, :].astype(np.uint32)) for spl_coeff in spl_coeffs]),
139
+ tuple([tuple(spl_coeff[1, :].astype(np.int64)) for spl_coeff in spl_coeffs]),
140
+ tuple([tuple(spl_coeff[2, :].astype(np.int64)) for spl_coeff in spl_coeffs]),
141
+ tuple([tuple(spl_coeff[3, :].astype(np.int64)) for spl_coeff in spl_coeffs]),
142
+ )
143
+ case 2:
144
+ return (
145
+ tuple([tuple(segment) for segment in segments]),
146
+ tuple([tuple(spl_coeff[0, :].astype(np.uint32)) for spl_coeff in spl_coeffs]),
147
+ tuple([tuple(spl_coeff[1, :].astype(np.int64)) for spl_coeff in spl_coeffs]),
148
+ None,
149
+ None,
150
+ )
151
+ case 1:
152
+ return (
153
+ tuple([tuple(segment) for segment in segments]),
154
+ tuple([tuple(spl_coeff[0, :].astype(np.uint32)) for spl_coeff in spl_coeffs]),
155
+ None,
156
+ None,
157
+ None,
158
+ )
159
+ case _:
160
+ raise ValueError(f"PPoly with order {len(ppoly.c)} can not be converted!")
161
+
162
+ def content_k(self) -> tuple:
163
+ """
164
+ Returns:
165
+ tuple of content keys of the class for serialization.
166
+ """
167
+ return (
168
+ "segment_length",
169
+ "x0",
170
+ "x1",
171
+ "x2",
172
+ "x3",
173
+ )
174
+
175
+ def __repr__(self) -> str:
176
+ return f"{self._ppoly}"
177
+
178
+ @classmethod
179
+ def test_ppoly_roots(cls, ppoly: PPoly, min_val: float, max_val: float, name: str = "") -> None:
180
+ """Calculate roots of the ppoly to test accumulator limits. Less accurate than test_ppoly_coeff"""
181
+ _min_val = np.array(min_val).astype(np.float64)
182
+ _max_val = np.array(max_val).astype(np.float64)
183
+ ppoly.c[-1] = ppoly.c[-1].astype(np.float64) - _min_val
184
+ roots_min = ppoly.roots()
185
+ # filter to roots within the span of the poly
186
+ roots_min_in_range = np.logical_and(roots_min > ppoly.x[0], roots_min < ppoly.x[-1])
187
+ # filter roots which are exactly 0
188
+ min_violations = np.logical_and(
189
+ ppoly(roots_min[roots_min_in_range]) < 0, roots_min_in_range[roots_min_in_range]
190
+ )
191
+ roots_min = roots_min[roots_min_in_range]
192
+ ppoly.c[-1] += _min_val
193
+ if np.any(min_violations):
194
+ raise ValueError(
195
+ f"PPoly for {name} exceeds minimum value {min_val} with value "
196
+ f"{ppoly(roots_min[min_violations])} at times {roots_min[min_violations]}"
197
+ )
198
+ ppoly.c[-1] -= _max_val
199
+ roots_max = ppoly.roots()
200
+ # filter to roots within the span of the poly
201
+ roots_max_in_range = np.logical_and(roots_max > ppoly.x[0], roots_max < ppoly.x[-1])
202
+ # filter roots which are exactly 0
203
+ max_violations = np.logical_and(
204
+ ppoly(roots_max[roots_max_in_range]) > 0, roots_max_in_range[roots_max_in_range]
205
+ )
206
+ roots_max = roots_max[roots_max_in_range]
207
+ ppoly.c[-1] += _max_val
208
+ if np.any(max_violations):
209
+ raise ValueError(
210
+ f"PPoly for {name} exceeds maximum value {max_val} with value "
211
+ f"{ppoly(roots_max[max_violations])} at times {roots_max[max_violations]}"
212
+ )
213
+
214
+ @classmethod
215
+ def _generate_cache_key(cls, coeff: np.ndarray, x: np.ndarray) -> str:
216
+ coeff_bytes = coeff.tobytes()
217
+ x_bytes = x.tobytes()
218
+ hash_obj = hashlib.sha256()
219
+ hash_obj.update(coeff_bytes)
220
+ hash_obj.update(x_bytes)
221
+ return hash_obj.hexdigest()
222
+
223
+ @classmethod
224
+ def test_ppoly_coeff(cls, coeff, x, name) -> None:
225
+ """Accumulates the polynomial to test for over/underflows"""
226
+ cache_key = cls._generate_cache_key(coeff, x)
227
+
228
+ if cache_key in cls._test_ppoly_coeff_cache:
229
+ return
230
+
231
+ x = x.astype(np.uint32)
232
+ out = np.zeros(x[-1], dtype=np.uint32)
233
+ for i, segment_length in enumerate(np.diff(x)):
234
+ acc = np.zeros(segment_length, dtype=np.uint64)
235
+ for o in range(coeff.shape[0]):
236
+ if o == 0:
237
+ acc[coeff.shape[0] - 1 - o :] = np.repeat(coeff[o, i], segment_length - coeff.shape[0] + 1 + o)
238
+ else:
239
+ acc[coeff.shape[0] - 1 - o] = coeff[o, i] << 16 * o
240
+ acc[coeff.shape[0] - 1 - o :] = np.cumsum(acc[coeff.shape[0] - 1 - o :])
241
+ out[x[i] : x[i + 1]] = acc >> 48
242
+ if np.any(out < 0.0):
243
+ raise ValueError(f"PPoly accumulator underflow for {name}!")
244
+ if np.any(out > 2**16 - 1):
245
+ raise ValueError(f"PPoly accumulator overflow for {name}!")
246
+
247
+ cls._test_ppoly_coeff_cache[cache_key] = True
248
+
249
+
250
+ class FreqSpline(SplineParameter):
251
+ _instances: ClassVar[dict[int, Any]] = {}
252
+ """All instances of the class, keeping track of existing objects."""
253
+ _instance_dict: ClassVar[dict] = {}
254
+ """Lookup dict to enable register() to find existing objects."""
255
+ typename = "freq_spline_parameter"
256
+ """A string to name the class type."""
257
+
258
+ @classmethod
259
+ def generate_spline(cls, function, time: Time, freq: Freq) -> PPoly:
260
+ """
261
+ Generates a first order (linar) piecewise polynomial for frequency splines
262
+
263
+ Args:
264
+ function: Function to generate the spline from. Must be defined and (piecewise) monotonous on (0,1) -> (0,1)
265
+ time (Time): Times to evaluate the function at, mapped such that (t0, ..., tn) -> (0, ... ,1)
266
+ freq (Freq): Frequency range the function gets mapped to (0, 1) -> (freq[0], freq[1])
267
+
268
+ Returns:
269
+ PPoly: Piecewise linear polynomial representing the function
270
+ """
271
+ cls.check_min_shape_interval(time)
272
+ x = np.array(time._value / QuenchHardware._time_resolution_ns)
273
+ y = function(x / x[-1]) * (freq._value[1].astype(np.float64) - freq._value[0]) + freq._value[0]
274
+ return PPoly([(y[1:] - y[:-1]) / (x[1:] - x[:-1]), y[:-1]], x)
275
+
276
+ def __init__(self, ppoly: PPoly | list[PPoly] | np.ndarray, name="") -> None:
277
+ """
278
+ Provides 1st order (linear) frequency interpolation for Quench interpolators.
279
+ To create polynomials, it is recommended to use generate_spline()
280
+
281
+ Args:
282
+ ppoly (PPoly | list[PPoly] | np.ndarray): Piecewise polynimial in machine units
283
+ name (str, optional): Parameter name used for debugging. Defaults to "".
284
+
285
+ Raises:
286
+ ValueError if the ppoly is out of bounds (f_min, f_max)
287
+ """
288
+ super().__init__(np.array(ppoly), name, interpolator_max_order=QuenchHardware._freq_interpolator_max_order)
289
+ for coeff, x in zip(self._coeff, self._x):
290
+ self.test_ppoly_coeff(coeff, x, name)
291
+
292
+
293
+ class PhaseSpline(SplineParameter):
294
+ _instances: ClassVar[dict[int, Any]] = {}
295
+ """All instances of the class, keeping track of existing objects."""
296
+ _instance_dict: ClassVar[dict] = {}
297
+ """Lookup dict to enable register() to find existing objects."""
298
+ typename = "phase_spline_parameter"
299
+ """A string to name the class type."""
300
+
301
+ @classmethod
302
+ def generate_spline(cls, function, time: Time, phase: Phase) -> PPoly:
303
+ """
304
+ Generates a 0th order (stepped) piecewise polynomial for phase splines
305
+
306
+ Args:
307
+ function: Function to generate the spline from. Must be defined and (piecewise) monotonous on (0,1) -> (0,1)
308
+ time (Time): Times to evaluate the function at, mapped such that (t0, ..., tn) -> (0, ... ,1)
309
+ amp (Amp): Phase range the function gets mapped to (0, 1) -> (phase[0], phase[1])
310
+
311
+ Returns:
312
+ PPoly: Stepped approximation representing the function
313
+ """
314
+ cls.check_min_shape_interval(time)
315
+ x = np.array(time._value / QuenchHardware._time_resolution_ns)
316
+ y = function(x / x[-1]) * (phase._value[1].astype(np.float64) - phase._value[0]) + phase._value[0]
317
+ return PPoly([y[1:]], x)
318
+
319
+ def __init__(self, ppoly: PPoly | list[PPoly] | np.ndarray, name="") -> None:
320
+ """
321
+ Provides 0th order (stepped) phase interpolation for Quench interpolators.
322
+ To create polynomials, it is recommended to use generate_spline()
323
+
324
+ Args:
325
+ ppoly (PPoly | list[PPoly] | np.ndarray): Piecewise polynimial in machine units
326
+ name (str, optional): Parameter name used for debugging. Defaults to "".
327
+ """
328
+ super().__init__(np.array(ppoly), name, interpolator_max_order=QuenchHardware._phase_interpolator_max_order)
329
+
330
+
331
+ class AmpSpline(SplineParameter):
332
+ _instances: ClassVar[dict[int, Any]] = {}
333
+ """All instances of the class, keeping track of existing objects."""
334
+ _instance_dict: ClassVar[dict] = {}
335
+ """Lookup dict to enable register() to find existing objects."""
336
+ typename = "amp_spline_parameter"
337
+ """A string to name the class type."""
338
+
339
+ @classmethod
340
+ def generate_spline(cls, function, time: Time, amp: Amp, bc_type="clamped") -> PPoly:
341
+ """
342
+ Generates a third order piecewise polynomial for amplitude splines
343
+
344
+ Args:
345
+ function: Function to generate the spline from. Must be defined and (piecewise) monotonous on (0,1) -> (0,1)
346
+ time (Time): Times to evaluate the function at, mapped such that (t0, ..., tn) -> (0, ... ,1)
347
+ amp (Amp): Amplitude range the function gets mapped to (0, 1) -> (amp[0], amp[1])
348
+
349
+ Returns:
350
+ PPoly: Third order cubic amplitude spline representing the function
351
+ """
352
+ cls.check_min_shape_interval(time)
353
+ x = np.array(time._value / QuenchHardware._time_resolution_ns)
354
+ # FIXME: Because DDS Cards are 14 bit and the conversion to Amp gives us a 14 bit value
355
+ # we have to multiply by 4 to get the correct value for the interpolator
356
+ y = (function(x / x[-1]) * (amp._value[1].astype(np.float64) - amp._value[0]) + amp._value[0]) * 4
357
+ return CubicSpline(x, y, bc_type=bc_type)
358
+
359
+ def __init__(self, ppoly: PPoly | list[PPoly] | np.ndarray, name="") -> None:
360
+ """
361
+ Provides 3rd order (cubic)) amplitude interpolation for Quench interpolators.
362
+ To create polynomials, it is recommended to use generate_spline()
363
+
364
+ Args:
365
+ ppoly (PPoly | list[PPoly] | np.ndarray): Piecewise polynimial in machine units
366
+ name (str, optional): Parameter name used for debugging. Defaults to "".
367
+ """
368
+ super().__init__(np.array(ppoly), name, interpolator_max_order=QuenchHardware._amp_interpolator_max_order)
369
+ for coeff, x in zip(self._coeff, self._x):
370
+ self.test_ppoly_coeff(coeff, x, name)
File without changes
File without changes
@@ -0,0 +1,121 @@
1
+ from __future__ import annotations
2
+
3
+ import logging
4
+
5
+ import numpy as np
6
+
7
+ from ionpulse_sequence_generator.hardware.channel import ChannelMask
8
+ from ionpulse_sequence_generator.hardware.system import System
9
+ from ionpulse_sequence_generator.hardware.units import Units
10
+ from ionpulse_sequence_generator.parameter.parameter import Time
11
+
12
+ from .sequence import Sequence
13
+
14
+ logger = logging.getLogger(__name__)
15
+ system = System()
16
+
17
+
18
+ class ConditionalSequence(Sequence):
19
+ """
20
+ # ConditionalSequence
21
+ Sequence class to create real-time decision trees depending on given conditions.
22
+ Can be re-used and added to other sequences.
23
+ """
24
+
25
+ __slots__ = (
26
+ "_conditions",
27
+ "paths",
28
+ )
29
+
30
+ def __init__(self, conditions: list, name: str | None = None, ch_mask: ChannelMask = ChannelMask()) -> None:
31
+ """
32
+ Args:
33
+ conditions (list): Conditions for each path. Each condition must have
34
+ a `readout_channel` and a given `state`. The number of Paths added to this
35
+ Fork must be 1+len(conditions), as the first path is always the default
36
+ if none of the conditions are met.
37
+ name (str | None, optional): Name of the sequence, exported to the json for debugging. Defaults to None.
38
+ ch_mask (ChannelMask, optional): ChannelMask for the sequence, extended as events
39
+ and subsequences are added. Defaults to ChannelMask().
40
+
41
+ Raises:
42
+ KeyError: If a condition is missing 'readout_channel' or 'state'
43
+ """
44
+ super().__init__(
45
+ name=name,
46
+ ch_mask=ch_mask,
47
+ )
48
+ for condition in conditions:
49
+ if "readout_channel" not in condition:
50
+ raise KeyError(f"Fork condition of {self._name} is missing ")
51
+ if "state" not in condition:
52
+ raise KeyError(f"Fork condition of {self._name} is missing 'state'")
53
+ # We could store global paths instead of resolving it per channel
54
+ # This makes the C++ parser more complicated and would require introducing a has_readout and has_digital_io entry to the JSON format
55
+ # Additionally, this way we can introduce partial paths (a path with doesn't cover all channels addressed by the fork) later
56
+ self._conditions = conditions
57
+ self._last_sync_time = {}
58
+
59
+ # will lock the channel masks of other sequenes this is added to
60
+ self._lock_channel_mask = True
61
+
62
+ def content_v(self):
63
+ return (
64
+ self._type,
65
+ self._ch_mask,
66
+ self._conditions,
67
+ tuple(self._sequences),
68
+ )
69
+
70
+ def content_k(self) -> tuple[str, str, str, str]:
71
+ return (
72
+ "type",
73
+ ChannelMask.typename,
74
+ "conditions",
75
+ "sequences",
76
+ )
77
+
78
+ # First path is default path
79
+ # TODO: Check that channels match between all fork paths on add
80
+ # TODO: Check when adding a fork to another sequence that all channels of the sequence are in the fork and
81
+ # freeze the channel mask of the sequence afterwards, such that forks are forced to be global
82
+ # until retriggering is implemented
83
+ def __add__(self, other: Sequence):
84
+ if not other._synced:
85
+ raise RuntimeError("Can not add an unsynced path to a fork!")
86
+ self._sequences.append(other.register())
87
+ self._last_sync_time[other] = other.get_time()._value
88
+ if len(self._sequences) > len(self._conditions) + 1: # +1 because of default path
89
+ raise IndexError(f"Adding {len(self._sequences)}th path to fork {self._name}")
90
+
91
+ self._ch_mask |= other._ch_mask
92
+ self._synced = False
93
+ return self
94
+
95
+ def get_time(self) -> Time:
96
+ if not self._synced:
97
+ raise RuntimeError("Can not get time for an unsynced sequence!")
98
+ # For non-deterministic forks we take the maximum time
99
+ # TODO: Change this for deterministic forks, if we need them
100
+ return Time(value=max(self._last_sync_time.values()), unit=Units.ns)
101
+
102
+ def sync(self, ch_mask: ChannelMask | None = None, to_time: float = 0):
103
+ raise NotImplementedError("Sync can not be called for forks. Do you mean sync_paths instead?")
104
+
105
+ def sync_paths(self) -> None:
106
+ if self._synced:
107
+ return
108
+ max_time = 0
109
+ min_edge_time, _ = system.get_timing_constraints_from_ch_mask(ch_mask=self._ch_mask, unit=Units.ns)
110
+
111
+ for path in self._sequences:
112
+ max_time = np.max(path.get_time()._value, initial=max_time)
113
+ if max_time == 0:
114
+ self._synced = True
115
+ return
116
+ elif max_time < min_edge_time:
117
+ max_time = min_edge_time
118
+ # add wait to paths
119
+ for path in self._sequences:
120
+ path.sync(ch_mask=None, to_time=Time(max_time, Units.ns))
121
+ self._synced = True
@@ -0,0 +1,108 @@
1
+ from __future__ import annotations
2
+
3
+ import logging
4
+ from typing import TYPE_CHECKING
5
+
6
+ import numpy as np
7
+
8
+ from ionpulse_sequence_generator.hardware.channel import ChannelMask
9
+ from ionpulse_sequence_generator.hardware.system import System
10
+ from ionpulse_sequence_generator.hardware.units import Units
11
+ from ionpulse_sequence_generator.parameter.parameter import Time
12
+
13
+ from .sequence import Sequence
14
+
15
+ if TYPE_CHECKING:
16
+ from ionpulse_sequence_generator.event.event import Event
17
+
18
+ logger = logging.getLogger(__name__)
19
+ system = System()
20
+
21
+
22
+ class LoopSequence(Sequence):
23
+ """
24
+ # LoopSequence
25
+ Sequence class to execute events or other sequence multiple times. Can be re-used and added to other sequences.
26
+
27
+ Loops are natively implemented in ionpulse and should be preferred over using a for or while loop in python.
28
+ i.e. prefer
29
+ ```
30
+ loop = LoopSequence(iterations = 5)
31
+ loop += Event1
32
+ loop += Event2
33
+ loop += Subsequence1
34
+ ```
35
+ over
36
+ ```
37
+ for i in range(5)
38
+ sequence += Event1
39
+ sequence += Event2
40
+ sequence += Subsequence1
41
+ ```
42
+ as the latter is much less efficient on the decoder.
43
+
44
+ Additionally, parameters of Events and Sequences can be updated, e.g.
45
+ ```
46
+ a = Amp([10,20,30], Units.percent)
47
+ f = Freq([100,110,120], Units.MHz)
48
+ loop = LoopSequence(iterations = 3)
49
+ loop += Event1(a, ...)
50
+ loop += Event2(f, ...)
51
+ loop += Subsequence1
52
+ ```
53
+ will be equivalent to
54
+ ```
55
+ a = [10,20,30]
56
+ f = [100,110,120]
57
+ for i in range(3)
58
+ sequence += Event1(Amp(a[i], Units.percent), ....)
59
+ sequence += Event2(Freq(f[i], Units.MHz))
60
+ sequence += Subsequence1
61
+ ```
62
+ with the latter beeing much less efficient on the decoder.
63
+ """
64
+
65
+ __slots__ = ("_iterations",)
66
+
67
+ def __init__(self, iterations: int, name: str | None = None, ch_mask: ChannelMask = ChannelMask()) -> None:
68
+ """
69
+ Args:
70
+ name (str | None, optional): Name of the sequence, exported to the json for debugging. Defaults to None.
71
+ ch_mask (ChannelMask, optional): ChannelMask for the sequence, extended as events
72
+ and subsequences are added. Defaults to ChannelMask().
73
+ """
74
+ super().__init__(
75
+ name=name,
76
+ ch_mask=ch_mask,
77
+ )
78
+ self._iterations = iterations
79
+
80
+ def content_v(self):
81
+ return (
82
+ self._type,
83
+ self._ch_mask,
84
+ self._iterations,
85
+ tuple(self._sequences),
86
+ )
87
+
88
+ def content_k(self) -> tuple[str, str, str, str]:
89
+ return (
90
+ "type",
91
+ ChannelMask.typename,
92
+ "iterations",
93
+ "sequences",
94
+ )
95
+
96
+ def get_time(self) -> Time:
97
+ if not self._synced:
98
+ raise RuntimeError("Can not get time for an unsynced sequence!")
99
+ time = next(iter(self._last_sync_time._time.values()))
100
+ if time.shape == (): # time is not looped in sequence
101
+ return Time(value=time * self._iterations, unit=Units.ns)
102
+ elif time.shape[-1] != self._iterations: # time is looped, but does not match the sequence
103
+ raise RuntimeError("Looped time does not match loop iterations!")
104
+ else: # time is looped and matches the sequence, collapse once to represent the length of the loop
105
+ return Time(value=np.sum(time, -1), unit=Units.ns)
106
+
107
+ def __add__(self, other: Event | Sequence | tuple) -> LoopSequence:
108
+ return super().__add__(other) # type: ignore