-
Notifications
You must be signed in to change notification settings - Fork 2
/
runwsclean.py
executable file
·4431 lines (3632 loc) · 186 KB
/
runwsclean.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
#!/usr/bin/env python
# findrefant needs to check for flagged antenna
# do not use os.system for DP3/WSClean to catch errors properly
# decrease niter if multiscale is triggered, smart move?
# make ms backups (also deals with NaNs issues)
# linear to circular solution conversion
# do not predict sky second time in pertubation solve?
# only do scalarphasediff solve once?
# to do: log command into the FITS header
# solnorm fulljones fix? is very tricky....
# fulljones flagging and medamps not working correctly
# avg to units of Hertz and seconds? (for input data that hass different averaging)
# BLsmooth not for gain solves opttion
# BLsmooth constant smooth for gain solves
# Look into Wiener/Kalman smoothing
# only trigger HBA upper band selection for sources outside the FWHM?
# add 1 Jy source in phase center option
# stop selfcal if MODEL_DATA / noise is too low
# if noise goes up stop selfcal
# for phaseup option add back core stations in solution file via https://github.com/lmorabit/lofar-vlbi/blob/master/bin/gains_toCS_h5parm.py
# make Ateam plot
# example:
# python /net/rijn/data2/rvweeren/LoTSS_ClusterCAL/runwscleanLBautoR.py -b box_18.reg --forwidefield --usewgridder --avgfreqstep=2 --avgtimestep=2 --smoothnessconstraint-list="[0.0,0.0,5.0]" --antennaconstraint-list="['core']" --solint-list=[1,20,120] --soltypecycles-list="[0,1,3]" --soltype-list="['tecandphase','tecandphase','scalarcomplexgain']" test.ms
import logging
logger = logging.getLogger(__name__)
logging.basicConfig(filename='selfcal.log', format='%(levelname)s:%(asctime)s ---- %(message)s', datefmt='%m/%d/%Y %H:%M:%S')
logger.setLevel(logging.DEBUG)
import matplotlib
matplotlib.use('Agg')
import os, sys
import numpy as np
import losoto
import losoto.lib_operations
import glob, time
from astropy.io import fits
import astropy.stats
import astropy
from astroquery.skyview import SkyView
import pyrap.tables as pt
import os.path
from losoto import h5parm
import bdsf
import pyregion
import argparse
import pickle
import aplpy
import fnmatch
import tables
from astropy.io import ascii
import multiprocessing
import ast
from lofar.stationresponse import stationresponse
from itertools import product
#from astropy.utils.data import clear_download_cache
#clear_download_cache()
# this function does not work, for some reason cannot modify the source table
#def copy_over_sourcedirection_h5(h5ref, h5):
#Href = tables.open_file(h5ref, mode='r')
#ssdir = np.copy(Href.root.sol000.source[0]['dir'])
#Href.close()
#H = tables.open_file(h5, mode='a')
#print(ssdir, H.root.sol000.source[0]['dir'])
#H.root.sol000.source[0]['dir'] = np.copy(ssdir)
#H.flush()
#print(ssdir, H.root.sol000.source[0]['dir'])
#H.close()
#return
def create_mergeparmdbname(mslist, selfcalcycle):
parmdblist = mslist[:]
for ms_id, ms in enumerate(mslist):
parmdblist[ms_id] = 'merged_selfcalcyle' + str(selfcalcycle).zfill(3) + '_' + ms + '.avg.h5'
print('Created parmdblist', parmdblist)
return parmdblist
def preapply(H5filelist, mslist, updateDATA=True):
for ms in mslist:
parmdb = time_match_mstoH5(H5filelist, ms)
applycal(ms, parmdb, msincol='DATA',msoutcol='CORRECTED_DATA')
if updateDATA:
os.system("taql 'update " + ms + " set DATA=CORRECTED_DATA'")
return
def time_match_mstoH5(H5filelist, ms):
t = pt.table(ms)
timesms = np.unique(t.getcol('TIME'))
t.close()
H5filematch = None
for H5file in H5filelist:
H = tables.open_file(H5file, mode='r')
try:
times = H.root.sol000.amplitude000.time[:]
except:
pass
try:
times = H.root.sol000.rotation000.time[:]
except:
pass
try:
times = H.root.sol000.phase000.time[:]
except:
pass
try:
times = H.root.sol000.tec000.time[:]
except:
pass
if np.median(times) >= np.min(timesms) and np.median(times) <= np.max(timesms):
print(H5file, 'overlaps in time with', ms)
H5filematch = H5file
H.close()
if H5filematch == None:
print('Cannot find matching H5file and ms')
sys.exit()
return H5filematch
def logbasicinfo(args, fitsmask, mslist, version, inputsysargs):
logger.info(' '.join(map(str,inputsysargs)))
logger.info('Version: ' + str(version))
logger.info('Imsize: ' + str(args['imsize']))
logger.info('Pixelscale: ' + str(args['pixelscale']))
logger.info('Niter: ' + str(args['niter']))
logger.info('Uvmin: ' + str(args['uvmin'] ))
logger.info('Multiscale: ' + str(args['multiscale']))
logger.info('No beam correction: ' + str(args['no_beamcor']))
logger.info('IDG: ' + str(args['idg']))
logger.info('Widefield: ' + str(args['forwidefield']))
logger.info('Flagslowamprms: ' + str(args['flagslowamprms']))
logger.info('flagslowphaserms: ' + str(args['flagslowphaserms']))
logger.info('Do linear: ' + str(args['dolinear']))
logger.info('Do circular: ' + str(args['docircular']))
if args['boxfile'] != None:
logger.info('Bobxfile: ' + args['boxfile'])
logger.info('Mslist: ' + ' '.join(map(str,mslist)))
logger.info('User specified clean mask: ' + str(fitsmask))
logger.info('Threshold for MakeMask: ' + str(args['maskthreshold']))
logger.info('Briggs robust: ' + str(args['robust']))
return
def max_area_of_island(grid):
rlen, clen = len(grid), len(grid[0])
def neighbors(r, c):
"""
Generate the neighbor coordinates of the given row and column that
are within the bounds of the grid.
"""
for dr, dc in [(-1, 0), (1, 0), (0, -1), (0, 1)]:
if (0 <= r + dr < rlen) and (0 <= c + dc < clen):
yield r + dr, c + dc
visited = [[False] * clen for _ in range(rlen)]
def island_size(r, c):
"""
Find the area of the land connected to the given coordinate.
Return 0 if the coordinate is water or if it has already been
explored in a previous call to island_size().
"""
if grid[r][c] == 0 or visited[r][c]:
return 0
area = 1
stack = [(r, c)]
visited[r][c] = True
while stack:
for r, c in neighbors(*stack.pop()):
if grid[r][c] and not visited[r][c]:
stack.append((r, c))
visited[r][c] = True
area += 1
return area
return max(island_size(r, c) for r, c in product(range(rlen), range(clen)))
def getlargestislandsize(fitsmask):
hdulist = fits.open(fitsmask)
data = hdulist[0].data
max_area = max_area_of_island(data[0,0,:,:])
hdulist.close()
return max_area
def create_phase_slope(inmslist, incol='DATA', outcol='DATA_PHASE_SLOPE', ampnorm=False):
if not isinstance(inmslist,list):
inmslist = [inmslist]
for ms in inmslist:
t = pt.table(ms, readonly=False, ack=True)
if outcol not in t.colnames():
print('Adding',outcol,'to',ms)
desc = t.getcoldesc(incol)
newdesc = pt.makecoldesc(outcol, desc)
newdmi = t.getdminfo(incol)
newdmi['NAME'] = 'Dysco' + outcol
t.addcols(newdesc, newdmi)
data = t.getcol(incol)
dataslope = np.copy(data)
for ff in range(data.shape[1]-1):
if ampnorm:
dataslope[:,ff,0] = np.copy(np.exp(1j * (np.angle(data[:,ff,0])-np.angle(data[:,ff+1,0]))))
dataslope[:,ff,3] = np.copy(np.exp(1j * (np.angle(data[:,ff,3])-np.angle(data[:,ff+1,3]))))
else:
dataslope[:,ff,0] = np.copy(np.abs(data[:,ff,0])*np.exp(1j * (np.angle(data[:,ff,0])-np.angle(data[:,ff+1,0]))))
dataslope[:,ff,3] = np.copy(np.abs(data[:,ff,3])*np.exp(1j * (np.angle(data[:,ff,3])-np.angle(data[:,ff+1,3]))))
#last freq set to second to last freq because difference reduces length of freq axis with one
dataslope[:,-1,:] = np.copy(dataslope[:,-2,:])
t.putcol(outcol, dataslope)
t.close()
#print( np.nanmedian(np.abs(data)))
#print( np.nanmedian(np.abs(dataslope)))
del data, dataslope
return
def create_phasediff_column(inmslist, incol='DATA', outcol='DATA_CIRCULAR_PHASEDIFF'):
if not isinstance(inmslist,list):
inmslist = [inmslist]
for ms in inmslist:
t = pt.table(ms, readonly=False, ack=True)
if outcol not in t.colnames():
print('Adding',outcol,'to',ms)
desc = t.getcoldesc(incol)
newdesc = pt.makecoldesc(outcol, desc)
newdmi = t.getdminfo(incol)
newdmi['NAME'] = 'Dysco' + outcol
t.addcols(newdesc, newdmi)
data = t.getcol(incol)
phasediff = np.copy(np.angle(data[:,:,0]) - np.angle(data[:,:,3])) #RR - LL
data[:,:,0] = 0.5*np.exp(1j * phasediff) # because I = RR+LL/2 (this is tricky because we work with phase diff)
data[:,:,3] = data[:,:,0]
t.putcol(outcol, data)
t.close()
del data
del phasediff
if False:
#data = t.getcol(incol)
#t.putcol(outcol, data)
#t.close()
time.sleep(2)
cmd = "taql 'update " + ms + " set "
cmd += outcol + "[,0]=0.5*EXP(1.0i*(PHASE(" + incol + "[,0])-PHASE(" + incol + "[,3])))'"
#cmd += outcol + "[,3]=" + outcol + "[,0],"
#cmd += outcol + "[,1]=0+0i,"
#cmd += outcol + "[,2]=0+0i'"
print(cmd)
os.system(cmd)
cmd = "taql 'update " + ms + " set "
#cmd += outcol + "[,0]=0.5*EXP(1.0i*(PHASE(" + incol + "[,0])-PHASE(" + incol + "[,3]))),"
cmd += outcol + "[,3]=" + outcol + "[,0]'"
#cmd += outcol + "[,1]=0+0i,"
#cmd += outcol + "[,2]=0+0i'"
print(cmd)
os.system(cmd)
return
def create_phase_column(inmslist, incol='DATA', outcol='DATA_PHASEONLY'):
if not isinstance(inmslist,list):
inmslist = [inmslist]
for ms in inmslist:
t = pt.table(ms, readonly=False, ack=True)
if outcol not in t.colnames():
print('Adding',outcol,'to',ms)
desc = t.getcoldesc(incol)
newdesc = pt.makecoldesc(outcol, desc)
newdmi = t.getdminfo(incol)
newdmi['NAME'] = 'Dysco' + outcol
t.addcols(newdesc, newdmi)
data = t.getcol(incol)
data[:,:,0] = np.copy(np.exp(1j * np.angle(data[:,:,0]))) # because I = xx+yy/2
data[:,:,3] = np.copy(np.exp(1j * np.angle(data[:,:,3]))) # because I = xx+yy/2
t.putcol(outcol, data)
t.close()
del data
return
def create_MODEL_DATA_PDIFF(inmslist):
if not isinstance(inmslist,list):
inmslist = [inmslist]
for ms in inmslist:
os.system('DPPP msin=' + ms + ' msout=. msout.datacolumn=MODEL_DATA_PDIFF steps=[]')
os.system("taql" + " 'update " + ms + " set MODEL_DATA_PDIFF[,0]=(0.5+0i)'") # because I = RR+LL/2 (this is tricky because we work with phase diff)
os.system("taql" + " 'update " + ms + " set MODEL_DATA_PDIFF[,3]=(0.5+0i)'") # because I = RR+LL/2 (this is tricky because we work with phase diff)
os.system("taql" + " 'update " + ms + " set MODEL_DATA_PDIFF[,1]=(0+0i)'")
os.system("taql" + " 'update " + ms + " set MODEL_DATA_PDIFF[,2]=(0+0i)'")
def fulljonesparmdb(h5):
H=tables.open_file(h5)
try:
phase = H.root.sol000.phase000.val[:]
amplitude = H.root.sol000.amplitude000.val[:]
if phase.shape[-1] == 4 and amplitude.shape[-1] == 4:
fulljones = True
else:
fulljones = False
except:
fulljones = False
H.close()
return fulljones
def reset_gains_noncore(h5parm, keepanntennastr='CS'):
fulljones = fulljonesparmdb(h5parm) # True/False
hasphase = True
hasamps = True
hasrotatation = True
hastec = True
H=tables.open_file(h5parm, mode='a')
# figure of we have phase and/or amplitude solutions
try:
antennas = H.root.sol000.amplitude000.ant[:]
axisn = H.root.sol000.amplitude000.val.attrs['AXES'].decode().split(',')
except:
hasamps = False
try:
antennas = H.root.sol000.phase000.ant[:]
axisn = H.root.sol000.phase000.val.attrs['AXES'].decode().split(',')
except:
hasphase = False
try:
antennas = H.root.sol000.tec000.ant[:]
axisn = H.root.sol000.tec000.val.attrs['AXES'].decode().split(',')
except:
hastec = False
try:
antennas = H.root.sol000.rotation000.ant[:]
axisn = H.root.sol000.rotation000.val.attrs['AXES'].decode().split(',')
except:
hasrotatation = False
if hasphase:
phase = H.root.sol000.phase000.val[:]
if hasamps:
amp = H.root.sol000.amplitude000.val[:]
if hastec:
tec = H.root.sol000.tec000.val[:]
if hasrotatation:
rotation = H.root.sol000.rotation000.val[:]
for antennaid,antenna in enumerate(antennas):
if antenna[0:2] != keepanntennastr:
if hasphase:
antennaxis = axisn.index('ant')
axisn = H.root.sol000.phase000.val.attrs['AXES'].decode().split(',')
print('Resetting phase', antenna, 'Axis entry number', axisn.index('ant'))
#print(phase[:,:,antennaid,...])
if antennaxis == 0:
phase[antennaid,...] = 0.0
if antennaxis == 1:
phase[:,antennaid,...] = 0.0
if antennaxis == 2:
phase[:,:,antennaid,...] = 0.0
if antennaxis == 3:
phase[:,:,:,antennaid,...] = 0.0
if antennaxis == 4:
phase[:,:,:,:,antennaid,...] = 0.0
#print(phase[:,:,antennaid,...])
if hasamps:
antennaxis = axisn.index('ant')
axisn = H.root.sol000.amplitude000.val.attrs['AXES'].decode().split(',')
print('Resetting amplitude', antenna, 'Axis entry number', axisn.index('ant'))
if antennaxis == 0:
amp[antennaid,...] = 1.0
if antennaxis == 1:
amp[:,antennaid,...] = 1.0
if antennaxis == 2:
amp[:,:,antennaid,...] = 1.0
if antennaxis == 3:
amp[:,:,:,antennaid,...] = 1.0
if antennaxis == 4:
amp[:,:,:,:,antennaid,...] = 1.0
if fulljones:
amp[...,1] = 0.0 # XY, assumpe pol is last axis
amp[...,2] = 0.0 # YX, assume pol is last axis
if hastec:
antennaxis = axisn.index('ant')
axisn = H.root.sol000.tec000.val.attrs['AXES'].decode().split(',')
print('Resetting TEC', antenna, 'Axis entry number', axisn.index('ant'))
if antennaxis == 0:
tec[antennaid,...] = 0.0
if antennaxis == 1:
tec[:,antennaid,...] = 0.0
if antennaxis == 2:
tec[:,:,antennaid,...] = 0.0
if antennaxis == 3:
tec[:,:,:,antennaid,...] = 0.0
if antennaxis == 4:
tec[:,:,:,:,antennaid,...] = 0.0
if hasrotatation:
antennaxis = axisn.index('ant')
axisn = H.root.sol000.rotation000.val.attrs['AXES'].decode().split(',')
print('Resetting rotation', antenna, 'Axis entry number', axisn.index('ant'))
if antennaxis == 0:
rotation[antennaid,...] = 0.0
if antennaxis == 1:
rotation[:,antennaid,...] = 0.0
if antennaxis == 2:
rotation[:,:,antennaid,...] = 0.0
if antennaxis == 3:
rotation[:,:,:,antennaid,...] = 0.0
if antennaxis == 4:
rotation[:,:,:,:,antennaid,...] = 0.0
# fill values back in
if hasphase:
H.root.sol000.phase000.val[:] = np.copy(phase)
if hasamps:
H.root.sol000.amplitude000.val[:] = np.copy(amp)
if hastec:
H.root.sol000.tec000.val[:] = np.copy(tec)
if hasrotatation:
H.root.sol000.rotation000.val[:] = np.copy(rotatation)
H.flush()
H.close()
return
#reset_gains_noncore('merged_selfcalcyle11_testquick260.ms.avg.h5')
#sys.exit()
def phaseup(msinlist,datacolumn='DATA',superstation='core', parmdbmergelist=None):
msoutlist = []
for ms in msinlist:
msout=ms + '.phaseup'
msoutlist.append(msout)
if os.path.isdir(msout):
os.system('rm -rf ' + msout)
cmd = "DPPP msin=" + ms + " msout.storagemanager=dysco steps=[add,filter] msout.writefullresflag=False "
cmd += "msout=" + msout + " msin.datacolumn=" + datacolumn + " "
cmd += "filter.type=filter filter.remove=True "
cmd += "add.type=stationadder "
if superstation == 'core':
cmd += "add.stations={ST001:'CS*'} filter.baseline='!CS*&&*' "
if superstation == 'superterp':
cmd += "add.stations={ST001:'CS00[2-7]*'} filter.baseline='!CS00[2-7]*&&*' "
print(cmd)
os.system(cmd)
return msoutlist
def findfreqavg(ms, imsize, bwsmearlimit=1.0):
t = pt.table(ms + '/SPECTRAL_WINDOW',ack=False)
bwsmear = bandwidthsmearing(np.median(t.getcol('CHAN_WIDTH')), \
np.min(t.getcol('CHAN_FREQ')[0]), np.float(imsize), verbose=False)
nfreq = len(t.getcol('CHAN_FREQ')[0])
t.close()
avgfactor = 0
for count in range(2,21): # try average values between 2 to 20
if bwsmear < (bwsmearlimit/np.float(count)): # factor X avg
if nfreq % count == 0:
avgfactor = count
return avgfactor
def ntimesH5(H5file):
# function to return number of timeslots in H5 solution
H=tables.open_file(H5file, mode='r')
try:
times= H.root.sol000.amplitude000.time[:]
except: # apparently no slow amps available
try:
times= H.root.sol000.phase000.time[:]
except:
print('No amplitude000 or phase000 solution found')
sys.exit()
H.close()
return len(times)
def create_backup_flag_col(ms, flagcolname='FLAG_BACKUP'):
cname = 'FLAG'
flags = []
t = pt.table(ms, readonly=False, ack=True)
if flagcolname not in t.colnames():
flags = t.getcol('FLAG')
print('Adding flagging column',flagcolname,'to',ms)
desc = t.getcoldesc(cname)
newdesc = pt.makecoldesc(flagcolname, desc)
newdmi = t.getdminfo(cname)
newdmi['NAME'] = flagcolname
t.addcols(newdesc, newdmi)
t.putcol(flagcolname, flags)
t.close()
del flags
return
def checklongbaseline(ms):
t = pt.table(ms + '/ANTENNA',ack=False)
antennasms = list(t.getcol('NAME'))
t.close()
substr = 'DE' # to check if a German station is present, if yes assume this is long baseline data
haslongbaselines = any(substr in mystring for mystring in antennasms)
print('Contains long baselines?', haslongbaselines)
return haslongbaselines
def average(mslist, freqstep, timestep=None, start=0, msinnchan=None, phaseshiftbox=None, msinntimes=None):
# sanity check
if len(mslist) != len(freqstep):
print('Hmm, made a mistake with freqstep?')
sys.exit()
outmslist = []
for ms_id, ms in enumerate(mslist):
if (freqstep[ms_id] > 0) or (timestep != None) or (msinnchan != None) or \
(phaseshiftbox != None) or (msinntimes != None): # if this is True then average
msout = ms + '.avg'
cmd = 'DPPP msin=' + ms + ' msout.storagemanager=dysco av.type=averager '
cmd += 'msout='+ msout + ' msin.weightcolumn=WEIGHT_SPECTRUM msout.writefullresflag=False '
if phaseshiftbox != None:
cmd += ' steps=[shift,av] '
cmd += ' shift.type=phaseshifter '
cmd += ' shift.phasecenter=\['+getregionboxcenter(phaseshiftbox)+'\] '
else:
cmd +=' steps=[av] '
if freqstep[ms_id] != None:
cmd +='av.freqstep=' + str(freqstep[ms_id]) + ' '
if timestep != None:
cmd +='av.timestep=' + str(timestep) + ' '
if msinnchan != None:
cmd +='msin.nchan=' + str(msinnchan) + ' '
if msinntimes != None:
cmd +='msin.ntimes=' + str(msinntimes) + ' '
if start == 0:
print('Average with default WEIGHT_SPECTRUM:', cmd)
if os.path.isdir(msout):
os.system('rm -rf ' + msout)
os.system(cmd)
msouttmp = ms + '.avgtmp'
cmd = 'DPPP msin=' + ms + ' msout.storagemanager=dysco steps=[av] av.type=averager '
cmd+= 'msout='+ msouttmp + ' msin.weightcolumn=WEIGHT_SPECTRUM_SOLVE msout.writefullresflag=False '
if freqstep[ms_id] != None:
cmd+='av.freqstep=' + str(freqstep[ms_id]) + ' '
if timestep != None:
cmd+='av.timestep=' + str(timestep) + ' '
if msinnchan != None:
cmd+='msin.nchan=' + str(msinnchan) + ' '
if msinntimes != None:
cmd +='msin.ntimes=' + str(msinntimes) + ' '
if start == 0:
t = pt.table(ms)
if 'WEIGHT_SPECTRUM_SOLVE' in t.colnames(): # check if present otherwise this is not needed
t.close()
print('Average with default WEIGHT_SPECTRUM_SOLVE:', cmd)
if os.path.isdir(msouttmp):
os.system('rm -rf ' + msouttmp)
os.system(cmd)
# Make a WEIGHT_SPECTRUM from WEIGHT_SPECTRUM_SOLVE
t = pt.table(msout, readonly=False)
print('Adding WEIGHT_SPECTRUM_SOLVE')
desc = t.getcoldesc('WEIGHT_SPECTRUM')
desc['name']='WEIGHT_SPECTRUM_SOLVE'
t.addcols(desc)
t2 = pt.table(msouttmp, readonly=True)
imweights = t2.getcol('WEIGHT_SPECTRUM')
t.putcol('WEIGHT_SPECTRUM_SOLVE', imweights)
# Fill WEIGHT_SPECTRUM with WEIGHT_SPECTRUM from second ms
t2.close()
t.close()
# clean up
os.system('rm -rf ' + msouttmp)
outmslist.append(msout)
else:
outmslist.append(ms) # so no averaging happened
return outmslist
#def makeh5templates(mslist, parmdb, phasesoltype, slowsoltype, solint_phase, solint_ap, nchan_phase, nchan_ap):
#for msnumber, ms in enumerate(mslist):
#if phasesoltype == 'scalarphase':
#runDPPP(ms, np.int(solint_ap[msnumber]), np.int(solint_phase[msnumber]), \
#np.int(nchan_phase[msnumber]), np.int(nchan_ap[msnumber]), \
#ms + parmdb + str(0).zfill(3) + '_polversion.h5' ,args['phase_soltype'], \
#preapplyphase=False, TEC=TEC, puretec=args['pure_tec'], maxiter=1)
#if slowsoltype != 'fulljones':
#runDPPP(ms, np.int(solint_ap[msnumber]), np.int(solint_phase[msnumber]), \
#np.int(nchan_phase[msnumber]), np.int(nchan_ap[msnumber]), \
#ms + parmdb + str(0).zfill(3) + '_slowgainversion.h5' ,'complexgain', \
#preapplyphase=False, TEC=False, puretec=False, maxiter=1)
#else:
#runDPPP(ms, np.int(solint_ap[msnumber]), np.int(solint_phase[msnumber]), \
#np.int(nchan_phase[msnumber]), np.int(nchan_ap[msnumber]), \
#ms + parmdb + str(0).zfill(3) + '_slowgainversion.h5' ,'fulljones', \
#preapplyphase=False, TEC=False, puretec=False, maxiter=1)
#resetgains(ms + parmdb + str(0).zfill(3) + '_slowgainversion.h5')
#return
def tecandphaseplotter(h5, ms, outplotname='plot.png'):
if not os.path.isdir('plotlosoto%s' % ms): # needed because if this is the first plot this directory does not yet exist
os.system('mkdir plotlosoto%s' % ms)
cmd = 'python plot_tecandphase.py '
cmd += '--H5file=' + h5 + ' --outfile=plotlosoto%s/%s_nolosoto.png' % (ms,outplotname)
print(cmd)
os.system(cmd)
return
def runaoflagger(mslist):
for ms in mslist:
cmd = 'aoflagger ' + ms
os.system(cmd)
return
def applycal(ms, inparmdblist, msincol='DATA',msoutcol='CORRECTED_DATA'):
# to allow both a list or a single file (string)
if not isinstance(inparmdblist,list):
inparmdblist = [inparmdblist]
cmd = 'DPPP numthreads='+ str(multiprocessing.cpu_count()) + ' msin=' + ms +' msout=. '
cmd +='msin.datacolumn=' + msincol + ' '
cmd += 'msout.datacolumn=' + msoutcol + ' msout.storagemanager=dysco '
count = 0
for parmdb in inparmdblist:
if fulljonesparmdb(parmdb):
cmd += 'ac' + str(count) +'.parmdb='+parmdb + ' '
cmd += 'ac' + str(count) +'.type=applycal '
cmd += 'ac' + str(count) +'.correction=fulljones '
cmd += 'ac' + str(count) +'.soltab=[phase000,amplitude000] '
count = count + 1
else:
H=tables.open_file(parmdb)
try:
phase = H.root.sol000.phase000.val[:]
cmd += 'ac' + str(count) +'.parmdb='+parmdb + ' '
cmd += 'ac' + str(count) +'.type=applycal '
cmd += 'ac' + str(count) +'.correction=phase000 '
count = count + 1
except:
pass
try:
phase = H.root.sol000.tec000.val[:]
cmd += 'ac' + str(count) +'.parmdb='+parmdb + ' '
cmd += 'ac' + str(count) +'.type=applycal '
cmd += 'ac' + str(count) +'.correction=tec000 '
count = count + 1
except:
pass
try:
phase = H.root.sol000.rotation000.val[:]
cmd += 'ac' + str(count) +'.parmdb='+parmdb + ' '
cmd += 'ac' + str(count) +'.type=applycal '
cmd += 'ac' + str(count) +'.correction=rotation000 '
count = count + 1
except:
pass
try:
phase = H.root.sol000.amplitude000.val[:]
cmd += 'ac' + str(count) +'.parmdb='+parmdb + ' '
cmd += 'ac' + str(count) +'.type=applycal '
cmd += 'ac' + str(count) +'.correction=amplitude000 '
count = count + 1
except:
pass
H.close()
if count < 1:
print('Something went wrong, cannot build the applycal command. H5 file is valid?')
sys.exit(1)
# build the steps command
cmd += 'steps=['
for i in range(count):
cmd += 'ac'+ str(i)
if i < count-1: # to avoid last comma in the steps list
cmd += ','
cmd += ']'
print('DPPP applycal:', cmd)
os.system(cmd)
return
def inputchecker(args):
if args['ionfactor'] <= 0.0:
print('BLsmooth ionfactor needs to be positive')
sys.exit(1)
if args['ionfactor'] > 10.0:
print('BLsmooth ionfactor is way too high')
sys.exit(1)
if not os.path.isfile('lib_multiproc.py'):
print('Cannot find lib_multiproc.py, file does not exist, use --helperscriptspath')
sys.exit(1)
if not os.path.isfile('h5_merger.py'):
print('Cannot find h5_merger.py, file does not exist, use --helperscriptspath')
sys.exit(1)
if not os.path.isfile('plot_tecandphase.py'):
print('Cannot find plot_tecandphase.py, file does not exist, use --helperscriptspath')
sys.exit(1)
if not os.path.isfile('lin2circ.py'):
print('Cannot find lin2circ.py, file does not exist, use --helperscriptspath')
sys.exit(1)
if not os.path.isfile('BLsmooth.py'):
print('Cannot find BLsmooth.py, file does not exist, use --helperscriptspath')
sys.exit(1)
if args['phaseshiftbox'] != None:
if not os.path.isfile(args['phaseshiftbox']):
print('Cannot find:',args['phaseshiftbox'])
sys.exit(1)
if not args['no_beamcor'] and args['idg']:
print('beamcor=True and IDG=True is not possible')
sys.exit(1)
for antennaconstraint in args['antennaconstraint_list']:
if antennaconstraint not in ['superterp', 'coreandfirstremotes','core', 'remote',\
'all', 'international', 'alldutch', 'core-remote','coreandallbutmostdistantremotes'] \
and antennaconstraint != None:
print('Invalid input, antennaconstraint can only be core, superterp, coreandfirstremotes, remote, alldutch, international, or all')
sys.exit(1)
for soltype in args['soltype_list']:
if soltype not in ['complexgain','scalarcomplexgain','scalaramplitude','amplitudeonly', 'phaseonly',\
'fulljones', 'rotation', 'rotation+diagonal','tec','tecandphase','scalarphase',\
'scalarphasediff','scalarphasediffFR' , 'phaseonly_phmin', 'rotation_phmin', 'tec_phmin',\
'tecandphase_phmin','scalarphase_phmin','scalarphase_slope','phaseonly_slope']:
print('Invalid soltype input')
sys.exit(1)
if args['boxfile'] != None:
if not (os.path.isfile(args['boxfile'])):
print('Cannot find boxfile, file does not exist')
sys.exit(1)
if args['fitsmask'] != None:
if not (os.path.isfile(args['fitsmask'])):
print('Cannot find fitsmask, file does not exist')
sys.exit(1)
if args['skymodel'] != None:
if not (os.path.isfile(args['skymodel'])) and not (os.path.isdir(args['skymodel'])):
print('Cannot find skymodel, file does not exist')
sys.exit(1)
if args['docircular'] and args['dolinear']:
print('Conflicting input, docircular and dolinear used')
sys.exit(1)
if which('DPPP') == None:
print('Cannot find DPPP, forgot to source lofarinit.[c]sh?')
sys.exit(1)
# Check boxfile and imsize settings
if args['boxfile'] == None and args['imsize'] == None:
print('Incomplete input detected, either boxfile or imsize is required')
sys.exit(1)
if args['boxfile'] != None and args['imsize'] != None:
print('Wrong input detected, both boxfile and imsize are set')
sys.exit(1)
if args['imager'] not in ['DDFACET', 'WSCLEAN']:
print('Wrong input detected for option --imager, should be DDFACET or WSCLEAN')
sys.exit(1)
if args['phaseupstations'] != None:
if args['phaseupstations'] not in ['core', 'superterp']:
print('Wrong input detected for option --phaseupstations, should be core or superterp')
sys.exit(1)
if args['soltypecycles_list'][0] != 0:
print('Wrong input detected for option --soltypecycles-list should always start with 0')
sys.exit(1)
if len(args['soltypecycles_list']) != len(args['soltype_list']):
print('Wrong input detected, length soltypecycles-list does not match that of soltype-list')
sys.exit(1)
for soltype_id, soltype in enumerate(args['soltype_list']):
wronginput = False
if soltype in ['tecandphase', 'tec', 'tec_phmin', 'tecandphase_phmin']:
try: # in smoothnessconstraint_list is not filled by the user
if args['smoothnessconstraint_list'][soltype_id] > 0.0:
print('smoothnessconstraint should be 0.0 for a tec-like solve')
wronginput = True
except:
pass
if wronginput:
sys.exit(1)
for smoothnessconstraint in args['smoothnessconstraint_list']:
if smoothnessconstraint < 0.0:
print('Smoothnessconstraint must be equal or larger than 0.0')
sys.exit(1)
for smoothnessreffrequency in args['smoothnessreffrequency_list']:
if smoothnessreffrequency < 0.0:
print('Smoothnessreffrequency must be equal or larger than 0.0')
sys.exit(1)
if (args['skymodel'] != None) and (args['skymodelpointsource']) !=None:
print('Wrong input, you cannot use a separate skymodel file and then also set skymodelpointsource')
sys.exit(1)
if (args['skymodelpointsource'] != None):
if (args['skymodelpointsource'] <= 0.0):
print('Wrong input, flux density provided for skymodelpointsource is <= 0.0')
sys.exit(1)
if (args['msinnchan'] != None):
if (args['msinnchan'] <= 0):
print('Wrong input for msinnchan, must be larger than zero')
sys.exit(1)
if (args['msinntimes'] != None):
if (args['msinntimes'] <= 1):
print('Wrong input for msinntimes, must be larger than 1')
sys.exit(1)
if (args['skymodelpointsource'] != None) and (args['predictskywithbeam']):
print('Combination of skymodelpointsource and predictskywithbeam not supported')
print('Provide a skymodel file to predict the sky with the beam')
sys.exit(1)
if (args['wscleanskymodel'] != None) and (args['skymodelpointsource']) !=None:
print('Wrong input, you cannot use a wscleanskymodel and then also set skymodelpointsource')
sys.exit(1)
if (args['wscleanskymodel'] != None) and (args['skymodel']) !=None:
print('Wrong input, you cannot use a wscleanskymodel and then also set skymodel')
sys.exit(1)
if (args['wscleanskymodel'] != None) and (args['predictskywithbeam']):
print('Combination of wscleanskymodel and predictskywithbeam not supported')
print('Provide a skymodel component file to predict the sky with the beam')
sys.exit(1)
if (args['wscleanskymodel'] != None) and (args['imager'] == 'DDFACET'):
print('Combination of wscleanskymodel and DDFACET as an imager is not supported')
sys.exit(1)
if (args['wscleanskymodel'] != None):
if len(glob.glob(args['wscleanskymodel'] + '-????-model.fits')) < 2:
print('Not enough WSClean channel model images found')
print(glob.glob(args['wscleanskymodel'] + '-????-model.fits'))
sys.exit(1)
if (args['wscleanskymodel'].find('/') != -1):
print('wscleanskymodel contains a slash, not allowed, needs to be in pwd')
sys.exit(1)
if (args['wscleanskymodel'].find('..') != -1):
print('wscleanskymodel contains .., not allowed, needs to be in pwd')
sys.exit(1)
return
def get_uvwmax(ms):
t = pt.table(ms)
uvw = t.getcol('UVW')
ssq = np.sqrt(np.sum(uvw**2, axis=1))
print(uvw.shape)
t.close()
return np.max(ssq)
def makeBBSmodelforTGSS(boxfile=None, fitsimage=None, pixelscale=None, imsize=None, ms=None):
tgsspixsize = 6.2
if boxfile == None and imsize == None:
print('Wring input detected, boxfile or imsize needs to be set')
sys.exit()
if boxfile != None:
r = pyregion.open(boxfile)
if len(r[:]) > 1:
print('Composite region file, not allowed')
sys.exit()
phasecenter = getregionboxcenter(boxfile)
phasecenterc = phasecenter.replace('deg','')
xs = np.ceil((r[0].coord_list[2])*3600./tgsspixsize)
ys = np.ceil((r[0].coord_list[3])*3600./tgsspixsize)
else:
t2 = pt.table(ms + '::FIELD')
phasedir = t2.getcol('PHASE_DIR').squeeze()
t2.close()
phasecenterc = ('{:12.8f}'.format(180.*np.mod(phasedir[0], 2.*np.pi)/np.pi) + ',' + '{:12.8f}'.format(180.*phasedir[1]/np.pi)).replace(' ','')
#phasecenterc = str() + ', ' + str()
xs = np.ceil(imsize*pixelscale/tgsspixsize)
ys = np.ceil(imsize*pixelscale/tgsspixsize)
print('TGSS imsize:', xs)
print('TGSS image center:', phasecenterc)
logger.info('TGSS imsize:' + str(xs))
logger.info('TGSS image center:' + str(phasecenterc))
#sys.exit()
if fitsimage == None:
filename = SkyView.get_image_list(position=phasecenterc,survey='TGSS ADR1', pixels=np.int(xs), cache=False)
print(filename)
if os.path.isfile(filename[0].split('/')[-1]):
os.system('rm -f ' + filename[0].split('/')[-1])
time.sleep(10)
os.system('wget ' + filename[0])
filename = filename[0].split('/')[-1]
print(filename)
else:
filename = fitsimage
img = bdsf.process_image(filename,mean_map='zero', rms_map=True, rms_box = (100,10), \
frequency=150e6, beam=(25./3600,25./3600,0.0) )
img.write_catalog(format='bbs', bbs_patches='single', outfile='tgss.skymodel', clobber=True)
#bbsmodel = 'bla.skymodel'
del img
return 'tgss.skymodel'
def getregionboxcenter(regionfile, standardbox=True):
"""
Extract box center of a DS9 box region.
Input is regionfile Return NDPPP compatible string for phasecenter shifting
"""
r = pyregion.open(regionfile)
if len(r[:]) > 1:
print('Only one region can be specified, your file contains', len(r[:]))
sys.exit()
if r[0].name != 'box':
print('Only box region supported')
sys.exit()
ra = r[0].coord_list[0]
dec = r[0].coord_list[1]
boxsizex = r[0].coord_list[2]
boxsizey = r[0].coord_list[3]
angle = r[0].coord_list[4]
if standardbox:
if boxsizex != boxsizey:
print('Only a square box region supported, you have these sizes:', boxsizex, boxsizey)
sys.exit()
if np.abs(angle) > 1:
print('Only normally oriented sqaure boxes are supported, your region is oriented under angle:', angle)
sys.exit()
regioncenter = ('{:12.8f}'.format(ra) + 'deg,' + '{:12.8f}'.format(dec) + 'deg').replace(' ', '')
return regioncenter
def bandwidthsmearing(chanw, freq, imsize, verbose=True):
R = (chanw/freq)*(imsize/6.) # asume we have used 3 pixels per beam
if verbose:
print('R value for bandwidth smearing is:', R)
logger.info('R value for bandwidth smearing is: ' + str(R))
if R > 1.:
print('Warning, try to increase your frequency resolution, or lower imsize, to reduce the R value below 1')
logger.warning('Warning, try to increase your frequency resolution, or lower imsize, to reduce the R value below 1')
return R
def number_freqchan_h5(h5parm):
'''
Function to get the number of freqcencies in H5 solution file
Input: H5 file
Return: Number of freqcencies in the H5 file
'''