-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathtest_rig.py
More file actions
2678 lines (2017 loc) · 106 KB
/
test_rig.py
File metadata and controls
2678 lines (2017 loc) · 106 KB
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
import ipdb
def extractDataFromPipeline(pipelineDir,outDir,stages=[29,31,33],copyCont=False, contsubstages=None):
'''
copy the *target.ms and casalog data from imaging stages of a pipeline
run and put them in their own test directory
'''
# Purpose: extract the tclean commands and target.ms files from the
# Cycle 5 pipeline tests.
#
# Input:
# List of pipeline data directories
# List of stages to extract casalog files for
# output directory name
# copyCont: copy continuum
# contsubstages: continuum subtraction stages to copy
# Output:
# target files and casalog files for particular stages
#
# TODO:
# -- Make a driver function that takes list of files
# Date Programmer Description of Code
# ----------------------------------------------------------------------
# 10/26/2017 A.A. Kepley Original Code
# 10/14/2021 A.A. Kepley Original Code
import os.path
import os
import glob
import shutil
import re
# the directory path exists
if os.path.exists(pipelineDir):
# find and copy over the benchmark data sets
dataDir = os.path.split(pipelineDir)[0]
targetFiles = glob.glob(os.path.join(dataDir,'*target.ms'))
# fix for new PL2022 targets.ms file
if len(targetFiles) == 0:
targetFiles = glob.glob(os.path.join(dataDir,'*targets*.ms'))
benchmarkName = re.findall('\w\w\w\w\.\w.\d\d\d\d\d\.\w_\d\d\d\d_\d\d_\d\dT\d\d_\d\d_\d\d\.\d\d\d',dataDir)[0]
benchmarkDir = os.path.join(outDir,benchmarkName)
if not os.path.exists(benchmarkDir):
print("Creating directory for data: ", benchmarkDir)
os.mkdir(benchmarkDir)
for myfile in targetFiles:
targetFileName = os.path.basename(myfile)
benchmarkData = os.path.join(benchmarkDir,targetFileName)
if not os.path.exists(benchmarkData):
print("Copying over data: ", targetFileName)
shutil.copytree(myfile,benchmarkData)
# find, copy, and modify over the relevant casalog files
for stage in stages:
stageDir = os.path.join(pipelineDir,'html/stage'+str(stage))
stageLog = os.path.join(stageDir,'casapy.log')
outStageLog = os.path.join(benchmarkDir,'stage'+str(stage)+'.log')
if not os.path.exists(outStageLog):
print("Copying over stage " + str(stage)+ " log" )
shutil.copy(stageLog,outStageLog)
# extracting tclean commands from the casalog file
outTcleanCmd = os.path.join(benchmarkDir,benchmarkName+'_stage'+str(stage)+'.py')
extractTcleanFromLog(outStageLog,benchmarkDir,outTcleanCmd)
os.system("cat " + os.path.join(benchmarkDir,benchmarkName)+"_stage??.py > "+os.path.join(benchmarkDir,benchmarkName)+".py")
# copy over the cont.data file
if copyCont:
contFile = os.path.join(os.path.split(pipelineDir)[0],'cont.dat')
outContFile = os.path.join(benchmarkDir,'cont.dat')
if not os.path.exists(outContFile):
print("Copying over cont.dat file")
shutil.copy(contFile,outContFile)
contTabs = glob.glob(os.path.join(os.path.split(pipelineDir)[0],"*.uvcont.tbl"))
for tab in contTabs:
outFile = os.path.join(benchmarkDir,os.path.basename(tab))
if not os.path.exists(outFile):
print("copying over uvcontsub tables")
shutil.copytree(tab, outFile)
# find, copy, and modify over relevant casalog files for uvcontsub
if contsubstages:
for stage in contsubstages:
stageDir = os.path.join(pipelineDir,'html/stage'+str(stage))
stageLog = os.path.join(stageDir,'casapy.log')
outStageLog = os.path.join(benchmarkDir,'stage'+str(stage)+'.log')
if not os.path.exists(outStageLog):
print("Copying over stage " + str(stage)+ " log" )
shutil.copy(stageLog,outStageLog)
outcontsubCmd = os.path.join(benchmarkDir,benchmarkName+'_stage'+str(stage)+'_uvcontsub.py')
extractContsubFromLog(outStageLog,benchmarkDir,outcontsubCmd)
os.system("cat " + os.path.join(benchmarkDir,benchmarkName)+"_stage??_uvcontsub.py > " + os.path.join(benchmarkDir,benchmarkName)+"_uvcontsub.py")
else:
print("path doesn't exist: " + pipelineDir)
#----------------------------------------------------------------------
def regenerateTcleanCmds(benchmarkDir, stages=[31,33,35]):
'''
Purpose: regenerate Tclean commands from existing pipeline logs
'''
import os
import glob
import re
# if the benchmark directory exists
if os.path.exists(benchmarkDir):
# get all the benchmarks
dataDirs = os.listdir(benchmarkDir)
for mydir in dataDirs:
benchmarkName = re.findall('\w\w\w\w\.\w.\d\d\d\d\d\.\w_\d\d\d\d_\d\d_\d\dT\d\d_\d\d_\d\d\.\d\d\d',mydir)[0]
for stage in stages:
outTcleanCmd = os.path.join(benchmarkDir,mydir,benchmarkName+'_stage'+str(stage)+'.py')
outStageLog = os.path.join(benchmarkDir,mydir,'stage'+str(stage)+'.log')
extractTcleanFromLog(outStageLog,os.path.join(benchmarkDir,mydir),outTcleanCmd)
os.system("cat " + os.path.join(benchmarkDir,mydir,benchmarkName)+"_stage??.py > "+os.path.join(benchmarkDir,mydir,benchmarkName)+".py")
#----------------------------------------------------------------------
def extractTcleanFromLog(casalogfile,dataDir,outfile):
'''
extract the tclean commands from a casalogfile and create a
executable script that will run tclean commands.
'''
# Purpose: extract tclean commands from casalogfile and create an
# executable script
#
# Input:
#
# casalogfile: logfile name
# outfile: output file name
# dataDir: data directory name
# Output:
#
# executable casa script to run tests.
# Date Programmer Description of Code
# ----------------------------------------------------------------------
# 10/26/2017 A.A. Kepley Original Code
# 11/29/2017 A.A. Kepley Fixing aggregate continuum.
import os.path
import re
import ast
if os.path.exists(casalogfile):
tcleanCmd = re.compile(r"""
(?P<cmd>tclean\(vis=(?P<vis>\[.*?\]) ## visibility name
.* ## skip junk in command
imagename='(?P<imagename>.*?)' ## imagename
.*
deconvolver='(?P<deconvolver>.*?)' ## deconvolver
.*\) ## end of tclean command
)
""",re.VERBOSE)
ntermsRE = re.compile("nterms=(?P<nterms>.*?),")
copytreeRE = re.compile("(?P<copytree>copytree\(src=(?P<src>'.*?'),.*\))")
filein = open(casalogfile,'r')
fileout = open(outfile,'w')
fileout.write('import shutil\n')
fileout.write('import os\n')
fileout.write('\n')
# this may need to be modified for mfs images
imageExt = ['.pb','.psf','.residual','.sumwt','.weight','.workdirectory','.gridwt_moswt']
copytreePresent = False
lastImageIter0 = False
for line in filein:
# look for tclean command
findtclean = tcleanCmd.search(line)
# if you find the tclean command go to work
if findtclean:
# extract key values
cmd = findtclean.group('cmd')
vis = findtclean.group('vis')
imagename = findtclean.group('imagename')
deconvolver = findtclean.group('deconvolver')
# update the data directory in the command for the new data location
newvis = [dataDir+'/'+val for val in ast.literal_eval(vis)]
newcmd = cmd.replace(vis,repr(newvis))
# follow the iter0 with commands to copy iter0 to iter1 if no copytree commands are present.
if re.search('iter1',imagename) and not copytreePresent and lastImageIter0:
# dealing with the mtmfs case.
if deconvolver == 'mtmfs':
nterms = ntermsRE.search(line).group('nterms')
for ext in imageExt:
if ext == '.pb':
fileout.write("if os.path.exists('"+imagename.replace('iter1','iter0')+ext+".tt0"+"'):\n")
fileout.write("\t shutil.copytree(src='"+imagename.replace('iter1','iter0')+ext+".tt0', dst='"+imagename+ext+".tt0')\n")
elif ext == '.workdirectory':
iter0work = imagename.replace('iter1','iter0')+ext
iter1work = imagename+ext
fileout.write("if os.path.exists('"+iter0work+"'):\n")
#fileout.write("\t shutil.copytree(src='"+iter0work+"', dst='"+iter1work+"')\n")
# more complex method below not needed and causes tclean failures. -- I"m not sure this is true.
fileout.write("\t iter0work = '" + iter0work + "'\n")
fileout.write("\t iter1work = '" + iter1work + "'\n")
fileout.write("\t os.mkdir(iter1work)\n")
fileout.write("\t dirlist = os.listdir(iter0work)\n")
fileout.write("\t for mydir in dirlist:\n")
fileout.write("\t\t iter0 = os.path.join(iter0work,mydir)\n")
fileout.write("\t\t iter1 = os.path.join(iter1work,mydir.replace('iter0','iter1'))\n")
fileout.write("\t\t shutil.copytree(src=iter0, dst=iter1)\n")
elif ext == '.gridwt_moswt':
fileout.write("if os.path.exists('"+imagename.replace('iter1','iter0')+ext+"'):\n")
fileout.write("\t shutil.copytree(src='"+imagename.replace('iter1','iter0')+ext+"', dst='"+imagename+ext+"')\n")
elif ((ext == '.residual') or (ext == '.model')):
for term in range(int(nterms)):
fileout.write("if os.path.exists('"+imagename.replace('iter1','iter0')+ext+".tt"+str(term)+"'):\n")
fileout.write("\t shutil.copytree(src='"+imagename.replace('iter1','iter0')+ext+".tt"+str(term)+"', dst='"+imagename+ext+".tt"+str(term)+"')\n")
else:
for term in range(int(nterms)+1):
fileout.write("if os.path.exists('"+imagename.replace('iter1','iter0')+ext+".tt"+str(term)+"'):\n")
fileout.write("\t shutil.copytree(src='"+imagename.replace('iter1','iter0')+ext+".tt"+str(term)+"', dst='"+imagename+ext+".tt"+str(term)+"')\n")
# dealing with the rest of the cases.
else:
for ext in imageExt:
if ext == '.workdirectory':
iter0work = imagename.replace('iter1','iter0')+ext
iter1work = imagename+ext
#fileout.write("if os.path.exists('"+iter0work+"'):\n")
#fileout.write("\t shutil.copytree(src='"+iter0work+"', dst='"+iter1work+"')\n")
fileout.write("if os.path.exists('"+imagename.replace('iter1','iter0')+ext+"'):\n")
fileout.write("\t iter0work = '" + imagename.replace('iter1','iter0')+ext+"'\n")
fileout.write("\t iter1work = '" + imagename+ext+ "'\n")
fileout.write("\t os.mkdir(iter1work)\n")
fileout.write("\t dirlist = os.listdir(iter0work)\n")
fileout.write("\t for mydir in dirlist:\n")
fileout.write("\t\t iter0 = os.path.join(iter0work,mydir)\n")
fileout.write("\t\t iter1 = os.path.join(iter1work,mydir.replace('iter0','iter1'))\n")
fileout.write("\t\t shutil.copytree(src=iter0, dst=iter1)\n")
else:
fileout.write("if os.path.exists('"+imagename.replace('iter1','iter0')+ext+"'):\n")
fileout.write("\t shutil.copytree(src='"+imagename.replace('iter1','iter0')+ext+"', dst='"+imagename+ext+"')\n")
fileout.write('\n')
# Write out the necessary commands to a file.
fileout.write(newcmd+'\n\n')
if re.search('iter0',imagename):
lastImageIter0 = True
else:
lastImageIter0 = False
# find copy tree command
findcopytree = copytreeRE.search(line)
# if present then write out command and set the copytreePresent variable to True.
if findcopytree:
fileout.write('if os.path.exists('+findcopytree.group('src')+'):\n')
fileout.write(" shutil."+findcopytree.group('copytree')+"\n\n")
copytreePresent = True
filein.close()
fileout.close()
else:
print("Couldn't open file: " + casalogfile)
#----------------------------------------------------------------------
def extractContsubFromLog(casalogfile,dataDir,outfile):
'''
extract continuum fitting and subtraction commands from log
Input:
casalogfile: logfile name
outfile: output file name
dataDir: data directory name
Date Programmer Description of Code
----------------------------------------------------------------------
10/14/2021 A.A. Kepley Original Code
'''
import os.path
import re
import ast
if os.path.exists(casalogfile):
uvcontfitCmd = re.compile(r"""
(?P<cmd>uvcontfit\(vis='(?P<vis>.*?)' ## visibility name
.*\) ## end of command
)
""",re.VERBOSE)
applycalCmd = re.compile(r"""
(?P<cmd>applycal\(vis='(?P<vis>.*?)' ## visibility name
.*\) ## end of command
)
""",re.VERBOSE)
filein = open(casalogfile,'r')
fileout = open(outfile, 'w')
for line in filein:
finduvcontfit = uvcontfitCmd.search(line)
findapplycal = applycalCmd.search(line)
if finduvcontfit:
cmd = finduvcontfit.group('cmd')
vis = finduvcontfit.group('vis')
newvis = dataDir+'/'+vis
newcmd = cmd.replace(vis,newvis,1) # only replace first (vis) instance.
fileout.write(newcmd+'\n')
fileout.write('\n')
if findapplycal:
cmd = findapplycal.group('cmd')
vis = findapplycal.group('vis')
newvis = dataDir+'/'+vis
newcmd = cmd.replace(vis,newvis,1) # only replace first (vis) instance.
fileout.write(newcmd+'\n')
fileout.write('\n')
filein.close()
fileout.close()
#----------------------------------------------------------------------
def setupTest(benchmarkDir,testDir):
'''
Automatically populate a test directory with directories for
individual data sets and copies over the relevant run scripts.
'''
# Purpose: automatically populate a test directory with directories for
# individual data sets and copy over the relevant scripts
#
#
# Input:
# benchmarkDir: directory with benchmarks
# testDir: directory to run test in.
#
#
# Output:
# scripts and directory structure for test
#
# TO-DO:
# -- needs to be tested.
# -- also could add something in here to modify parameters, although the regex's would have to be carefully constructed. Note that I don't need this for now.
# Date Programmer Description of Code
# ---------- ------------------------------------------------------------
# 11/02/2017 A.A. Kepley Original Code
import shutil
import glob
import os
import os.path
# if the benchmark directory exists
if os.path.exists(benchmarkDir):
# get all the benchmarks
dataDirs = os.listdir(benchmarkDir)
# go to test directory, create directory structure, and copy scripts
currentDir = os.getcwd()
if not os.path.exists(testDir):
os.mkdir(testDir)
os.chdir(testDir)
for mydir in dataDirs:
if not os.path.exists(mydir):
os.mkdir(mydir)
scripts = glob.glob(os.path.join(benchmarkDir,mydir)+"/*.py")
for myscript in scripts:
scriptDir = os.path.join(testDir,mydir)
scriptPath = os.path.join(scriptDir,os.path.basename(myscript))
if not os.path.isfile(scriptPath):
shutil.copy(myscript,scriptDir)
# switch back to original directory
os.chdir(currentDir)
#----------------------------------------------------------------------
def tCleanTime(testDir):
'''
Time how long the parts in clean take for an individual test directory.
'''
# Purpose: mine logs for information about timing.
# Input:
# testDir: I'm assuming that the testDirectory contains one
# casalog file, but may want to add the option to specify a log
# Output:
# a structure with all the timing information, plus vital stats
# on the data set. Right now I'm keeping the imagename, whether
# or not it's a cube and number of cycles. Some other
# information that might be useful to keep:
# image size on disk -- get from os
# threshold? -- from tclean input
# nchan - will have to calculate -- can get from msmd? Ask Remy about this part.
#
# Date Programmer Description of Changes
#----------------------------------------------------------------------
# 2017/11/08 A.A. Kepley Original Code
import os
import os.path
import glob
import re
from datetime import datetime
import copy
import pdb
if os.path.exists(testDir):
# get the file name
logfile = glob.glob(os.path.join(testDir,"*.log"))
if len(logfile) > 1:
print("Multiple logs found. Using the first one")
mylog = logfile[0]
print("using log: ", mylog)
elif len(logfile) == 0:
print("no logs found returning")
return
else:
mylog = logfile[0]
print("using log: ", mylog)
# regex patterns for below.
tcleanBeginRE = re.compile(r"Begin Task: tclean")
imagenameRE = re.compile(r'imagename=\"(?P<imagename>.*?)\"')
specmodeRE = re.compile(r'specmode=\"(?P<specmode>.*?)\"')
startMaskRE = re.compile(r'Generating AutoMask')
sidelobeRE = re.compile(r'SidelobeLevel = ')
modelFluxRE = re.compile(r'Total Model Flux : (?P<flux>\d*\.\d+|\d+)')
startMinorCycleRE = re.compile(r'Run Minor Cycle Iterations')
endMajorCycleRE = re.compile(r'Completed \w+ iterations.')
startMajorCycleRE = re.compile(r'Major Cycle (?P<cycle>\d*)')
startPrune1RE = re.compile(r'Pruning the current mask')
startGrowRE = re.compile(r'Growing the previous mask')
startPrune2RE = re.compile(r'Pruning the growed previous mask')
startNegativeThresholdRE = re.compile(r'Creating a mask for negative features.')
endNegativeThresholdRE = re.compile(r'No negative region was found by auotmask.')
endCleanRE = re.compile(r'Reached global stopping criterion : (?P<stopreason>.*)')
startRestoreRE = re.compile(r'Restoring model image')
endRestoreRE = re.compile(r'Applying PB correction')
tcleanEndRE = re.compile(r"End Task: tclean")
#tcleanFailRE = re.compile(r"An error occurred running task tclean.") ## catch artifact of running in batch mode.
tcleanFailRE = re.compile(r'Exception from task_tclean : couldn\'t connect to display ":0"') ## catch artifact of running batch mode without xbuffer
dateFmtRE = re.compile(r"(?P<timedate>\d{4}-\d{2}-\d{2} \d{2}:\d{2}:\d{2})")
# open file
filein = open(mylog,'r')
#initialize loop status
imagename = ''
allresults = {}
results = {}
cycleresults = {}
cycle = '0'
specmode=''
# go through file
for line in filein:
#print line
# capture start of tclean
if tcleanBeginRE.search(line):
startTimeStr = dateFmtRE.search(line)
if startTimeStr:
results['startTime'] = datetime.strptime(startTimeStr.group('timedate'),'%Y-%m-%d %H:%M:%S')
# capture image name
if imagenameRE.search(line):
imagename = imagenameRE.search(line).group('imagename')
# capture line vs. continuum
if specmodeRE.search(line):
if re.match(specmodeRE.search(line).group('specmode'),'cube'):
specmode='cube'
else:
specmode='cont'
# if imagename is iter1, record automasking information.
if re.search('iter1', imagename):
# capture the start of the mask
if startMaskRE.search(line):
maskStartTimeStr = dateFmtRE.search(line)
if maskStartTimeStr:
cycleresults['maskStartTime'] = datetime.strptime(maskStartTimeStr.group('timedate'),'%Y-%m-%d %H:%M:%S')
# capture noise calculation
if sidelobeRE.search(line):
sidelobeStartTimeStr = dateFmtRE.search(line)
if sidelobeStartTimeStr:
cycleresults['noiseEndTime'] = datetime.strptime(sidelobeStartTimeStr.group('timedate'),'%Y-%m-%d %H:%M:%S')
cycleresults['noiseTime'] = cycleresults['noiseEndTime'] - cycleresults['maskStartTime']
# capture first prune
if startPrune1RE.search(line):
startPrune1TimeStr = dateFmtRE.search(line)
if startPrune1TimeStr:
cycleresults['startPrune1Time'] = datetime.strptime(startPrune1TimeStr.group('timedate'),'%Y-%m-%d %H:%M:%S')
# capture start of grow
if startGrowRE.search(line):
startGrowTimeStr = dateFmtRE.search(line)
if startGrowTimeStr:
cycleresults['startGrowTime'] = datetime.strptime(startGrowTimeStr.group('timedate'),'%Y-%m-%d %H:%M:%S')
# capture 2nd prune
if startPrune2RE.search(line):
startPrune2TimeStr = dateFmtRE.search(line)
if startPrune2TimeStr:
cycleresults['startPrune2Time'] = datetime.strptime(startPrune2TimeStr.group('timedate'),'%Y-%m-%d %H:%M:%S')
# capture the negative threshold start
if startNegativeThresholdRE.search(line):
startNegativeThresholdTimeStr = dateFmtRE.search(line)
if startNegativeThresholdTimeStr:
cycleresults['startNegativeThresholdTime'] = datetime.strptime(startNegativeThresholdTimeStr.group('timedate'),'%Y-%m-%d %H:%M:%S')
# capture the negative threshold end
if endNegativeThresholdRE.search(line):
endNegativeThresholdTimeStr = dateFmtRE.search(line)
if endNegativeThresholdTimeStr:
cycleresults['endNegativeThresholdTime'] = datetime.strptime(endNegativeThresholdTimeStr.group('timedate'),'%Y-%m-%d %H:%M:%S')
# capture the start of the Major Cycle
if startMajorCycleRE.search(line):
cycle = startMajorCycleRE.search(line).group('cycle')
startMajorCycleTimeStr = dateFmtRE.search(line)
if startMajorCycleTimeStr:
cycleresults['startMajorCycleTime'] = datetime.strptime(startMajorCycleTimeStr.group('timedate'),'%Y-%m-%d %H:%M:%S')
# capture amount of flux in model
if modelFluxRE.search(line):
modelFlux = modelFluxRE.search(line).group('flux')
cycleresults['modelFlux'] = float(modelFlux)
# capture the start of the minor cycle
if startMinorCycleRE.search(line):
startMinorCycleTimeStr = dateFmtRE.search(line)
if startMinorCycleTimeStr:
cycleresults['startMinorCycleTime'] = datetime.strptime(startMinorCycleTimeStr.group('timedate'),'%Y-%m-%d %H:%M:%S')
# capture the end of the major cycle
if endMajorCycleRE.search(line):
endMajorCycleTimeStr = dateFmtRE.search(line)
if endMajorCycleTimeStr:
cycleresults['endMajorCycleTime'] = datetime.strptime(endMajorCycleTimeStr.group('timedate'),'%Y-%m-%d %H:%M:%S')
# calculate times
cycleresults['totalMaskTime'] = cycleresults['startMinorCycleTime'] - cycleresults['maskStartTime']
cycleresults['thresholdTime'] = cycleresults['startPrune1Time'] - cycleresults['maskStartTime']
cycleresults['cycleTime'] = cycleresults['endMajorCycleTime'] - cycleresults['maskStartTime']
#if cycleresults.has_key('startGrowTime'):
if 'startGrowTime' in cycleresults.keys():
cycleresults['prune1Time'] = cycleresults['startGrowTime'] - cycleresults['startPrune1Time']
cycleresults['growTime'] = cycleresults['startPrune2Time'] - cycleresults['startGrowTime']
if 'startNegativeThresholdTime' in cycleresults.keys():
cycleresults['prune2Time'] = cycleresults['startNegativeThresholdTime'] - cycleresults['startPrune2Time']
else:
cycleresults['prune2Time'] = cycleresults['startMinorCycleTime'] - cycleresults['startPrune2Time']
else:
cycleresults['prune1Time'] = cycleresults['startMinorCycleTime'] - cycleresults['startPrune1Time']
if 'negativeThresholdTime' in cycleresults.keys():
cycleresults['negativeThresholdTime'] = cycleresults['endNegativeThresholdTime'] - cycleresults['startNegativeThresholdTime']
## save major cycle information here
results[cycle] = cycleresults
cycleresults={}
# if clean terminates catch this
if endCleanRE.search(line):
endCleanStr = dateFmtRE.search(line)
if endCleanStr:
cycleresults['endCleanTime'] = datetime.strptime(endCleanStr.group('timedate'),'%Y-%m-%d %H:%M:%S')
# save final cycle results
cycleresults['totalMaskTime'] = cycleresults['endCleanTime'] - cycleresults['maskStartTime']
cycleresults['thresholdTime'] = cycleresults['startPrune1Time'] - cycleresults['maskStartTime']
cycleresults['cycleTime'] = cycleresults['endCleanTime'] - cycleresults['maskStartTime']
if 'startGrowTime' in cycleresults.keys():
cycleresults['prune1Time'] = cycleresults['startGrowTime'] - cycleresults['startPrune1Time']
cycleresults['growTime'] = cycleresults['startPrune2Time'] - cycleresults['startGrowTime']
if 'startNegativeThresholdTime' in cycleresults.keys():
cycleresults['prune2Time'] = cycleresults['startNegativeThresholdTime'] - cycleresults['startPrune2Time']
else:
cycleresults['prune2Time'] = cycleresults['endCleanTime'] - cycleresults['startPrune2Time']
else:
cycleresults['prune1Time'] = cycleresults['endCleanTime'] - cycleresults['startPrune1Time']
if 'startNegativeThresholdTime' in cycleresults.keys():
cycleresults['negativeThresholdTime'] = cycleresults['endNegativeThresholdTime'] - cycleresults['startNegativeThresholdTime']
# get exit criteria
if endCleanRE.search(line):
results['stopreason'] = endCleanRE.search(line).group('stopreason')
## save major cycle information here
results[cycle] = cycleresults
cycleresults={}
# capture restore time here
if startRestoreRE.search(line):
startRestoreStr = dateFmtRE.search(line)
if startRestoreStr:
results['startRestoreTime'] = datetime.strptime(startRestoreStr.group('timedate'),'%Y-%m-%d %H:%M:%S')
if endRestoreRE.search(line):
endRestoreStr = dateFmtRE.search(line)
if endRestoreStr:
results['endRestoreTime'] = datetime.strptime(endRestoreStr.group('timedate'), '%Y-%m-%d %H:%M:%S')
results['restoreTime'] = results['endRestoreTime'] - results['startRestoreTime']
# capture the end of the clean
if tcleanEndRE.search(line) or tcleanFailRE.search(line):
endTimeStr = dateFmtRE.search(line)
if endTimeStr:
results['endTime'] = datetime.strptime(endTimeStr.group('timedate'),'%Y-%m-%d %H:%M:%S')
# calculate overall statistics.
results['tcleanTime'] = results['endTime']-results['startTime']
results['ncycle'] = cycle
results['specmode'] = specmode
# if iter1 image, save results and clear variables.
if re.search('iter1',imagename):
allresults[imagename] = results
#pdb.set_trace()
# clear for next clean run
results = {}
cycleresults = {}
imagename = ''
cycle = '0'
specmode=''
filein.close()
else:
print("no path found")
allresults = {}
return allresults
#----------------------------------------------------------------------
def tCleanTime_newlogs(testDir):
'''
Time how long the parts in clean take for an individual test directory.
'''
# Purpose: mine logs for information about timing.
# Input:
# testDir: I'm assuming that the testDirectory contains one
# casalog file, but may want to add the option to specify a log
# Output:
# a structure with all the timing information, plus vital stats
# on the data set. Right now I'm keeping the imagename, whether
# or not it's a cube and number of cycles. Some other
# information that might be useful to keep:
# image size on disk -- get from os
# threshold? -- from tclean input
# nchan - will have to calculate -- can get from msmd? Ask Remy about this part.
#
# Date Programmer Description of Changes
#----------------------------------------------------------------------
# 2017/11/08 A.A. Kepley Original Code
# 2018/06/08 A.A. Kepley Created a new copy of this function to deal with the new log structure.
# 2019/02/25 A.A. Kepley Added features to deal with MPI logs.
import os
import os.path
import glob
import re
#import ipdb
mpiRE = re.compile(r"MPIServer-(?P<mpinum>\d+?)")
mpiStopRE = re.compile(r"CASA Version")
casaonlyRE = re.compile(r"::casa")
if os.path.exists(testDir):
# initialize lists
allresults = {}
# get the file name
logfilelist = glob.glob(os.path.join(testDir,"casa-????????-??????.log"))
# go through logs and extract info.
for logfile in logfilelist:
f = open(logfile,'r')
line = f.readline()
if casaonlyRE.search(line) and not mpiRE.search(line):
line = f.readline()
# if it's in mpi mode, figure out how many nodes were used.
if mpiRE.search(line):
mpimax = 0
while not mpiStopRE.search(line):
mpinum = int(mpiRE.search(line).group('mpinum'))
if mpinum > mpimax:
mpimax = mpinum
line = f.readline()
while not mpiRE.search(line):
line = f.readline()
f.close()
split_mpi_logs(logfile,n=mpimax+1)
for mpi in range(1,mpimax+1):
mpistr = 'mpi'+str(mpi)
tmpresults = parseLog_newlog(logfile.replace('.log','_'+mpistr+'.log'))
for imagename in tmpresults.keys():
if imagename in allresults:
allresults[imagename][mpistr] = tmpresults[imagename]
else:
allresults[imagename] = {}
allresults[imagename][mpistr] = tmpresults[imagename]
#ipdb.set_trace()
else:
f.close()
tmpresults = parseLog_newlog(logfile)
#mpistr='mpi0'
#for imagename in tmpresults.keys():
# if imagename in allresults:
# allresults[imagename][mpistr] = tmpresults[imagename]
# else:
# allresults[imagename] = {}
# allresults[imagename][mpistr] = tmpresults[imagename]
allresults = tmpresults
else:
print("no path found")
allresults = {}
return allresults
# ----------------------------------------------------------------------
def parseLog_newlog(logfile):
'''
Parse an individual log file and return an object with the data in it
'''
import re
from datetime import datetime
import copy
#import ipdb
# regex patterns for below.
tcleanBeginRE = re.compile(r"Begin Task: tclean")
imagenameRE = re.compile(r'imagename=\"(?P<imagename>.*?)\"')
specmodeRE = re.compile(r'specmode=\"(?P<specmode>.*?)\"')
startMaskRE = re.compile(r'Generating AutoMask')
sidelobeRE = re.compile(r'SidelobeLevel = ')
startThresholdRE = re.compile(r'Start thresholding: create an initial mask by threshold')
endThresholdRE = re.compile(r'End thresholding: time to create the initial threshold mask:')
startPrune1RE = re.compile(r'Start pruning: the initial threshold mask')
endPrune1RE = re.compile(r'End pruning: time to prune the initial threshold mask:')
startSmooth1RE = re.compile(r'Start smoothing: the initial threshold mask')
endSmooth1RE = re.compile(r'End smoothing: time to create the smoothed initial threshold mask:')
startGrowRE = re.compile(r'Start grow mask: growing the previous mask')
endGrowRE = re.compile(r'End grow mask:')
startPrune2RE = re.compile(r'Start pruning: on the grow mask')
endPrune2RE = re.compile(r'End pruning: time to prune the grow mask:')
startSmooth2RE = re.compile(r'Start smoothing: the grow mask')
endSmooth2RE = re.compile(r'End smoothing: time to create the smoothed grow mask:')
startNegativeThresholdRE = re.compile(r'Start thresholding: create a negative mask')
endNegativeThresholdRE = re.compile(r'End thresholding: time to create the negative mask:')
modelFluxRE = re.compile(r'Total Model Flux : (?P<flux>\d*\.\d+|\d+)')
startMinorCycleRE = re.compile(r'Run Minor Cycle Iterations')
endMajorCycleRE = re.compile(r'Completed \w+ iterations.')
startMajorCycleRE = re.compile(r'Major Cycle (?P<cycle>\d*)')
endCleanRE = re.compile(r'Reached global stopping criterion : (?P<stopreason>.*)')
startRestoreRE = re.compile(r'Restoring model image')
endRestoreRE = re.compile(r'Applying PB correction')
tcleanEndRE = re.compile(r"End Task: tclean")
dateFmtRE = re.compile(r"(?P<timedate>\d{4}-\d{2}-\d{2} \d{2}:\d{2}:\d{2})")
# open file
filein = open(logfile,'r')
#initialize loop status
imagename = ''
allresults = {}
results = {}
cycleresults = {}
cycle = '0'
specmode=''
# go through file
for line in filein:
# capture start of tclean
if tcleanBeginRE.search(line):
startTimeStr = dateFmtRE.search(line)
if startTimeStr:
results['startTime'] = datetime.strptime(startTimeStr.group('timedate'),'%Y-%m-%d %H:%M:%S')
# capture image name
if imagenameRE.search(line):
imagename = imagenameRE.search(line).group('imagename')
# capture line vs. continuum
if specmodeRE.search(line):
if re.match(specmodeRE.search(line).group('specmode'),'cube'):
specmode='cube'
else:
specmode='cont'
# if imagename is iter1, record automasking information.
if re.search('iter1', imagename):
# capture the start of the mask
if startMaskRE.search(line):
maskStartTimeStr = dateFmtRE.search(line)
if maskStartTimeStr:
cycleresults['maskStartTime'] = datetime.strptime(maskStartTimeStr.group('timedate'),'%Y-%m-%d %H:%M:%S')
# capture noise calculation
if sidelobeRE.search(line):
sidelobeStartTimeStr = dateFmtRE.search(line)
if sidelobeStartTimeStr:
cycleresults['noiseEndTime'] = datetime.strptime(sidelobeStartTimeStr.group('timedate'),'%Y-%m-%d %H:%M:%S')
cycleresults['noiseTime'] = cycleresults['noiseEndTime'] - cycleresults['maskStartTime']
# capture the threshold time
if startThresholdRE.search(line):
startThresholdTimeStr = dateFmtRE.search(line)
if startThresholdTimeStr:
cycleresults['startThresholdTime'] = datetime.strptime(startThresholdTimeStr.group('timedate'),'%Y-%m-%d %H:%M:%S')
if endThresholdRE.search(line):
endThresholdTimeStr = dateFmtRE.search(line)
if endThresholdTimeStr:
cycleresults['endThresholdTime'] = datetime.strptime(endThresholdTimeStr.group('timedate'),'%Y-%m-%d %H:%M:%S')
# capture the prune time
if startPrune1RE.search(line):
startPrune1TimeStr = dateFmtRE.search(line)
if startPrune1TimeStr:
cycleresults['startPrune1Time'] = datetime.strptime(startPrune1TimeStr.group('timedate'),'%Y-%m-%d %H:%M:%S')
if endPrune1RE.search(line):
endPrune1TimeStr = dateFmtRE.search(line)
if endPrune1TimeStr:
cycleresults['endPrune1Time'] = datetime.strptime(endPrune1TimeStr.group('timedate'),'%Y-%m-%d %H:%M:%S')
# capture the smooth time
if startSmooth1RE.search(line):
startSmooth1TimeStr = dateFmtRE.search(line)
if startSmooth1TimeStr:
cycleresults['startSmooth1Time'] = datetime.strptime(startSmooth1TimeStr.group('timedate'),'%Y-%m-%d %H:%M:%S')
if endSmooth1RE.search(line):
endSmooth1TimeStr = dateFmtRE.search(line)
if endSmooth1TimeStr:
cycleresults['endSmooth1Time'] = datetime.strptime(endSmooth1TimeStr.group('timedate'),'%Y-%m-%d %H:%M:%S')
# capture the grow
if startGrowRE.search(line):
startGrowTimeStr = dateFmtRE.search(line)
if startGrowTimeStr:
cycleresults['startGrowTime'] = datetime.strptime(startGrowTimeStr.group('timedate'),'%Y-%m-%d %H:%M:%S')
if endGrowRE.search(line):
endGrowTimeStr = dateFmtRE.search(line)
if endGrowTimeStr:
cycleresults['endGrowTime'] = datetime.strptime(endGrowTimeStr.group('timedate'),'%Y-%m-%d %H:%M:%S')
# capture 2nd prune
if startPrune2RE.search(line):
startPrune2TimeStr = dateFmtRE.search(line)
if startPrune2TimeStr:
cycleresults['startPrune2Time'] = datetime.strptime(startPrune2TimeStr.group('timedate'),'%Y-%m-%d %H:%M:%S')
if endPrune2RE.search(line):
endPrune2TimeStr = dateFmtRE.search(line)
if endPrune2TimeStr:
cycleresults['endPrune2Time'] = datetime.strptime(endPrune2TimeStr.group('timedate'),'%Y-%m-%d %H:%M:%S')
# capture 2nd smooth
if startSmooth2RE.search(line):
startSmooth2TimeStr = dateFmtRE.search(line)
if startSmooth2TimeStr:
cycleresults['startSmooth2Time'] = datetime.strptime(startSmooth2TimeStr.group('timedate'),'%Y-%m-%d %H:%M:%S')
if endSmooth2RE.search(line):