-
Notifications
You must be signed in to change notification settings - Fork 8
/
facetselfcal.py
11748 lines (10065 loc) · 524 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
# auto update channels out and fitspectralpol for high dynamic range
#h5_merger.merge_h5(h5_out=outparmdb,h5_tables=parmdb,add_directions=sourcedir_removed.tolist(),propagate_flags=False) Needs to be propagate_flags to be fully correct, this is a h5_merger issue
# check that MODEL_DATA_DD etc XY,YX are set to zero/or clean if wsclean predicts are used for Stokes I/dual
# time, timefreq, freq med/avg steps (via losoto)
# BDA step DP3
# compression: blosc2
# useful? https://learning-python.com/thumbspage.html
# bdsf still steals the logger https://github.com/lofar-astron/PyBDSF/issues/176
# add html summary overview
# Stacking check that freq and time axes are identical
# Add multi-run stacking
# scalaraphasediff solve WEIGHT_SPECTRUM_PM should not be dysco compressed! Or not update weights there...
# BLsmooth cannot smooth more than bandwidth and time smearing allows, not checked now
# bug related to sources-pb.txt in facet imaging being empty if no -apply-beam is used
# fix RR-LL referencing for flaged solutions, check for possible superterp reference station
# put all fits images in images folder, all solutions in solutions folder? to reduce clutter
# phase detrending.
# log command into the FITS header
# BLsmooth constant smooth for gain solves
# stop selfcal based on some metrics
# use scalarphasediff sols stats for solints? test amplitude stats as well
# parallel solving with DP3, given that DP3 often does not use all cores?
# uvmin, uvmax, uvminim, uvmaxim per ms per soltype
#antidx = 0
#pt.taql("select ANTENNA1,ANTENNA2,gntrue(FLAG)/(gntrue(FLAG)+gnfalse(FLAG)) as NFLAG from L656064_129_164MHz_uv_pre-cal.concat.ms WHERE (ANTENNA1=={:d} OR ANTENNA2=={:d}) AND ANTENNA1!=ANTENNA2".format(antidx, antidx)).getcol('NFLAG')
# example:
# python facetselfal.py -b box_18.reg --forwidefield --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
# Standard library imports
import argparse
import ast
import configparser
import fnmatch
import glob
import logging
import multiprocessing
import os
import os.path
import pickle
import re
import subprocess
import sys
import time
from itertools import product
from itertools import groupby
# Third party imports
import astropy
import astropy.stats
import astropy.units as units
import bdsf
import casacore.tables as pt
import losoto
import losoto.lib_operations
import matplotlib
import matplotlib.pyplot as plt
import numpy as np
import pyregion
import tables
import scipy.special
from astropy.io import fits
from astropy.wcs import WCS
from astropy.io import ascii
from astropy.coordinates import AltAz, EarthLocation, ITRS, SkyCoord
#from astropy.coordinates import angular_separation
from astropy.time import Time
from astroquery.skyview import SkyView
from losoto import h5parm
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)
try:
import everybeam
except ImportError:
logger.warning('Failed to import EveryBeam, functionality will not be available.')
matplotlib.use('Agg')
# For NFS mounted disks
os.environ["HDF5_USE_FILE_LOCKING"] = "FALSE"
# from astropy.utils.data import clear_download_cache
# clear_download_cache()
def fix_h5(h5_list):
'''
Fix for h5_merger that cannot handle multi-dir merges where both h5 with and without pol-axis are included
'''
import h5_merger
for h5file in h5_list:
outparmdb = h5file.replace('.h5', '.tmp.h5')
if os.path.isfile(outparmdb):
os.system('rm -f ' + outparmdb)
# copy to get a clean h5 with standard dimensions
h5_merger.merge_h5(h5_out=outparmdb,h5_tables=h5file,propagate_flags=True)
# overwrite original
os.system('cp -f ' + outparmdb + ' ' + h5file )
os.system('rm -f ' + outparmdb)
return
def update_fitspectralpol(args):
if args['update_fitspectralpol']:
args['fitspectralpol'] = set_fitspectralpol(args['channelsout'])
return args['fitspectralpol']
def update_channelsout(args, selfcalcycle, mslist):
if args['update_channelsout']:
t = pt.table(mslist[0] + '/OBSERVATION', ack=False)
telescope = t.getcol('TELESCOPE_NAME')[0]
t.close()
# set stackstr
for msim_id, mslistim in enumerate(nested_mslistforimaging(mslist, stack=args['stack'])):
if args['stack']:
stackstr= '_stack' + str(msim_id).zfill(2)
else:
stackstr='' # empty string
# set imagename
if args['imager'] == 'WSCLEAN':
if args['idg']:
imagename = args['imagename'] + str(selfcalcycle).zfill(3) + stackstr + '-MFS-image.fits'
else:
imagename = args['imagename'] + str(selfcalcycle).zfill(3) + stackstr + '-MFS-image.fits'
if args['imager'] == 'DDFACET':
imagename = args['imagename'] + str(selfcalcycle).zfill(3) + stackstr + '.app.restored.fits'
if args['channelsout'] == 1: # strip MFS from name if no channels images present
imagename = imagename.replace('-MFS', '').replace('-I','')
dr = get_image_dynamicrange(imagename)
if dr > 1500 and telescope == 'LOFAR':
args['channelsout'] = set_channelsout(mslist, factor=2)
if dr > 3000 and telescope == 'LOFAR':
args['channelsout'] = set_channelsout(mslist, factor=3)
if dr > 6000 and telescope == 'LOFAR':
args['channelsout'] = set_channelsout(mslist, factor=4)
if dr > 30000 and telescope == 'MeerKAT':
args['channelsout'] = set_channelsout(mslist, factor=1.5)
if dr > 60000 and telescope == 'MeerKAT':
args['channelsout'] = set_channelsout(mslist, factor=2)
if dr > 90000 and telescope == 'MeerKAT':
args['channelsout'] = set_channelsout(mslist, factor=3)
return args['channelsout']
def round_up_to_even(number):
return int(np.ceil(number / 2.) * 2)
def set_channelsout(mslist, factor=1):
t = pt.table(mslist[0] + '/OBSERVATION', ack=False)
telescope = t.getcol('TELESCOPE_NAME')[0]
t.close()
f_bw = get_fractional_bandwidth(mslist)
if telescope == 'LOFAR':
channelsout = round_up_to_even(f_bw*12*factor)
elif telescope == 'MeerKAT':
channelsout = round_up_to_even(f_bw*16*factor)
else:
channelsout = round_up_to_even(f_bw*12*factor)
return channelsout
def set_fitspectralpol(channelsout):
if channelsout == 1:
fitspectralpol = 1
elif channelsout == 2:
fitspectralpol = 2
elif channelsout <= 6:
fitspectralpol = 3
elif channelsout <= 8:
fitspectralpol = 5
elif channelsout <= 12:
fitspectralpol = 7
elif channelsout > 12 :
fitspectralpol = 9
else:
print('channelsout', channelsout)
raise Exception('channelsout has an invalid value')
return fitspectralpol
def get_fractional_bandwidth(mslist):
'''
Compute fractional bandwidth of a list of MS
input mslist: list of ms
return fractional bandwidth
'''
freqaxis = []
for ms in mslist:
t = pt.table(ms + '/SPECTRAL_WINDOW', readonly=True, ack=False)
freq = t.getcol('CHAN_FREQ')[0]
t.close()
freqaxis.append(freq)
freqaxis = np.hstack(freqaxis)
f_bw = (np.max(freqaxis) - np.min(freqaxis))/np.min(freqaxis)
if f_bw == 0.0: # single channel data
t = pt.table(mslist[0] + '/SPECTRAL_WINDOW', readonly=True, ack=False) # just take the first and assume this is ok
f_bw = t.getcol('TOTAL_BANDWIDTH')[0]/np.min(freqaxis)
t.close()
return f_bw
def MeerKAT_antconstraint(antfile='MeerKATlayout.csv', ctype='all'):
if ctype not in ['core','remote','all']:
print('Wrong input detected, ctype needs to be in core,remote,or all')
sys.exit()
data = ascii.read(antfile,delimiter=';',header_start=0)
distance = np.sqrt(data['East']**2+ data['North']**2 + data['Up']**2)
#print(distance
idx_core = np.where(distance <= 1000.)
idx_rs = np.where(distance > 1000.)
if ctype == 'core':
return data['Antenna'][idx_core].tolist()
if ctype == 'remote':
return data['Antenna'][idx_rs].tolist()
if ctype == 'all':
return data['Antenna'].tolist()
def remove_column_ms(mslist, colname):
'''
Remove a column from a Measurement Sets
mslist (str/list): input ms(list)
colname: column that will be removed
'''
if type(mslist) == list:
for ms in mslist:
ts = pt.table(ms, readonly=False, ack=False)
ts.removecols([colname])
ts.close()
else:
ts = pt.table(mslist, readonly=False, ack=False)
ts.removecols([colname])
ts.close()
return
def update_sourcedirname_h5_dde(h5, modeldatacolumns):
'''
Replace direction names in h5 with the modeldatacolumns names
'''
modeldatacolumns_outname = []
for mm_id, mm in enumerate(modeldatacolumns):
modeldatacolumns_outname.append('DIL' + str(mm_id).zfill(2)) # need a name that has only 5 characters because otherwise we cannot copy over the names
H = tables.open_file(h5,mode='a')
for direction_id, direction in enumerate(modeldatacolumns):
H.root.sol000.source[direction_id] = (modeldatacolumns[direction_id], H.root.sol000.source[direction_id]['dir'])
print(H.root.sol000.source[direction_id]['name'], modeldatacolumns[direction_id])
try:
H.root.sol000.phase000.dir[:] = modeldatacolumns_outname
print('Update direction names phase000',modeldatacolumns_outname)
except:
pass
try:
H.root.sol000.amplitude000.dir[:] = modeldatacolumns_outname
print('Update direction names amplitude000',modeldatacolumns_outname)
except:
pass
try:
H.root.sol000.tec000.dir[:] = modeldatacolumns_outname
print('Update direction names tec000',modeldatacolumns_outname)
except:
pass
try:
H.root.sol000.rotation000.dir[:] = modeldatacolumns_outname
print('Update direction names rotation000',modeldatacolumns_outname)
except:
pass
H.close()
print('Done fixing direction names')
return
def merge_splitted_h5_ordered(modeldatacolumnsin, parmdb_out, clean_up=False):
h5list_sols = []
for colid, coln in enumerate(modeldatacolumnsin):
h5list_sols.append('Dir' + str(colid).zfill(2) + '.h5')
print('These are the h5 that need merging:', h5list_sols)
if os.path.isfile(parmdb_out):
os.system('rm -f ' + parmdb_out)
f = open('facetdirections.p', 'rb')
sourcedir = pickle.load(f) # units are radian
f.close()
parmdb_merge_list = []
for direction in sourcedir:
print(direction)
c1 = SkyCoord(direction[0] * units.radian, direction[1] * units.radian, frame='icrs')
distance = 1e9
#print(c1)
for hsol in h5list_sols:
H5 = tables.open_file(hsol, mode='r')
dd = H5.root.sol000.source[:][0]
H5.close()
ra, dec = dd[1]
c2 = SkyCoord(ra * units.radian, dec * units.radian, frame='icrs')
angsep = c1.separation(c2).to(units.degree)
#print(c2)
#print(hsol, angsep.value, '[degree]')
if angsep.value < distance:
distance = angsep.value
matchging_h5 = hsol
parmdb_merge_list.append(matchging_h5)
print('separation direction entry and h5 entry is:', distance, matchging_h5)
assert abs(distance) < 0.00001 # there should always be a close to perfect match
import h5_merger
h5_merger.merge_h5(h5_out=parmdb_out,h5_tables=parmdb_merge_list,propagate_flags=True)
if clean_up:
for h5 in h5list_sols:
os.system('rm -f ' + h5)
return
def copy_over_solutions_from_skipped_directions(modeldatacolumnsin,id_kept):
'''
modeldatacolumnsin: all modeldatacolumns
id_kept: indices of the modeldatacolumns kept in the solve id_kept
'''
h5list_sols = []
h5list_empty = []
for colid, coln in enumerate(modeldatacolumnsin):
if colid >= len(id_kept):
h5list_empty.append('Dir' + str(colid).zfill(2) + '.h5')
else:
h5list_sols.append('Dir' + str(colid).zfill(2) + '.h5')
print('These h5 have solutions:', h5list_sols)
print('These h5 are empty:',h5list_empty)
# fill the empty directions (those that were removed and not solve) with the closest valid solutions
for h5 in h5list_empty:
hempty = tables.open_file(h5, mode='a')
direction = hempty.root.sol000.source[:][0]
ra, dec = direction[1]
c1 = SkyCoord(ra * units.radian, dec * units.radian, frame='icrs')
#print(c1)
distance = 1e9
for h5sol in h5list_sols:
hsol = tables.open_file(h5sol, mode='r')
directionsol = hsol.root.sol000.source[:][0]
rasol, decsol = directionsol[1]
c2 = SkyCoord(rasol * units.radian, decsol * units.radian, frame='icrs')
angsep = c1.separation(c2).to(units.degree)
#print(h5, h5sol, angsep.value, '[degree]')
if angsep.value < distance:
distance = angsep.value
matchging_h5 = h5sol
hsol.close()
print(h5 + ' needs solutions copied from ' + matchging_h5, distance)
# copy over the values
hmatch = tables.open_file(matchging_h5, mode='r')
try:
hempty.root.sol000.phase000.val[:] = np.copy(hmatch.root.sol000.phase000.val[:])
print('Copied over phase000')
except:
pass
try:
hempty.root.sol000.amplitude000.val[:] = np.copy(hmatch.root.sol000.amplitude000.val[:])
print('Copied over amplitude000')
except:
pass
try:
hempty.root.sol000.tec000.val[:] = np.copy(hmatch.root.sol000.tec000.val[:])
print('Copied over tec000')
except:
pass
try:
hempty.root.sol000.rotation000.val[:] = np.copy(hmatch.root.sol000.rotation000.val[:])
print('Copied over rotation000')
except:
pass
hmatch.close()
hempty.flush()
hempty.close()
return
def filter_baseline_str_removestations(stationlist):
fbaseline = "'"
for station_id, station in enumerate(stationlist):
fbaseline = fbaseline +"!" +station + "&&*"
if station_id+1 < len(stationlist):
fbaseline = fbaseline + ";"
return fbaseline + "'"
def return_antennas_highflaggingpercentage(ms, percentage=0.85):
### Find all antennas with more than 80% flagged data
print('Finding stations with a flagging percentage above ' + str(100*percentage) + ' ....')
from casacore.tables import taql
t = taql(""" SELECT antname, gsum(numflagged) AS numflagged, gsum(numvis) AS numvis,
gsum(numflagged)/gsum(numvis) as percflagged FROM [[ SELECT mscal.ant1name() AS antname, ntrue(FLAG) AS numflagged, count(FLAG) AS numvis FROM """ + ms + """ ],[ SELECT mscal.ant2name() AS antname, ntrue(FLAG) AS numflagged, count(FLAG) AS numvis FROM """ + ms + """ ] ] GROUP BY antname HAVING percflagged > """ + str(percentage) + """ """)
flaggedants = [ row["antname"] for row in t ]
print('Found:', flaggedants)
return flaggedants
def create_empty_fitsimage(ms, imsize, pixelsize, outfile):
'''
Create emtpy (zeros) FITS file with size imsize and pixelsize
Image center coincides with the phase center of the provided ms
'''
data = np.zeros((imsize, imsize))
w = WCS(naxis=2)
# what is the center pixel of the XY grid.
w.wcs.crpix = [imsize/2, imsize/2]
# coordinate of the pixel.
w.wcs.crval = grab_coord_MS(ms)
# the pixel scale
w.wcs.cdelt = np.array([pixelsize/3600., pixelsize/3600.])
# projection
w.wcs.ctype = ["RA---SIN", "DEC--SIN"]
# write the HDU object WITH THE HEADER
header = w.to_header()
hdu = fits.PrimaryHDU(data, header=header)
hdu.writeto(outfile, overwrite=True)
return
def copy_over_sourcedirection_h5(h5ref, h5):
'''
Replace source direction in h5 with the one in h5ref
'''
from overwrite_table import overwrite_table
Href = tables.open_file(h5ref, mode='r')
refsource = Href.root.sol000.source[:]
Href.close()
overwrite_table(h5, 'source', refsource)
return
def set_DDE_predict_skymodel_solve(wscleanskymodel):
if wscleanskymodel is not None:
return 'WSCLEAN'
else:
return 'DP3'
def getAntennas(ms):
"""
Return a list of antenna names
"""
t = pt.table(ms + "/ANTENNA", readonly=True, ack=False)
antennas = t.getcol('NAME')
t.close()
return antennas
def grab_coord_MS(MS):
"""
Read the coordinates of a field from one MS corresponding to the selection given in the parameters
Parameters
----------
MS : str
Full name (with path) to one MS of the field
Returns
-------
RA, Dec : "tuple"
coordinates of the field (RA, Dec in deg , J2000)
"""
# reading the coordinates ("position") from the MS
# NB: they are given in rad,rad (J2000)
[[[ra,dec]]] = pt.table(MS+'::FIELD', readonly=True, ack=False).getcol('PHASE_DIR')
# RA is stocked in the MS in [-pi;pi]
# => shift for the negative angles before the conversion to deg (so that RA in [0;2pi])
if ra<0:
ra=ra+2*np.pi
# convert radians to degrees
ra_deg = ra/np.pi*180.
dec_deg = dec/np.pi*180.
# and sending the coordinates in deg
return(ra_deg,dec_deg)
def getGSM(ms_input, SkymodelPath='gsm.skymodel', Radius="5.", DoDownload="Force", Source="GSM", targetname = "pointing", fluxlimit = None):
"""
Download the skymodel for the target field
Parameters
----------
ms_input : str
String from the list (map) of the target MSs
SkymodelPath : str
Full name (with path) to the skymodel; if YES is true, the skymodel will be downloaded here
Radius : string with float (default = "5.")
Radius for the TGSS/GSM cone search in degrees
DoDownload : str ("Force" or "True" or "False")
Download or not the TGSS skymodel or GSM.
"Force": download skymodel from TGSS or GSM, delete existing skymodel if needed.
"True" or "Yes": use existing skymodel file if it exists, download skymodel from
TGSS or GSM if it does not.
"False" or "No": Do not download skymodel, raise an exception if skymodel
file does not exist.
targetname : str
Give the patch a certain name, default: "pointing"
"""
import lsmtool
FileExists = os.path.isfile(SkymodelPath)
if (not FileExists and os.path.exists(SkymodelPath)):
raise ValueError("download_tgss_skymodel_target: Path: \"%s\" exists but is not a file!"%(SkymodelPath))
download_flag = False
#if not os.path.exists(os.path.dirname(SkymodelPath)):
# os.makedirs(os.path.dirname(SkymodelPath))
if DoDownload.upper() == "FORCE":
if FileExists:
os.remove(SkymodelPath)
download_flag = True
elif DoDownload.upper() == "TRUE" or DoDownload.upper() == "YES":
if FileExists:
print("USING the exising skymodel in "+ SkymodelPath)
return(0)
else:
download_flag = True
elif DoDownload.upper() == "FALSE" or DoDownload.upper() == "NO":
if FileExists:
print("USING the exising skymodel in "+ SkymodelPath)
return(0)
else:
raise ValueError("download_tgss_skymodel_target: Path: \"%s\" does not exist and skymodel download is disabled!"%(SkymodelPath))
# If we got here, then we are supposed to download the skymodel.
assert download_flag is True # Jaja, belts and suspenders...
print("DOWNLOADING skymodel for the target into "+ SkymodelPath)
# Reading a MS to find the coordinate (pyrap)
[RATar,DECTar]=grab_coord_MS(ms_input)
# Downloading the skymodel, skip after five tries
errorcode = 1
tries = 0
while errorcode != 0 and tries < 5:
if Source == 'TGSS':
errorcode = os.system("wget -O "+SkymodelPath+ " \'http://tgssadr.strw.leidenuniv.nl/cgi-bin/gsmv5.cgi?coord="+str(RATar)+","+str(DECTar)+"&radius="+str(Radius)+"&unit=deg&deconv=y\' ")
elif Source == 'GSM':
errorcode = os.system("wget -O "+SkymodelPath+ " \'https://lcs165.lofar.eu/cgi-bin/gsmv1.cgi?coord="+str(RATar)+","+str(DECTar)+"&radius="+str(Radius)+"&unit=deg&deconv=y\' ")
time.sleep(5)
tries += 1
if not os.path.isfile(SkymodelPath):
raise IOError("download_tgss_skymodel_target: Path: \"%s\" does not exist after trying to download the skymodel."%(SkymodelPath))
# Treat all sources as one group (direction)
skymodel = lsmtool.load(SkymodelPath)
if fluxlimit:
skymodel.remove('I<' + str(fluxlimit))
skymodel.group('single', root = targetname)
skymodel.write(clobber=True)
return SkymodelPath
def concat_ms_wsclean_facetimaging(mslist, h5list=None,concatms=True):
import h5_merger
keyfunct = lambda x: ' '.join(sorted(getAntennas(x)))
MSs_list = sorted(mslist, key=keyfunct) # needs to be sorted
groups = []
for k, g in groupby(MSs_list, keyfunct):
groups.append(list(g))
print(f"Found {len(groups)} groups of datasets with same antennas.")
for i, group in enumerate(groups, start=1):
antennas = ', '.join(getAntennas(group[0]))
print(f"WSClean MS group {i}: {group}")
print(f"List of antennas: {antennas}")
MSs_files_clean = []
H5s_files_clean = []
for g, group in enumerate(groups):
if os.path.isdir(f'wsclean_concat_{g}.ms') and concatms:
os.system(f'rm -rf wsclean_concat_{g}.ms')
if h5list is not None:
h5group = []
for ms in group:
h5group.append(time_match_mstoH5(h5list, ms))
print('------------------------------')
print('MS group and matched h5 group', group, h5group)
print('------------------------------')
if os.path.isfile(f'wsclean_concat_{g}.h5'):
os.system(f'rm -rf wsclean_concat_{g}.h5')
h5_merger.merge_h5(h5_out=f'wsclean_concat_{g}.h5', h5_tables=h5group, \
propagate_flags=True, time_concat=True)
H5s_files_clean.append(f'wsclean_concat_{g}.h5')
if concatms:
print(f'taql select from {group} giving wsclean_concat_{g}.ms as plain')
run(f'taql select from {group} giving wsclean_concat_{g}.ms as plain')
MSs_files_clean.append(f'wsclean_concat_{g}.ms')
#MSs_files_clean = ' '.join(MSs_files_clean)
#print('Use the following ms files as input in wsclean:')
#print(MSs_files_clean)
return MSs_files_clean, H5s_files_clean
def check_for_BDPbug_longsolint(mslist, facetdirections, args=None):
#try:
dirs, solints, soltypelist_includedir = parse_facetdirections(facetdirections, 1000, args=args)
#except:
# try:
# f = open(facetdirections, 'rb')
# PatchPositions_array = pickle.load(f)
# f.close()
# solints = None
# except:
# raise Exception('Trouble read file format:' + facetdirections)
if solints is None:
return
solint_reformat= np.array(solints)
import math
for ms in mslist:
t = pt.table(ms, readonly=True, ack=False)
time = np.unique(t.getcol('TIME'))
t.close()
print('------------' + ms)
ms_ntimes = len(time)
#print(ms, ms_ntimes)
for solintcyle_id, tmpval in enumerate(solint_reformat[0]):
print(' --- ' + str('pertubation cycle=') + str(solintcyle_id) + '--- ')
solints_cycle = solint_reformat[:,solintcyle_id]
solints = [int(format_solint(x, ms)) for x in solints_cycle]
print('Solint unmodified per direction', solints)
solints = tweak_solints(solints, ms_ntimes=ms_ntimes)
print('Solint tweaked per direction ', solints)
#print('Here')
#sys.exit()
lcm = math.lcm(*solints)
divisors = [int(lcm/i) for i in solints]
print('Solint passed to DP3 would be:', lcm, ' --Number of timeslots in MS:', ms_ntimes)
if lcm > ms_ntimes:
print('Bad divisor for solutions_per_direction DDE solve. DP3 Solint > number of timeslots in the MS')
sys.exit()
print('------------')
return
def selfcal_animatedgif(fitsstr, outname):
limit_min = -250e-6
limit_max = 2.5e-2
cmd = 'ds9 ' + fitsstr + ' '
cmd += '-single -view basic -frame first -geometry 800x800 -zoom to fit -sqrt -scale limits '
cmd += str(limit_max) + ' ' + str(limit_max) + ' '
cmd += '-cmap ch05m151008 -colorbar lock yes -frame lock wcs '
cmd += '-lock scalelimits yes -movie frame gif 10 '
cmd += outname + ' -quit'
run(cmd)
return
def find_closest_ddsol(h5, ms): #
"""
find closest direction in multidir h5 files to the phasecenter of the ms
"""
t2 = pt.table(ms + '::FIELD', ack=False)
phasedir = t2.getcol('PHASE_DIR').squeeze()
t2.close()
c1 = SkyCoord(phasedir[0] * units.radian, phasedir[1] * units.radian, frame='icrs')
H5 = tables.open_file(h5)
distance = 1e9 # just a big number
for direction_id, direction in enumerate (H5.root.sol000.source[:]):
ra, dec = direction[1]
c2 = SkyCoord(ra * units.radian, dec * units.radian, frame='icrs')
angsep = c1.separation(c2).to(units.degree)
print(direction[0], angsep.value, '[degree]')
if angsep.value < distance:
distance = angsep.value
dirname = direction[0]
H5.close()
return dirname
def set_beamcor(ms, beamcor_var):
"""
Determine whether to do beam correction or note
"""
if beamcor_var == 'no':
logger.info('Run DP3 applybeam: no')
return False
if beamcor_var == 'yes':
logger.info('Run DP3 applybeam: yes')
return True
t = pt.table(ms + '/OBSERVATION', ack=False)
if t.getcol('TELESCOPE_NAME')[0] != 'LOFAR':
t.close()
logger.info('Run DP3 applybeam: no (because we are not using LOFAR observations)')
return False
t.close()
# If we arrive here beamcor_var was set to auto and we are using a LOFAR observation
if not beamkeywords(ms):
# we have old prefactor data in this case, no beam keywords available
# assume beam was taken out in the field center only if user as set 'auto'
logger.info('Run DP3 applybeam: yes')
return True
# now check if beam was taken out in the current phase center
t = pt.table(ms, readonly=True, ack=False)
beamdir = t.getcolkeyword('DATA', 'LOFAR_APPLIED_BEAM_DIR')
t2 = pt.table(ms + '::FIELD', ack=False)
phasedir = t2.getcol('PHASE_DIR').squeeze()
t.close()
t2.close()
c1 = SkyCoord(beamdir['m0']['value']* units.radian, beamdir['m1']['value'] * units.radian, frame='icrs')
c2 = SkyCoord(phasedir[0] * units.radian, phasedir[1] * units.radian, frame='icrs')
angsep = c1.separation(c2).to(units.arcsec)
# angular_separation is recent astropy functionality, do not use, instead use the older SkyCoord.seperation
#angsep = 3600.*180.*astropy.coordinates.angular_separation(phasedir[0], phasedir[1], beamdir['m0']['value'], beamdir['m1']['value'])/np.pi
print('Angular separation between phase center and applied beam direction is', angsep.value, '[arcsec]')
logger.info('Angular separation between phase center and applied beam direction is:' + str(angsep.value) + ' [arcsec]')
# of less than 10 arcsec than do beam correction
if angsep.value < 10.0:
logger.info('Run DP3 applybeam: no')
return False
else:
logger.info('Run DP3 applybeam: yes')
return True
def isfloat(num):
"""
Check if value is a float
"""
try:
float(num)
return True
except ValueError:
return False
def parse_history(ms, hist_item):
"""
Grep specific history item from MS
:param ms: measurement set
:param hist_item: history item
:return: parsed string
"""
hist = os.popen('taql "SELECT * FROM '+ms+'::HISTORY" | grep '+hist_item).read().split(' ')
for item in hist:
if hist_item in item and len(hist_item)<=len(item):
return item
print('WARNING:' + hist_item + ' not found')
return None
def find_prime_factors(n):
factorlist = []
num = n
while (n % 2 == 0):
factorlist.append(2)
n = n/2
for i in range(3,int(num/2)+1,2):
while (n % i == 0):
factorlist.append(i)
n = n/i
if (n==1):
break
return(factorlist)
def tweak_solintsold(solints, solval=20):
solints_return = []
for sol in solints:
soltmp = sol
if soltmp > solval:
soltmp += (int)(soltmp & 1) # round up to even
solints_return.append((soltmp))
return solints_return
def tweak_solints(solints, solvalthresh=11, ms_ntimes=None):
"""
Returns modified solints that can be factorized by 2 or 3 if input contains number >= solvalthresh
"""
solints_return = []
if np.max(solints) < solvalthresh:
return solints
possible_solints = listof2and3prime(startval=2, stopval=10000)
if ms_ntimes is not None:
possible_solints= remove_bad_endrounding(possible_solints,ms_ntimes)
for sol in solints:
solints_return.append(find_nearest(possible_solints, sol))
return solints_return
def tweak_solints_single(solint, ms_ntimes, solvalthresh=11, ):
"""
Returns modified solint that avoids a short number of left over timeslots near the end of the ms
"""
if np.max(solint) < solvalthresh:
return solint
possible_solints = np.arange(1,2*solint)
possible_solints= remove_bad_endrounding(possible_solints,ms_ntimes)
return find_nearest(possible_solints, solint)
def remove_bad_endrounding(solints, ms_ntimes, ignorelessthan=11):
'''
list of possible solints to start with
ms_ntimes: number of timeslots in the MS
if ignorelessthan then do not use this extra option
'''
solints_out = []
for solint in solints:
if (float(ms_ntimes)/float(solint)) - (np.floor(float(ms_ntimes)/float(solint))) > 0.5 or solint<ignorelessthan:
solints_out.append(solint)
return solints_out
def listof2and3prime(startval=2, stopval=10000):
solint=[1]
for i in np.arange(startval,stopval):
factors = find_prime_factors(i)
if len(factors) > 0:
if factors[-1] == 2 or factors[-1] == 3 :
solint.append(i)
return solint
def find_nearest(array, value):
array = np.asarray(array)
idx = (np.abs(array - value)).argmin()
return array[idx]
def get_time_preavg_factor_LTAdata(ms):
"""
Get time pre-averaging factor (given by demixer.timestep)
:param ms: measurement set
:return: averaging integer
"""
parse_str = "demixer.timestep="
parsed_history = parse_history(ms, parse_str)
avg_num = re.findall(r'\d+', parsed_history.replace(parse_str, ''))[0]
if avg_num.isdigit():
factor = int(float(avg_num))
if factor!=1:
print("WARNING: " + ms + " time has been pre-averaged with factor "+str(factor)+". This might cause time smearing effects.")
return factor
elif isfloat(avg_num):
factor = float(avg_num)
print("WARNING: parsed factor in " + ms + " is not a digit but a float")
return factor
else:
print("WARNING: parsed factor in " + ms + " is not a float or digit")
return None
def add_dummyms(msfiles):
'''
Add dummy ms to create a regular freuqency grid when doing a concat with DPPP
'''
if len(msfiles) == 1:
return msfiles
keyname = 'REF_FREQUENCY'
freqaxis = []
newmslist = []
# Check for wrong REF_FREQUENCY which happens after a DPPP split in frequency
for ms in msfiles:
t = pt.table(ms + '/SPECTRAL_WINDOW', readonly=True)
freq = t.getcol('REF_FREQUENCY')[0]
t.close()
freqaxis.append(freq)
freqaxis = np.sort( np.array(freqaxis))
minfreqspacing = np.min(np.diff(freqaxis))
if minfreqspacing == 0.0:
keyname = 'CHAN_FREQ'
freqaxis = []
for ms in msfiles:
t = pt.table(ms + '/SPECTRAL_WINDOW', readonly=True)
if keyname == 'CHAN_FREQ':
freq = t.getcol(keyname)[0][0]
else:
freq = t.getcol(keyname)[0]
t.close()
freqaxis.append(freq)
# put everything in order of increasing frequency
freqaxis = np.array(freqaxis)
idx = np.argsort(freqaxis)
freqaxis = freqaxis[np.array(tuple(idx))]
sortedmslist = list( msfiles[i] for i in idx )
freqspacing = np.diff(freqaxis)
minfreqspacing = np.min(np.diff(freqaxis))
# insert dummies in the ms list if needed
count = 0
newmslist.append(sortedmslist[0]) # always start with the first ms the list
for msnumber, ms in enumerate(sortedmslist[1::]):
if int(round(freqspacing[msnumber]/minfreqspacing)) > 1:
ndummy = int(round(freqspacing[msnumber]/minfreqspacing)) - 1
for dummy in range(ndummy):
newmslist.append('dummy' + str(count) + '.ms')
print('Added dummy:', 'dummy' + str(count) + '.ms')
count = count + 1
newmslist.append(ms)
print('Updated ms list with dummies inserted to create a regular frequency grid')
print(newmslist)
return newmslist
def number_of_unique_obsids(msfiles):
'''
Basic function to get numbers of observations based on first part of ms name
(assumes one uses "_" here)
Args:
command (list): the list of ms
Returns:
reval (int): number of observations
'''
obsids = []
for ms in msfiles:
obsids.append(os.path.basename(ms).split('_')[0])
print('Using these observations ', np.unique(obsids))
return len(np.unique(obsids))
def getobsmslist(msfiles, observationnumber):
'''
make a list of ms beloning to the same observation
'''
obsids = []
for ms in msfiles:
obsids.append(os.path.basename(ms).split('_')[0])
obsidsextract = np.unique(obsids)[observationnumber]
mslist = []
for ms in msfiles:
if (os.path.basename(ms).split('_')[0]) == obsidsextract:
mslist.append(ms)
return mslist
def mscolexist(ms, colname):
""" Check if a colname exists in the measurement set ms, returns either True or False """
if os.path.isdir(ms):
t = pt.table(ms,readonly=True, ack=False)
colnames =t.colnames()
if colname in colnames: # check if the column is in the list
exist = True
else:
exist = False
t.close()
else:
exist = False # ms does not exist
return exist
def concat_ms_from_same_obs(mslist, outnamebase, colname='DATA', dysco=True):
for observation in range(number_of_unique_obsids(mslist)):
# insert dummies for completely missing blocks to create a regular freuqency grid for DPPP
obs_mslist = getobsmslist(mslist, observation)
obs_mslist = add_dummyms(obs_mslist)