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,882 @@
1
+ from __future__ import annotations
2
+
3
+ import inspect
4
+ import logging
5
+ from enum import Enum
6
+ from typing import Any, ClassVar
7
+
8
+ import msgpack
9
+ import numpy as np
10
+ import orjson
11
+
12
+ from ionpulse_sequence_generator.base.configuration import Configuration
13
+ from ionpulse_sequence_generator.base.header import Header
14
+ from ionpulse_sequence_generator.base.jsonexportable import JSONexportable, garbage_collection_warning_threshold
15
+ from ionpulse_sequence_generator.event.event import Event
16
+ from ionpulse_sequence_generator.event.wait import Wait
17
+ from ionpulse_sequence_generator.hardware.channel import ChannelMask
18
+ from ionpulse_sequence_generator.hardware.hardware import DIOHardware
19
+ from ionpulse_sequence_generator.hardware.readout import DataChannel
20
+ from ionpulse_sequence_generator.hardware.system import System
21
+ from ionpulse_sequence_generator.hardware.units import Units
22
+ from ionpulse_sequence_generator.parameter.parameter import Amp, Freq, Phase, Time
23
+ from ionpulse_sequence_generator.parameter.pid_parameter import PIDParameter
24
+ from ionpulse_sequence_generator.parameter.spline_parameter import AmpSpline, FreqSpline, PhaseSpline
25
+
26
+ logger = logging.getLogger(__name__)
27
+ system = System()
28
+ configuration = Configuration()
29
+
30
+ _IS_COMPILED = globals().get("__compiled__", False)
31
+
32
+
33
+ class ChannelTime:
34
+ """
35
+ # Channel Time
36
+ Helper Class for sequences to store time per channel.
37
+ Adding two `ChannelTime` instances will add the time per channel.
38
+
39
+ ChannelTime operates with internal channel indices and internal time values.
40
+ """
41
+
42
+ def __init__(self, ch_mask: ChannelMask, time: np.ndarray = np.array(0)) -> None:
43
+ """
44
+ Args:
45
+ ch_mask (ChannelMask): All channels this channel time is defined on.
46
+ Can not be extended by add_time.
47
+ time (np.ndarray, optional): Time to initialize all channels. Defaults to np.array(0).
48
+ """
49
+ self._time: dict[int, np.ndarray] = {}
50
+ self._channels = ch_mask
51
+ _time = time.astype(np.uint64)
52
+ for idx in ch_mask.to_idx_list():
53
+ self._time[idx] = _time.copy()
54
+
55
+ def add_time(self, time: np.ndarray, ch_mask: ChannelMask) -> None:
56
+ """
57
+ Adds a time to all the channels within the given ChannelMask
58
+ """
59
+ for idx in ch_mask.to_idx_list():
60
+ self._time[idx] = Time.add_array(self._time[idx], time)
61
+
62
+ def set_time(self, time: np.ndarray, ch_mask: ChannelMask) -> None:
63
+ """
64
+ Sets a time to the given channel, potentially extending the channel mask.
65
+ """
66
+ self._channels |= ch_mask
67
+ for idx in ch_mask.to_idx_list():
68
+ self._time[idx] = time
69
+
70
+ def get_time(self, idx: int) -> Time | None:
71
+ """
72
+ Returns:
73
+ Time : A Time instance with the value of the given Channel
74
+ """
75
+ if self._time[idx].shape == ():
76
+ if self._time[idx] == 0:
77
+ return None
78
+ else: # noqa: PLR5501
79
+ if (self._time[idx] == 0).all():
80
+ return None
81
+ return Time(self._time[idx], unit=Units.ns)
82
+
83
+ def get_sync(self, ch_mask: ChannelMask | None = None) -> tuple[bool, ChannelTime, Time]:
84
+ """
85
+ Calculates sync timing for this channel time.
86
+
87
+ Args:
88
+ ch_mask (ChannelMask | None, optional): Channels to consider for sync, must be a subset
89
+ of the channels the ChannelTime is defined on. If None all channels within
90
+ the ChannelTime will be considered. Defaults to None.
91
+
92
+ Returns:
93
+ tuple[bool, ChannelTime, Time]:
94
+ is_synced: True if all channels have the same time, False otherwise.
95
+ time_difference: Time difference for each channel as a new ChannelTime
96
+ max_looped_time: maximum looped time over all channels and iterations
97
+ """
98
+
99
+ _ch_mask = self._channels if ch_mask is None else ch_mask
100
+ _idx_list = _ch_mask.to_idx_list()
101
+
102
+ # If we want iterations to be synced individually, we have to find the max
103
+ # time per iteration. To do this, we can either expand all times to the largest
104
+ # shape we find among times and add arrays together, or loop through all iterations
105
+ # and add times together.
106
+ # Since most calls to sync will not include looped times, separating looped times
107
+ # first is less expensive than expanding all non looped times to the largest dimension.
108
+ # After separation we can check if we need to treat looped times by checking max_shape.
109
+
110
+ scalar_times = []
111
+ array_times = []
112
+ array_shapes = []
113
+
114
+ for ch in _idx_list:
115
+ time_data = self._time[ch]
116
+ if time_data.shape == ():
117
+ scalar_times.append(float(time_data))
118
+ else:
119
+ array_times.append(time_data)
120
+ array_shapes.append(time_data.shape)
121
+
122
+ if not array_times:
123
+ max_lt = np.array(max(scalar_times) if scalar_times else 0)
124
+
125
+ else:
126
+ max_ndim = max(len(shape) for shape in array_shapes)
127
+ target_shape = [1] * max_ndim
128
+
129
+ for shape in array_shapes:
130
+ for i in range(len(shape)):
131
+ dim_idx = max_ndim - len(shape) + i
132
+ target_shape[dim_idx] = max(target_shape[dim_idx], shape[i])
133
+
134
+ broadcasted_arrays = []
135
+
136
+ if scalar_times:
137
+ scalar_max = max(scalar_times)
138
+ broadcasted_arrays.append(np.full(target_shape, scalar_max))
139
+
140
+ for time_array in array_times:
141
+ broadcasted = np.broadcast_to(time_array, target_shape)
142
+ broadcasted_arrays.append(broadcasted)
143
+
144
+ if broadcasted_arrays:
145
+ stacked = np.stack(broadcasted_arrays, axis=0)
146
+ max_lt = np.max(stacked, axis=0)
147
+
148
+ if max_lt.size > 1 and np.all(max_lt == max_lt.flat[0]):
149
+ max_lt = np.array(max_lt.flat[0])
150
+ else:
151
+ max_lt = np.array(0)
152
+
153
+ # TODO: This could be more efficient if we observe timing constraints per channel
154
+ # i.e. check that each channel has his min. wait time instead of using the max of all channels
155
+ # however, this is computationally quite a bit more expensive.
156
+
157
+ min_edge_time, _ = system.get_timing_constraints_from_ch_mask(_ch_mask, unit=Units.ns) # type: ignore
158
+
159
+ diff_time = ChannelTime(time=np.array(0), ch_mask=_ch_mask) # type: ignore
160
+ sync_diff = 0
161
+ min_diff_time = np.max(max_lt)
162
+ min_edge_time_violation = False
163
+ for ch in _idx_list:
164
+ tdiff_ch = max_lt - self._time[ch]
165
+
166
+ if tdiff_ch.shape != () and tdiff_ch.size > 1:
167
+ first_val = tdiff_ch.flat[0]
168
+ if np.all(tdiff_ch == first_val):
169
+ tdiff_ch = np.array(first_val)
170
+ elif np.any(tdiff_ch < min_edge_time):
171
+ min_edge_time_violation = True
172
+ elif np.any(tdiff_ch > 0) and np.any(tdiff_ch < min_edge_time):
173
+ min_edge_time_violation = True
174
+
175
+ min_diff_time = min(min_diff_time, float(np.min(tdiff_ch)))
176
+ diff_time._time[ch] = tdiff_ch
177
+ sync_diff = max(float(np.max(tdiff_ch)), sync_diff)
178
+
179
+ if min_edge_time_violation:
180
+ add_time = min_edge_time - min_diff_time
181
+ for ch in _idx_list:
182
+ diff_time._time[ch] += add_time
183
+
184
+ max_time = Time(max_lt, unit=Units.ns)
185
+ return sync_diff == 0, diff_time, max_time
186
+
187
+ def __add__(self, other: ChannelTime):
188
+ """
189
+ Adds another channel time to all channels within this time,
190
+ ignoring channels which are in other but not in self.
191
+ """
192
+ for ch in other._time:
193
+ if ch in self._time:
194
+ self._time[ch] = Time.add_array(self._time[ch], other._time[ch])
195
+ else:
196
+ self._time[ch] = other._time[ch]
197
+ return self
198
+
199
+ def __repr__(self) -> str:
200
+ return f"{self._time}"
201
+
202
+ def smaller_equal(self, time: Time, ch_mask: ChannelMask) -> bool:
203
+ """
204
+ Returns:
205
+ bool: True if all times for the given channel mask are smaller or equal to the times
206
+ in this channel time, including all loop iterations.
207
+ """
208
+ smeq = True
209
+ for idx in ch_mask.to_idx_list():
210
+ smeq &= bool(np.all(self._time[idx] <= time._value))
211
+ return smeq
212
+
213
+ def __le__(self, other: ChannelTime) -> bool:
214
+ """
215
+ Returns:
216
+ bool: True if all times for channels which are in self but not in other are
217
+ smaller or equal to the times in this channel time, including all loop iterations.
218
+ """
219
+ smeq = True
220
+ for ch in other._time:
221
+ if ch in self._time:
222
+ smeq &= bool(np.any(self._time[ch] <= other._time[ch]))
223
+ return smeq
224
+
225
+ def is_zero(self, ch_mask: ChannelMask | None = None) -> bool:
226
+ """
227
+ _summary_
228
+
229
+ Args:
230
+ ch_mask (ChannelMask): _description_
231
+
232
+ Returns:
233
+ _type_: _description_
234
+ """
235
+ zero = True
236
+ if ch_mask is None:
237
+ ch_mask = self._channels
238
+ for idx in ch_mask.to_idx_list():
239
+ zero &= bool(np.all(self._time[idx] == 0))
240
+ return zero
241
+
242
+
243
+ def convert_to_json_member(o):
244
+ """
245
+ Helper method to convert non primitives to primitives for JSON export as members of a
246
+ JSON object.
247
+ """
248
+ match o:
249
+ case JSONexportable():
250
+ return o.to_json_member()
251
+ case np.ndarray():
252
+ return list(o.reshape(-1))
253
+ case Enum():
254
+ return o.value
255
+ case np.integer():
256
+ return int(o)
257
+ case np.floating():
258
+ return float(o)
259
+ case ChannelMask():
260
+ return o.to_json_member()
261
+ case DataChannel():
262
+ return o.to_json()
263
+ case _:
264
+ raise TypeError(f"Encountered unknown data type {type(o)} in object {o} when converting to JSON!")
265
+
266
+
267
+ class Sequence(JSONexportable):
268
+ """
269
+ # Sequence
270
+ This abstract base class can contain Events or other Sequences:
271
+ ```
272
+ <-Event-><-Event->|<-Sequence-> |<-Event->
273
+ |<-Event-><-Event->|
274
+ ```
275
+ It implements some of the basic functions to export the sequence (get_main_dict), adding other
276
+ sequences and events (__add__) to it as well as syncronizing all channels within the sequence (sync).
277
+ """
278
+
279
+ __slots__ = (
280
+ "_ch_mask",
281
+ "_last_sync_idx",
282
+ "_last_sync_time",
283
+ "_lock_channel_mask",
284
+ "_main_dict",
285
+ "_n_sync",
286
+ "_post_time",
287
+ "_pre_time",
288
+ "_sequences",
289
+ "_synced",
290
+ "_time",
291
+ "_type",
292
+ )
293
+ _instances: dict[int, Any] = {}
294
+ """All instances of the class, keeping track of existing objects."""
295
+ _instance_dict: ClassVar[dict] = {}
296
+ """Lookup dict to enable register() to find existing objects."""
297
+ typename = "sequence"
298
+
299
+ def __init__(self, name: str | None = None, ch_mask: ChannelMask = ChannelMask()) -> None:
300
+ """
301
+ Args:
302
+ name (str | None, optional): Name of the sequence, exported to the json for debugging. Defaults to None.
303
+ ch_mask (ChannelMask, optional): ChannelMask for the sequence, extended as events
304
+ and subsequences are added. Defaults to ChannelMask().
305
+ """
306
+ super().__init__(name)
307
+
308
+ self._last_sync_time = ChannelTime(ch_mask=ch_mask)
309
+ self._last_sync_idx = 0
310
+ self._type = self.__class__.__name__
311
+ self._ch_mask = ch_mask
312
+ self._n_sync: int = 0
313
+ self._synced: bool = True
314
+ self._sequences: list[Sequence | Event] = []
315
+ self._main_dict = None
316
+ self._lock_channel_mask = False
317
+ if configuration.check_post_time:
318
+ # required time for the next event per channel
319
+ self._post_time = ChannelTime(ch_mask=ChannelMask())
320
+ # time of the first event per channel, propagated from subsequences
321
+ self._pre_time = ChannelTime(ch_mask=ChannelMask())
322
+
323
+ def content_v(self):
324
+ return (
325
+ self._type,
326
+ self._ch_mask,
327
+ tuple(self._sequences),
328
+ )
329
+
330
+ def content_k(self) -> tuple[str, str, str]:
331
+ return (
332
+ "type",
333
+ ChannelMask.typename,
334
+ "sequences",
335
+ )
336
+
337
+ def mark(self) -> None:
338
+ self._marked = True
339
+ for seq in self._sequences:
340
+ seq.mark()
341
+
342
+ def set_name_to_variable_name(self) -> None:
343
+ """
344
+ Tries to use inspect to return the variable name for the sequence as debug name.
345
+
346
+ Raises:
347
+ RuntimeError: If the automatic name resolution fails
348
+ (e.g. the same variable name exists multiple times int the current frame).
349
+ """
350
+ try:
351
+ callers_local_vars = inspect.currentframe().f_back.f_back.f_locals.items() # type: ignore
352
+ self._name = next(
353
+ var_name
354
+ for var_name, var_val in callers_local_vars
355
+ if isinstance(var_val, Sequence) and var_val is self
356
+ )
357
+ except:
358
+ raise RuntimeError(
359
+ "Could not automatically obtain a name for the sequence. Please set a name in the constructor."
360
+ )
361
+
362
+ def get_subsequence(self, ch_idx: ChannelMask) -> list[Any]:
363
+ """Returns
364
+ list[Any]: A list containing the Sequences/Events on the corresponding
365
+ channel `ch_idx` of the sequence."""
366
+ return [seq for seq in self._sequences if seq._ch_mask.contains(ch_idx)]
367
+
368
+ def get_time(self) -> Time:
369
+ """
370
+ Raises:
371
+ RuntimeError: If the sequence is not synchronized, as the time of the sequence is undefined.
372
+
373
+ Returns:
374
+ Time: time of this sequence
375
+ """
376
+ if not self._synced:
377
+ raise RuntimeError("Can not get time for an unsynced sequence!")
378
+ if self._last_sync_time._time:
379
+ return Time(value=next(iter(self._last_sync_time._time.values())), unit=Units.ns)
380
+ return Time(value=0, unit=Units.ns)
381
+
382
+ def get_main_dict(self, header: Header | None = None) -> dict:
383
+ """
384
+ Marks this Sequence as the main sequence and creates a dict for conversion into a JSON string.
385
+ Before exporting, garbage collection will delete unused instances. After generating the dict
386
+ for the first time, all instances will be cleared. Subsequent calls to get_main_dict will not
387
+ attempt to re-generate the dict but instead return the cached dict.
388
+
389
+ Returns:
390
+ dict: A dict representing the sequence to export to ionpulse.
391
+ """
392
+ if self._main_dict is not None:
393
+ return self._main_dict
394
+ self._name = "main"
395
+ if not self._synced:
396
+ synced, _, _ = self.get_sync(self._ch_mask).get_sync()
397
+ if not synced:
398
+ logger.warning("Main Sequences is not synced!")
399
+
400
+ if not any(isinstance(hw, DIOHardware) for hw in system.get_hw_from_ch_mask(self._ch_mask)):
401
+ logger.warning("Warning: Main Sequences generated without DIOHardware, automatically adding wait.")
402
+ for hw in system.get_hw_by_type(DIOHardware):
403
+ self += Wait(
404
+ "Force DIOHardware",
405
+ hw.channel(),
406
+ Time(hw.get_min_edge_time(Units.ns), Units.ns),
407
+ )
408
+ self.sync()
409
+
410
+ self.register()
411
+ # run garbage collection, note that this invalidates _instance_dict
412
+ # garbace collection marks all registerd objects belonging to this sequence, then deletes
413
+ # all unmarked objects. After the export is done,
414
+ self.mark()
415
+ types: list[JSONexportable] = [
416
+ Freq,
417
+ Phase,
418
+ Amp,
419
+ FreqSpline,
420
+ PhaseSpline,
421
+ AmpSpline,
422
+ Time,
423
+ Event,
424
+ Sequence,
425
+ PIDParameter,
426
+ ] # type: ignore
427
+ deleted_instances = 0
428
+ for type in types:
429
+ cleanup_inst = [inst[0] for inst in type._instances.items() if not inst[1]._marked]
430
+ for inst in cleanup_inst:
431
+ deleted_instances += 1
432
+ _inst = type._instances.pop(inst)
433
+ logger.debug(
434
+ "cleaning up %s %s %s",
435
+ type.typename,
436
+ _inst._name,
437
+ _inst,
438
+ )
439
+ # re-enumerate
440
+ for type in types:
441
+ for idx, inst in enumerate(type._instances.values()):
442
+ inst._idx = idx
443
+ logger.info("Garbage collection complete, deleted %d instances", deleted_instances)
444
+ if deleted_instances > garbage_collection_warning_threshold:
445
+ logger.info(
446
+ "Found over %s unused instances,consider conditional creation of sequences to decrease build time!",
447
+ garbage_collection_warning_threshold,
448
+ )
449
+ # update f, p, a splines with the correct indices
450
+ for n, i in enumerate(FreqSpline._instances.values()):
451
+ i._idx = n + len(Freq._instances)
452
+ for n, i in enumerate(PhaseSpline._instances.values()):
453
+ i._idx = n + len(Phase._instances)
454
+ for n, i in enumerate(AmpSpline._instances.values()):
455
+ i._idx = n + len(Amp._instances)
456
+ # update sequences with correct indices
457
+ for n, i in enumerate(Sequence._instances.values()):
458
+ i._idx = n + len(Event._instances)
459
+ main_dict = {Header.typename: None}
460
+ for type in types:
461
+ main_dict[type.typename] = [instance.to_json() for instance in type._instances.values()] # type: ignore
462
+ system.readout.build_name_index_lists()
463
+ system.readout.check()
464
+ if header is not None:
465
+ main_dict[Header.typename] = header.to_json() # type: ignore
466
+ # clear all sequences
467
+ for type in types:
468
+ type.clear()
469
+ system.clear_readout()
470
+ self._main_dict = main_dict
471
+ return self._main_dict
472
+
473
+ def save_to_json_file(self, fname: str, header: Header | None = None) -> None:
474
+ """
475
+ Serializes the sequence (see get_main_dict()) and saves it as a JSON file
476
+
477
+ Args:
478
+ fname (str): file name to write.
479
+ header (Header): header for the main dict generation.
480
+ """
481
+ with open(fname, "w", encoding="utf-8") as f:
482
+ f.write(self.get_json_string(header, indent=True))
483
+
484
+ def save_to_msgpack_file(self, fname: str, header: Header) -> None:
485
+ """
486
+ Serializes the sequence (see get_main_dict()) and saves it as a msgpack file
487
+
488
+ Args:
489
+ fname (str): file name to write.
490
+ header (Header): header for the main dict generation.
491
+ """
492
+ main_dict = self.get_main_dict(header)
493
+ with open(fname, "wb") as f:
494
+ f.write(msgpack.packb(main_dict, default=lambda o: o.to_json_member())) # type: ignore
495
+
496
+ def get_json_string(self, header: Header | None, indent: bool = False) -> str:
497
+ """
498
+ Serializes the sequence (see get_main_dict()) and returns it as a JSON string
499
+
500
+ Args:
501
+ header (Header): header for the main dict generation.
502
+ """
503
+ main_dict = self.get_main_dict(header)
504
+ if indent:
505
+ json_bytes = orjson.dumps(
506
+ main_dict,
507
+ default=lambda o: convert_to_json_member(o),
508
+ option=orjson.OPT_INDENT_2,
509
+ )
510
+ else:
511
+ json_bytes = orjson.dumps(
512
+ main_dict,
513
+ default=lambda o: convert_to_json_member(o),
514
+ )
515
+ return json_bytes.decode("utf-8")
516
+
517
+ def get_post_time(self, ch_idx: ChannelMask) -> Time:
518
+ if not ch_idx.is_single_channel():
519
+ raise ValueError("Channel Index can only be single channel!")
520
+ post_time = self._post_time.get_time(ch_idx.to_idx_list()[0])
521
+ if post_time is None:
522
+ return Time(0, Units.ns)
523
+ return post_time
524
+
525
+ def get_max_post_time(self) -> Time:
526
+ time = Time(0, Units.ns)
527
+ for ch_idx in self._ch_mask:
528
+ time = Time.maximum(time, self.get_post_time(ch_idx))
529
+ return time
530
+
531
+ def _check_post_time(self, other: Event | Sequence) -> None:
532
+ """
533
+ Channel wise post-time check called in __add__ for an added Sequence or Event.
534
+ Checks the current _post_time of the sequence against the event time on the given channel(s),
535
+ and updates the post time with the post time of the given event / sequence.
536
+
537
+ Raises:
538
+ ValueError: If time of other is shorter than post_time.
539
+ """
540
+ # FIXME replace with is_empty from timestamp branch
541
+ if len(other._ch_mask - system._async_channels) == 0:
542
+ return
543
+ # Check channels which are in both post_time and other and are not readout:
544
+ ch_mask = (other._ch_mask & self._post_time._channels) - system._async_channels
545
+ # check that the element meets the timing constraints of this sequence
546
+ post_time_valid = False
547
+ if self._post_time.is_zero(ch_mask):
548
+ post_time_valid = True
549
+ if isinstance(other, Event):
550
+ other_time = other._time._value
551
+ post_time_valid = self._post_time.smaller_equal(other._time, ch_mask)
552
+ else:
553
+ other_time = other._sequences[0]._time._value
554
+ # FIXME: First sequence element can be on a different channel. Instead loop through sequence and
555
+ # it's subsequences to x depth to find the first event which is on the appropriate channels
556
+ post_time_valid = self._post_time <= other._pre_time
557
+ if not post_time_valid:
558
+ raise ValueError(
559
+ f"Element {other._name} can not be added, wait time {other_time} too short "
560
+ f"to comply with most recent element in this sequence {self._sequences[-1]._name} "
561
+ f"requiring {self._post_time}."
562
+ )
563
+ # reset the checked elements
564
+ self._post_time.set_time(np.array(0), ch_mask)
565
+
566
+ def __add__(self, other: Event | Sequence | tuple) -> Sequence:
567
+ """
568
+ Adds a subsequence or event to this sequence. Tuples of events or sequences can be added
569
+ for better performance.
570
+ """
571
+ if isinstance(other, tuple):
572
+ for other_ele in other:
573
+ self += other_ele
574
+ return self
575
+
576
+ is_event = isinstance(other, Event)
577
+ is_sequence = isinstance(other, Sequence)
578
+
579
+ # filter empty sequences
580
+ if is_sequence and other._ch_mask.is_empty() and len(other._sequences) == 0:
581
+ return self
582
+
583
+ # add naming for clearer error messages
584
+ if not _IS_COMPILED:
585
+ if is_sequence and other._name is None:
586
+ other.set_name_to_variable_name()
587
+ if self._name is None:
588
+ self.set_name_to_variable_name()
589
+
590
+ ch_intersection = self._ch_mask & other._ch_mask
591
+ self_contains_other = self._ch_mask.contains(other._ch_mask)
592
+
593
+ # don't allow expansion of a locked channel mask
594
+ if self._lock_channel_mask and not ch_intersection:
595
+ raise ValueError(
596
+ f"Sequence {self._name} contains a fork. All channels added to this sequence must be within the fork."
597
+ )
598
+
599
+ # don't allow empty channel masks to be added
600
+ if other._ch_mask.is_empty():
601
+ raise ValueError(
602
+ f"{other._name} has an empty channel mask. Events and"
603
+ "non-empty sequences with empty channel masks are not supported."
604
+ )
605
+
606
+ # check weather we can add the other sequence, i.e. the channel subset is synced
607
+ # good cases:
608
+ # A) other is an event (addressing only a single channel)
609
+ # B) sequence is synced & all channels of other are in self
610
+ # C) sequence is not synced and no all channels are contained
611
+ # D) sequence is not synced and time is the same for all channels concerned
612
+ channel_subset_synced = False
613
+ add_wait = False
614
+ if is_event:
615
+ if not other._ch_mask.is_single_channel:
616
+ raise ValueError("Events must target only one channel")
617
+ channel_subset_synced = True
618
+ if not self_contains_other: # respect sync() time windows
619
+ add_wait = True
620
+ else:
621
+ # check other
622
+ if not other._synced:
623
+ raise RuntimeError(
624
+ f"Channels in sequence {other._name} need to be synced before adding it to another sequence!"
625
+ )
626
+ # check self
627
+ if self._synced:
628
+ channel_subset_synced = True
629
+ if not self_contains_other:
630
+ add_wait = True
631
+ elif not ch_intersection:
632
+ channel_subset_synced = True
633
+ add_wait = True # respect sync() time windows
634
+ else: # we are not synced, but it could be that the subset of channels is synced
635
+ ch_mask_no_async = other._ch_mask - system._async_channels
636
+
637
+ if self._synced:
638
+ time_since_last_sync = ChannelTime(ch_mask=ChannelMask())
639
+ else:
640
+ time_since_last_sync = ChannelTime(time=np.array(0), ch_mask=ch_mask_no_async)
641
+ for seq in self._sequences[self._last_sync_idx :]:
642
+ seq_ch_mask = seq._ch_mask & ch_mask_no_async
643
+ if seq_ch_mask:
644
+ time = seq.get_time()._value
645
+ for idx in seq_ch_mask._channels:
646
+ time_since_last_sync._time[idx] = Time.add_array(time_since_last_sync._time[idx], time)
647
+
648
+ channel_subset_synced, _, _ = time_since_last_sync.get_sync()
649
+
650
+ # If the sequence added is a fork, we lock the channel mask and check that it is indeed global.
651
+ # We do the same if a subsequnce which is added is locked.
652
+ if other._lock_channel_mask:
653
+ self._lock_channel_mask = True
654
+ if not other._ch_mask == self._ch_mask:
655
+ raise ValueError("ConditionalSequences must be global and address all channels in the sequence!")
656
+
657
+ if not channel_subset_synced:
658
+ raise RuntimeError(
659
+ f"Channels in sequence {self._name} need to be synced before adding sequence {other._name}!"
660
+ )
661
+
662
+ check_post_time = configuration.check_post_time
663
+
664
+ if check_post_time and not self._post_time.is_zero():
665
+ self._check_post_time(other)
666
+
667
+ if check_post_time:
668
+ # update current post time with the added elements post time
669
+ if is_event:
670
+ if other._post_time is not None:
671
+ self._post_time.set_time(other._post_time._value, other._ch_mask) # type: ignore
672
+ else:
673
+ self._post_time += other._post_time # type: ignore
674
+
675
+ if ( # add wait before changing ch_mask of this sequence
676
+ add_wait and self._last_sync_time._time
677
+ ): # fill until last sync with a wait on the concerend channels
678
+ # Note: We could reduce amount of events generated by grouping channels
679
+ # These waits could extend over multiple channels, since they will be split up in the parser
680
+ # this could only reduce the sequence size in the JSON
681
+ wait_time = Time(
682
+ next(iter(self._last_sync_time._time.values())),
683
+ unit=Units.ns,
684
+ )
685
+ # We only care about channels in other that are not in self. Set.difference() takes care of that.
686
+ # Additionally, we need to remove all async channels, as they do not need Waits
687
+ reduced_channels = (other._ch_mask - self._ch_mask) - system._async_channels
688
+ # check that the wait time complies with the min wait time for the hardware added:
689
+ time_min_edge, _ = system.get_timing_constraints_from_ch_mask(reduced_channels, Units.ns)
690
+ if wait_time < Time(time_min_edge, Units.ns):
691
+ raise ValueError(
692
+ f"{other._name} can not be added to the sequence without adding waits to all channels \n"
693
+ "of the sequence to comply with the minimum edge time.\n"
694
+ "If this is intended, use\n"
695
+ f"{self._name} += Wait(Time({Time(time_min_edge, Units.ns) - wait_time}), {self._name}._ch_mask)\n"
696
+ f"{self._name}.sync()\n"
697
+ "to get this behaviour."
698
+ )
699
+ # We only care about channels in other that are not in self. Set.difference() takes care of that.
700
+ # Additionally, we need to remove the readout channel, as it does not need Waits
701
+ for idx in reduced_channels.to_idx_list():
702
+ # advance last sync time, add waits
703
+ self._last_sync_time._time[idx] = wait_time._value
704
+ self._sequences.insert(
705
+ self._last_sync_idx,
706
+ Wait(f"add_time{self._last_sync_idx}", ChannelMask([idx]), wait_time).register(),
707
+ )
708
+ # advance sync index
709
+ self._last_sync_idx += 1
710
+ # Update pre_time for added waits:
711
+ if configuration.check_post_time:
712
+ for idx in (reduced_channels - self._pre_time._channels).to_idx_list():
713
+ self._pre_time.set_time(wait_time._value, ChannelMask([idx]))
714
+
715
+ if check_post_time:
716
+ # Update pre_time from sequence/event:
717
+ if (
718
+ is_event
719
+ and len(other._ch_mask & self._pre_time._channels) == 0
720
+ and len(other._ch_mask - system._async_channels) != 0
721
+ ):
722
+ self._pre_time.set_time(other.get_time()._value, other._ch_mask)
723
+ elif not add_wait and is_sequence:
724
+ # if add_wait == True the sequence is not at the start of any of the channels in this sequence
725
+ self._pre_time += other._pre_time
726
+
727
+ # update the ch_mask first, because register might return an element with a different channel mask
728
+ # if the element already exists
729
+ # Note: Currently this is not an issue, as register takes the channel mask into account since the _sequences
730
+ # array is not grouped by channel, which does not allow us to extend the channel mask of Events or Sequences
731
+ self._ch_mask = self._ch_mask | other._ch_mask
732
+ other = other.register()
733
+ self._synced = False
734
+
735
+ # append the sequence
736
+ self._sequences.append(other) # type: ignore -> tuples are already filtered
737
+
738
+ return self
739
+
740
+ def get_sync(
741
+ self,
742
+ ch_mask: ChannelMask | None = None,
743
+ ) -> ChannelTime:
744
+ """
745
+ Args:
746
+ ch_mask (ChannelMask | None, optional): Channels to obtain sync information for.
747
+ If None, all channels of the sequence will be considered. Defaults to None.
748
+
749
+ Returns:
750
+ ChannelTime: Time for each channel for this sequence.
751
+ """
752
+
753
+ if self._synced:
754
+ return ChannelTime(ch_mask=ChannelMask())
755
+
756
+ # check all channels by default
757
+ if ch_mask is None:
758
+ ch_mask = self._ch_mask
759
+ # don't sync async channels
760
+ ch_mask = ch_mask - system._async_channels
761
+
762
+ # iterate over un-synced sequences and add time to a new channel time
763
+ time_since_last_sync = ChannelTime(time=np.array(0), ch_mask=ch_mask)
764
+ for seq in self._sequences[self._last_sync_idx :]:
765
+ if seq._ch_mask & ch_mask: # avoid calling get_time() on readout channels
766
+ time_since_last_sync.add_time(seq.get_time()._value, seq._ch_mask & ch_mask)
767
+ return time_since_last_sync
768
+
769
+ def advance_time(self, time: Time, ch_mask: ChannelMask | None = None) -> None:
770
+ """
771
+ Adds a given wait time after the last element in the Sequence and syncronizes all channels.
772
+
773
+ Args:
774
+ time (Time): Time to add after the last element in the sequence
775
+ ch_mask (ChannelMask | None, optional): Channels to add the time to and synchronize,
776
+ if None, all channels in the sequence will be used. Defaults to None.
777
+ """
778
+ if ch_mask is None:
779
+ ch_mask = self._ch_mask
780
+ time_since_last_sync = self.get_sync(ch_mask)
781
+ _, _, max_time = time_since_last_sync.get_sync(ch_mask & time_since_last_sync._channels)
782
+ current_time = Time(value=next(iter(self._last_sync_time._time.values())), unit=Units.ns)
783
+ self.sync(ch_mask, max_time + time + current_time)
784
+
785
+ def sync(self, ch_mask: ChannelMask | None = None, to_time: Time | None = None) -> None:
786
+ """
787
+ Synchronizes all channels within the sequence by adding Wait events.
788
+
789
+ Args:
790
+ ch_mask (ChannelMask | None, optional): Channels to synchronize.
791
+ If None, all channels within the sequence will be synchronized. Defaults to None.
792
+ to_time (Time | None, optional): Desired time of the sequence.
793
+ Must be longer than the minimum time of any channel. Defaults to None.
794
+
795
+ Raises:
796
+ ValueError: If to_time is shorter than the minimum time in the sequence.
797
+ """
798
+ if self._synced and to_time is None:
799
+ return
800
+ if ch_mask is None:
801
+ ch_mask = self._ch_mask
802
+
803
+ ch_mask_no_async = ch_mask - system._async_channels
804
+
805
+ if self._synced:
806
+ time_since_last_sync = ChannelTime(ch_mask=ChannelMask())
807
+ else:
808
+ time_since_last_sync = ChannelTime(time=np.array(0), ch_mask=ch_mask_no_async)
809
+ for seq in self._sequences[self._last_sync_idx :]:
810
+ seq_ch_mask = seq._ch_mask & ch_mask_no_async
811
+ if seq_ch_mask:
812
+ time = seq.get_time()._value
813
+ for idx in seq_ch_mask._channels:
814
+ time_since_last_sync._time[idx] = Time.add_array(time_since_last_sync._time[idx], time)
815
+
816
+ self._synced, diff_time, max_time = time_since_last_sync.get_sync(ch_mask & time_since_last_sync._channels)
817
+
818
+ if to_time is not None:
819
+ current_time = (
820
+ Time(value=next(iter(self._last_sync_time._time.values())), unit=Units.ns)
821
+ if self._last_sync_time._time
822
+ else Time(0, Units.ns)
823
+ )
824
+ if current_time + max_time > to_time:
825
+ raise ValueError(
826
+ f"Sync failed: Provided sync time {to_time} is shorter"
827
+ f"than the sequence time {current_time + max_time}"
828
+ )
829
+ add_time = to_time - (current_time + max_time)
830
+ diff_time += ChannelTime(ch_mask - system._async_channels, add_time._value)
831
+
832
+ # NOTE: If check_post_time is off, syncing will not be able to get the post time
833
+ # from this sequence, which means it is able to violate the post time requirements
834
+ # of the last pulse.
835
+ if configuration.check_post_time:
836
+ post_time_ch = ch_mask & self._post_time._channels - system._async_channels
837
+ if len(post_time_ch) > 0:
838
+ _, _, max_post_time = self._post_time.get_sync(post_time_ch)
839
+ diff_time += ChannelTime(ch_mask - system._async_channels, max_post_time._value)
840
+
841
+ # update sync info
842
+ self._last_sync_idx = len(self._sequences)
843
+ self._last_sync_time += time_since_last_sync + diff_time
844
+
845
+ if self._synced: # nothing to do here
846
+ return
847
+
848
+ # TODO: group channels with the same time requirements for better efficiency
849
+ # unique_times = list(set(diff_time._time.values()))
850
+
851
+ # add diff time to each channel
852
+ ch_mask = ch_mask - system._async_channels
853
+ for idx in ch_mask.to_idx_list():
854
+ time = diff_time.get_time(idx)
855
+ if time is not None and np.all(time._value != 0):
856
+ self += Wait(f"sync{self._n_sync}", ChannelMask([idx]), time)
857
+
858
+ self._last_sync_idx = len(self._sequences) # update sync idx to avoid adding previous sync times
859
+ self._n_sync += 1
860
+ self._synced = True
861
+
862
+
863
+ class LinearSequence(Sequence):
864
+ """
865
+ # LinearSequence
866
+ Sequence class to execute events linearly. Can be re-used and added to other sequences.
867
+ """
868
+
869
+ def __init__(self, name: str | None = None, ch_mask: ChannelMask = ChannelMask()) -> None:
870
+ """
871
+ Args:
872
+ name (str | None, optional): Name of the sequence, exported to the json for debugging. Defaults to None.
873
+ ch_mask (ChannelMask, optional): ChannelMask for the sequence, extended as events
874
+ and subsequences are added. Defaults to ChannelMask().
875
+ """
876
+ super().__init__(
877
+ name=name,
878
+ ch_mask=ch_mask,
879
+ )
880
+
881
+ def __add__(self, other: Event | Sequence | tuple) -> LinearSequence:
882
+ return super().__add__(other) # type: ignore