-
Notifications
You must be signed in to change notification settings - Fork 0
/
drawWaveforms.py
executable file
·2589 lines (2099 loc) · 79.9 KB
/
drawWaveforms.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 stopwatch import WatchCollection
import sys
import os
import re
import math
import csv
import logging
import numpy
import struct
from SelectedRange import SelectedRange
################################################################################
def capitalize(word): return word[:1].upper() + word[1:]
def camelCase(*words):
try: s = words[0]
except IndexError: return ""
for word in words[1:]:
try:
if s[-1].islower(): word = capitalize(word)
except IndexError: pass
s += word
# for
return s
# camelCase()
def objectValues(obj, keys):
def callOrValue(obj, attrName):
attr = getattr(obj, attrName)
return attr() if callable(attr) else attr
# callOrValue()
return dict( ( key, callOrValue(obj, key) ) for key in keys)
# objectValues()
def inverseLookup(myValue, table):
for key, value in table.items():
if myValue == value: return key
else: raise KeyError(myValue)
# inverseLookup()
def readWaveformTextFile(path):
# here we keep it very simple...
columns = [ [], [], ] # start with at least one column
with open(path, 'r') as f:
for tokens in csv.reader(f):
assert len(tokens) == 2
columns[0].append(float(tokens[0]))
columns[1].append(float(tokens[1]))
# for
# with
return map(numpy.array, columns)
# readWaveformTextFile()
def writeWaveformTextFile(t, V, path):
"""
Writes the specified waveform as a CSV text file, each line a `t,V` entry.
"""
with open(path, 'w') as f:
for a, b in zip(t, V):
f.write('{t:g},{V:g}'.format(a, b))
# for
# with
# writeWaveformTextFile()
DefaultBinaryVersion = 1
class BinaryFileVersion1:
TimeDataStruct = struct.Struct('<Ldd')
# class BinaryFileVersion1
def readWaveformBinaryFile(path, version = None):
"""
Reads waveform data from a binary file with specified version.
Formats:
* version 1 (current default):
* integer: version number
* integer (`N`): number of sampling points
* double (C type): sampling of first time
* double (C type): sampling of last time
* numpy.float (x `N`): voltage sampled at each of the sampling times, in order
Parameters
-----------
path _(string)_
path to the input file
version _(integer, default: autodetect)_
binary file format (if `None`, it is autodetected);
see `writeWaveformBinaryFile()` for a description of the formats
Returns
--------
t, V
iterables of sampling time and sampled voltage
"""
with open(path, 'rb') as inputFile:
fileVersion = ord(inputFile.read(1))
if version is None:
version = fileVersion
elif version != fileVersion:
raise RuntimeError(
"File '{}' is version {} (attempted read as version {})".format(
path, fileVersion, version
))
# version
if version == 1:
timeStruct = BinaryFileVersion1.TimeDataStruct
buf = inputFile.read(timeStruct.size)
nSamples, minT, maxT = timeStruct.unpack_from(buf)
t = numpy.linspace(minT, maxT, nSamples)
V = numpy.fromfile(inputFile, count=nSamples)
return t, V
# version 1
raise RuntimeError("Unknown data format: version {}".format(version))
# with
# readWaveformBinaryFile()
def writeWaveformBinaryFile(t, V, path, version = None):
"""
Writes the specified data into a binary file with specified version.
Formats:
* version 1 (current default):
* integer: version number
* integer (`N`): number of sampling points
* float: sampling of first time
* float: sampling of last time
* floats (x `N`): voltage sampled at each of the sampling times, in order
Parameters
-----------
t, V
lists of sampling time and sampled voltage, to be written
path _(string)_
path to the output file; it will be forcibly recreated
version _(integer, default: latest)_
binary file format (if `None`, the latest will be picked)
"""
# here we keep it very simple...
if version is None: version = DefaultBinaryVersion
with open(path, 'wb') as outputFile:
outputFile.write(chr(version))
if version == 1:
timeStruct = BinaryFileVersion1.TimeDataStruct
outputFile.write(timeStruct.pack(len(t), t[0], t[-1], ))
V.tofile(outputFile)
return
# if version 1
raise RuntimeError("Unknown data format: version {}".format(version))
# with
# writeWaveformBinaryFile()
def isTextFile(path):
return os.path.splitext(path)[-1].lower() in [ '.txt', '.csv', ]
def readWaveformFile(path, version = None):
"""
Reads waveform data from a file.
The input format of the file can be specified (or it will be autodetected).
Returns two iterables, for time and voltage.
"""
if version is None and isTextFile(path): version = 0
if version == 0:
return readWaveformTextFile(path)
else:
return readWaveformBinaryFile(path, version=version)
# readWaveformFile()
def writeWaveformFile(t, V, path, version = None):
"""
Writes waveform data into a file.
The output format of the file can be specified, or the default binary format
(`DefaultBinaryVersion`) will be used.
"""
if version == 0:
return writeWaveformTextFile(t, V, path)
else:
return writeWaveformBinaryFile(t, V, path, version=version)
# readWaveformFile()
def indentText(
msg,
indent = " ",
firstIndent = None,
suppressIndentation = False
):
if firstIndent is None: firstIndent = indent
indentStr = lambda iLine: (firstIndent if iLine == 0 else indent)
return "\n".join([
indentStr(iLine) + (line.lstrip() if suppressIndentation else line)
for iLine, line in enumerate(msg.split('\n'))
])
# indentText()
################################################################################
### WaveformSourceInfo: data structure with waveform identification parameters
class ChimneyInfo:
@staticmethod
def _matchedParsing(match):
chimneyNumber = match.group(2).lstrip('0')
return ( match.group(1), int(chimneyNumber) if chimneyNumber else 0, ) \
if match is not None else None
# _matchedParsing()
class StyleBase:
@classmethod
def split(cls, chimney):
match = cls.Pattern.match(chimney.upper())
return ChimneyInfo._matchedParsing(match) if match else None
@staticmethod
def format_(row, number):
return '{row}{number:02d}'.format(row=row.upper(), number=number)
# StyleBase
class GeographicStyle(StyleBase):
Name = 'geographic'
Pattern = re.compile('([EW]{2})([0-9]+)')
StandardTable = { 'EE': 'A', 'EW': 'B', 'WE': 'C', 'WW': 'D', }
@staticmethod
def fromStandard(row, number):
return (
inverseLookup(row, ChimneyInfo.GeographicStyle.StandardTable),
21 - number,
)
# fromStandard()
@staticmethod
def toStandard(row, number):
return ( ChimneyInfo.GeographicStyle.StandardTable[row], 21 - number )
# GeographicStyle
class AlphabeticStyle(StyleBase):
Name = 'alphabetic'
Pattern = re.compile('([A-D])([0-9]+)')
@staticmethod
def fromStandard(row, number): return (row, number)
@staticmethod
def toStandard(row, number): return (row, number)
# AlphabeticStyle
StandardStyle = GeographicStyle
class FlangeStyle(StyleBase):
Name = 'flange'
Pattern = re.compile('(F)([0-9]+)')
@staticmethod
def fromStandard(row, number):
raise RuntimeError(
"Special chimney style '{}' can't be converted from a different style"
.format(ChimneyInfo.FlangeStyle.Name)
)
@staticmethod
def toStandard(row, number):
raise RuntimeError(
"Special chimney style '{}' can't be converted to a different style"
.format(ChimneyInfo.FlangeStyle.Name)
)
# FlangeStyle
class InvalidStyle(StyleBase):
Name = 'invalid'
Pattern = re.compile('')
@staticmethod
def fromStandard(row, number):
raise RuntimeError(
"Special chimney style '{}' can't be converted from a different style"
.format(ChimneyInfo.InvalidStyle.Name)
)
@staticmethod
def toStandard(row, number):
raise RuntimeError(
"Special chimney style '{}' can't be converted to a different style"
.format(ChimneyInfo.InvalidStyle.Name)
)
# InvalidStyle
ValidStyles = ( GeographicStyle, AlphabeticStyle, FlangeStyle, )
@staticmethod
def styleMatcher(chimney):
for class_ in ChimneyInfo.ValidStyles:
if class_ is ChimneyInfo.InvalidStyle: continue
info = class_.split(chimney)
if not info: continue
return class_, info
else: return ChimneyInfo.InvalidStyle, None
# styleMatcher()
@staticmethod
def split(chimney):
"""Returns a tuple ( row, column, style ). Raises RuntimeError on error."""
style, info = ChimneyInfo.styleMatcher(chimney)
if info is None:
raise RuntimeError("'{}' is not a valid chimney.".format(chimney))
return info + tuple([ style, ])
# split()
@staticmethod
def format_(series, n): return "{}{:02d}".format(series, n)
@staticmethod
def isChimney(chimney):
return ChimneyInfo.split(chimney.upper()) is not None
@staticmethod
def detectStyle(chimney):
style, _ = ChimneyInfo.styleMatcher(chimney)
return style.Name
# detectStyle()
@staticmethod
def expandStyle(style):
try: isStyle = issubclass(style, ChimneyInfo.StyleBase)
except TypeError: isStyle = False
if isStyle:
styleName = style.Name
else:
styleName = style
style = ChimneyInfo.findStyle(styleName)
if style is None:
raise RuntimeError("Chimney name style '{}' invalid".format(styleName))
return style, styleName
# expandStyle()
@staticmethod
def convertToStyleAndSplit(style, chimney, srcStyle = None):
style, styleName = ChimneyInfo.expandStyle(style)
if not srcStyle: # autodetect original style
srcStyle, info = ChimneyInfo.styleMatcher(chimney)
if srcStyle is ChimneyInfo.InvalidStyle:
raise RuntimeError("'{}' is not a valid chimney.".format(chimney))
row, number = info
else:
srcStyle, _ = ChimneyInfo.expandStyle(srcStyle)
row, number = srcStyle.split(chimney)
#
if srcStyle is not style:
row, number = srcStyle.toStandard(row, number)
row, number = style.fromStandard(row, number)
return (row, number)
# convertToStyleAndSplit()
@staticmethod
def convertToStyle(style, chimney, srcStyle = None):
style, _ = ChimneyInfo.expandStyle(style)
return style.format_ \
(*ChimneyInfo.convertToStyleAndSplit(style, chimney, srcStyle=srcStyle))
# convertToStyle()
@staticmethod
def findStyle(styleName):
for style in ChimneyInfo.ValidStyles:
if style.Name.lower() == styleName.lower(): return style
else: return None
# findStyle()
@staticmethod
def _matchedParsing(match):
chimneyNumber = match.group(2).lstrip('0')
return ( match.group(1), int(chimneyNumber) if chimneyNumber else 0, ) \
if match is not None else None
# _matchedParsing()
# class ChimneyInfo
class CableInfo:
Pattern = re.compile('([A-Z]?)([0-9]{1,2})')
@staticmethod
def isCable(cable):
return CableInfo.Pattern.match(cable.upper()) is not None
@staticmethod
def parse(cable):
if isinstance(cable, str):
match = CableInfo.Pattern.match(cable.upper())
if match is None:
raise RuntimeError("'{}' is not a valid cable identifier.")
cableNumber = match.group(2).lstrip('0')
cableTag = match.group(1)
else:
cableNumber = cable
cableTag = ''
return cableTag, int(cableNumber)
# parse()
@staticmethod
def extract(cable, chimney = None):
cableTag, cableNumber = CableInfo.parse(cable)
if not cableTag:
if chimney is None:
raise RuntimeError \
("A chimney is required in order to parse cable identifier '{}'")
# if
cableTag = CableInfo.tagFor(chimney)
# if
return cableTag, cableNumber
# extract()
@staticmethod
def format_(cableTag, cableNo, chimney = None):
if not cableTag:
if chimney is None:
raise RuntimeError(
"Either cable tag or chimney are required for formatting a cable name."
)
cableTag = CableInfo.tagFor(chimney)
# if not cableTag
return "{tag}{no:02d}".format(tag=cableTag, no=cableNo)
# format_()
@staticmethod
def tagFor(chimney):
chimneySeries, chimneyNo = ChimneyInfo.convertToStyleAndSplit \
(ChimneyInfo.StandardStyle, chimney)
if chimneySeries in [ 'EE', 'WE', ]:
if chimneyNo == 1: return 'C'
elif chimneyNo == 20: return 'D'
else: return 'V'
elif chimneySeries in [ 'EW', 'WW', ]:
if chimneyNo == 1: return 'A'
elif chimneyNo == 20: return 'B'
else: return 'S'
elif chimneySeries == "F": return 'V'
raise RuntimeError("No cable tag for chimneys '{}'".format(chimneySeries))
# tagFor()
# class CableInfo
class ChimneyID:
def __init__(self,
chimney = None, col = None, cryostat = None, TPC = None, row = None
):
"""
E.g. for "EW06", chimney='EW06', col='EW', cryostat='E', TPC='W', row=6.
"""
if chimney is not None:
assert col is None and cryostat is None and TPC is None and row is None
col, row \
= ChimneyInfo.convertToStyleAndSplit(ChimneyInfo.GeographicStyle, chimney)
chimney = None
# if chimney
if col is not None:
assert cryostat is None and TPC is None
( cryostat, TPC, ) = col
# if
assert row is not None
row = int(row)
assert cryostat in ( 'E', 'W', )
assert TPC in ( 'E', 'W', )
self.cryostat = cryostat
self.TPC = TPC
self.number = row
# __init__()
def toString(self, style = ChimneyInfo.StandardStyle):
return ChimneyInfo.convertToStyle \
(style, str(self), srcStyle=ChimneyInfo.StandardStyle)
# toString()
def __str__(self):
return ChimneyInfo.StandardStyle.format_ \
(self.cryostat + self.TPC, self.number)
# __str__()
# class ChimneyID
class ChannelInfo:
"""Identification of a channel in the connectivity test.
The elements of the identification are:
* chimney: a string that can be interpreted by `ChimneyInfo` (e.g. 'EW03')
* connection (or cable()): identifier of the 68-wire cable (e.g. 'S12')
* position: setting of the 8-position test box switch, 1-8 (e.g. 6)
* channelIndex: oscilloscope/test box channel number, 1-4 (e.g. 3)
Possible queries include, in addition to the direct access to the above
attributes:
* cable(), cableTag(), cableNo() (e.g. 'S12', 'S' and 12)
* channel: number of channel on the cable, 1-32 (e.g. 23)
* board(): number of the readout board in the minicrate for this channel
* slot(): number of the minicrate slot of the board reading the channel
* side(), sideName(): side of the board (e.g. ChannelInfo.RightSide, 'right')
* readoutChannel() channel within the chimney, 0-575 (e.g. 137)
* boardChannel() channel on the readout board, 0-63 (e.g. 9)
"""
# NOTE: we support a state where the channel is not known (None)
MaxChannels = 4
MaxPositions = 8
# it should be `MaxChannels`, but it's already taken:
CableChannels = MaxChannels * MaxPositions
MaxSlots = 9 # number of slots in a readout minicrate
LeftSide, RightSide, MaxSides = range(3)
MaxCables = MaxSlots * MaxSides # number of cables in a readout minicrate
SideNames = { LeftSide: "left", RightSide: "right", None: "unknown", }
BoardChannels = CableChannels * MaxSides
ChimneyChannels = CableChannels * MaxCables
def __init__(self,
chimney=None, connection=None, channelIndex=None, position=None,
channel=None
):
assert \
((channel is None) != ((position is None) and (channelIndex is None)))
self.chimney = None
self.connection = connection
self.position = position
self.channelIndex = channelIndex
self.channel = channel
self.setChimney(chimney)
if self.channel is None: self.updateChannel()
else: self.updatePositionAndChannelIndex()
self.updateConnection()
# __init__()
def copy(self):
return ChannelInfo(
chimney=self.chimney, connection=self.connection,
channelIndex=self.channelIndex, position=self.position
)
# copy()
def formatString(self, s): return s % vars(self)
def cryostat(self): return self.chimneyID.cryostat
def TPC(self): return self.chimneyID.TPC
def setChimney(self, chimney):
if isinstance(chimney, ChimneyID):
self.chimneyID = chimney
self.chimney = str(self.chimneyID)
else:
self.chimney = chimney
self.chimneyID = ChimneyID(self.chimney)
self.updateConnection()
def setConnection(self, connection):
self.connection = connection
self.updateConnection()
def setChannelIndex(self, channelIndex):
self.channelIndex = channelIndex
self.updateChannel()
def setPosition(self, position):
self.position = position
self.updateChannel()
def setChannel(self, channel):
self.channel = channel
self.updatePositionAndChannelIndex()
def updateChannel(self):
self.channel = \
None if self.position is None or self.channelIndex is None \
else (self.position - 1) * ChannelInfo.MaxChannels + self.channelIndex
# updateChannel()
def updatePositionAndChannelIndex(self):
self.position = None if self.channel is None \
else ChannelInfo.positionOfChannel(self.channel)
self.channelIndex = None if self.channel is None \
else ChannelInfo.indexOfChannel(self.channel)
# updatePositionAndChannelIndex()
def updateConnection(self):
if (self.chimney is None) or (self.connection is None): return
cableTag, cableNo = CableInfo.extract(self.connection, chimney=self.chimney)
self.connection = CableInfo.format_(cableTag, cableNo)
# updateConnection()
def cable(self): return self.connection
def cableInfo(self):
return CableInfo.extract(self.connection, chimney=self.chimney)
def cableTag(self): return self.cableInfo()[0]
def cableNo(self): return self.cableInfo()[1]
def board(self): return (self.cableNo() - 1) % ChannelInfo.MaxSlots
def slot(self): return self.board() + 1
def side(self):
cableNo = self.cableNo()
if cableNo is None: return None
if cableNo <= 0*ChannelInfo.MaxSlots: return None
if cableNo <= 1*ChannelInfo.MaxSlots: return ChannelInfo.LeftSide
if cableNo <= 2*ChannelInfo.MaxSlots: return ChannelInfo.RightSide
return None
# side()
def sideName(self): return ChannelInfo.SideNames[self.side()]
def boardChannel(self):
if self.channel is None: return None
return (ChannelInfo.CableChannels - self.channel) \
+ (ChannelInfo.CableChannels if self.side() == ChannelInfo.LeftSide else 0)
# boardChannel()
def readoutChannel(self):
if self.channel is None: return None
return self.board() * ChannelInfo.BoardChannels + self.boardChannel()
# readoutChannel()
AllFormatKeys = (
'chimney', 'cable', 'channel',
'channelIndex', 'position',
'cableNo', 'cableTag',
'slot', 'board', 'boardChannel', 'readoutChannel',
)
def formatString(self, format_, keys = AllFormatKeys):
return format_.format(**(objectValues(self, keys)))
@staticmethod
def indexOfChannel(channel):
return ((channel - 1) % ChannelInfo.MaxChannels) + 1
@staticmethod
def positionOfChannel(channel):
return ((channel - 1) // ChannelInfo.MaxChannels) + 1
# class ChannelInfo
class WaveformSourceInfo(ChannelInfo):
"""A channel identifier with a test name and a waveform index added."""
def __init__(self,
chimney=None, connection=None, channelIndex=None, position=None,
index=None,
testName="",
channel=None,
):
ChannelInfo.__init__(self,
chimney=chimney, connection=connection,
channelIndex=channelIndex, position=position, channel=channel,
)
self.test = testName
self.index = index
# __init__()
def copy(self):
return WaveformSourceInfo(
chimney=self.chimney, connection=self.connection,
channelIndex=self.channelIndex, position=self.position,
index=self.index, testName=self.test,
)
# copy()
def setIndex(self, index): self.index = index
def setFirstIndex(self, N = 10):
self.setIndex(self.firstIndexOf(self.position, N=N))
def increaseIndex(self, amount = 1): self.index += amount
AllFormatKeys = ChannelInfo.AllFormatKeys + (
'test', 'index',
)
def formatString(self, format_, keys = AllFormatKeys):
return format_.format(**(objectValues(self, keys)))
@staticmethod
def firstIndexOf(position, N = 10): return (position - 1) * N + 1
# class WaveformSourceInfo
################################################################################
### `WaveformSourceFilePath`: waveform parameter management
class WaveformSourceFilePath:
StandardDirectory = "CHIMNEY_{chimney}"
StandardPattern = "{test}waveform_CH{channelIndex:d}_CHIMNEY_{chimney}_CONN_{cable}_POS_{position:d}_{index:d}.csv"
def __init__(self,
sourceInfo, filePattern = StandardPattern, sourceDir = ".",
):
"""
The expected pattern is:
"path/HVwaveform_CH3_CHIMNEY_A11_CONN_V12_POS_7_62.csv"
"""
self.sourceDir = sourceDir
self.sourceFilePattern = filePattern
self.sourceInfo = sourceInfo
self.sourceInfo.updateChannel()
# __init__()
def copy(self):
return self.__class__(
self.sourceInfo.copy(),
filePattern=self.sourceFilePattern,
sourceDir=self.sourceDir,
)
# copy()
def setSourceInfo(self, sourceInfo): self.sourceInfo = sourceInfo
def formatString(self, s):
return s.format \
(**objectValues(self.sourceInfo, WaveformSourceInfo.AllFormatKeys))
# formatString()
def buildDir(self):
return self.formatString(self.sourceDir)
def buildPath(self):
return os.path.join(self.sourceDir, self.formatString(self.sourceFilePattern))
def describe(self):
msg = "Source directory: '%s'\nPattern: '%s'" % (self.sourceDir, self.sourceFilePattern)
msg += "\nTriggering file: '" + os.path.join(self.sourceDir, self.sourceFilePattern % vars(self.sourceInfo)) + "'"
return msg
# describe()
def allChannelSources(self, channelIndex = None, channel = None, N = 10):
"""
Returns the list of N expected waveform files at the specified channel index.
"""
values = self.sourceInfo.copy()
if channelIndex is not None:
values.setChannelIndex(channelIndex)
assert channel is None
elif channel is not None:
values.setChannel(channel)
assert channelIndex is None
values.setIndex((self.sourceInfo.position - 1) * N)
files = []
for i in xrange(N):
values.increaseIndex()
files.append(
os.path.join(
self.sourceDir, values.formatString(self.sourceFilePattern)
))
# for i
return files
# allChannelSources()
def allPositionSources(self, N = 10):
"""Returns the list of 4N expected waveform files for the current position."""
files = []
for channelIndex in xrange(1, ChannelInfo.MaxChannels + 1): files.extend(self.allChannelSources(channelIndex=channelIndex, N=N))
return files
# allPositionSources()
# class WaveformSourceFilePath
def parseWaveformSource(path):
"""Parses `path` and returns a filled `WaveformSourceFilePath`.
The expected pattern is:
"path/PULSEwaveform_CH3_CHIMNEY_EE11_CONN_V12_POS_7_62.csv"
"""
sourceDir, triggerFileName = os.path.split(path)
name, ext = os.path.splitext(triggerFileName)
if ext.lower() != '.csv':
print >>sys.stderr, "Warning: the file '%s' has not the name of a comma-separated values file (CSV)." % path
tokens = name.split("_")
sourceInfo = WaveformSourceInfo()
sourceFilePattern = []
iToken = 0
while iToken < len(tokens):
Token = tokens[iToken]
iToken += 1
TOKEN = Token.upper()
if TOKEN == 'CHIMNEY':
try: sourceInfo.setChimney(tokens[iToken])
except IndexError:
raise RuntimeError("Error parsing file name '%s': no chimney." % triggerFileName)
iToken += 1
sourceFilePattern.extend([ Token, "{chimney}", ])
continue
elif TOKEN == 'CONN':
try: sourceInfo.setConnection(tokens[iToken])
except IndexError:
raise RuntimeError("Error parsing file name '%s': no connection code." % triggerFileName)
iToken += 1
sourceFilePattern.extend([ Token, "{cable}", ])
continue
elif TOKEN == 'POS':
try: sourceInfo.position = int(tokens[iToken])
except IndexError:
raise RuntimeError("Error parsing file name '%s': no connection code." % triggerFileName)
except ValueError:
raise RuntimeError("Error parsing file name '%s': '%s' is not a valid position." % (triggerFileName, tokens[iToken]))
sourceFilePattern.extend([ Token, "{position:d}", ])
iToken += 1
continue
elif TOKEN.endswith('WAVEFORM'):
testName = Token[:-len('WAVEFORM')]
channel = tokens[iToken]
if not channel.startswith('CH'):
raise RuntimeError("Error parsing file name '%s': '%s' is not a valid channel." % (triggerFileName, channel))
try: sourceInfo.setChannelIndex(int(channel[2:]))
except IndexError:
raise RuntimeError("Error parsing file name '%s': no connection code." % triggerFileName)
except ValueError:
raise RuntimeError("Error parsing file name '%s': '%s' is not a valid channel number." % (triggerFileName, channel[2:]))
sourceFilePattern.extend([ Token, "CH{channelIndex:d}", ])
iToken += 1
continue
else:
try:
sourceInfo.setIndex(int(Token))
sourceFilePattern.append('{index:d}')
except ValueError:
print >>sys.stderr, "Unexpected tag '%s' in file name '%s'" % (Token, triggerFileName)
sourceFilePattern.append(Token)
# if ... else
# while
if sourceInfo.chimney is None: raise RuntimeError("No chimney specified in file name '%s'" % triggerFileName)
if sourceInfo.connection is None: raise RuntimeError("No connection specified in file name '%s'" % triggerFileName)
if sourceInfo.position is None: raise RuntimeError("No position specified in file name '%s'" % triggerFileName)
if sourceInfo.channelIndex is None: raise RuntimeError("No channel specified in file name '%s'" % triggerFileName)
if sourceInfo.index is None: raise RuntimeError("No index specified in file name '%s'" % triggerFileName)
sourceInfo.updateChannel()
sourceFilePattern = "_".join(sourceFilePattern)
if ext: sourceFilePattern += ext
return WaveformSourceFilePath(sourceInfo, sourceFilePattern, sourceDir)
# parseWaveformSource()
def readWaveform(filePath):
columns = [ [], [] ]
with open(filePath, 'r') as inputFile:
for line in inputFile:
valueStrings = line.strip().split(",")
#
# columns = [ Xlist, Ylist ]
# valueStrings = [ Xvalue, Yvalue ]
# zip(columns, valueStrings) = ( ( Xlist, Xvalue ), ( Ylist, Yvalue ) )
#
for values, newValue in zip(columns, valueStrings):
values.append(float(newValue))
# for
# with
return columns
# readWaveform()
################################################################################
### Format conversions
class ChannelConversions:
class ChannelFormatError(RuntimeError): pass
class ChannelConverter:
Name = "ChannelConverter"
@classmethod
def parse(cls, spec): raise NotImplementedError
@staticmethod
def formatChannel(channelInfo): return "<invalid>"
# class ChannelConverter
class TestBoxChannel(ChannelConverter):
"""The channel is specified in the connectivity test box format.
The string specification is: '<chimney>:<cable>:<position>:<channel index>'
with:
* <chimney> the usual chimney specification, e.g. 'EW03'
* <cable> a 68-wire cable label (e.g. 'S12') or number (e.g. 12)
* <position> number 1-8 of the test box switch position (e.g. 6)
* <channel index> oscilloscope channel 1-4 (e.g. 3)
"""
Name = "connectivity test box"
@classmethod
def parse(cls, spec):
try:
chimney, connection, position, channelIndex = spec.split(':')
except ValueError:
raise ChannelConversions.ChannelFormatError(
"Channel specification '{}' not in {} format"
.format(spec, cls.__name__)
)
# if
try: position = int(position)
except ValueError:
raise ChannelConversions.ChannelFormatError(
"Position '{}' not valid in '{}' channel specification"
.format(position, spec)
)
# try ... except
if position <= 0 or position > ChannelInfo.MaxPositions:
raise ChannelConversions.ChannelFormatError(
"Test box switch position {} not in range in '{}' channel specification"
.format(position, spec)
)
# try ... except
if channelIndex.upper().startswith('CH'):
channelIndex = channelIndex[2:]
try: channelIndex = int(channelIndex)
except ValueError:
raise ChannelConversions.ChannelFormatError(
"Oscilloscope channel '{}' not valid in '{}' channel specification"
.format(channelIndex, spec)
)
# try ... except
if channelIndex <= 0 or channelIndex > ChannelInfo.MaxChannels:
raise ChannelConversions.ChannelFormatError(
"Oscilloscope channel {} not in range in '{}' channel specification"
.format(channelIndex, spec)
)
# try ... except
if not ChimneyInfo.isChimney(chimney):
raise ChannelConversions.ChannelFormatError(
"Chimney '{}' in channel specification '{}' not valid"
.format(chimney, spec)
)
# if
return ChannelInfo(
chimney=chimney, connection=connection,
position=position, channelIndex=channelIndex,
)
# parse()
@staticmethod
def formatChannel(channelInfo):
return channelInfo.formatString(
'{chimney}:{cable}:{position}:{channelIndex}',
( 'chimney', 'cable', 'position', 'channelIndex', )
)
# formatChannel()
# class TestBoxChannel
class ChimneyCableChannel(ChannelConverter):
"""The channel is specified in the readout format of chimney and channel.
The string specification is: '<chimney>:<cable>:<channel>' with:
* <chimney> the usual chimney specification, e.g. 'EW03'
* <cable> a 68-wire cable label (e.g. 'S12') or number (e.g. 12)
* <channel> number 1-32 of the channel within the cable (e.g. 23)
"""
Name = "chimney/cable/channel"
@classmethod