-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathtestDriver.py
executable file
·2226 lines (1883 loc) · 68.7 KB
/
testDriver.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
#!/usr/bin/env python
#
# from testDriver import ChimneyReader ; reader = ChimneyReader("config/FlangeChimneyTest_scope1.ini"); reader.resume("A0")
# reader.next()
#
__doc__ = """
Interactive driver for the scope reader.
So far, only python environment stuff is usable interactively
(see `ChimneyReader`), but running from python is still quite better.
"""
__version__ = "6.4.1"
# TODO:
# * `ChimneyReader.start()` warn if the chimney has already been completed
# * create a wrapper python script dropping to interactive
# * compactify the output of readout
# * check how `plotLast()` work (seems to plot the next, not the last)
# * try to mitigate the problem when ROOT canvas is closed interactively
###############################################################################
### importing and default setup
import drawWaveforms
from stopwatch import StopWatch, WatchCollection
from scopeTalker import TDS3054Ctalker
import numpy
import random
import sys
import re
import os
import logging
# set verbosity level to `INFO`; not all output has been converted to `logging`
# this value is reset by `ChimneyReader`.
logging.getLogger().setLevel(logging.INFO)
################################################################################
### general utilities
def confirm(msg, yes="Y", no="N", caseSensitive=False):
options = []
if isinstance(yes, str): yes = [ yes, ]
elif yes is None: yes = []
if yes: options.append(yes[0])
if isinstance(no, str): no = [ no, ]
elif no is None: no = []
if no: options.append(no[0])
print "%s [%s] " % (msg, "/".join(options)),
caseProc = (lambda s:s) if caseSensitive else str.lower
yesAnswers = map(caseProc, yes)
noAnswers = map(caseProc, no)
while True:
try: Answer = sys.stdin.readline().strip()
except KeyboardInterrupt:
if no: print no[0]
return False
answer = caseProc(Answer)
if answer in yesAnswers: return True
if answer in noAnswers: return False
# while
assert False
# confirm()
def getCaseUnsensitive(d, key, *default):
assert(len(default) <= 1)
key = key.lower()
for k, v in d.items():
if key == k.lower(): return v
if len(default) > 0: return default[0]
raise KeyError(key)
# getCaseUnsensitive()
def flatten(l):
fl = []
for item in l: fl.extend(item)
return fl
# flatten()
def inRange(value, low, high): return (value >= low) and (value <= high)
class ANSIClass:
Black = 0
Red = 1
Green = 2
Blue = 4
Yellow = Red + Green
Cyan = Blue + Green
Magenta = Red + Blue
White = Red + Green + Blue
def __init__(self, colors = True):
self.colors = colors
def enableColor(self, enable = True): self.colors = enable
def fgColor(self, color, highlight = False):
return self._activate(ANSIClass.composeColor(
ANSIClass.highlight() if highlight else None, ANSIClass.fgCode(color),
))
# fgColor()
def red(self, highlight = False):
return self.fgColor(ANSIClass.Red, highlight=highlight)
def green(self, highlight = False):
return self.fgColor(ANSIClass.Green, highlight=highlight)
def blue(self, highlight = False):
return self.fgColor(ANSIClass.Blue, highlight=highlight)
def yellow(self, highlight = True):
return self.fgColor(ANSIClass.Yellow, highlight=highlight)
def magenta(self, highlight = False):
return self.fgColor(ANSIClass.Magenta, highlight=highlight)
def cyan(self, highlight = False):
return self.fgColor(ANSIClass.Cyan, highlight=highlight)
def white(self, highlight = True):
return self.fgColor(ANSIClass.White, highlight=highlight)
def black(self, highlight = False):
return self.fgColor(ANSIClass.Black, highlight=highlight)
def gray(self, highlight = False): return self.white(highlight=highlight)
def _activate(self, code): return code if self.colors else ""
@staticmethod
def fgCode(color): return str(30 + color)
@staticmethod
def reset(): return ANSIClass.composeColor("0")
@staticmethod
def highlight(): return "1"
@staticmethod
def composeColor(*codes):
return ANSIClass.escapeCode(';'.join(filter(None, codes)) + 'm')
@staticmethod
def escapeCode(code): return "\x1B[" + code
# class ANSIClass
ANSI = ANSIClass()
################################################################################
### Reader state: describes what we are doing right now (incomplete)
class ReaderState:
def __init__(self, chimney = None, N = 10, ):
self.enabled = False
self.confirm = True
self.test = ""
self.cableTag = None
self.cableNo = None
self.position = None
self.N = N
self.setChimney(chimney)
self.quiet = False
self.fake = False
# __init__()
def makeCopy(self, chimney = None, N = None):
state = self.__class__()
state.enabled = self.enabled
state.confirm = self.confirm
state.test = self.test
state.cableTag = self.cableTag
state.cableNo = self.cableNo
state.position = self.position
state.N = self.N if N is None else N
state.setChimney(self.chimney if chimney is None else chimney)
state.quiet = self.quiet
state.fake = self.fake
return state
# makeCopy()
def enable(self):
print "All commands are now going to be executed for real."
self.enabled = True
def disable(self):
print "All commands are now just being printed and NOT going to be executed."
self.enabled = False
def hasChimney(self): return self.chimney is not None
def setChimney(self, chimney):
if chimney is None:
self.chimney = None
self.chimneySeries = None
self.chimneyNumber = 0
return
try:
self.chimneySeries, self.chimneyNumber, style \
= drawWaveforms.ChimneyInfo.split(chimney.upper())
except RuntimeError, e:
raise RuntimeError \
("ReaderState.setChimney('{}'): {}".format(chimney, str(e)))
self.chimney = drawWaveforms.ChimneyInfo.format_ \
(self.chimneySeries, self.chimneyNumber)
self.chimneyStyle = style
self.cableTag = drawWaveforms.CableInfo.tagFor(self.chimney)
# setChimney()
def cable(self): return "%(cableTag)s%(cableNo)02d" % vars(self)
def firstIndex(self):
return drawWaveforms.WaveformSourceInfo.firstIndexOf(self.position, self.N)
def stateStr(self):
return "Test %(test)s chimney %(chimney)s connection %(cableTag)s%(cableNo)02d position %(position)d" % vars(self)
def execute(self, command):
if self.enabled:
if self.confirm:
yesKey = str(random.randint(0, 9))
print "Run: '%s'? [<%s>,<Enter> for yes] " % (command, yesKey),
answer = sys.stdin.readline().strip()
if answer != yesKey:
print "(chickened out)"
return
# if confirm
print "$ " + command
else:
print "$ " + command
# if ... else
# execute()
def makeWaveformSourceInfo(self,
channelNo = None, index = None, testName = None,
):
return drawWaveforms.WaveformSourceInfo(
chimney=self.chimney, connection=self.cable(), channelIndex=channelNo,
position=self.position, index=index,
testName=(testName if testName is not None else self.test),
)
# makeWaveformSourceInfo()
def updateWaveformSourceInfo(self, sourceInfo):
"""Updates a `WaveformSourceInfo` after `ReaderState` has moved to a
different position."""
sourceInfo.setConnection(self.cable())
sourceInfo.setPosition(self.position)
sourceInfo.test = self.test
# updateWaveformSourceInfo()
# class ReaderState
class ReaderStateSequence:
"""Defines a sequence of states for the complete test.
The sequence defined by `goNext()`, `goPrev()` and `reset()` is to
* go through the sequence of all positions for each test
* go through the sequence of all tests for each cable
* go through all cables in the chimney
The list of positions is 1 to 8, while the list of cables is descending,
18 to 1. The list of test is directly adopted from the constructor parameter.
Other implementations can derive from this one and redefine the sequence
and the ranges.
"""
def __init__(self, state,
tests = [ '' ],
cables = range(18, 0, -1),
positions = range(1, 9),
):
self.readerState = state
self.setPositions(positions)
self.setTests(tests)
self.setCables(cables)
self.reset()
# __init__()
def reset(self):
self.iPosition = 0
self.iCable = 0
self.iTest = 0
self.updateState()
assert self.isValid()
assert self.isAtStart()
# reset()
def setCables(self, cables):
assert cables
self.cables = cables[:]
# setCables()
def setTests(self, tests):
assert tests
self.tests = tests[:]
# setTests()
def setPositions(self, positions):
assert positions
self.positions = positions[:]
# setPositions()
def state(self): return self.readerState
def position(self): return self.positions[self.iPosition]
def firstPosition(self): return self.positions[0]
def lastPosition(self): return self.positions[-1]
def isPosition(self):
return (self.iPosition >= 0) and (self.iPosition < self.nPositions())
def isFirstPosition(self): return self.iPosition == 0
def isLastPosition(self): return self.iPosition >= (self.nPositions() - 1)
def nPositions(self): return len(self.positions)
def cable(self): return self.cables[self.iCable]
def firstCable(self): return self.cables[0]
def lastCable(self): return self.cables[-1]
def isCable(self):
return (self.iCable >= 0) and (self.iCable < self.nCables())
def isFirstCable(self): return self.iCable == 0
def isLastCable(self): return self.iCable >= (self.nCables() - 1)
def nCables(self): return len(self.cables)
def test(self): return self.tests[self.iTest]
def firstTest(self): return self.tests[0]
def lastTest(self): return self.tests[-1]
def isTest(self): return (self.iTest >= 0) and (self.iTest < self.nTests())
def isFirstTest(self): return self.iTest == 0
def isLastTest(self): return self.iTest >= (self.nTests() - 1)
def nTests(self): return len(self.tests)
def __iter__(self): return ReaderStateSequence.Iterator(self, reset=True)
def __len__(self): return self.nPositions() * self.nTests() * self.nCables()
def setPosition(self, position):
if self.positions.count(position) > 1:
raise RuntimeError(
"Can't set position {} since it's present in the sequence {} times."
.format(position, self.positions.count(position))
)
# if too many position
try: self.iPosition = self.positions.index(position)
except ValueError:
raise RuntimeError("{} is not a valid position to set.".format(position))
self.updateState()
# setPosition()
def setCable(self, cableNo, resetTest = False, resetPosition = False):
if self.cables.count(cableNo) > 1:
raise RuntimeError(
"Can't set cable {} since it's present in the sequence {} times."
.format(cableNo, self.cables.count(cableNo))
)
# if too many cable
try: self.iCable = self.cables.index(cableNo)
except ValueError:
raise RuntimeError("{} is not a valid cable to set.".format(cableNo))
if resetTest: self.iTest = 0
if resetPosition: self.iPosition = 0
self.updateState()
# setCable()
def setTest(self, test, resetPosition = False):
count = 0
for iTest, testName in enumerate(self.tests):
if testName.lower() != test.lower(): continue
count += 1
pos = iTest
# for
if count > 1:
raise RuntimeError(
"Can't set test {} since it's present in the sequence {} times."
.format(test, count)
)
# if too many test
if count == 0:
raise RuntimeError("{} is not a valid test to set.".format(test))
self.iTest = pos
if resetPosition: self.iPosition = 0
self.updateState()
# setTest()
def isValid(self):
return self.isCable() and self.isTest() and self.isPosition()
def isAtStart(self):
return (self.iPosition == 0) and (self.iTest == 0) and (self.iCable <= 0)
def isAtEnd(self): return self.iCable >= self.nCables()
def hint(self):
"""Return a hint of what to do to prepare for the next step
(which is the current state)."""
return None
# hint()
def goNext(self, n = 1):
self.iPosition += 1
if not self.isPosition():
self.iPosition = 0
self.iTest += 1
if not self.isTest():
self.iTest = 0
self.iCable += 1
if not self.isCable():
self.iPosition = 0
self.iTest = 0
self.iCable = self.nCables()
if (n > 1) and not self.goNext(n-1): return False
self.updateState()
return self.isCable()
# goNext()
def goPrev(self, n = 1):
self.iPosition -= 1
if not self.isPosition():
self.iPosition = self.nPositions() - 1
self.iTest -= 1
if not self.isTest():
self.iTest = self.nTests() - 1
self.iCable -= 1
if not self.isCable():
self.iPosition = self.nPositions() - 1
self.iTest = self.nTests() - 1
self.iCable = -1
if (n > 1) and not self.goPrev(n-1): return False
self.updateState()
return self.isCable()
# goPrev()
def updateState(self):
self.readerState.position = self.position()
self.readerState.test = self.test()
self.readerState.cableNo = self.cable() if self.isCable() else None
return True
# updateState()
def stateStr(self): return self.readerState.stateStr()
def __str__(self):
return "Connection {cable} (#{iCable}) test {test} (#{iTest})" \
" position {position} (#{iPosition})".format(
cable=self.cable(), iCable=self.iCable,
test=self.test(), iTest=self.iTest,
position=self.position(), iPosition=self.iPosition,
)
# __str__()
class Iterator:
def __init__(self, stateSeq, reset = True):
self.reset = reset
self.stateSeq = stateSeq
def __iter__(self): return self
def next(self):
if not self.stateSeq.isValid(): self.reset = True # this is for autoreset
if self.reset:
self.reset = False
self.stateSeq.reset()
return self.stateSeq
elif not self.stateSeq.goNext():
self.reset = True
raise StopIteration
return self.stateSeq
# next()
# class Iterator
# class ReaderStateSequence
class HVandPulseSequence(ReaderStateSequence):
def __init__(self, state,
tests = [ '' ],
cables = flatten(zip(range(1, 10), range(10, 19))),
positions = range(1, 9),
):
ReaderStateSequence.__init__(self,
state,
tests=tests, cables=cables, positions=positions,
)
# __init__()
def slot(self): return 1 + (self.cable() - 1) % 9
def isLeft(self):
return (self.cable() >= 1) and (self.cable() <= 9)
def isRight(self):
return (self.cable() >= 10) and (self.cable() <= 18)
def isHV(self):
return self.test().upper() == "HV"
def isPulse(self):
return self.test().lower() == "pulse"
LeftColor = ANSI.red(highlight=True)
RightColor = ANSI.yellow(highlight=False)
PositionColor = ANSI.white()
SlotColor = ANSI.green(highlight=True)
@staticmethod
def colorLeft(s): return HVandPulseSequence.LeftColor + s + ANSI.reset()
@staticmethod
def colorRight(s): return HVandPulseSequence.RightColor + s + ANSI.reset()
@staticmethod
def colorPosition(p):
return HVandPulseSequence.PositionColor + str(p) + ANSI.reset()
def sideColor(self):
if self.isLeft():
return HVandPulseSequence.LeftColor
elif self.isRight():
return HVandPulseSequence.RightColor
else:
return ""
# sideColor()
def sideName(self):
if self.isLeft():
return "left"
elif self.isRight():
return "right"
else:
return "unknown side"
# sideName()
def stateStr(self):
# coloring
chimney = self.readerState.chimney # no color
cable = drawWaveforms.CableInfo(self.readerState.cableTag, self.cable())
if self.isLeft():
cable = self.colorLeft(cable)
elif self.isRight():
cable = self.colorRight(cable)
if self.isPulse():
test = (
"p"
+ ANSI.white() + "u"
+ ANSI.green() + "l"
+ ANSI.black(highlight=True) + "s"
+ ANSI.red(highlight=True) + "e"
+ ANSI.reset()
)
elif self.isHV():
test = ANSI.cyan() + self.test() + ANSI.reset()
else:
test = self.test()
position = self.colorPosition(self.position())
return (
"Test {test} chimney {chimney} connection {cable} position {position}"
.format(
test=test,
chimney=chimney,
cable=cable,
position=position,
)
)
# stateStr()
def hint(self):
if self.isAtEnd():
return "The test sequence of chimney {} is complete." \
.format(self.readerState.chimney)
# in the middle of the position sequence...
if not self.isFirstPosition():
return "* just turn to {posCol}position {pos}{reset}".format(
posCol=self.PositionColor,
reset=ANSI.reset(),
pos=self.position(),
)
# if position
# if changing between left and right (first position of first test)
msg = []
if self.isLeft(): # new slot (right to left)
msg.append(
"* remove pulser and ribbon cables and switch the board to {slotCol}slot {slot}{reset}"
.format(
slotCol=self.SlotColor, reset=ANSI.reset(),
slot=self.slot(),
))
if self.isHV():
msg.append("* direct test box pulser output to the {sideCol}{side} HV input{reset}"
.format(
sideCol=self.sideColor(),
side=self.sideName(),
reset=ANSI.reset(),
))
elif self.isPulse():
msg.append(
"* direct test box pulser output to the {sideCol}pulse input for {cable}{reset}"
.format(
sideCol=self.sideColor(),
cable=self.readerState.cable(),
reset=ANSI.reset(),
))
if self.cable() in [ 1, 10, ]:
msg.append(" => {white}test all the different pulse inputs to find the best one{reset}"
.format(
white=ANSI.white(),
reset=ANSI.reset(),
))
elif self.cable() in [ 2, 9, 11, 18, ]:
msg.append("* {white}you may need to test different pulse inputs to find the best one{reset}"
.format(
white=ANSI.white(),
reset=ANSI.reset(),
))
# if pulse
msg.extend([
"* plug the {sideCol}{side} signal ribbon{reset} into the test box".format(
sideCol=self.sideColor(),
side=self.sideName(),
reset=ANSI.reset(),
),
"* turn to {posCol}position {pos}{reset}".format(
posCol=self.PositionColor,
reset=ANSI.reset(),
pos=self.position(),
),
])
# if ... else
return "\n".join(filter(None, msg)) if msg else None
# hint()
# class HVandPulseSequence
class HorizontalHVandPulseSequence(ReaderStateSequence):
"""Sequence for horizontal wire chimneys.
The sequence goes from top to bottom, from left to right.
These coordinates are defined with respect to a person facing the chimneys.
This also means that "left" and "right" do not refer to the flange itself
(that is, they do not refer to the frame based on the flange mark).
"""
Settings = {
'normal': {
'inverted': False,
#'chimneys': [ 'A20', 'B01', 'C20', 'D01', ],
'chimneys': [ 'A20', 'B01', 'C20', 'D01', 'A01', 'B20', 'C01', 'D20', ],
'cables': [
7, 15,
6, 14,
5, 13,
4, 12,
3, 11,
2, 10,
1, 9,
8,
24, 33,
23, 32,
22, 31,
21, 30,
20, 29,
19, 28,
18, 27,
17, 26,
16, 25,
],
'cablesOnFlanges': [ 15, 18, ],
}, # 'normal'
'inverted': {
'inverted': True,
# 'chimneys': [ 'A01', 'B20', 'C01', 'D20', ],
'chimneys': [ ],
'cables': [
8, # top flange
9, 1,
10, 2,
11, 3,
12, 4,
13, 5,
14, 6,
15, 7,
25, 16, # middle flange
26, 17,
27, 18,
28, 19,
29, 20,
30, 21,
31, 22,
32, 23,
33, 24,
],
'cablesOnFlanges': [ 15, 18, ],
}, # 'inverted'
} # Settings{}
def __init__(self, state,
tests = [ '' ],
cables = None,
positions = range(1, 9),
):
#raise NotImplementedError("Need to implement '{}'".format(self.__class__.__name__))
for settings in HorizontalHVandPulseSequence.Settings.values():
if state.chimney not in settings['chimneys']: continue
self.settings = settings
break
else:
raise RuntimeError(
"No HorizontalHVandPulseSequence sequence for chimney series {}"
.format(state.chimney)
)
# for ... else
if cables is None: cables = self.settings['cables']
ReaderStateSequence.__init__(self,
state,
tests=tests, cables=cables, positions=positions,
)
self.slotAt, self.flangeAt \
= HorizontalHVandPulseSequence.buildSlotTable(self.settings)
# __init__()
def slot(self): return self.slotAt[self.iCable]
def isLeft(self):
return (inRange(self.cable(), 1, 7) or inRange(self.cable(), 16, 24)) \
!= self.settings['inverted']
def isRight(self):
return (inRange(self.cable(), 8, 15) or inRange(self.cable(), 25, 33)) \
!= self.settings['inverted']
def isTop(self):
return inRange(self.cable(), 1, 15)
def isMiddle(self):
return inRange(self.cable(), 16, 33)
def isHV(self):
return self.test().upper() == "HV"
def isPulse(self):
return self.test().lower() == "pulse"
LeftColor = ANSI.red(highlight=True)
RightColor = ANSI.yellow(highlight=True)
PositionColor = ANSI.white()
SlotColor = ANSI.green(highlight=True)
TopColor = ANSI.magenta(highlight=False)
MiddleColor = ANSI.green(highlight=False)
@staticmethod
def colorLeft(s):
return HorizontalHVandPulseSequence.LeftColor + s + ANSI.reset()
@staticmethod
def colorRight(s):
return HorizontalHVandPulseSequence.RightColor + s + ANSI.reset()
@staticmethod
def colorPosition(p):
return HorizontalHVandPulseSequence.PositionColor + str(p) + ANSI.reset()
@staticmethod
def colorTopFlange(s = "top flange"):
return HorizontalHVandPulseSequence.TopColor + s + ANSI.reset()
@staticmethod
def colorMiddleFlange(s = "middle flange"):
return HorizontalHVandPulseSequence.MiddleColor + s + ANSI.reset()
def sideColor(self):
if self.isLeft():
return HorizontalHVandPulseSequence.LeftColor
elif self.isRight():
return HorizontalHVandPulseSequence.RightColor
else:
return ""
# sideColor()
def sideName(self):
if self.isLeft():
return "RED"
elif self.isRight():
return "YELLOW"
else:
return "unknown side"
# sideName()
def stateStr(self):
# coloring
chimney = self.readerState.chimney # no color
cable = drawWaveforms.CableInfo(self.readerState.cableTag, self.cable())
if self.isLeft():
cable = self.colorLeft(cable)
elif self.isRight():
cable = self.colorRight(cable)
if self.isTop():
flangePosition = self.colorTopFlange()
elif self.isMiddle():
flangePosition = self.colorMiddleFlange()
else:
flangePosition = ""
if self.isPulse():
test = (
"p"
+ ANSI.white() + "u"
+ ANSI.green() + "l"
+ ANSI.black(highlight=True) + "s"
+ ANSI.red(highlight=True) + "e"
+ ANSI.reset()
)
elif self.isHV():
test = ANSI.cyan() + self.test() + ANSI.reset()
else:
test = self.test()
slot = self.SlotColor + "slot {}".format(self.slot()) + ANSI.reset()
position = self.colorPosition(self.position())
return (
"Test {test} chimney {chimney} {flange} {slot} connection {cable} position {position}"
.format(
test=test,
flange=flangePosition,
slot=slot,
chimney=chimney,
cable=cable,
position=position,
)
)
# stateStr()
def hint(self):
msg = []
if self.isAtEnd():
msg.append("* check the bias voltage of the last cable (all positions)")
msg.append("Then the test sequence of chimney {} is complete." \
.format(self.readerState.chimney))
elif self.isFirstPosition():
if not self.isFirstCable():
msg.append \
("* check the bias voltage of the last cable (all positions)")
msg.append(
"* switch the test box cable to {sideCol}{cable} ({side} side){reset} on {slotCol}slot {slot}{reset}"
.format(
sideCol=self.sideColor(),
cable=self.readerState.cable(),
side=self.sideName(),
slotCol=self.SlotColor,
slot=self.slot(),
reset=ANSI.reset(),
))
if self.iCable == self.firstCableOnFlange(self.settings, flange=2):
msg.append(" => it's on the {}".format(self.colorMiddleFlange()))
else:
msg.append("* just turn to {posCol}position {pos}{reset}".format(
posCol=self.PositionColor,
reset=ANSI.reset(),
pos=self.position(),
))
# if first position ... else
return "\n".join(filter(None, msg)) if msg else None
# hint()
@staticmethod
def firstCableOnFlange(settings, flange=2):
return settings['cables'] \
[sum(settings['cablesOnFlanges'][:(flange-1)]) if (flange > 1) else 0]
@staticmethod
def buildSlotTable(settings):
newFlangeOn = [
HorizontalHVandPulseSequence.firstCableOnFlange(settings, flange=flange)
for flange in (1, 2, )
]
slots = []
flanges = []
slot = 0
side = 1
flange = 0
for cable in settings['cables']:
if cable in newFlangeOn:
flange += 1
slot = 0
if (cable in newFlangeOn) or (side == 1):
slot += 1
side = 0
else: side += 1
slots.append(slot)
flanges.append(flange)
# for
return slots, flanges
# buildSlotTable()
# class HorizontalHVandPulseSequence
################################################################################
### ChimneyReader: helper with functions for a DAQ workflow
class ChimneyReader:
"""
`ChimneyReader` now controls the communication with the oscilloscope, via a
`ScopeTalker` object (in fact, a `TDS3054Ctalker` object).
"""
MinPosition = 1
MaxPosition = 8
MinCable = 1
MaxCable = 18
TestSets = {
'HV': {
'tests': [ 'HV', ],
'sequence': HVandPulseSequence,
},
'Pulse': {
'tests': [ '', ],
},
'Flange': {
'tests': [ 'PULSE', 'HV', ],
'sequence': HVandPulseSequence,
},
'FastFlange': {
'tests': [ 'PULSE', ],
'sequence': HVandPulseSequence,
},
'FastFlangeHorizontal': {
'tests': [ 'PULSE', ],
'sequence': HorizontalHVandPulseSequence,
},
} # TestSets
WaveformFilePattern = drawWaveforms.WaveformSourceFilePath.StandardPattern
WaveformDirectory = drawWaveforms.WaveformSourceFilePath.StandardDirectory
DefaultVerificationThoroughness = 4 # see `verify()`
TimerPlotNamespace = 'plot'
class ConfigurationError(RuntimeError):
def __init__(self, msg, *args, **kargs):
RuntimeError.__init__(self, "Configuration error: " + msg, *args, **kargs)
# ConfigurationError
def __init__(self,
configurationFile,
chimney = None,
renderer = None,
IP = None, N = None, fake = None
):
"""Creates a new `ChimneyReader`.
This object *requires* a configuration file, although most of the options
have default values which kick in if no configuration is provided.
Also, the additional arguments override the values in the configuration
file.
"""
params = self._configure(configurationFile)
# override configuration parameters with specified arguments
if IP is not None: params.IP = IP
if fake is not None: params.fake = fake
if N is not None: params.N = N
self.scope = TDS3054Ctalker(params.IP, connect=not params.fake)
self.selectTestSuite(params.testSuite)
ANSI.enableColor(params.useColors)
self.nextHints = params.printHints
self.readerState = self._makeFakeReaderState(chimney=chimney, N=params.N)
self.setQuiet(True) # this will be one day removed
self.setFake(params.fake)
self.storageParams = params.storage
self.drawWaveforms \
= drawWaveforms.useRenderer(renderer if renderer else params.drawWaveforms)
self.drawOptions = params.draw
self.canvas = None
self.timers = WatchCollection(
'setup' ,
'channel' ,
'writing' ,
{ 'name': 'readout', 'comment': '(breakout below)', },
{ 'name': 'graphicUpdate', 'description': 'update display', 'namespace': ChimneyReader.TimerPlotNamespace, },
title="Timing of `ChimneyReader.readout()`",
) # timers
# __init__()