forked from slaclab/Q0Measurement
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathcontainer.py
2352 lines (1781 loc) · 84.8 KB
/
container.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
################################################################################
# Utility classes to hold calibration data for a cryomodule, and Q0 measurement
# data for each of that cryomodule's cavities
# Authors: Lisa Zacarias, Ben Ripman
################################################################################
from __future__ import print_function, division
from csv import writer, reader
from decimal import Decimal
from os.path import isfile
from subprocess import CalledProcessError
from time import sleep
from numpy import mean, exp, log10, sqrt, linspace, empty, polyfit, nanmean, nan
from scipy.stats import linregress
from scipy.signal import medfilt
from matplotlib import pyplot as plt
from collections import OrderedDict
from datetime import datetime, timedelta
from abc import ABCMeta, abstractmethod
from typing import List, Dict, Optional, Union
from utils import (writeAndFlushStdErr, MYSAMPLER_TIME_INTERVAL, TEST_MODE,
VALVE_POS_TOL, HEATER_TOL, GRAD_TOL,
MIN_RUN_DURATION, isYes, writeAndWait, MAX_DS_LL, cagetPV,
caputPV, getTimeParams, MIN_DS_LL, getAndParseRawData,
genAxis, NUM_CAL_STEPS, NUM_LL_POINTS_TO_AVG,
CAV_HEATER_RUN_LOAD, TARGET_LL_DIFF, CAL_HEATER_DELTA,
JT_SEARCH_TIME_RANGE, JT_SEARCH_HOURS_PER_STEP,
HOURS_NEEDED_FOR_FLATNESS, getDataAndHeaterCols,
collapseHeaterVals, ValveParams, TimeParams, compatibleNext,
compatibleMkdirs)
RUN_STATUS_MSSG = ("\nWaiting for the LL to drop {DIFF}% "
"or below {MIN}%...".format(MIN=MIN_DS_LL, DIFF=TARGET_LL_DIFF))
class Container(object):
# setting this allows me to create abstract methods and parameters, which
# are basically things that all inheriting classes MUST implement
__metaclass__ = ABCMeta
def __init__(self, cryModNumSLAC, cryModNumJLAB):
# type: (int, int) -> None
self.cryModNumSLAC = cryModNumSLAC
self.cryModNumJLAB = cryModNumJLAB
self.dsPressurePV = self.addNumToStr("CPT:CM0{CM}:2302:DS:PRESS")
self.jtModePV = self.addNumToStr("CPV:CM0{CM}:3001:JT:MODE")
self.jtPosSetpointPV = self.addNumToStr("CPV:CM0{CM}:3001:JT:POS_SETPT")
# The double curly braces are to trick it into a partial formatting
# (CM gets replaced first, and {{INFIX}} -> {INFIX} for later)
lvlFormatStr = self.addNumToStr("CLL:CM0{CM}:{{INFIX}}:{{LOC}}:LVL")
self.dsLevelPV = lvlFormatStr.format(INFIX="2301", LOC="DS")
self.usLevelPV = lvlFormatStr.format(INFIX="2601", LOC="US")
valveLockFormatter = "CPID:CM0{CM}:3001:JT:CV_{SUFF}"
self.cvMaxPV = self.addNumToStr(valveLockFormatter, "MAX")
self.cvMinPV = self.addNumToStr(valveLockFormatter, "MIN")
self.valvePV = self.addNumToStr(valveLockFormatter, "VALUE")
self.dataSessions = {}
@property
@abstractmethod
def name(self):
raise NotImplementedError
@property
@abstractmethod
def idxFile(self):
raise NotImplementedError
@property
@abstractmethod
def heaterDesPVs(self):
# type: () -> List[str]
raise NotImplementedError
@property
@abstractmethod
def heaterActPVs(self):
# type: () -> List[str]
raise NotImplementedError
@property
@abstractmethod
def liquidLevelDS(self):
raise NotImplementedError
@property
@abstractmethod
def totalHeatDes(self):
raise NotImplementedError
@abstractmethod
def waitForTotalHeatDes(self, valveParams):
# type: (ValveParams) -> None
raise NotImplementedError
@abstractmethod
def walkHeaters(self, perHeaterDelta):
raise NotImplementedError
@abstractmethod
def addDataSessionFromRow(self, row, indices, refHeatLoad, refHeatLoadAct,
calibSession=None, refGradVal=None):
raise NotImplementedError
@abstractmethod
def genDataSession(self, timeParams, valveParams, refGradVal=None,
calibSession=None):
raise NotImplementedError
# Returns a list of the PVs used for this container's data acquisition
@abstractmethod
def getPVs(self):
raise NotImplementedError
@abstractmethod
def hash(self, timeParams, slacNum, jlabNum,
calibSession=None, refGradVal=None):
raise NotImplementedError
# getRefValveParams searches over the last timeRange hours for a period
# when the liquid level was stable and then fetches an averaged JT valve
# position during that time as well as summed cavity heater DES and ACT
# values. All three numbers get packaged and returned in a ValveParams
# object.
# noinspection PyTupleAssignmentBalance,PyTypeChecker
def getRefValveParams(self, timeRange=JT_SEARCH_TIME_RANGE):
# type: (float) -> ValveParams
def halfHourRoundDown(timeToRound):
# type: (datetime) -> datetime
newMinute = 0 if timeToRound.minute < 30 else 30
return datetime(timeToRound.year, timeToRound.month,
timeToRound.day, timeToRound.hour, newMinute, 0)
print("\nDetermining required JT Valve position...")
loopStart = datetime.now()
searchStart = loopStart - timedelta(hours=HOURS_NEEDED_FOR_FLATNESS)
searchStart = halfHourRoundDown(searchStart)
numPoints = int((60 / MYSAMPLER_TIME_INTERVAL)
* (HOURS_NEEDED_FOR_FLATNESS * 60))
while (loopStart - searchStart) <= timedelta(hours=timeRange):
formatter = "Checking {START} to {END} for liquid level stability."
searchEnd = searchStart + timedelta(hours=HOURS_NEEDED_FOR_FLATNESS)
startStr = searchStart.strftime("%m/%d/%y %H:%M:%S")
endStr = searchEnd.strftime("%m/%d/%y %H:%M:%S")
print(formatter.format(START=startStr, END=endStr))
csvReaderLL = getAndParseRawData(searchStart, numPoints,
[self.dsLevelPV], verbose=False)
compatibleNext(csvReaderLL)
llVals = []
for row in csvReaderLL:
try:
llVals.append(float(row.pop()))
except ValueError:
pass
# Fit a line to the liquid level over the last [numHours] hours
m, b, _, _, _ = linregress(range(len(llVals)), llVals)
# If the LL slope is small enough, this may be a good period from
# which to get a reference valve position & heater params
if log10(abs(m)) < -5:
signals = ([self.valvePV] + self.heaterDesPVs
+ self.heaterActPVs)
(header, heaterActCols, heaterDesCols, _,
csvReader) = getDataAndHeaterCols(searchStart, numPoints,
self.heaterDesPVs,
self.heaterActPVs, signals,
verbose=False)
valveVals = []
heaterDesVals = []
heaterActVals = []
valveIdx = header.index(self.valvePV)
for row in csvReader:
valveVals.append(float(row[valveIdx]))
(heatLoadDes,
heatLoadAct) = collapseHeaterVals(row, heaterDesCols,
heaterActCols)
heaterDesVals.append(heatLoadDes)
heaterActVals.append(heatLoadAct)
desValSet = set(heaterDesVals)
# We only want to use time periods in which there were no
# changes made to the heater settings
if len(desValSet) == 1:
desPos = round(mean(valveVals), 1)
heaterDes = desValSet.pop()
heaterAct = mean(heaterActVals)
print("Stable period found.")
formatter = "{THING} is {VAL}"
print(formatter.format(THING="Desired JT valve position",
VAL=desPos))
print(formatter.format(THING="Total heater DES setting",
VAL=heaterDes))
return ValveParams(desPos, heaterDes, heaterAct)
searchStart -= timedelta(hours=JT_SEARCH_HOURS_PER_STEP)
# If we broke out of the while loop without returning anything, that
# means that the LL hasn't been stable enough recently. Wait a while for
# it to stabilize and then try again.
complaint = ("Cryo conditions were not stable enough over the last"
" {NUM} hours - determining new JT valve position. Please"
" do not adjust the heaters. Allow the PID loop to "
"regulate the JT valve position.")
print(complaint.format(NUM=timeRange))
writeAndWait("\nWaiting 30 minutes for LL to stabilize then "
"retrying...")
start = datetime.now()
while (datetime.now() - start).total_seconds() < 1800:
writeAndWait(".", 5)
# Try again but only search the recent past. We have to manipulate the
# search range a little bit due to how the search start time is rounded
# down to the nearest half hour.
return self.getRefValveParams(HOURS_NEEDED_FOR_FLATNESS + 0.5)
# We consider the cryo situation to be good when the liquid level is high
# enough and the JT valve is locked in the correct position
def waitForCryo(self, refValvePos):
# type: (float) -> None
self.waitForLL()
self.waitForJT(refValvePos)
def waitForLL(self):
# type: () -> None
writeAndWait("\nWaiting for downstream liquid level to be {LL}%..."
.format(LL=MAX_DS_LL))
while (MAX_DS_LL - self.liquidLevelDS) > 0:
writeAndWait(".", 5)
writeAndWait(" downstream liquid level at required value.")
def waitForJT(self, refValvePos):
# type: (float) -> None
writeAndWait("\nWaiting for JT Valve to be locked at {POS}..."
.format(POS=refValvePos))
mode = cagetPV(self.jtModePV)
# One way for the JT valve to be locked in the correct position is for
# it to be in manual mode and at the desired value
if mode == "0":
while float(cagetPV(self.jtPosSetpointPV)) != refValvePos:
writeAndWait(".", 5)
# Another way for the JT valve to be locked in the correct position is
# for it to be automatically regulating and have the upper and lower
# regulation limits be set to the desired value
else:
while float(cagetPV(self.cvMinPV)) != refValvePos:
writeAndWait(".", 5)
while float(cagetPV(self.cvMaxPV)) != refValvePos:
writeAndWait(".", 5)
writeAndWait(" JT Valve locked.")
def addNumToStr(self, formatStr, suffix=None):
# type: (str, Optional[str]) -> str
if suffix:
return formatStr.format(CM=self.cryModNumJLAB, SUFF=suffix)
else:
return formatStr.format(CM=self.cryModNumJLAB)
def addDataSession(self, timeParams, valveParams, refGradVal=None,
calibSession=None):
# type: (TimeParams, ValveParams, float, CalibDataSession) -> DataSession
sessionHash = self.hash(timeParams, self.cryModNumSLAC,
self.cryModNumJLAB, calibSession, refGradVal)
# Only create a new calibration data session if one doesn't already
# exist with those exact parameters
if sessionHash not in self.dataSessions:
session = self.genDataSession(timeParams, valveParams, refGradVal,
calibSession)
self.dataSessions[sessionHash] = session
return self.dataSessions[sessionHash]
class Cryomodule(Container):
def __init__(self, cryModNumSLAC, cryModNumJLAB):
# type: (int, int) -> None
super(Cryomodule, self).__init__(cryModNumSLAC, cryModNumJLAB)
# Give each cryomodule 8 cavities
cavities = {}
self._heaterDesPVs = []
self._heaterActPVs = []
for i in range(1, 9):
cav = Cavity(cryMod=self, cavNumber=i)
cavities[i] = cav
self._heaterDesPVs.append(cav.heaterDesPV)
self._heaterActPVs.append(cav.heaterActPV)
# Using an ordered dictionary so that when we generate the report
# down the line (iterating over the cavities in a cryomodule), we
# print the results in order (basic dictionaries aren't guaranteed to
# be ordered)
self.cavities = OrderedDict(sorted(cavities.items())) # type: OrderedDict[int, Cavity]
self._dsRollingBuff = empty(NUM_LL_POINTS_TO_AVG)
self._dsRollingBuff[:] = nan
self._idxFile = ("calibrations/calibrationsCM{CM}.csv"
.format(CM=self.cryModNumSLAC))
@property
def name(self):
# type: () -> str
return "CM{CM}".format(CM=self.cryModNumSLAC)
@property
def idxFile(self):
# type: () -> str
if not isfile(self._idxFile):
compatibleMkdirs(self._idxFile)
with open(self._idxFile, "w+") as f:
csvWriter = writer(f)
csvWriter.writerow(["JLAB Number", "Reference Heat Load (Des)",
"Reference Heat Load (Act)",
"JT Valve Position", "Start", "End",
"MySampler Time Interval"])
return self._idxFile
@property
def heaterDesPVs(self):
# type: () -> List[str]
return self._heaterDesPVs
@property
def heaterActPVs(self):
# type: () -> List[str]
return self._heaterActPVs
@property
def liquidLevelDS(self):
# type: () -> float
try:
start = datetime.now() - timedelta(seconds=NUM_LL_POINTS_TO_AVG)
dsValReader = getAndParseRawData(start, NUM_LL_POINTS_TO_AVG,
[self.dsLevelPV],
MYSAMPLER_TIME_INTERVAL,
False)
# Getting rid of the header
compatibleNext(dsValReader)
for row in dsValReader:
idx = (dsValReader.line_num - 2) % NUM_LL_POINTS_TO_AVG
self._dsRollingBuff[idx] = float(row[1])
return nanmean(self._dsRollingBuff)
except AttributeError:
return float(cagetPV(self.dsLevelPV))
@property
def totalHeatDes(self):
# type: () -> float
heatDes = 0
for pv in self.heaterDesPVs:
heatDes += float(cagetPV(pv))
return heatDes
def waitForTotalHeatDes(self, valveParams):
# type: (ValveParams) -> None
writeAndWait("\nWaiting for total heater setting to be {LOAD} W..."
.format(LOAD=valveParams.refHeatLoadDes))
while self.totalHeatDes != valveParams.refHeatLoadDes:
writeAndWait(".", 5)
def hash(self, timeParams, slacNum, jlabNum, calibSession=None,
refGradVal=None):
# type: (TimeParams, int, int, CalibDataSession, float) -> int
return DataSession.hash(timeParams, slacNum, jlabNum)
# calibSession and refGradVal are unused here, they're just there to match
# the signature of the overloading method in Cavity (which is why they're in
# the signature for Container - could probably figure out a way around this)
def addDataSessionFromRow(self, row, indices, refHeatLoad, refHeatLoadAct,
calibSession=None, refGradVal=None):
# type: (List[str], dict, float, float, CalibDataSession, float) -> CalibDataSession
timeParams = getTimeParams(row, indices)
valveParams = ValveParams(float(row[indices["jtIdx"]]),
refHeatLoad, refHeatLoadAct)
return self.addDataSession(timeParams, valveParams)
def getPVs(self):
# type: () -> List[str]
return ([self.valvePV, self.dsLevelPV, self.usLevelPV]
+ self.heaterDesPVs + self.heaterActPVs)
def walkHeaters(self, perHeaterDelta):
# type: (float) -> None
formatter = "\nWalking CM{NUM} heaters {DIR} by {VAL}"
dirStr = "up" if perHeaterDelta > 0 else "down"
formatter = formatter.format(NUM=self.cryModNumSLAC, DIR=dirStr,
VAL=abs(perHeaterDelta))
print(formatter)
for heaterSetpointPV in self.heaterDesPVs:
currVal = float(cagetPV(heaterSetpointPV))
caputPV(heaterSetpointPV, str(currVal + perHeaterDelta))
writeAndWait("\nWaiting 5s for cryo to stabilize...\n", 5)
def genDataSession(self, timeParams, valveParams, refGradVal=None,
calibSession=None):
# type: (TimeParams, ValveParams, float, CalibDataSession) -> CalibDataSession
return CalibDataSession(self, timeParams, valveParams)
def runCalibration(self, valveParams=None):
# type: (ValveParams) -> (CalibDataSession, ValveParams)
def launchHeaterRun(delta=CAL_HEATER_DELTA):
# type: (float) -> None
print("Ramping heaters to the next setting...")
self.walkHeaters(delta)
writeAndWait(RUN_STATUS_MSSG)
startingLevel = self.liquidLevelDS
avgLevel = startingLevel
while ((startingLevel - avgLevel) < TARGET_LL_DIFF and (
avgLevel > MIN_DS_LL)):
writeAndWait(".", 10)
avgLevel = self.liquidLevelDS
print("\nDone\n")
# Check whether or not we've already found a good JT position during
# this program execution
if not valveParams:
valveParams = self.getRefValveParams()
self.waitForCryo(valveParams.refValvePos)
self.waitForTotalHeatDes(valveParams)
startTime = datetime.now().replace(microsecond=0)
launchHeaterRun(8)
if (self.liquidLevelDS - MIN_DS_LL) < TARGET_LL_DIFF:
print("Please ask the cryo group to refill to {LL} on the"
" downstream sensor".format(LL=MAX_DS_LL))
self.waitForCryo(valveParams.refValvePos)
for _ in range(NUM_CAL_STEPS - 1):
launchHeaterRun()
if (self.liquidLevelDS - MIN_DS_LL) < TARGET_LL_DIFF:
print("Please ask the cryo group to refill to {LL} on the"
" downstream sensor".format(LL=MAX_DS_LL))
self.waitForCryo(valveParams.refValvePos)
# Kinda jank way to avoid waiting for cryo conditions after the final
# run
launchHeaterRun()
endTime = datetime.now().replace(microsecond=0)
print("\nStart Time: {START}".format(START=startTime))
print("End Time: {END}".format(END=datetime.now()))
duration = (datetime.now() - startTime).total_seconds() / 3600
print("Duration in hours: {DUR}".format(DUR=duration))
# Walking the heaters back to their starting settings
# self.walkHeaters(-NUM_CAL_RUNS)
self.walkHeaters(-((NUM_CAL_STEPS * CAL_HEATER_DELTA) + 1))
timeParams = TimeParams(startTime, endTime, MYSAMPLER_TIME_INTERVAL)
dataSession = self.addDataSession(timeParams, valveParams)
# Record this calibration dataSession's metadata
with open(self.idxFile, 'a') as f:
csvWriter = writer(f)
csvWriter.writerow([self.cryModNumJLAB, valveParams.refHeatLoadDes,
valveParams.refHeatLoadAct,
valveParams.refValvePos,
startTime.strftime("%m/%d/%y %H:%M:%S"),
endTime.strftime("%m/%d/%y %H:%M:%S"),
MYSAMPLER_TIME_INTERVAL])
return dataSession, valveParams
class Cavity(Container):
def __init__(self, cryMod, cavNumber):
# type: (Cryomodule, int) -> None
super(Cavity, self).__init__(cryMod.cryModNumSLAC, cryMod.cryModNumJLAB)
self.parent = cryMod
self.cavNum = cavNumber
self._fieldEmissionPVs = None
heaterDesStr = cryMod.addNumToStr("CHTR:CM0{CM}:1{{CAV}}55:HV:{SUFF}",
"POWER_SETPT")
heaterActStr = cryMod.addNumToStr("CHTR:CM0{CM}:1{{CAV}}55:HV:{SUFF}",
"POWER")
self.heaterDesPV = heaterDesStr.format(CAV=cavNumber)
self.heaterActPV = heaterActStr.format(CAV=cavNumber)
self._idxFile = ("q0Measurements/q0MeasurementsCM{CM}.csv"
.format(CM=self.parent.cryModNumSLAC))
@property
def name(self):
# type: () -> str
return "Cavity {CAVNUM}".format(CAVNUM=self.cavNum)
@property
def idxFile(self):
# type: () -> str
if not isfile(self._idxFile):
compatibleMkdirs(self._idxFile)
with open(self._idxFile, "w+") as f:
csvWriter = writer(f)
csvWriter.writerow(["Cavity", "Gradient",
"JT Valve Position", "Start", "End",
"Reference Heat Load (Des)",
"Reference Heat Load (Act)",
"MySampler Time Interval"])
return self._idxFile
@property
def heaterDesPVs(self):
# type: () -> List[str]
return self.parent.heaterDesPVs
@property
def heaterActPVs(self):
# type: () -> List[str]
return self.parent.heaterActPVs
@property
def gradPV(self):
# type: () -> str
return self.genAcclPV("GACT")
@property
def fieldEmissionPVs(self):
# type: () -> List[str]
if not self._fieldEmissionPVs:
lst = [self.gradPV]
for suffix in ["ADES", "FWD:PWRMEAN", "REV:PWRMEAN", "CAV:PWRMEAN",
"DF"]:
lst.append(self.genAcclPV(suffix))
for suffix in ["PEAK", "AVG"]:
for i in range(1, 3):
lst.append("HOM:PWR{IDX}:POWER_{SUFF}".format(IDX=i,
SUFF=suffix))
for i in range(1, 10):
lst.append("IDRFEL1RAD0{IDX}".format(IDX=i))
lst.append("IDRFEL2RAD0{IDX}".format(IDX=i))
for i in range(1, 3):
lst.append("IDRFEL{IDX}RAD10".format(IDX=i))
lst.append("IDRFEL{IDX}HVMON".format(IDX=i))
lst.append(self.dsPressurePV)
self._fieldEmissionPVs = lst
return self._fieldEmissionPVs
@property
def liquidLevelDS(self):
# type: () -> float
return self.parent.liquidLevelDS
@property
def totalHeatDes(self):
# type: () -> float
return self.parent.totalHeatDes
def waitForTotalHeatDes(self, valveParams):
# type: (ValveParams) -> None
self.parent.waitForTotalHeatDes(valveParams)
def walkHeater(self, heatDelta):
# type: (int) -> None
# negative if we're decrementing heat
step = 1 if heatDelta > 0 else -1
formatter = "\nWalking cavity {NUM} heater to {{VAL}}"
formatter = formatter.format(NUM=self.cavNum)
for _ in range(abs(heatDelta)):
currVal = float(cagetPV(self.heaterDesPV))
newVal = currVal + step
caputPV(self.heaterDesPV, str(newVal))
writeAndWait(formatter.format(VAL=newVal), 2)
# refGradVal and calibSession are required parameters but are nullable to
# match the signature in Container
def genDataSession(self, timeParams, valveParams, refGradVal=None,
calibSession=None):
# type: (TimeParams, ValveParams, float, CalibDataSession) -> Q0DataSession
return Q0DataSession(self, timeParams, valveParams, refGradVal,
calibSession)
def hash(self, timeParams, slacNum, jlabNum, calibSession=None,
refGradVal=None):
# type: (TimeParams, int, int, CalibDataSession, float) -> int
return Q0DataSession.hash(timeParams, slacNum, jlabNum, calibSession,
refGradVal)
def walkHeaters(self, perHeaterDelta):
# type: (int) -> None
self.parent.walkHeaters(perHeaterDelta)
# calibSession and refGradVal are required parameters for Cavity data
# sessions, but they're nullable to match the signature in Container
def addDataSessionFromRow(self, row, indices, refHeatLoad, refHeatLoadAct,
calibSession=None, refGradVal=None):
# type: (List[str], Dict[str, int], float, float, CalibDataSession, float) -> Q0DataSession
timeParams = getTimeParams(row, indices)
valveParams = ValveParams(float(row[indices["jtIdx"]]), refHeatLoad,
refHeatLoadAct)
return self.addDataSession(timeParams, valveParams, refGradVal,
calibSession)
def genPV(self, formatStr, suffix):
# type: (str, str) -> str
return formatStr.format(CM=self.cryModNumJLAB, CAV=self.cavNum,
SUFF=suffix)
def genAcclPV(self, suffix):
# type: (str) -> str
return self.genPV("ACCL:L1B:0{CM}{CAV}0:{SUFF}", suffix)
def getPVs(self):
# type: () -> List[str]
return ([self.parent.valvePV, self.parent.dsLevelPV,
self.parent.usLevelPV, self.gradPV,
self.parent.dsPressurePV] + self.parent.heaterDesPVs
+ self.parent.heaterActPVs)
# Checks that the parameters associated with acquisition of the cavity RF
# waveforms are configured properly
def checkAcqControl(self):
# type: () -> None
print("Checking Waveform Data Acquisition Control...")
for infix in ["CAV", "FWD", "REV"]:
enablePV = self.genAcclPV(infix + ":ENABLE")
if float(cagetPV(enablePV)) != 1:
print("Enabling {INFIX}".format(INFIX=infix))
caputPV(enablePV, "1")
suffixValPairs = [("MODE", 1), ("HLDOFF", 0.1), ("STAT_START", 0.065),
("STAT_WIDTH", 0.004), ("DECIM", 255)]
for suffix, val in suffixValPairs:
pv = self.genAcclPV("ACQ_" + suffix)
if float(cagetPV(enablePV)) != val:
print("Setting {SUFFIX}".format(SUFFIX=suffix))
caputPV(pv, str(val))
def setPowerStateSSA(self, turnOn):
# type: (bool) -> None
# Using double curly braces to trick it into a partial formatting
ssaFormatPV = self.genAcclPV("SSA:{SUFFIX}")
def genPV(suffix):
return ssaFormatPV.format(SUFFIX=suffix)
ssaStatusPV = genPV("StatusMsg")
value = cagetPV(ssaStatusPV)
if turnOn:
stateMap = {"desired": "3", "opposite": "2", "pv": "PowerOn"}
else:
stateMap = {"desired": "2", "opposite": "3", "pv": "PowerOff"}
if value != stateMap["desired"]:
if value == stateMap["opposite"]:
print("\nSetting SSA power...")
caputPV(genPV(stateMap["pv"]), "1")
if cagetPV(ssaStatusPV) != stateMap["desired"]:
raise AssertionError("Could not set SSA Power")
else:
print("\nResetting SSA...")
caputPV(genPV("FaultReset"), "1")
if cagetPV(ssaStatusPV) not in ["2", "3"]:
raise AssertionError("Could not reset SSA")
self.setPowerStateSSA(turnOn)
print("SSA power set\n")
############################################################################
# Characterize various cavity parameters.
# * Runs the SSA through its range and constructs a polynomial describing
# the relationship between requested SSA output and actual output
# * Calibrates the cavity's RF probe so that the gradient readback will be
# accurate.
############################################################################
def characterize(self):
# type: () -> None
def askForVerification(prefix, desAction):
mssg = "Please {ACTION} manually then press y/Y to continue or n/N to abort"
if not isYes(prefix + mssg.format(ACTION=desAction)):
raise AssertionError(
"User unsatisfied with characterization - aborting")
def pushAndWait(suffix):
caputPV(self.genAcclPV(suffix + "STRT"), "1")
statusPV = self.genAcclPV(suffix + "STS")
# 2 is Running
while cagetPV(statusPV) == "2":
sleep(1)
# 0 is Crash
if cagetPV(statusPV) == "0":
askForVerification("{CONTROL} crashed. ".format(CONTROL=suffix),
"rerun")
def checkAndPush(basePV, pushPV, param, tol, newPV=None):
oldVal = float(cagetPV(self.genAcclPV(basePV)))
newVal = (float(cagetPV(self.genAcclPV(newPV)))
if newPV
else float(cagetPV(self.genAcclPV(basePV + "_NEW"))))
if abs(newVal - oldVal) < tol:
# pushAndWait(pushPV)
caputPV(self.genAcclPV(pushPV), "1")
else:
askForVerification(
"Large difference in {PARAM} ".format(PARAM=param),
"inspect and push")
pushAndWait("SSACAL")
checkAndPush("SSA:SLOPE", "PUSH_SSASLOPE.PROC", "slopes", 0.15)
# TODO confirm with Janice what should actually be here
caputPV(self.genAcclPV("INTLK_RESET_ALL"), "1")
sleep(2)
pushAndWait("PROBECAL")
checkAndPush("QLOADED", "PUSH_QLOADED.PROC", "Loaded Qs", 0.15e7)
checkAndPush("CAV:SCALER_SEL.B", "PUSH_CAV_SCALE.PROC", "Cavity Scales",
0.2, "CAV:CAL_SCALEB_NEW")
# Switches the cavity to a given operational mode (pulsed, CW, etc.)
def setModeRF(self, modeDesired):
# type: (str) -> None
rfModePV = self.genAcclPV("RFMODECTRL")
if cagetPV(rfModePV) is not modeDesired:
caputPV(rfModePV, modeDesired)
assert cagetPV(rfModePV) == modeDesired, "Unable to set RF mode"
# Turn the cavity on or off
def setStateRF(self, turnOn):
# type: (bool) -> None
rfStatePV = self.genAcclPV("RFSTATE")
rfControlPV = self.genAcclPV("RFCTRL")
rfState = cagetPV(rfStatePV)
desiredState = ("1" if turnOn else "0")
if rfState != desiredState:
print("\nSetting RF State...")
caputPV(rfControlPV, desiredState)
print("RF state set\n")
# Many of the changes made to a cavity don't actually take effect until the
# go button is pressed
def pushGoButton(self):
# type: (Cavity) -> None
rfStatePV = self.genAcclPV("PULSEONSTRT")
caputPV(rfStatePV, "1")
sleep(2)
if cagetPV(rfStatePV) != "1":
raise AssertionError("Unable to set RF state")
# In pulsed mode the cavity has a duty cycle determined by the on time and
# off time. We want the on time to be 70 ms or else the various cavity
# parameters calculated from the waveform (e.g. the RF gradient) won't be
# accurate.
def checkAndSetOnTime(self):
# type: () -> None
print("Checking RF Pulse On Time...")
onTimePV = self.genAcclPV("PULSE_ONTIME")
onTime = cagetPV(onTimePV)
if onTime != "70":
print("Setting RF Pulse On Time to 70 ms")
caputPV(onTimePV, "70")
self.pushGoButton()
# Ramps the cavity's RF drive (only relevant in pulsed mode) up until the RF
# gradient is high enough for phasing
def checkAndSetDrive(self):
# type: () -> None
print("Checking drive...")
drivePV = self.genAcclPV("SEL_ASET")
currDrive = float(cagetPV(drivePV))
while (float(cagetPV(self.gradPV)) < 1) or (currDrive < 15):
print("Increasing drive...")
driveDes = str(currDrive + 1)
caputPV(drivePV, driveDes)
self.pushGoButton()
currDrive = float(cagetPV(drivePV))
print("Drive set")
# Corrects the cavity phasing in pulsed mode based on analysis of the RF
# waveform. Doesn't currently work if the phase is very far off and the
# waveform is distorted.
def phaseCavity(self):
# type: () -> None
waveformFormatStr = self.genAcclPV("{INFIX}:AWF")
def getWaveformPV(infix):
return waveformFormatStr.format(INFIX=infix)
# Get rid of trailing zeros - might be more elegant way of doing this
def trimWaveform(inputWaveform):
try:
maxValIdx = inputWaveform.index(max(inputWaveform))
del inputWaveform[maxValIdx:]
first = inputWaveform.pop(0)
while inputWaveform[0] >= first:
first = inputWaveform.pop(0)
except IndexError:
pass
def getAndTrimWaveforms():
res = []
for suffix in ["REV", "FWD", "CAV"]:
res.append(cagetPV(getWaveformPV(suffix), startIdx=2))
res[-1] = list(map(lambda x: float(x), res[-1]))
trimWaveform(res[-1])
return res
def getLine(inputWaveform, lbl):
return ax.plot(range(len(inputWaveform)), inputWaveform, label=lbl)
# The waveforms have trailing and leading tails down to zero that would
# mess with our analysis - have to trim those off.
revWaveform, fwdWaveform, cavWaveform = getAndTrimWaveforms()
plt.ion()
ax = genAxis("Waveforms", "Seconds", "Amplitude")
ax.set_autoscale_on(True)
ax.autoscale_view(True, True, True)
lineRev, = getLine(revWaveform, "Reverse")
lineCav, = getLine(cavWaveform, "Cavity")
lineFwd, = getLine(fwdWaveform, "Forward")
ax.figure.canvas.draw()
ax.figure.canvas.flush_events()
phasePV = self.genAcclPV("SEL_POFF")
# When the cavity is properly phased the reverse waveform should dip
# down very close to zero. Phasing the cavity consists of minimizing
# that minimum value as we vary the RF phase.
minVal = min(revWaveform)
print("Minimum reverse waveform value: {MIN}".format(MIN=minVal))
step = 1
while abs(minVal) > 0.5:
val = float(cagetPV(phasePV))
print("step: {STEP}".format(STEP=step))
newVal = val + step
caputPV(phasePV, str(newVal))
if float(cagetPV(phasePV)) != newVal:
writeAndFlushStdErr("Mismatch between desired and actual phase")
revWaveform, fwdWaveform, cavWaveform = getAndTrimWaveforms()
lineWaveformPairs = [(lineRev, revWaveform), (lineCav, cavWaveform),
(lineFwd, fwdWaveform)]
for line, waveform in lineWaveformPairs:
line.set_data(range(len(waveform)), waveform)
ax.set_autoscale_on(True)
ax.autoscale_view(True, True, True)
ax.figure.canvas.draw()
ax.figure.canvas.flush_events()
prevMin = minVal
minVal = min(revWaveform)
print("Minimum reverse waveform value: {MIN}".format(MIN=minVal))
# I think this accounts for inflection points? Hopefully the
# decrease in step size addresses the potential for it to get stuck
if (prevMin <= 0 < minVal) or (prevMin >= 0 > minVal):
step *= -0.5
elif abs(minVal) > abs(prevMin) + 0.01:
step *= -1
# Lowers the requested CW amplitude to a safe level where cavities have a
# very low chance of quenching at turnon
def lowerAmplitude(self):
# type: () -> None
print("Lowering amplitude")
caputPV(self.genAcclPV("ADES"), "2")
# Walks the cavity to a given gradient in CW mode with exponential back-off
# in the step size (steps get smaller each time you cross over the desired
# gradient until the error is very low)
def walkToGradient(self, desiredGradient, step=0.5, loopTime=2.5, pv="ADES",
getFieldEmissionData=False, gradTol=0.05):
# type: (float, float, float, str, bool, float) -> None
amplitudePV = self.genAcclPV(pv)
gradient = float(cagetPV(self.gradPV))
diff = gradient - desiredGradient
prevDiff = diff
writeAndWait("\nWalking gradient...")