-
Notifications
You must be signed in to change notification settings - Fork 53
/
labscript.py
2105 lines (1810 loc) · 108 KB
/
labscript.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
#####################################################################
# #
# /labscript.py #
# #
# Copyright 2013, Monash University #
# #
# This file is part of the program labscript, in the labscript #
# suite (see http://labscriptsuite.org), and is licensed under the #
# Simplified BSD License. See the license.txt file in the root of #
# the project for the full license. #
# #
#####################################################################
from __future__ import division
import os
import sys
import subprocess
import keyword
from inspect import getargspec
from functools import wraps
import runmanager
import labscript_utils.h5_lock, h5py
import labscript_utils.properties
from pylab import *
import functions
try:
from labscript_utils.unitconversions import *
except ImportError:
sys.stderr.write('Warning: Failed to import unit conversion classes\n')
ns = 1e-9
us = 1e-6
ms = 1e-3
s = 1
Hz = 1
kHz = 1e3
MHz = 1e6
GHz = 1e9
# We need to backup the builtins as they are now, as well as have a
# reference to the actual builtins dictionary (which will change as we
# add globals and devices to it), so that we can restore the builtins
# when labscript_cleanup() is called.
import __builtin__
_builtins_dict = __builtin__.__dict__
_existing_builtins_dict = _builtins_dict.copy()
# Startupinfo, for ensuring subprocesses don't launch with a visible command window:
if os.name=='nt':
startupinfo = subprocess.STARTUPINFO()
startupinfo.dwFlags |= 1 #subprocess.STARTF_USESHOWWINDOW # This variable isn't defined, but apparently it's equal to one.
else:
startupinfo = None
class config:
suppress_mild_warnings = True
suppress_all_warnings = False
compression = 'gzip' # set to 'gzip' for compression
class NoWarnings(object):
"""A context manager which sets config.suppress_mild_warnings to True
whilst in use. Allows the user to suppress warnings for specific
lines when they know that the warning does not indicate a problem."""
def __enter__(self):
self.existing_warning_setting = config.suppress_all_warnings
config.suppress_all_warnings = True
def __exit__(self, *args):
config.suppress_all_warnings = self.existing_warning_setting
no_warnings = NoWarnings() # This is the object that should be used, not the class above
def max_or_zero(*args, **kwargs):
"""returns max(*args) or zero if given an empty sequence (in which case max() would throw an error)"""
if not args:
return 0
if not args[0]:
return 0
else:
return max(*args, **kwargs)
def bitfield(arrays,dtype):
"""converts a list of arrays of ones and zeros into a single
array of unsigned ints of the given datatype."""
n = {uint8:8,uint16:16,uint32:32}
if arrays[0] is 0:
y = zeros(max([len(arr) if iterable(arr) else 1 for arr in arrays]),dtype=dtype)
else:
y = array(arrays[0],dtype=dtype)
for i in range(1,n[dtype]):
if iterable(arrays[i]):
y |= arrays[i]<<i
return y
def fastflatten(inarray, dtype):
"""A faster way of flattening our arrays than pylab.flatten.
pylab.flatten returns a generator which takes a lot of time and memory
to convert into a numpy array via array(list(generator)). The problem
is that generators don't know how many values they'll return until
they're done. This algorithm produces a numpy array directly by
first calculating what the length will be. It is several orders of
magnitude faster. Note that we can't use numpy.ndarray.flatten here
since our inarray is really a list of 1D arrays of varying length
and/or single values, not a N-dimenional block of homogeneous data
like a numpy array."""
total_points = sum([len(element) if iterable(element) else 1 for element in inarray])
flat = empty(total_points,dtype=dtype)
i = 0
for val in inarray:
if iterable(val):
flat[i:i+len(val)] = val[:]
i += len(val)
else:
flat[i] = val
i += 1
return flat
def set_passed_properties(property_names = {}):
"""
This decorator is intended to wrap the __init__ functions and to
write any selected kwargs into the properties.
names is a dictionary {key:val}, where each val
is a list [var1, var2, ...] of variables to be pulled from
properties_dict and added to the property with name key (it's location)
internally they are all accessed by calling self.get_property()
"""
def decorator(func):
@wraps(func)
def new_function(inst, *args, **kwargs):
return_value = func(inst, *args, **kwargs)
# Introspect arguments and named arguments functions. in python 3 this is
# a pair of func.__something__ calls and no import from argspec is needed
a = getargspec(func)
if a.defaults is not None:
args_dict = {key:val for key,val in zip(a.args[-len(a.defaults):],a.defaults)}
else:
args_dict = {}
# Update this list with the values from the passed keywords
args_dict.update(kwargs)
# print args_dict
# print property_names
inst.set_properties(args_dict, property_names)
return return_value
return new_function
return decorator
class Device(object):
description = 'Generic Device'
allowed_children = None
@set_passed_properties(
property_names = {"device_properties": ["added_properties"]}
)
def __init__(self,name,parent_device,connection, call_parents_add_device=True,
added_properties = {}, **kwargs):
# Verify that no invalid kwargs were passed and the set properties
if len(kwargs) != 0:
raise LabscriptError('Invalid keyword arguments: %s.'%kwargs)
if self.allowed_children is None:
self.allowed_children = [Device]
self.name = name
self.parent_device = parent_device
self.connection = connection
self.child_devices = []
# self._properties may be instantiated already
if not hasattr(self, "_properties"):
self._properties = {}
for location in labscript_utils.properties.VALID_PROPERTY_LOCATIONS:
if location not in self._properties:
self._properties[location] = {}
if parent_device and call_parents_add_device:
# This is optional by keyword argument, so that subclasses
# overriding __init__ can call call Device.__init__ early
# on and only call self.parent_device.add_device(self)
# a bit later, allowing for additional code in
# between. If setting call_parents_add_device=False,
# self.parent_device.add_device(self) *must* be called later
# on, it is not optional.
parent_device.add_device(self)
# Check that the name doesn't already exist in the python namespace
if name in locals() or name in globals() or name in _builtins_dict:
raise LabscriptError('The device name %s already exists in the Python namespace. Please choose another.'%name)
if name in keyword.kwlist:
raise LabscriptError('%s is a reserved Python keyword.'%name +
' Please choose a different device name.')
try:
# Test that name is a valid Python variable name:
exec '%s = None'%name
assert '.' not in name
except:
raise ValueError('%s is not a valid Python variable name.'%name)
# Put self into the global namespace:
_builtins_dict[name] = self
# Add self to the compiler's device inventory
compiler.inventory.append(self)
# Method to set a property for this device.
#
# The property will be stored in the connection table and be used
# during connection table comparisons.
#
# The value must satisfy eval(repr(value)) == value
#
# You cannot overwrite an existing property unless you set the
# overwrite flag to True on subsequent calls to this method
#
# you can specify a location = "device_properties" or "connection_table_properties"
# to set where these are stored.
def set_property(self, name, value, location=None, overwrite=False):
if location is None or location not in labscript_utils.properties.VALID_PROPERTY_LOCATIONS:
raise LabscriptError('Device %s requests invalid property assignment %s for property %s'%(self.name, location, name))
# if this try failes then self."location" may not be instantiated
if not hasattr(self, "_properties"):
self._properties = {}
if location not in self._properties:
self._properties[location] = {}
selected_properties = self._properties[location]
if name in selected_properties and not overwrite:
raise LabscriptError('Device %s has had the property %s set more than once. This is not allowed unless the overwrite flag is explicitly set'%(self.name, name))
selected_properties[name] = value
def set_properties(self, properties_dict, property_names, overwrite = False):
"""
Add one or a bunch of properties packed into properties_dict
property_names is a dictionary {key:val, ...} where each val
is a list [var1, var2, ...] of variables to be pulled from
properties_dict and added to the property with name key (it's location)
"""
for location, names in property_names.items():
if not isinstance(names, list) and not isinstance(names, tuple):
raise TypeError('%s names (%s) must be list or tuple, not %s'%(location, repr(names), str(type(names))))
temp_dict = {key:val for key, val in properties_dict.items() if key in names}
for (name, value) in temp_dict.items():
self.set_property(name, value,
overwrite = overwrite,
location = location)
# Method to get a property of this device already set using Device.set_property
#
# If the property is not already set, a default value will be returned
# if specified as the argument after 'name' if there is only one argument
# after 'name' and the argument is either not a keyword argument or is a
# keyword argument with the name 'default'
#
# If the property is not already set, or one of the above conventions is
# violated, a LabscriptError will be raised
#
# Example acceptable signatures:
#
# get_property('example') # 'example will be returned if set, or an exception will be raised
# get_property('example', 7) # 7 will be returned if 'example' is not set
# get_property('example', default=7) # 7 will be returned is 'example' is not set
#
#
# Example signatures that WILL ALWAYS RAISE AN EXCEPTION:
# get_property('example', 7, 8)
# get_property('example', 7, default=9)
# get_property('example', default=7, x=9)
#
# the named argument location, if passed, requests the keyword be searched
# from only that location
def get_property(self, name, location = None, *args, **kwargs):#default = None):
if len(kwargs) == 1 and 'default' not in kwargs:
raise LabscriptError('A call to %s.get_property had a keyword argument that was not name or default'%self.name)
if len(args) + len(kwargs) > 1:
raise LabscriptError('A call to %s.get_property has too many arguments and/or keyword arguments'%self.name)
if (location is not None) and (location not in labscript_utils.properties.VALID_PROPERTY_LOCATIONS):
raise LabscriptError('Device %s requests invalid property read location %s'%(self.name, location))
# self._properties may not be instantiated
if not hasattr(self, "_properties"):
self._properties = {}
# Run through all keys of interest
for key, val in self._properties.items():
if (location is None or key == location) and (name in val):
return val[name]
if 'default' in kwargs:
return kwargs['default']
elif len(args) == 1:
return args[0]
else:
raise LabscriptError('The property %s has not been set for device %s'%(name, self.name))
def get_properties(self, location = None):
"""
Get all properties in location
If location is None we return all keys
"""
# self._properties may not be instantiated
if not hasattr(self, "_properties"):
self._properties = {}
if location is not None:
temp_dict = self._properties.get(location, {})
else:
temp_dict = {}
for key,val in self._properties.items(): temp_dict.update(val)
return temp_dict
def add_device(self, device):
if any([isinstance(device,DeviceClass) for DeviceClass in self.allowed_children]):
self.child_devices.append(device)
else:
raise LabscriptError('Devices of type %s cannot be attached to devices of type %s.'%(device.description,self.description))
@property
def pseudoclock_device(self):
if isinstance(self, PseudoclockDevice):
return self
parent = self.parent_device
try:
while not isinstance(parent,PseudoclockDevice):
parent = parent.parent_device
return parent
except Exception as e:
raise LabscriptError('Couldn\'t find parent pseudoclock device of %s, what\'s going on? Original error was %s.'%(self.name, str(e)))
@property
def parent_clock_line(self):
if isinstance(self, ClockLine):
return self
parent = self.parent_device
try:
while not isinstance(parent,ClockLine):
parent = parent.parent_device
return parent
except Exception as e:
raise LabscriptError('Couldn\'t find parent ClockLine of %s, what\'s going on? Original error was %s.'%(self.name, str(e)))
@property
def t0(self):
"""The earliest time output can be commanded from this device at the start of the experiment.
This is nonzeo on secondary pseudoclock devices due to triggering delays."""
parent = self.pseudoclock_device
if parent.is_master_pseudoclock:
return 0
else:
return round(parent.trigger_times[0] + parent.trigger_delay, 10)
def get_all_outputs(self):
all_outputs = []
for device in self.child_devices:
if isinstance(device,Output):
all_outputs.append(device)
else:
all_outputs.extend(device.get_all_outputs())
return all_outputs
def get_all_children(self):
all_children = []
for device in self.child_devices:
all_children.append(device)
all_children.extend(device.get_all_children())
return all_children
def generate_code(self, hdf5_file):
for device in self.child_devices:
device.generate_code(hdf5_file)
def init_device_group(self, hdf5_file):
group = hdf5_file['/devices'].create_group(self.name)
return group
class IntermediateDevice(Device):
@set_passed_properties(property_names = {})
def __init__(self, name, parent_device, **kwargs):
self.name = name
# this should be checked here because it should only be connected a clockline
# The allowed_children attribute of parent classes doesn't prevent this from being connected to something that accepts
# an instance of 'Device' as a child
if not isinstance(parent_device, ClockLine):
if not hasattr(parent_device, 'name'):
parent_device_name = 'Unknown: not an instance of a labscript device class'
else:
parent_device_name = parent_device.name
raise LabscriptError('Error instantiating device %s. The parent (%s) must be an instance of ClockLine.'%(name, parent_device_name))
Device.__init__(self, name, parent_device, 'internal', **kwargs) # This 'internal' should perhaps be more descriptive?
class ClockLine(Device):
description = 'Generic ClockLine'
allowed_children = [IntermediateDevice]
_clock_limit = None
@set_passed_properties(property_names = {})
def __init__(self, name, pseudoclock, connection, ramping_allowed = True, **kwargs):
# TODO: Verify that connection is valid connection of Pseudoclock.parent_device (the PseudoclockDevice)
Device.__init__(self, name, pseudoclock, connection, **kwargs)
self.ramping_allowed = ramping_allowed
def add_device(self, device):
Device.add_device(self, device)
if hasattr(device, 'clock_limit') and (self._clock_limit is None or device.clock_limit < self.clock_limit):
self._clock_limit = device.clock_limit
# define a property to make sure no children overwrite this value themselves
# The calculation of maximum clock_limit should be done by the add_device method above
@property
def clock_limit(self):
# If no child device has specified a clock limit
if self._clock_limit is None:
# return the Pseudoclock clock_limit
# TODO: Maybe raise an error instead?
# Maybe all Intermediate devices should be required to have a clock_limit?
return self.parent_device.clock_limit
return self._clock_limit
class Pseudoclock(Device):
description = 'Generic Pseudoclock'
allowed_children = [ClockLine]
@set_passed_properties(property_names = {})
def __init__(self, name, pseudoclock_device, connection, **kwargs):
Device.__init__(self, name, pseudoclock_device, connection, **kwargs)
self.clock_limit = pseudoclock_device.clock_limit
self.clock_resolution = pseudoclock_device.clock_resolution
def add_device(self, device):
Device.add_device(self, device)
#TODO: Maybe verify here that device.connection (the ClockLine connection) is a valid connection of the parent PseudoClockDevice
# Also see the same comment in ClockLine.__init__
# if device.connection not in self.clock_lines:
# self.clock_lines[
def collect_change_times(self, all_outputs, outputs_by_clockline):
"""Asks all connected outputs for a list of times that they
change state. Takes the union of all of these times. Note
that at this point, a change from holding-a-constant-value
to ramping-through-values is considered a single state
change. The clocking times will be filled in later in the
expand_change_times function, and the ramp values filled in with
expand_timeseries."""
change_times = {}
all_change_times = []
ramps_by_clockline = {}
for clock_line, outputs in outputs_by_clockline.items():
change_times.setdefault(clock_line, [])
ramps_by_clockline.setdefault(clock_line, [])
for output in outputs:
# print 'output name: %s'%output.name
output_change_times = output.get_change_times()
# print output_change_times
change_times[clock_line].extend(output_change_times)
all_change_times.extend(output_change_times)
ramps_by_clockline[clock_line].extend(output.get_ramp_times())
# print 'initial_change_times for %s: %s'%(clock_line.name,change_times[clock_line])
# Change to a set and back to get rid of duplicates:
if not all_change_times:
all_change_times.append(0)
all_change_times.append(self.parent_device.stop_time)
# include trigger times in change_times, so that pseudoclocks always have an instruction immediately following a wait:
all_change_times.extend(self.parent_device.trigger_times)
####################################################################################################
# Find out whether any other clockline has a change time during a ramp on another clockline. #
# If it does, we need to let the ramping clockline know it needs to break it's loop at that time #
####################################################################################################
# convert all_change_times to a numpy array
all_change_times_numpy = array(all_change_times)
# Loop through each clockline
# print ramps_by_clockline
for clock_line, ramps in ramps_by_clockline.items():
# for each clockline, loop through the ramps on that clockline
for ramp_start_time, ramp_end_time in ramps:
# for each ramp, check to see if there is a change time in all_change_times which intersects
# with the ramp. If there is, add a change time into this clockline at that point
indices = np.where((ramp_start_time < all_change_times_numpy) & (all_change_times_numpy < ramp_end_time))
for idx in indices[0]:
change_times[clock_line].append(all_change_times_numpy[idx])
# Get rid of duplicates:
all_change_times = list(set(all_change_times))
all_change_times.sort()
# Check that the pseudoclock can handle updates this fast
for i, t in enumerate(all_change_times[:-1]):
dt = all_change_times[i+1] - t
if dt < 1.0/self.clock_limit:
raise LabscriptError('Commands have been issued to devices attached to %s at t= %s s and %s s. '%(self.name, str(t),str(all_change_times[i+1])) +
'This Pseudoclock cannot support update delays shorter than %s sec.'%(str(1.0/self.clock_limit)))
####################################################################################################
# For each clockline, make sure we have a change time for triggers, stop_time, t=0 and #
# check that no change tiems are too close together #
####################################################################################################
for clock_line, change_time_list in change_times.items():
# include trigger times in change_times, so that pseudoclocks always have an instruction immediately following a wait:
change_time_list.extend(self.parent_device.trigger_times)
# Get rid of duplicates if trigger times were already in the list:
change_time_list = list(set(change_time_list))
change_time_list.sort()
# Check that no two instructions are too close together:
for i, t in enumerate(change_time_list[:-1]):
dt = change_time_list[i+1] - t
if dt < 1.0/clock_line.clock_limit:
raise LabscriptError('Commands have been issued to devices attached to %s at t= %s s and %s s. '%(self.name, str(t),str(change_time_list[i+1])) +
'One or more connected devices on ClockLine %s cannot support update delays shorter than %s sec.'%(clock_line.name, str(1.0/clock_line.clock_limit)))
# If the device has no children, we still need it to have a
# single instruction. So we'll add 0 as a change time:
if not change_time_list:
change_time_list.append(0)
# Also add the stop time as as change time. First check that it isn't too close to the time of the last instruction:
if not self.parent_device.stop_time in change_time_list:
dt = self.parent_device.stop_time - change_time_list[-1]
if abs(dt) < 1.0/clock_line.clock_limit:
raise LabscriptError('The stop time of the experiment is t= %s s, but the last instruction for a device attached to %s is at t= %s s. '%( str(self.stop_time), self.name, str(change_time_list[-1])) +
'One or more connected devices cannot support update delays shorter than %s sec. Please set the stop_time a bit later.'%str(1.0/clock_line.clock_limit))
change_time_list.append(self.parent_device.stop_time)
# Sort change times so self.stop_time will be in the middle
# somewhere if it is prior to the last actual instruction. Whilst
# this means the user has set stop_time in error, not catching
# the error here allows it to be caught later by the specific
# device that has more instructions after self.stop_time. Thus
# we provide the user with sligtly more detailed error info.
change_time_list.sort()
# because we made the list into a set and back to a list, it is now a different object
# so modifying it won't update the list in the dictionary.
# So store the updated list in the dictionary
change_times[clock_line] = change_time_list
return all_change_times, change_times
def expand_change_times(self, all_change_times, change_times, outputs_by_clockline):
"""For each time interval delimited by change_times, constructs
an array of times at which the clock for this device needs to
tick. If the interval has all outputs having constant values,
then only the start time is stored. If one or more outputs are
ramping, then the clock ticks at the maximum clock rate requested
by any of the outputs. Also produces a higher level description
of the clocking; self.clock. This list contains the information
that facilitates programming a pseudo clock using loops."""
all_times = {}
clocks_in_use = []
# for output in outputs:
# if output.parent_device.clock_type != 'slow clock':
# if output.parent_device.clock_type not in all_times:
# all_times[output.parent_device.clock_type] = []
# if output.parent_device.clock_type not in clocks_in_use:
# clocks_in_use.append(output.parent_device.clock_type)
clock = []
clock_line_current_indices = {}
for clock_line, outputs in outputs_by_clockline.items():
clock_line_current_indices[clock_line] = 0
all_times[clock_line] = []
# iterate over all change times
# for clock_line, times in change_times.items():
# print '%s: %s'%(clock_line.name, times)
for i, time in enumerate(all_change_times):
if time in self.parent_device.trigger_times[1:]:
# A wait instruction:
clock.append('WAIT')
# list of enabled clocks
enabled_clocks = []
enabled_looping_clocks = []
# enabled_non_looping_clocks = []
# update clock_line indices
for clock_line in clock_line_current_indices:
try:
while change_times[clock_line][clock_line_current_indices[clock_line]] < time:
clock_line_current_indices[clock_line] += 1
except IndexError:
# Fix the index to the last one
clock_line_current_indices[clock_line] = len(change_times[clock_line]) - 1
# print a warning
message = ''.join(['WARNING: ClockLine %s has it\'s last change time at t=%.10f but another ClockLine has a change time at t=%.10f. '%(clock_line.name, change_times[clock_line][-1], time),
'This should never happen, as the last change time should always be the time passed to stop(). ',
'Perhaps you have an instruction after the stop time of the experiment?'])
sys.stderr.write(message+'\n')
# Let's work out which clock_lines are enabled for this instruction
if time == change_times[clock_line][clock_line_current_indices[clock_line]]:
enabled_clocks.append(clock_line)
# what's the fastest clock rate?
maxrate = 0
local_clock_limit = self.clock_limit # the Pseudoclock clock limit
for clock_line in enabled_clocks:
for output in outputs_by_clockline[clock_line]:
# Check if output is sweeping and has highest clock rate
# so far. If so, store its clock rate to max_rate:
if hasattr(output,'timeseries') and isinstance(output.timeseries[clock_line_current_indices[clock_line]],dict):
if clock_line not in enabled_looping_clocks:
enabled_looping_clocks.append(clock_line)
if output.timeseries[clock_line_current_indices[clock_line]]['clock rate'] > maxrate:
# It does have the highest clock rate? Then store that rate to max_rate:
maxrate = output.timeseries[clock_line_current_indices[clock_line]]['clock rate']
# only check this for ramping clock_lines
# non-ramping clock-lines have already had the clock_limit checked within collect_change_times()
if local_clock_limit > clock_line.clock_limit:
local_clock_limit = clock_line.clock_limit
# find non-looping clocks
# for clock_line in enabled_clocks:
# if clock_line not in enabled_looping_clocks:
# enabled_non_looping_clocks.append(clock_line)
if maxrate:
# round to the nearest clock rate that the pseudoclock can actually support:
period = 1/maxrate
quantised_period = period/self.clock_resolution
quantised_period = round(quantised_period)
period = quantised_period*self.clock_resolution
maxrate = 1/period
if maxrate > local_clock_limit:
raise LabscriptError('At t = %s sec, a clock rate of %s Hz was requested. '%(str(time),str(maxrate)) +
'One or more devices connected to %s cannot support clock rates higher than %sHz.'%(str(self.name),str(local_clock_limit)))
if maxrate:
# If there was ramping at this timestep, how many clock ticks fit before the next instruction?
n_ticks, remainder = divmod((all_change_times[i+1] - time)*maxrate,1)
n_ticks = int(n_ticks)
# Can we squeeze the final clock cycle in at the end?
if remainder and remainder/float(maxrate) >= 1/float(local_clock_limit):
# Yes we can. Clock speed will be as
# requested. Otherwise the final clock cycle will
# be too long, by the fraction 'remainder'.
n_ticks += 1
duration = n_ticks/float(maxrate) # avoiding integer division
ticks = linspace(time,time + duration,n_ticks,endpoint=False)
for clock_line in enabled_clocks:
if clock_line in enabled_looping_clocks:
all_times[clock_line].append(ticks)
else:
all_times[clock_line].append(time)
if n_ticks > 1:
# If n_ticks is only one, then this step doesn't do
# anything, it has reps=0. So we should only include
# it if n_ticks > 1.
if n_ticks > 2:
#If there is more than one clock tick here,
#then we split the ramp into an initial clock
#tick, during which the slow clock ticks, and
#the rest of the ramping time, during which the
#slow clock does not tick.
clock.append({'start': time, 'reps': 1, 'step': 1/float(maxrate), 'enabled_clocks':enabled_clocks})
clock.append({'start': time + 1/float(maxrate), 'reps': n_ticks-2, 'step': 1/float(maxrate), 'enabled_clocks':enabled_looping_clocks})
else:
clock.append({'start': time, 'reps': n_ticks-1, 'step': 1/float(maxrate), 'enabled_clocks':enabled_clocks})
# clock.append({'start': time, 'reps': n_ticks-1, 'step': 1/float(maxrate), 'enabled_clocks':enabled_clocks})
# The last clock tick has a different duration depending on the next step.
clock.append({'start': ticks[-1], 'reps': 1, 'step': all_change_times[i+1] - ticks[-1], 'enabled_clocks':enabled_clocks if n_ticks == 1 else enabled_looping_clocks})
else:
for clock_line in enabled_clocks:
all_times[clock_line].append(time)
try:
# If there was no ramping, here is a single clock tick:
clock.append({'start': time, 'reps': 1, 'step': all_change_times[i+1] - time, 'enabled_clocks':enabled_clocks})
except IndexError:
if i != len(all_change_times) - 1:
raise
if self.parent_device.stop_time > time:
# There is no next instruction. Hold the last clock
# tick until self.parent_device.stop_time.
raise Exception('This shouldn\'t happen -- stop_time should always be equal to the time of the last instruction. Please report a bug.')
# I commented this out because it is after a raised exception so never ran.... - Phil
# clock.append({'start': time, 'reps': 1, 'step': self.parent_device.stop_time - time,'slow_clock_tick':True})
# Error if self.parent_device.stop_time has been set to less
# than the time of the last instruction:
elif self.parent_device.stop_time < time:
raise LabscriptError('%s %s has more instructions after the experiment\'s stop time.'%(self.description,self.name))
# If self.parent_device.stop_time is the same as the time of the last
# instruction, then we'll get the last instruction
# out still, so that the total number of clock
# ticks matches the number of data points in the
# Output.raw_output arrays. We'll make this last
# cycle be at ten times the minimum step duration.
else:
# find the slowest clock_limit
enabled_clocks = []
local_clock_limit = 1.0/self.clock_resolution # the Pseudoclock clock limit
for clock_line, outputs in outputs_by_clockline.items():
if local_clock_limit > clock_line.clock_limit:
local_clock_limit = clock_line.clock_limit
enabled_clocks.append(clock_line)
clock.append({'start': time, 'reps': 1, 'step': 10.0/self.clock_limit, 'enabled_clocks':enabled_clocks})
# for row in clock:
# print row
return all_times, clock
def get_outputs_by_clockline(self):
all_outputs = self.get_all_outputs()
outputs_by_clockline = {}
for output in all_outputs:
# TODO: Make this a bit more robust (can we assume things always have this hierarchy?)
clock_line = output.parent_clock_line
assert clock_line.parent_device == self
outputs_by_clockline.setdefault(clock_line, [])
outputs_by_clockline[clock_line].append(output)
return all_outputs, outputs_by_clockline
def generate_clock(self):
all_outputs, outputs_by_clockline = self.get_outputs_by_clockline()
# Get change_times for all outputs, and also grouped by clockline
all_change_times, change_times = self.collect_change_times(all_outputs, outputs_by_clockline)
# for each clock line
for clock_line, clock_line_change_times in change_times.items():
# and for each output on the clockline
for output in outputs_by_clockline[clock_line]:
# call make_timeseries to expand the list of instructions for each change_time on this clock line
output.make_timeseries(clock_line_change_times)
# now generate the clock meta data for the Pseudoclock
# also generate everytime point each clock line will tick (expand ramps)
all_times, self.clock = self.expand_change_times(all_change_times, change_times, outputs_by_clockline)
# for each clockline
for clock_line, outputs in outputs_by_clockline.items():
# and for each output
for output in outputs:
# evaluate the output at each time point the clock line will tick at
output.expand_timeseries(all_times[clock_line])
# TODO: is this needed? Let's say no...
# self.all_change_times = fastflatten(all_change_times, float)
# Flatten the clock line times for use by the child devices for writing instruction tables
# TODO: (if this needed or was it just for runviewer meta data that we don't need anymore?)
self.times = {}
for clock_line, time_array in all_times.items():
self.times[clock_line] = fastflatten(time_array,float)
def generate_code(self, hdf5_file):
self.generate_clock()
Device.generate_code(self, hdf5_file)
class TriggerableDevice(Device):
trigger_edge_type = 'rising'
# A class devices should inherit if they do
# not require a pseudoclock, but do require a trigger.
# This enables them to have a Trigger divice as a parent
@set_passed_properties(property_names = {})
def __init__(self, name, parent_device, connection, parentless=False, **kwargs):
if None in [parent_device, connection] and not parentless:
raise LabscriptError('No parent specified. If this device does not require a parent, set parentless=True')
if isinstance(parent_device, Trigger):
if self.trigger_edge_type != parent_device.trigger_edge_type:
raise LabscriptError('Trigger edge type for %s is \'%s\', ' % (name, self.trigger_edge_type) +
'but existing Trigger object %s ' % parent_device.name +
'has edge type \'%s\'' % parent_device.trigger_edge_type)
self.trigger_device = parent_device
elif parent_device is not None:
# Instantiate a trigger object to be our parent:
self.trigger_device = Trigger(name + '_trigger', parent_device, connection, self.trigger_edge_type)
parent_device = self.trigger_device
connection = 'trigger'
Device.__init__(self, name, parent_device, connection, **kwargs)
class PseudoclockDevice(TriggerableDevice):
description = 'Generic Pseudoclock Device'
allowed_children = [Pseudoclock]
trigger_edge_type = 'rising'
# How long after a trigger the next instruction is actually output:
trigger_delay = 0
# How long a trigger line must remain high/low in order to be detected:
trigger_minimum_duration = 0
# How long after the start of a wait instruction the device is actually capable of resuming:
wait_delay = 0
@set_passed_properties(property_names = {})
def __init__(self, name, trigger_device=None, trigger_connection=None, **kwargs):
if trigger_device is None:
for device in compiler.inventory:
if isinstance(device, PseudoclockDevice) and device.is_master_pseudoclock:
raise LabscriptError('There is already a master pseudoclock device: %s.'%device.name +
'There cannot be multiple master pseudoclock devices - please provide a trigger_device for one of them.')
TriggerableDevice.__init__(self, name, parent_device=None, connection=None, parentless=True, **kwargs)
else:
# The parent device declared was a digital output channel: the following will
# automatically instantiate a Trigger for it and set it as self.trigger_device:
TriggerableDevice.__init__(self, name, parent_device=trigger_device, connection=trigger_connection, **kwargs)
# Ensure that the parent pseudoclock device is, in fact, the master pseudoclock device.
if not self.trigger_device.pseudoclock_device.is_master_pseudoclock:
raise LabscriptError('All secondary pseudoclock devices must be triggered by a device being clocked by the master pseudoclock device.' +
'Pseudoclocks triggering each other in series is not supported.')
self.trigger_times = []
self.wait_times = []
self.initial_trigger_time = 0
@property
def is_master_pseudoclock(self):
return self.parent_device is None
def set_initial_trigger_time(self, t):
t = round(t,10)
if compiler.start_called:
raise LabscriptError('Initial trigger times must be set prior to calling start()')
if self.is_master_pseudoclock:
raise LabscriptError('Initial trigger time of master clock is always zero, it cannot be changed.')
else:
self.initial_trigger_time = t
def trigger(self, t, duration, wait_delay = 0):
"""Ask the trigger device to produce a digital pulse of a given duration to trigger this pseudoclock"""
if t == 'initial':
t = self.initial_trigger_time
t = round(t,10)
if self.is_master_pseudoclock:
if compiler.wait_monitor is not None:
# Make the wait monitor pulse to signify starting or resumption of the experiment:
compiler.wait_monitor.trigger(t, duration)
elif t != self.initial_trigger_time:
raise LabscriptError("You cannot use waits in unless you have a wait monitor." +
"Please instantiate a WaitMonitor in your connection table.")
self.trigger_times.append(t)
else:
self.trigger_device.trigger(t, duration)
self.trigger_times.append(round(t + wait_delay,10))
def do_checks(self, outputs):
"""Basic error checking to ensure the user's instructions make sense"""
for output in outputs:
output.do_checks(self.trigger_times)
def offset_instructions_from_trigger(self, outputs):
for output in outputs:
output.offset_instructions_from_trigger(self.trigger_times)
if not self.is_master_pseudoclock:
# Store the unmodified initial_trigger_time
initial_trigger_time = self.trigger_times[0]
# Adjust the stop time relative to the last trigger time
self.stop_time = round(self.stop_time - initial_trigger_time - self.trigger_delay * len(self.trigger_times),10)
# Modify the trigger times themselves so that we insert wait instructions at the right times:
self.trigger_times = [round(t - initial_trigger_time - i*self.trigger_delay,10) for i, t in enumerate(self.trigger_times)]
def generate_code(self, hdf5_file):
outputs = self.get_all_outputs()
self.do_checks(outputs)
self.offset_instructions_from_trigger(outputs)
Device.generate_code(self, hdf5_file)
class Output(Device):
description = 'generic output'
allowed_states = {}
dtype = float64
scale_factor = 1
@set_passed_properties(property_names = {})
def __init__(self,name,parent_device,connection,limits = None,unit_conversion_class = None, unit_conversion_parameters = None, **kwargs):
Device.__init__(self,name,parent_device,connection, **kwargs)
self.instructions = {}
self.ramp_limits = [] # For checking ramps don't overlap
if not unit_conversion_parameters:
unit_conversion_parameters = {}
self.unit_conversion_class = unit_conversion_class
self.set_properties(unit_conversion_parameters,
{'unit_conversion_parameters': unit_conversion_parameters.keys()})
# Instantiate the calibration
if unit_conversion_class is not None:
self.calibration = unit_conversion_class(unit_conversion_parameters)
# Validate the calibration class
for units in self.calibration.derived_units:
#Does the conversion to base units function exist for each defined unit type?
if not hasattr(self.calibration,units+"_to_base"):
raise LabscriptError('The function "%s_to_base" does not exist within the calibration "%s" used in output "%s"'%(units,self.unit_conversion_class,self.name))
#Does the conversion to base units function exist for each defined unit type?
if not hasattr(self.calibration,units+"_from_base"):
raise LabscriptError('The function "%s_from_base" does not exist within the calibration "%s" used in output "%s"'%(units,self.unit_conversion_class,self.name))
# If limits exist, check they are valid
# Here we specifically differentiate "None" from False as we will later have a conditional which relies on
# self.limits being either a correct tuple, or "None"
if limits is not None:
if not isinstance(limits,tuple) or len(limits) is not 2:
raise LabscriptError('The limits for "%s" must be tuple of length 2. Eg. limits=(1,2)'%(self.name))
if limits[0] > limits[1]:
raise LabscriptError('The first element of the tuple must be lower than the second element. Eg limits=(1,2), NOT limits=(2,1)')
# Save limits even if they are None
self.limits = limits
@property
def clock_limit(self):
parent = self.parent_clock_line
return parent.clock_limit
@property
def trigger_delay(self):
"""The earliest time output can be commanded from this device after a trigger.
This is nonzeo on secondary pseudoclocks due to triggering delays."""
parent = self.pseudoclock_device
if parent.is_master_pseudoclock:
return 0
else:
return parent.trigger_delay
@property
def wait_delay(self):
"""The earliest time output can be commanded from this device after a wait.
This is nonzeo on secondary pseudoclocks due to triggering delays and the fact
that the master clock doesn't provide a resume trigger to secondary clocks until
a minimum time has elapsed: compiler.wait_delay. This is so that if a wait is
extremely short, the child clock is actually ready for the trigger.
"""
delay = compiler.wait_delay if self.pseudoclock_device.is_master_pseudoclock else 0
return self.trigger_delay + delay
def apply_calibration(self,value,units):
# Is a calibration in use?
if self.unit_conversion_class is None:
raise LabscriptError('You can not specify the units in an instruction for output "%s" as it does not have a calibration associated with it'%(self.name))
# Does a calibration exist for the units specified?
if units not in self.calibration.derived_units:
raise LabscriptError('The units "%s" does not exist within the calibration "%s" used in output "%s"'%(units,self.unit_conversion_class,self.name))
# Return the calibrated value
return getattr(self.calibration,units+"_to_base")(value)
def instruction_to_string(self,instruction):
"""gets a human readable description of an instruction"""
if isinstance(instruction,dict):
return instruction['description']
elif self.allowed_states:
return str(self.allowed_states[instruction])
else:
return str(instruction)
def add_instruction(self,time,instruction,units=None):
if not compiler.start_called:
raise LabscriptError('Cannot add instructions prior to calling start()')
# round to the nearest 0.1 nanoseconds, to prevent floating point
# rounding errors from breaking our equality checks later on.
time = round(time,10)
# Also round end time of ramps to the nearest 0.1 ns:
if isinstance(instruction,dict):
instruction['end time'] = round(instruction['end time'],10)
instruction['initial time'] = round(instruction['initial time'],10)
# Check that time is not negative or too soon after t=0: