forked from rvweeren/lofar_facet_selfcal
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathfacetselfcal.py
5148 lines (4280 loc) · 221 KB
/
facetselfcal.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
# normamps full jones, deal with solnorm on crosshands only? currently normaps not used for fulljones
# restart with updated soltype_list?
#('selfcalcycle, soltypenumber', 10, 2)
#Traceback (most recent call last):
# File "/net/rijn/data2/rvweeren/LoTSS_ClusterCAL/facetselfcal.py", line 4955, in <module>
# main()
# File "/net/rijn/data2/rvweeren/LoTSS_ClusterCAL/facetselfcal.py", line 4895, in main
# docircular=args['docircular'])
# File "/net/rijn/data2/rvweeren/LoTSS_ClusterCAL/facetselfcal.py", line 3648, in calibrateandapplycal
# print(selfcalcycle,soltypecycles_list[soltypenumber+1][msnumber])
#IndexError: list index out of range
# implement idea of phase detrending.
# do not use os.system for DP3/WSClean to catch errors properly
# decrease niter if multiscale is triggered, smart move?
# h5 linear to circular solution conversion
# do not predict sky second time in pertubation solve?
# to do: log command into the FITS header
# avg to units of Hertz and seconds? (for input data that hass different averaging) https://stackoverflow.com/questions/66909044/argparse-argument-may-be-str-or-int-and-the-simplest-way-to-handle-it
# BLsmooth not for gain solves opttion
# BLsmooth constant smooth for gain solves
# only trigger HBA upper band selection for sources outside the FWHM?
# 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 facetselfal.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]" --soltypelist="['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, re
from astropy.io import fits
import astropy.units as units
from astropy.coordinates import SkyCoord
import astropy.stats
import astropy
from astroquery.skyview import SkyView
import casacore.tables as pt
import os.path
from losoto import h5parm
import bdsf
import pyregion
import argparse
import pickle
import magic
import fnmatch
import tables
from astropy.io import ascii
import multiprocessing
import ast
from lofar.stationresponse import stationresponse
from itertools import product
import subprocess
import matplotlib.pyplot as plt
from astropy.wcs import WCS
os.environ["HDF5_USE_FILE_LOCKING"] = "FALSE" # for NFS mounted disks
#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 fix_bad_weightspectrum(mslist, clipvalue):
for ms in mslist:
print('Clipping WEIGHT_SPECTRUM manually', ms, clipvalue)
t = pt.table(ms, readonly=False)
ws = t.getcol('WEIGHT_SPECTRUM')
idx = np.where(ws > clipvalue)
ws[idx] = 0.0
t.putcol('WEIGHT_SPECTRUM', ws)
t.close()
return
def format_solint(solint, ms):
if str(solint).isdigit():
return str(solint)
else:
t = pt.table(ms, readonly=True, ack=False)
time = np.unique(t.getcol('TIME'))
tint = np.abs(time[1]-time[0])
t.close()
if 's' in solint:
solintout = int(np.rint(float(re.findall(r'[+-]?\d+(?:\.\d+)?',solint)[0])/tint))
if 'm' in solint:
solintout = int(np.rint(60.*float(re.findall(r'[+-]?\d+(?:\.\d+)?',solint)[0])/tint))
if 'h' in solint:
solintout = int(np.rint(3600.*float(re.findall(r'[+-]?\d+(?:\.\d+)?',solint)[0])/tint))
if solintout < 1:
solintout = 1
return str(solintout)
def FFTdelayfinder(h5, refant):
from scipy.fftpack import fft, fftfreq
H = tables.open_file(h5)
upsample_factor = 10
# reference to refant
refant_idx = np.where(H.root.sol000.phase000.ant[:] == refant)
phase = H.root.sol000.phase000.val[:]
phasen = phase - phase[:,:,refant_idx[0],:]
phasecomplex = np.exp(phasen *1j)
freq = H.root.sol000.phase000.freq[:]
timeaxis = H.root.sol000.phase000.time[:]
timeaxis = timeaxis - np.min(timeaxis)
delayaxis = fftfreq(upsample_factor*freq.size, d=np.abs(freq[1]-freq[0])/float(upsample_factor))
for ant_id,ant in enumerate(H.root.sol000.phase000.ant[:]):
delay = 0.0*H.root.sol000.phase000.time[:]
print('FFT delay finding for:', ant)
for time_id, time in enumerate(H.root.sol000.phase000.time[:]):
delay[time_id] = delayaxis[np.argmax(np.abs(fft(phasecomplex[time_id,:, ant_id, 0], n=upsample_factor*len(freq))))]
plt.plot(timeaxis/3600.,delay*1e9)
plt.ylim(-2e-6*1e9,2e-6*1e9)
plt.ylabel('Delay [ns]')
plt.xlabel('Time [hr]')
#plt.title(ant)
plt.show()
H.close()
return
def check_strlist_or_intlist(argin):
'''
check if argument is list of integers or list of strings with correct formatting
'''
# check if input is a list and make proper list format
arg = ast.literal_eval(argin)
if type(arg) is not list:
raise argparse.ArgumentTypeError("Argument \"%s\" is not a list" % (s))
# check for integer list
if all([isinstance(item, int) for item in arg]):
if np.min(arg) < 1:
raise argparse.ArgumentTypeError("solint_list cannot contain values smaller than 1")
else:
return arg
# so not an integer list, so now check for string list
if all([isinstance(item, str) for item in arg]):
# check if string contains numbers
for item2 in arg:
#print(item2)
if not any([ch.isdigit() for ch in item2]):
raise argparse.ArgumentTypeError("solint_list needs to contain some number characters, not only units")
# check in the number in there is smaller than 1
#print(re.findall(r'[+-]?\d+(?:\.\d+)?',item2)[0])
if float(re.findall(r'[+-]?\d+(?:\.\d+)?',item2)[0]) <= 0.0:
raise argparse.ArgumentTypeError("numbers in solint_list cannot be smaller than zero")
#check if string contains proper time formatting
if ('hr' in item2) or ('min' in item2) or ('sec' in item2) or ('h' in item2) or ('m' in item2) or ('s' in item2) or ('hour' in item2) or ('minute' in item2) or ('second' in item2):
pass
else:
raise argparse.ArgumentTypeError("solint_list needs to have proper time formatting (h(r), m(in), s(ec))")
#sys.exit()
return arg
else:
raise argparse.ArgumentTypeError("solint_list must be a list of positive integers or a list of properly formatted strings")
def compute_distance_to_pointingcenter(msname, HBAorLBA='HBA'):
'''
Compute distance to the pointing center, mainly useful for international baseline observation to check of the delay calibrator is not too far away
'''
if HBAorLBA == 'HBA':
warn_distance = 1.25
if HBAorLBA == 'LBA':
warn_distance = 3.0
field_table = pt.table(msname + '::FIELD')
direction = field_table.getcol('PHASE_DIR').squeeze()
ref_direction = field_table.getcol('REFERENCE_DIR').squeeze()
field_table.close()
c1 = SkyCoord(direction[0]*units.radian, direction[1]*units.radian, frame='icrs')
c2 = SkyCoord(ref_direction[0]*units.radian, ref_direction[1]*units.radian, frame='icrs')
seperation = c1.separation(c2).to(units.deg)
print('Distance to pointing center', seperation)
logger.info('Distance to pointing center:' + str (seperation))
if seperation.value > warn_distance:
print('Warning: you are trying to selfcal a source far from the pointing, this is probably going to produce bad results')
logger.warning('Warning: you are trying to selfcal a source far from the pointing, this is probably going to produce bad results')
return
def remove_flagged_data_startend(mslist):
taql = 'taql'
mslistout = []
for ms in mslist:
t=pt.table(ms, readonly=True, ack=False)
alltimes = t.getcol('TIME')
alltimes = np.unique(alltimes)
newt=pt.taql('select TIME from $t where FLAG[0,0]=False')
time=newt.getcol('TIME')
time=np.unique(time)
print('There are',len(alltimes),'times')
print('There are',len(time),'unique unflagged times')
print('First unflagged time',np.min(time))
print('Last unflagged time',np.max(time))
goodstartid = np.where(alltimes == np.min(time))[0][0]
goodendid = np.where(alltimes == np.max(time))[0][0] + 1
print(goodstartid,goodendid)
t.close()
if (goodstartid != 0) or (goodendid != len(alltimes)):
msout = ms + '.cut'
if os.path.isdir(msout):
os.system('rm -rf ' + msout)
cmd = taql + " ' select from " + ms + " where TIME in (select distinct TIME from " + ms
cmd+= " offset " + str(goodstartid)
cmd+= " limit " + str((goodendid-goodstartid)) +") giving "
cmd+= msout + " as plain'"
print(cmd)
os.system(cmd)
mslistout.append(msout)
else:
mslistout.append(ms)
return mslistout
#from https://jckantor.github.io/cbe61622/A.02-Downloading_Python_source_files_from_github.html
def check_code_is_uptodate():
import filecmp
url = "https://raw.githubusercontent.com/jurjen93/lofar_helpers/master/h5_merger.py"
try:
result = subprocess.run(["wget", "--no-cache", "--backups=1", url, "--output-document=tmpfile"], stderr=subprocess.PIPE, stdout=subprocess.PIPE)
print(result.stderr.decode("utf-8"))
except: # for Pythoon versions 3.5 and lower
os.system("wget --no-cache --backups=1 " + url + " --output-document=tmpfile")
if not filecmp.cmp('h5_merger.py', 'tmpfile'):
print('Warning, you are using an old version of h5_merger.py')
print('Download the latest version from https://github.com/jurjen93/lofar_helpers')
logger.warning('Using an old h5_merger.py version, download the latest one from https://github.com/jurjen93/lofar_helpers')
time.sleep(1)
with open('h5_merger.py') as f:
if not 'propagate_flags' in f.read():
print("Update h5_merger, this version misses the propagate_flags option")
sys.exit()
return
def force_close(h5):
"""Close indivdual HDF5 file by force"""
h5s = list(tables.file._open_files._handlers)
for h in h5s:
if h.filename == h5:
logger.warning('force_close: Closed --> ' + h5+'\n')
print('Forced (!) closing', h5)
h.close()
return
#sys.stderr.write(h5 + ' not found\n')
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 preapplydelay(H5filelist, mslist, applydelaytype, dysco=True):
for ms in mslist:
parmdb = time_match_mstoH5(H5filelist, ms)
# from LINEAR to CIRCULAR
if applydelaytype == 'circular':
scriptn = 'python lin2circ.py'
cmdlin2circ = scriptn + ' -i ' + ms + ' --column=DATA --outcol=DATA_CIRC'
if not dysco:
cmdlin2circ += ' --nodysco'
os.system(cmdlin2circ)
# APPLY solutions
applycal(ms, parmdb, msincol='DATA_CIRC',msoutcol='CORRECTED_DATA', dysco=dysco)
else:
applycal(ms, parmdb, msincol='DATA',msoutcol='CORRECTED_DATA', dysco=dysco)
# from CIRCULAR to LINEAR
if applydelaytype == 'circular':
cmdlin2circ = scriptn + ' -i ' + ms + ' --column=CORRECTED_DATA --lincol=DATA --back'
if not dysco:
cmdlin2circ += ' --nodysco'
os.system(cmdlin2circ)
else:
os.system("taql 'update " + ms + " set DATA=CORRECTED_DATA'")
return
def preapply(H5filelist, mslist, updateDATA=True, dysco=True):
for ms in mslist:
parmdb = time_match_mstoH5(H5filelist, ms)
applycal(ms, parmdb, msincol='DATA',msoutcol='CORRECTED_DATA', dysco=dysco)
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, dysco=True):
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)
if dysco:
newdmi['NAME'] = 'Dysco' + outcol
else:
newdmi['NAME'] = 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', dysco=True):
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)
if dysco:
newdmi['NAME'] = 'Dysco' + outcol
else:
newdmi['NAME'] = 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', dysco=True):
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)
if dysco:
newdmi['NAME'] = 'Dysco' + outcol
else:
newdmi['NAME'] = 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('DP3 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', start=0, dysco=True):
msoutlist = []
for ms in msinlist:
msout=ms + '.phaseup'
msoutlist.append(msout)
cmd = "DP3 msin=" + ms + " steps=[add,filter] msout.writefullresflag=False "
cmd += "msout=" + msout + " msin.datacolumn=" + datacolumn + " "
cmd += "filter.type=filter filter.remove=True "
if dysco:
cmd += "msout.storagemanager=dysco "
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]*&&*' "
if start == 0: # only phaseup if start selfcal from cycle 0, so skip for a restart
if os.path.isdir(msout):
os.system('rm -rf ' + msout)
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 compute_markersize(H5file):
ntimes = ntimesH5(H5file)
markersize = 2
if ntimes < 450:
markersize = 4
if ntimes < 100:
markersize = 10
if ntimes < 50:
markersize = 15
return markersize
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:
try:
times= H.root.sol000.tec000.time[:]
except:
try:
times= H.root.sol000.rotationmeasure000.time[:]
except:
try:
times= H.root.sol000.rotation000.time[:]
except:
print('No amplitude000,phase000, tec000, rotation000, or rotationmeasure000 solutions 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, makecopy=False, delaycal=False, timeresolution='32', freqresolution='195.3125kHz', dysco=True):
# 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
if makecopy:
msout = ms + '.copy'
else:
msout = ms + '.avg'
cmd = 'DP3 msin=' + ms + ' av.type=averager '
cmd += 'msout='+ msout + ' msin.weightcolumn=WEIGHT_SPECTRUM msout.writefullresflag=False '
if dysco:
cmd += 'msout.storagemanager=dysco '
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 = 'DP3 msin=' + ms + ' steps=[av] av.type=averager '
if dysco:
cmd+= ' msout.storagemanager=dysco '
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 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', msout='.', dysco=True):
# to allow both a list or a single file (string)
if not isinstance(inparmdblist,list):
inparmdblist = [inparmdblist]
cmd = 'DP3 numthreads='+ str(multiprocessing.cpu_count()) + ' msin=' + ms
cmd += ' msout=' + msout + ' '
cmd += 'msin.datacolumn=' + msincol + ' '
if msout == '.':
cmd += 'msout.datacolumn=' + msoutcol + ' '
if dysco:
cmd += '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=[amplitude000,phase000] '
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('DP3 applycal:', cmd)
os.system(cmd)
return
def inputchecker(args):
for ms_id, ms in enumerate(args['ms']):
if ms.find('/') != -1:
print('All ms need to be local, no "/" are allowed in ms name')
sys.exit(1)
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')