-
Notifications
You must be signed in to change notification settings - Fork 9
/
selfcal_helpers.py
3933 lines (3449 loc) · 188 KB
/
selfcal_helpers.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
import numpy as np
import numpy
import scipy.stats
import scipy.signal
import math
import os
import casatools
from casaplotms import plotms
from casatasks import *
from casatools import image, imager
from casatools import msmetadata as msmdtool
from casatools import table as tbtool
from casatools import ms as mstool
from casaviewer import imview
from PIL import Image
ms = mstool()
tb = tbtool()
msmd = msmdtool()
ia = image()
im = imager()
def tclean_wrapper(selfcal_library, imagename, band, telescope='undefined', scales=[0], smallscalebias = 0.6, mask = '',\
nsigma=5.0, interactive = False, robust = 0.5, gain = 0.1, niter = 50000,\
cycleniter = 300, uvtaper = [], savemodel = 'none',gridder='standard', sidelobethreshold=3.0,smoothfactor=1.0,noisethreshold=5.0,\
lownoisethreshold=1.5,parallel=False,cyclefactor=3,threshold='0.0Jy',phasecenter='',\
startmodel='',pblimit=0.1,pbmask=0.1,field='',datacolumn='',nfrms_multiplier=1.0, \
savemodel_only=False, resume=False, spw='all', image_mosaic_fields_separately=True, \
store_threshold=''):
"""
Wrapper for tclean with keywords set to values desired for the Large Program imaging
See the CASA 6.1.1 documentation for tclean to get the definitions of all the parameters
"""
msmd.open(selfcal_library['vislist'][0])
fieldid=msmd.fieldsforname(field)
msmd.done()
tb.open(selfcal_library['vislist'][0]+'/FIELD')
try:
ephem_column=tb.getcol('EPHEMERIS_ID')
tb.close()
if ephem_column[fieldid[0]] !=-1:
phasecenter='TRACKFIELD'
except:
tb.close()
phasecenter=''
if selfcal_library['obstype']=='mosaic' and phasecenter != 'TRACKFIELD':
phasecenter=get_phasecenter(selfcal_library['vislist'][0],field)
print('NF RMS Multiplier: ', nfrms_multiplier)
# Minimize out the nfrms_multiplier at 1.
nfrms_multiplier = max(nfrms_multiplier, 1.0)
baselineThresholdALMA = 400.0
if mask == '':
if selfcal_library['usermask'] != '':
mask = selfcal_library['usermask']
usemask = 'user'
else:
usemask='auto-multithresh'
else:
usemask='user'
if telescope=='ALMA':
if selfcal_library['75thpct_uv'] > baselineThresholdALMA:
fastnoise = True
else:
fastnoise = False
sidelobethreshold=2.5
smoothfactor=1.0
noisethreshold=5.0*nfrms_multiplier
lownoisethreshold=1.5*nfrms_multiplier
cycleniter=-1
negativethreshold = 0.0
dogrowprune = True
minpercentchange = 1.0
growiterations = 75
minbeamfrac = 0.3
#cyclefactor=1.0
if selfcal_library['75thpct_uv'] > 2000.0:
sidelobethreshold=2.0
if selfcal_library['75thpct_uv'] < 300.0:
sidelobethreshold=2.0
smoothfactor=1.0
noisethreshold=4.25*nfrms_multiplier
lownoisethreshold=1.5*nfrms_multiplier
if selfcal_library['75thpct_uv'] < baselineThresholdALMA:
sidelobethreshold = 2.0
if telescope=='ACA':
sidelobethreshold=1.25
smoothfactor=1.0
noisethreshold=5.0*nfrms_multiplier
lownoisethreshold=2.0*nfrms_multiplier
cycleniter=-1
fastnoise=False
negativethreshold = 0.0
dogrowprune = True
minpercentchange = 1.0
growiterations = 75
minbeamfrac = 0.3
#cyclefactor=1.0
elif 'VLA' in telescope:
fastnoise=True
sidelobethreshold=2.0
smoothfactor=1.0
noisethreshold=5.0*nfrms_multiplier
lownoisethreshold=1.5*nfrms_multiplier
pblimit=-0.1
cycleniter=-1
negativethreshold = 0.0
dogrowprune = True
minpercentchange = 1.0
growiterations = 75
minbeamfrac = 0.3
#cyclefactor=3.0
pbmask=0.0
wprojplanes=1
if band=='EVLA_L' or band =='EVLA_S':
gridder='wproject'
wplanes=384 # normalized to S-band A-config
#scale by 75th percentile uv distance divided by A-config value
wplanes=wplanes * selfcal_library['75thpct_uv']/20000.0
if band=='EVLA_L':
wplanes=wplanes*2.0 # compensate for 1.5 GHz being 2x longer than 3 GHz
wprojplanes=int(wplanes)
if (band=='EVLA_L' or band =='EVLA_S') and selfcal_library['obstype']=='mosaic':
print('WARNING DETECTED VLA L- OR S-BAND MOSAIC; WILL USE gridder="mosaic" IGNORING W-TERM')
if selfcal_library['obstype']=='mosaic':
gridder='mosaic'
else:
if gridder !='wproject':
gridder='standard'
if spw == 'all':
vlist = selfcal_library['vislist']
spws_per_vis = selfcal_library['spws_per_vis']
nterms = selfcal_library['nterms']
else:
vlist = [vis for vis in selfcal_library['vislist'] if vis in selfcal_library['spw_map'][spw]]
spws_per_vis = [str(selfcal_library['spw_map'][spw][vis]) for vis in vlist]
nterms = 1
if nterms == 1:
reffreq = ''
else:
reffreq = selfcal_library['reffreq']
if "theoretical" in threshold:
dr_mod=1.0
if telescope =='ALMA' or telescope =='ACA':
sensitivity=get_sensitivity(vlist,selfcal_library,field,virtual_spw=spw,
imsize=selfcal_library['imsize'],cellsize=selfcal_library['cellsize'])
dr_mod=get_dr_correction(telescope,selfcal_library['SNR_dirty']*selfcal_library['RMS_dirty'],sensitivity,vlist)
sensitivity_nomod=sensitivity.copy()
print('DR modifier: ',dr_mod, 'SPW: ',spw)
sensitivity=sensitivity*dr_mod # apply DR modifier
if (band =='Band_9' or band == 'Band_10') and spw != 'all': # adjust for DSB noise increase
sensitivity=4.0*sensitivity #*4.0 might be unnecessary with DR mods
selfcal_library['theoretical_sensitivity']=sensitivity_nomod
for fid in selfcal_library['sub-fields']:
selfcal_library[fid]['theoretical_sensitivity']=sensitivity_nomod
else:
sensitivity=0.0
selfcal_library['theoretical_sensitivity']=-99.0
for fid in selfcal_library['sub-fields']:
selfcal_library[fid]['theoretical_sensitivity']=-99.0
if threshold == "theoretical_with_drmod":
threshold = str(4.0*sensitivity)+'Jy'
else:
if spw == 'all':
sensitivity_scale_factor = 1.0
else:
sensitivity_agg=get_sensitivity(vlist,selfcal_library,field,virtual_spw=spw,imsize=selfcal_library['imsize'],
cellsize=selfcal_library['cellsize'])
sensitivity_scale_factor=selfcal_library['RMS_NF_curr']/sensitivity_agg
threshold = str(4.0*sensitivity_nomod*sensitivity_scale_factor)+'Jy'
if threshold != '0.0Jy':
nsigma=0.0
if nsigma != 0.0:
if nsigma*nfrms_multiplier*0.66 > nsigma:
nsigma=nsigma*nfrms_multiplier*0.66
if gridder=='mosaic' and startmodel!='':
parallel=False
if not savemodel_only:
if not resume:
for ext in ['.image*', '.mask', '.model*', '.pb*', '.psf*', '.residual*', '.sumwt*','.gridwt*']:
os.system('rm -rf '+ imagename + ext)
tclean_return = tclean(vis=vlist,
imagename = imagename,
field=field,
specmode = 'mfs',
deconvolver = 'mtmfs',
scales = scales,
gridder=gridder,
weighting='briggs',
robust = robust,
gain = gain,
imsize = selfcal_library['imsize'],
cell = selfcal_library['cellsize'],
smallscalebias = smallscalebias, #set to CASA's default of 0.6 unless manually changed
niter = niter, #we want to end on the threshold
interactive = interactive,
nsigma=nsigma,
cycleniter = cycleniter,
cyclefactor = selfcal_library['cyclefactor'],
uvtaper = uvtaper,
savemodel = 'none',
mask=mask,
usemask=usemask,
sidelobethreshold=sidelobethreshold,
noisethreshold=noisethreshold,
lownoisethreshold=lownoisethreshold,
smoothfactor=smoothfactor,
growiterations=growiterations,
negativethreshold=negativethreshold,
minbeamfrac=minbeamfrac,
dogrowprune=dogrowprune,
minpercentchange=minpercentchange,
fastnoise=fastnoise,
pbmask=pbmask,
pblimit=pblimit,
nterms = nterms,
reffreq = reffreq,
uvrange=selfcal_library['uvrange'],
threshold=threshold,
parallel=parallel,
phasecenter=phasecenter,
startmodel=startmodel,
datacolumn=datacolumn,spw=spws_per_vis,wprojplanes=wprojplanes, verbose=True)
if store_threshold != '':
if telescope == "ALMA" or telescope == "ACA":
selfcal_library["clean_threshold_"+store_threshold] = float(threshold[0:-2])
elif "VLA" in telescope and tclean_return['iterdone'] > 0:
selfcal_library["clean_threshold_"+store_threshold] = tclean_return['summaryminor'][0][0][0]['peakRes'][-1]
if image_mosaic_fields_separately and selfcal_library['obstype'] == 'mosaic':
for field_id in selfcal_library['sub-fields-phasecenters']:
if 'VLA' in telescope:
fov=45.0e9/selfcal_library['meanfreq']*60.0*1.5*0.5
if selfcal_library['meanfreq'] < 12.0e9:
fov=fov*2.0
if telescope=='ALMA':
fov=63.0*100.0e9/selfcal_library['meanfreq']*1.5*0.5*1.15
if telescope=='ACA':
fov=108.0*100.0e9/selfcal_library['meanfreq']*1.5*0.5
center = np.copy(selfcal_library['sub-fields-phasecenters'][field_id])
if phasecenter == 'TRACKFIELD':
center += imhead(imagename+".image.tt0")['refval'][0:2]
region = 'circle[[{0:f}rad, {1:f}rad], {2:f}arcsec]'.format(center[0], center[1], fov)
for ext in [".image.tt0", ".mask", ".residual.tt0", ".psf.tt0",".pb.tt0"]:
target = sanitize_string(field)
os.system('rm -rf '+ imagename.replace(target,target+"_field_"+str(field_id)) + ext.replace("pb","mospb"))
if ext == ".psf.tt0":
os.system("cp -r "+imagename+ext+" "+imagename.replace(target,target+"_field_"+str(field_id))+ext)
else:
imsubimage(imagename+ext, outfile=imagename.replace(target,target+"_field_"+str(field_id))+\
ext.replace("pb","mospb.tmp"), region=region, overwrite=True)
if ext == ".pb.tt0":
immath(imagename=[imagename.replace(target,target+"_field_"+str(field_id))+ext.replace("pb","mospb.tmp")], \
outfile=imagename.replace(target,target+"_field_"+str(field_id))+ext.replace("pb","mospb"), \
expr="IIF(IM0 == 0, 0.1, IM0)")
os.system("rm -rf "+imagename.replace(target,target+"_field_"+str(field_id))+ext.replace("pb","mospb.tmp"))
# Make an image of the primary beam for each sub-field.
if type(selfcal_library['vislist']) == list:
for v in selfcal_library['vislist']:
# Since not every field is in every v, we need to check them all so that we don't accidentally get a v without a given field_id
if field_id in selfcal_library['sub-fields-fid_map'][v]:
fid = selfcal_library['sub-fields-fid_map'][v][field_id]
break
im.open(v)
else:
fid = selfcal_library['sub-fields-fid_map'][selfcal_library['vislist']][field_id]
im.open(vis)
nx, ny, nfreq, npol = imhead(imagename=imagename.replace(target,target+"_field_"+str(field_id))+".image.tt0", mode="get", \
hdkey="shape")
im.selectvis(field=str(fid), spw=spws_per_vis)
im.defineimage(nx=nx, ny=ny, cellx=selfcal_library['cellsize'], celly=selfcal_library['cellsize'], phasecenter=fid, mode="mfs")
im.setvp(dovp=True)
im.makeimage(type="pb", image=imagename.replace(target,target+"_field_"+str(field_id)) + ".pb.tt0")
im.close()
#this step is a workaround a bug in tclean that doesn't always save the model during multiscale clean. See the "Known Issues" section for CASA 5.1.1 on NRAO's website
if savemodel=='modelcolumn' and selfcal_library['usermodel']=='':
print("")
print("Running tclean a second time to save the model...")
tclean(vis= vlist,
imagename = imagename,
field=field,
specmode = 'mfs',
deconvolver = 'mtmfs',
scales = scales,
gridder=gridder,
weighting='briggs',
robust = robust,
gain = gain,
imsize = selfcal_library['imsize'],
cell = selfcal_library['cellsize'],
smallscalebias = smallscalebias, #set to CASA's default of 0.6 unless manually changed
niter = 0,
interactive = False,
nsigma=0.0,
cycleniter = cycleniter,
cyclefactor = selfcal_library['cyclefactor'],
uvtaper = uvtaper,
usemask='user',
savemodel = savemodel,
sidelobethreshold=sidelobethreshold,
noisethreshold=noisethreshold,
lownoisethreshold=lownoisethreshold,
smoothfactor=smoothfactor,
growiterations=growiterations,
negativethreshold=negativethreshold,
minbeamfrac=minbeamfrac,
dogrowprune=dogrowprune,
minpercentchange=minpercentchange,
fastnoise=fastnoise,
pbmask=pbmask,
pblimit=pblimit,
calcres = False,
calcpsf = False,
restoration = False,
nterms = nterms,
uvrange=selfcal_library['uvrange'],
reffreq = reffreq,
threshold=threshold,
parallel=False,
phasecenter=phasecenter,spw=spws_per_vis,wprojplanes=wprojplanes)
elif savemodel=='modelcolumn' and selfcal_library['usermodel'] !='':
print('Using user model already filled to model column, skipping model write.')
if not savemodel_only:
return tclean_return
def usermodel_wrapper(selfcal_library, imagename, band, telescope='undefined',scales=[0], smallscalebias = 0.6, mask = '',\
nsigma=5.0, interactive = False, robust = 0.5, gain = 0.1, niter = 50000,\
cycleniter = 300, uvtaper = [], savemodel = 'none',gridder='standard', sidelobethreshold=3.0,smoothfactor=1.0,noisethreshold=5.0,\
lownoisethreshold=1.5,parallel=False,cyclefactor=3,threshold='0.0Jy',phasecenter='',\
startmodel='',pblimit=0.1,pbmask=0.1,field='',datacolumn='',spw='',\
savemodel_only=False, resume=False):
vlist = selfcal_library['vislist']
if type(selfcal_library['usermodel'])==list:
nterms=len(selfcal_library['usermodel'])
for i, image in enumerate(selfcal_library['usermodel']):
if 'fits' in image:
importfits(fitsimage=image,imagename=image.replace('.fits',''))
selfcal_library['usermodel'][i]=image.replace('.fits','')
elif type(selfcal_library['usermodel'])==str:
importfits(fitsimage=selfcal_library['usermodel'],imagename=usermmodel.replace('.fits',''))
nterms=1
msmd.open(vlist[0])
fieldid=msmd.fieldsforname(field)
msmd.done()
tb.open(vlist[0]+'/FIELD')
try:
ephem_column=tb.getcol('EPHEMERIS_ID')
tb.close()
if ephem_column[fieldid[0]] !=-1:
phasecenter='TRACKFIELD'
except:
tb.close()
phasecenter=''
if selfcal_library['obstype']=='mosaic' and phasecenter != 'TRACKFIELD':
phasecenter=get_phasecenter(selfcal_library['vislist'][0],field)
if nterms == 1:
reffreq = ''
else:
reffreq = selfcal_library['reffreq']
if mask == '':
if selfcal_library['usermask'] != '':
mask = selfcal_library['usermask']
usemask = 'user'
else:
usemask='auto-multithresh'
else:
usemask='user'
wprojplanes=1
if band=='EVLA_L' or band =='EVLA_S':
gridder='wproject'
wplanes=384 # normalized to S-band A-config
#scale by 75th percentile uv distance divided by A-config value
wplanes=wplanes * selfcal_library['75thpct_uv']/20000.0
if band=='EVLA_L':
wplanes=wplanes*2.0 # compensate for 1.5 GHz being 2x longer than 3 GHz
wprojplanes=int(wplanes)
if (band=='EVLA_L' or band =='EVLA_S') and selfcal_library['obstype']=='mosaic':
print('WARNING DETECTED VLA L- OR S-BAND MOSAIC; WILL USE gridder="mosaic" IGNORING W-TERM')
if selfcal_library['obstype']=='mosaic':
gridder='mosaic'
else:
if gridder !='wproject':
gridder='standard'
if gridder=='mosaic' and startmodel!='':
parallel=False
for ext in ['.image*', '.mask', '.model*', '.pb*', '.psf*', '.residual*', '.sumwt*','.gridwt*']:
os.system('rm -rf '+ imagename + ext)
#regrid start model
if not resume:
for ext in ['.image*', '.mask', '.model*', '.pb*', '.psf*', '.residual*', '.sumwt*','.gridwt*']:
os.system('rm -rf '+ imagename+'_usermodel_prep' + ext)
tclean(vis= vlist,
imagename = imagename+'_usermodel_prep',
field=field,
specmode = 'mfs',
deconvolver = 'mtmfs',
scales = scales,
gridder=gridder,
weighting='briggs',
robust = robust,
gain = gain,
imsize = selfcal_library['imsize'],
cell = selfcal_library['cellsize'],
smallscalebias = smallscalebias, #set to CASA's default of 0.6 unless manually changed
niter = 0, #we want to end on the threshold
interactive = interactive,
nsigma=nsigma,
cycleniter = cycleniter,
cyclefactor = selfcal_library['cyclefactor'],
uvtaper = uvtaper,
mask=mask,
usemask=usemask,
sidelobethreshold=sidelobethreshold,
noisethreshold=noisethreshold,
lownoisethreshold=lownoisethreshold,
smoothfactor=smoothfactor,
pbmask=pbmask,
pblimit=pblimit,
nterms = nterms,
reffreq = reffreq,
uvrange=selfcal_library['uvrange'],
threshold=threshold,
parallel=parallel,
phasecenter=phasecenter,
datacolumn=datacolumn,spw=spw,wprojplanes=wprojplanes, verbose=True,startmodel=selfcal_library['usermodel'],savemodel='modelcolumn')
#this step is a workaround a bug in tclean that doesn't always save the model during multiscale clean. See the "Known Issues" section for CASA 5.1.1 on NRAO's website
if savemodel=='modelcolumn':
print("")
print("Running tclean a second time to save the model...")
tclean(vis= vlist,
imagename = imagename+'_usermodel_prep',
field=field,
specmode = 'mfs',
deconvolver = 'mtmfs',
scales = scales,
gridder=gridder,
weighting='briggs',
robust = robust,
gain = gain,
imsize = selfcal_library['imsize'],
cell = selfcal_library['cellsize'],
smallscalebias = smallscalebias, #set to CASA's default of 0.6 unless manually changed
niter = 0,
interactive = False,
nsigma=0.0,
cycleniter = cycleniter,
cyclefactor = selfcal_library['cyclefactor'],
uvtaper = uvtaper,
usemask='user',
savemodel = savemodel,
sidelobethreshold=sidelobethreshold,
noisethreshold=noisethreshold,
lownoisethreshold=lownoisethreshold,
smoothfactor=smoothfactor,
pbmask=pbmask,
pblimit=pblimit,
calcres = False,
calcpsf = False,
restoration = False,
nterms = nterms,
reffreq = reffreq,
uvrange=selfcal_library['uvrange'],
threshold=threshold,
parallel=False,
phasecenter=phasecenter,spw=spw,wprojplanes=wprojplanes)
def collect_listobs_per_vis(vislist):
listdict={}
for vis in vislist:
listdict[vis]=listobs(vis)
return listdict
def fetch_scan_times(vislist,targets):
scantimesdict={}
integrationsdict={}
integrationtimesdict={}
integrationtimes=np.array([])
n_spws=np.array([])
min_spws=np.array([])
spwslist_dict = {}
spws_set_dict = {}
scansdict={}
for vis in vislist:
scantimesdict[vis]={}
integrationsdict[vis]={}
integrationtimesdict[vis]={}
scansdict[vis]={}
spws_set_dict[vis]={}
spwslist_dict[vis]=np.array([])
msmd.open(vis)
for target in targets:
scansdict[vis][target]=msmd.scansforfield(target)
for target in targets:
scantimes=np.array([])
integrations=np.array([])
for scan in scansdict[vis][target]:
spws_set_dict[vis][scan]=np.array([])
spws=msmd.spwsforscan(scan)
#print(scan, spws)
spws_set_dict[vis][scan]=spws.copy()
n_spws=np.append(len(spws),n_spws)
min_spws=np.append(np.min(spws),min_spws)
spwslist_dict[vis]=np.append(spws,spwslist_dict[vis])
integrationtime=msmd.exposuretime(scan=scan,spwid=spws[0])['value']
integrationtimes=np.append(integrationtimes,np.array([integrationtime]))
times=msmd.timesforscan(scan)
scantime=np.max(times)+integrationtime-np.min(times)
ints_per_scan=np.round(scantime/integrationtimes[0])
scantimes=np.append(scantimes,np.array([scantime]))
integrations=np.append(integrations,np.array([ints_per_scan]))
scantimesdict[vis][target]=scantimes.copy()
#assume each band only has a single integration time
integrationtimesdict[vis][target]=np.median(integrationtimes)
integrationsdict[vis][target]=integrations.copy()
msmd.close()
if np.mean(n_spws) != np.max(n_spws):
print('WARNING, INCONSISTENT NUMBER OF SPWS IN SCANS/MSes (Possibly expected if Multi-band VLA data or ALMA Spectral Scan)')
if np.max(min_spws) != np.min(min_spws):
print('WARNING, INCONSISTENT MINIMUM SPW IN SCANS/MSes (Possibly expected if Multi-band VLA data or ALMA Spectral Scan)')
for vis in vislist:
spwslist_dict[vis]=np.unique(spwslist_dict[vis]).astype(int)
# jump through some hoops to get the dictionary that has spws per scan into a dictionary of unique
# spw sets per vis file
for vis in vislist:
spws_set_list=[i for i in spws_set_dict[vis].values()]
spws_set_list=[i.tolist() for i in spws_set_list]
unique_spws_set_list=[list(i) for i in set(tuple(i) for i in spws_set_list)]
spws_set_list=[np.array(i) for i in unique_spws_set_list]
spws_set_dict[vis]=np.array(spws_set_list,dtype=object)
return scantimesdict,integrationsdict,integrationtimesdict, integrationtimes,np.max(n_spws),np.min(min_spws),spwslist_dict,spws_set_dict
def fetch_scan_times_band_aware(vislist,targets,band_properties,band):
scantimesdict={}
scanfieldsdict={}
scannfieldsdict={}
scanstartsdict={}
scanendsdict={}
integrationsdict={}
integrationtimesdict={}
integrationtimes=np.array([])
n_spws=np.array([])
min_spws=np.array([])
scansforspw=np.array([])
spwslist=np.array([])
spws_set_dict = {}
mosaic_field={}
scansdict={}
for vis in vislist:
mosaic_field[vis] = {}
scantimesdict[vis]={}
scanfieldsdict[vis]={}
scannfieldsdict[vis]={}
scanstartsdict[vis]={}
scanendsdict[vis]={}
integrationsdict[vis]={}
integrationtimesdict[vis]={}
spws_set_dict[vis] = {}
scansdict[vis]={}
msmd.open(vis)
for target in targets:
scansforfield=msmd.scansforfield(target)
for spw in band_properties[vis][band]['spwarray']:
scansforspw_temp=msmd.scansforspw(spw)
scansforspw=np.append(scansforspw,np.array(scansforspw_temp,dtype=int))
scansforspw=scansforspw.astype(int)
scansdict[vis][target]=list(set(scansforfield) & set(scansforspw))
scansdict[vis][target].sort()
for target in targets:
mosaic_field[vis][target]={}
mosaic_field[vis][target]['field_ids']=[]
mosaic_field[vis][target]['mosaic']=False
mosaic_field[vis][target]['field_ids']=msmd.fieldsforscans(scansdict[vis][target]).tolist()
mosaic_field[vis][target]['field_ids']=list(set(mosaic_field[vis][target]['field_ids']))
mosaic_field[vis][target]['phasecenters'] = []
for fid in mosaic_field[vis][target]['field_ids']:
tb.open(vis+'/FIELD')
mosaic_field[vis][target]['phasecenters'].append(tb.getcol("PHASE_DIR")[:,0,fid])
tb.close()
if len(mosaic_field[vis][target]['field_ids']) > 1:
mosaic_field[vis][target]['mosaic']=True
scantimes=np.array([])
scanfields=np.array([])
scannfields=np.array([])
integrations=np.array([])
scanstarts=np.array([])
scanends=np.array([])
for scan in scansdict[vis][target]:
spws=msmd.spwsforscan(scan)
spws_set_dict[vis][scan]=spws.copy()
n_spws=np.append(len(spws),n_spws)
min_spws=np.append(np.min(spws),min_spws)
spwslist=np.append(spws,spwslist)
integrationtime=msmd.exposuretime(scan=scan,spwid=spws[0])['value']
integrationtimes=np.append(integrationtimes,np.array([integrationtime]))
times=msmd.timesforscan(scan)
scantime=np.max(times)+integrationtime-np.min(times)
scanstarts=np.append(scanstarts,np.array([np.min(times)/86400.0]))
scanends=np.append(scanends,np.array([(np.max(times)+integrationtime)/86400.0]))
ints_per_scan=np.round(scantime/integrationtimes[0])
scantimes=np.append(scantimes,np.array([scantime]))
integrations=np.append(integrations,np.array([ints_per_scan]))
scanfields = np.append(scanfields,np.array([','.join(msmd.fieldsforscan(scan).astype(str))]))
scannfields = np.append(scannfields,np.array([msmd.fieldsforscan(scan).size]))
scantimesdict[vis][target]=scantimes.copy()
scanfieldsdict[vis][target]=scanfields.copy()
scannfieldsdict[vis][target]=scannfields.copy()
scanstartsdict[vis][target]=scanstarts.copy()
scanendsdict[vis][target]=scanends.copy()
#assume each band only has a single integration time
integrationtimesdict[vis][target]=np.median(integrationtimes)
integrationsdict[vis][target]=integrations.copy()
# jump through some hoops to get the dictionary that has spws per scan into a dictionary of unique
# spw sets per vis file
for vis in vislist:
spws_set_list=[i for i in spws_set_dict[vis].values()]
spws_set_list=[i.tolist() for i in spws_set_list]
unique_spws_set_list=[list(i) for i in set(tuple(i) for i in spws_set_list)]
spws_set_list=[np.array(i) for i in unique_spws_set_list]
spws_set_dict[vis]=np.array(spws_set_list,dtype=object)
if len(n_spws) > 0:
if np.mean(n_spws) != np.max(n_spws):
print('WARNING, INCONSISTENT NUMBER OF SPWS IN SCANS/MSes (Possibly expected if Multi-band VLA data or ALMA Spectral Scan)')
if np.max(min_spws) != np.min(min_spws):
print('WARNING, INCONSISTENT MINIMUM SPW IN SCANS/MSes (Possibly expected if Multi-band VLA data or ALMA Spectral Scan)')
spwslist=np.unique(spwslist).astype(int)
else:
return scantimesdict,scanfieldsdict,scannfieldsdict,scanstartsdict,scanendsdict,integrationsdict,integrationtimesdict, integrationtimes,-99,-99,spwslist,mosaic_field
return scantimesdict,scanfieldsdict,scannfieldsdict,scanstartsdict,scanendsdict,integrationsdict,integrationtimesdict, integrationtimes,np.max(n_spws),np.min(min_spws),spwslist,spws_set_dict,mosaic_field
def fetch_spws(vislist,targets):
scantimesdict={}
n_spws=np.array([])
min_spws=np.array([])
spwslist=np.array([])
scansdict={}
for vis in vislist:
scansdict[vis]={}
msmd.open(vis)
for target in targets:
scansdict[vis][target]=msmd.scansforfield(target)
scansdict[vis][target].sort()
for target in targets:
for scan in scansdict[vis][target]:
spws=msmd.spwsforscan(scan)
n_spws=np.append(len(spws),n_spws)
min_spws=np.append(np.min(spws),min_spws)
spwslist=np.append(spws,spwslist)
if len(n_spws) > 1:
if np.mean(n_spws) != np.max(n_spws):
print('WARNING, INCONSISTENT NUMBER OF SPWS IN SCANS/MSes (Possibly expected if Multi-band VLA data or ALMA Spectral Scan)')
if np.max(min_spws) != np.min(min_spws):
print('WARNING, INCONSISTENT MINIMUM SPW IN SCANS/MSes (Possibly expected if Multi-band VLA data or ALMA Spectral Scan)')
spwslist=np.unique(spwslist).astype(int)
if len(n_spws) == 1:
return n_spws,min_spws,spwslist
else:
return np.max(n_spws),np.min(min_spws),spwslist
#actual routine used for getting solints
def get_solints_simple(vislist,scantimesdict,scannfieldsdict,scanstartsdict,scanendsdict,integrationtimes,\
inf_EB_gaincal_combine,spwcombine=True,solint_decrement='fixed',solint_divider=2.0,n_solints=4.0,do_amp_selfcal=False, mosaic=False):
all_integrations=np.array([])
all_nscans_per_obs=np.array([])
all_time_between_scans=np.array([])
all_times_per_obs=np.array([])
allscantimes=np.array([]) # we put all scan times from all MSes into single array
#mix of short and long baseline data could have differing integration times and hence solints
#could do solints per vis file, but too complex for now at least use perhaps keep scan groups different
#per MOUS
nscans_per_obs={}
time_per_vis={}
time_between_scans={}
for vis in vislist:
nscans_per_obs[vis]={}
time_between_scans[vis]={}
time_per_vis[vis]=0.0
targets=integrationtimes[vis].keys()
earliest_start=1.0e10
latest_end=0.0
for target in targets:
nscans_per_obs[vis][target]=len(scantimesdict[vis][target])
allscantimes=np.append(allscantimes,scantimesdict[vis][target]/scannfieldsdict[vis][target])
for i in range(len(scanstartsdict[vis][target])):# way to get length of an EB with multiple targets without writing new functions; I could be more clever with np.where()
if scanstartsdict[vis][target][i] < earliest_start:
earliest_start=scanstartsdict[vis][target][i]
if scanendsdict[vis][target][i] > latest_end:
latest_end=scanstartsdict[vis][target][i]
if np.isfinite(integrationtimes[vis][target]):
all_integrations=np.append(all_integrations,integrationtimes[vis][target])
all_nscans_per_obs=np.append(all_nscans_per_obs,nscans_per_obs[vis][target])
#determine time between scans
delta_scan=np.zeros(len(scanstartsdict[vis][target])-1)
sortedstarts=np.sort(scanstartsdict[vis][target]) #scan list isn't sorted, so sort these so they're in order and we can subtract them from each other
sortedends=np.sort(scanstartsdict[vis][target])
#delta_scan=(sortedends[:-1]-sortedstarts[1:])*86400.0*-1.0
delta_scan=np.zeros(len(sortedends)-1)
for i in range(len(sortedstarts)-1):
delta_scan[i]=(sortedends[i]-sortedstarts[i+1])*86400.0*-1.0
all_time_between_scans=np.append(all_time_between_scans,delta_scan)
time_per_vis[vis]= (latest_end - earliest_start)*86400.0 # calculate length of EB
all_times_per_obs=np.append(all_times_per_obs,np.array([time_per_vis[vis]]))
integration_time=np.max(all_integrations) # use the longest integration time from all MS files
max_scantime=np.median(allscantimes)
median_scantime=np.max(allscantimes)
min_scantime=np.min(allscantimes)
median_scans_per_obs=np.median(all_nscans_per_obs)
median_time_per_obs=np.median(all_times_per_obs)
median_time_between_scans=np.median(all_time_between_scans)
print('median scan length: ',median_scantime)
print('median time between target scans: ',median_time_between_scans)
print('median scans per observation: ',median_scans_per_obs)
print('median length of observation: ',median_time_per_obs)
solints_gt_scan=np.array([])
gaincal_combine=[]
# commented completely, no solints between inf_EB and inf
#make solints between inf_EB and inf if more than one scan per source and scans are short
#if median_scans_per_obs > 1 and median_scantime < 150.0:
# # add one solint that is meant to combine 2 short scans, otherwise go to inf_EB
# solint=(median_scantime*2.0+median_time_between_scans)*1.1
# if solint < 300.0: # only allow solutions that are less than 5 minutes in duration
# solints_gt_scan=np.append(solints_gt_scan,[solint])
#code below would make solints between inf_EB and inf by combining scans
#sometimes worked ok, but many times selfcal would quit before solint=inf
'''
solint=median_time_per_obs/4.05 # divides slightly unevenly if lengths of observation are exactly equal, but better than leaving a small out of data remaining
while solint > (median_scantime*2.0+median_time_between_scans)*1.05: #solint should be greater than the length of time between two scans + time between to be better than inf
solints_gt_scan=np.append(solints_gt_scan,[solint]) # add solint to list of solints now that it is an integer number of integrations
solint = solint/2.0
#print('Next solint: ',solint) #divide solint by 2.0 for next solint
'''
print(max_scantime,integration_time)
if solint_decrement == 'fixed':
solint_divider=np.round(np.exp(1.0/n_solints*np.log(max_scantime/integration_time)))
#division never less than 2.0
if solint_divider < 2.0:
solint_divider=2.0
solints_lt_scan=np.array([])
n_scans=len(allscantimes)
solint=max_scantime/solint_divider
while solint > 1.90*integration_time: #1.1*integration_time will ensure that a single int will not be returned such that solint='int' can be appended to the final list.
ints_per_solint=solint/integration_time
if ints_per_solint.is_integer():
solint=solint
else:
remainder=ints_per_solint-float(int(ints_per_solint)) # calculate delta_T greater than an a fixed multile of integrations
solint=solint-remainder*integration_time # add remainder to make solint a fixed number of integrations
ints_per_solint=float(int(ints_per_solint))
print('Checking solint = ',ints_per_solint*integration_time)
delta=test_truncated_scans(ints_per_solint, allscantimes,integration_time)
solint=(ints_per_solint+delta)*integration_time
if solint > 1.90*integration_time:
solints_lt_scan=np.append(solints_lt_scan,[solint]) # add solint to list of solints now that it is an integer number of integrations
solint = solint/solint_divider
#print('Next solint: ',solint) #divide solint by 2.0 for next solint
solints_list=[]
if len(solints_gt_scan) > 0:
for solint in solints_gt_scan:
solint_string='{:0.2f}s'.format(solint)
solints_list.append(solint_string)
if spwcombine:
gaincal_combine.append('spw,scan')
else:
gaincal_combine.append('scan')
# insert inf_EB
solints_list.insert(0,'inf_EB')
gaincal_combine.insert(0,inf_EB_gaincal_combine)
# Insert scan_inf_EB if this is a mosaic.
if mosaic and median_scans_per_obs > 1:
solints_list.append('scan_inf')
if spwcombine:
gaincal_combine.append('spw,field,scan')
else:
gaincal_combine.append('field,scan')
#insert solint = inf
if (not mosaic and (median_scans_per_obs > 2 or (median_scans_per_obs == 2 and max_scantime / min_scantime < 4))) or mosaic: # if only a single scan per target, redundant with inf_EB and do not include
solints_list.append('inf')
if spwcombine:
gaincal_combine.append('spw')
else:
gaincal_combine.append('')
for solint in solints_lt_scan:
solint_string='{:0.2f}s'.format(solint)
solints_list.append(solint_string)
if spwcombine:
gaincal_combine.append('spw')
else:
gaincal_combine.append('')
#append solint = int to end
solints_list.append('int')
if spwcombine:
gaincal_combine.append('spw')
else:
gaincal_combine.append('')
solmode_list=['p']*len(solints_list)
if do_amp_selfcal:
if median_time_between_scans >150.0 or np.isnan(median_time_between_scans):
amp_solints_list=['inf_ap']
if spwcombine:
amp_gaincal_combine=['spw']
else:
amp_gaincal_combine=['']
else:
amp_solints_list=['300s_ap','inf_ap']
if spwcombine:
amp_gaincal_combine=['scan,spw','spw']
else:
amp_gaincal_combine=['scan','']
solints_list=solints_list+amp_solints_list
gaincal_combine=gaincal_combine+amp_gaincal_combine
solmode_list=solmode_list+['ap']*len(amp_solints_list)
return solints_list,integration_time,gaincal_combine,solmode_list
def test_truncated_scans(ints_per_solint, allscantimes,integration_time ):
delta_ints_per_solint=[0 , -1, 1,-2,2]
n_truncated_scans=np.zeros(len(delta_ints_per_solint))
n_remaining_ints=np.zeros(len(delta_ints_per_solint))
min_index=0
for i in range(len(delta_ints_per_solint)):
diff_ints_per_scan=((allscantimes-((ints_per_solint+delta_ints_per_solint[i])*integration_time))/integration_time)+0.5
diff_ints_per_scan=diff_ints_per_scan.astype(int)
trimmed_scans=( (diff_ints_per_scan > 0.0) & (diff_ints_per_scan < ints_per_solint+delta_ints_per_solint[i])).nonzero()
if len(trimmed_scans[0]) >0:
n_remaining_ints[i]=np.max(diff_ints_per_scan[trimmed_scans[0]])
else:
n_remaining_ints[i]=0.0
#print((ints_per_solint+delta_ints_per_solint[i])*integration_time,ints_per_solint+delta_ints_per_solint[i], diff_ints_per_scan)
#print('Max ints remaining: ', n_remaining_ints[i])
#print('N truncated scans: ', len(trimmed_scans[0]))
n_truncated_scans[i]=len(trimmed_scans[0])
# check if there are fewer truncated scans in the current trial and if
# if one trial has more scans left off or fewer. Favor more left off, such that remainder might be able to
# find a solution
# if ((i > 0) and (n_truncated_scans[i] <= n_truncated_scans[min_index]): # if we don't care about the amount of
#if ((i > 0) and (n_truncated_scans[i] <= n_truncated_scans[min_index]) and (n_remaining_ints[i] > n_remaining_ints[min_index])):
if ((i > 0) and (n_truncated_scans[i] <= n_truncated_scans[min_index]) and (n_remaining_ints[i] < n_remaining_ints[min_index])):
min_index=i
#print(delta_ints_per_solint[min_index])
return delta_ints_per_solint[min_index]
def fetch_targets(vis):
fields=[]
msmd.open(vis)
fieldnames=msmd.fieldnames()
for fieldname in fieldnames:
scans=msmd.scansforfield(fieldname)
if len(scans) > 0:
fields.append(fieldname)
msmd.close()
fields=list(set(fields)) # convert to set to only get unique items
return fields
def checkmask(imagename):
maskImage=imagename.replace('image','mask').replace('.tt0','')
image_stats= imstat(maskImage)
if image_stats['max'][0] == 0:
return False
else:
return True
def estimate_SNR(imagename,maskname=None,verbose=True, mosaic_sub_field=False):
MADtoRMS = 1.4826
headerlist = imhead(imagename, mode = 'list')
beammajor = headerlist['beammajor']['value']
beamminor = headerlist['beamminor']['value']
beampa = headerlist['beampa']['value']
if mosaic_sub_field:
os.system("rm -rf temp.image")
immath(imagename=[imagename, imagename.replace(".image",".pb"), imagename.replace(".image",".mospb")], outfile="temp.image", \
expr="IM0*IM1/IM2")
image_stats= imstat(imagename = "temp.image")
os.system("rm -rf temp.image")
else:
image_stats= imstat(imagename = imagename)
if maskname is None:
maskImage=imagename.replace('image','mask').replace('.tt0','')
else:
maskImage=maskname
residualImage=imagename # change to .image JT 04-15-2024 .replace('image','residual')
os.system('rm -rf temp.mask temp.residual')
if os.path.exists(maskImage):
os.system('cp -r '+maskImage+ ' temp.mask')
maskImage='temp.mask'
os.system('cp -r '+residualImage+ ' temp.residual') # leave this as .residual to avoid clashing with another temp.image
residualImage='temp.residual'
if 'dirty' not in imagename:
goodMask=checkmask(imagename)
else:
goodMask=False
if os.path.exists(maskImage) and goodMask:
ia.close()
ia.done()
ia.open(residualImage)
#ia.calcmask(maskImage+" <0.5"+"&& mask("+residualImage+")",name='madpbmask0')
ia.calcmask("'"+maskImage+"'"+" <0.5"+"&& mask("+residualImage+")",name='madpbmask0')
mask0Stats = ia.statistics(robust=True,axes=[0,1])
ia.maskhandler(op='set',name='madpbmask0')
rms = mask0Stats['medabsdevmed'][0] * MADtoRMS
residualMean = mask0Stats['median'][0]
else:
residual_stats=imstat(imagename=imagename,algorithm='chauvenet')
rms = residual_stats['rms'][0]
peak_intensity = image_stats['max'][0]
SNR = peak_intensity/rms
if verbose:
print("#%s" % imagename)
print("#Beam %.3f arcsec x %.3f arcsec (%.2f deg)" % (beammajor, beamminor, beampa))
print("#Peak intensity of source: %.2f mJy/beam" % (peak_intensity*1000,))
print("#rms: %.2e mJy/beam" % (rms*1000,))
print("#Peak SNR: %.2f" % (SNR,))
ia.close()
ia.done()
if mosaic_sub_field:
os.system("rm -rf temp.image")