forked from tammojan/facet-calibration
-
Notifications
You must be signed in to change notification settings - Fork 0
/
doDDE_v21_a2256.py
executable file
·2023 lines (1676 loc) · 80.4 KB
/
doDDE_v21_a2256.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
import matplotlib
import numpy
import os
import sys
from scipy import interpolate
import time
from subprocess import Popen, PIPE
import pyrap.tables as pt
import pyrap.images
import pwd
import logging
import logging.config
import glob
import pyfits
from facet_utilities import run, bg, angsep, getcpu, getmem
from backup_direction import backup_previous_direction_p
from numpy import pi
# check high-DR
# TO DO
# - HIGH-DYNAMIC RANGE (need to adjust merger/join parmdb, solution smoohting is ok)
# - make freq averaging for selfcal fieldsize dependent (in do_dde (selfcal is not needed))
# - increase SNR in slow A&P by adding nearby blocks?
# - parallel instrument_merged in selfcal (with pp?)
# - smoothcal in parallel
# - selfcal switch do wsclean?, but can do predict in parallel?
# - nterms/multiscale > 1 in Facet imaging WSclean
# - convolve images all to the same resolution (use casapy for that, easy to do)
# - What about second imaging and calibration cycle?
# - 1. ADD back skymodel using "master solutions", then CORRECT using "master solutions"
# - 2. image that again using the same setting
# - 3. redo the subtract (will be slightly better....but solutions remain the same, just better noise) or just proceed to the next field?
def verify_timegrid(parmdb, ms):
import lofar.parmdb
anttab = pt.table(ms + '/ANTENNA')
antenna_list = anttab.getcol('NAME')
anttab.close()
t = pt.table(ms)
ms_ntime = len(numpy.unique(t.getcol('TIME')))
t.close()
pdb = lofar.parmdb.parmdb(parmdb)
parms = pdb.getValuesGrid("*")
parmdb_ntime = len(parms['CommonScalarPhase:'+ antenna_list[0]]['values'][:, 0]) # CommonScalarPhase should always exist
#print 'number of timesamples ' + ms + ' :', ms_ntime
if ms_ntime != parmdb_ntime:
logging.debug('number of timesamples ' + ms + ' : '+str(ms_ntime))
logging.debug('number of timesamples ' + parmdb + ' : '+str(parmdb_ntime))
raise Exception('Number of timescales of the parmdb template does not match with the ms')
return
def find_newsize(mask):
"""
FIXME
"""
img = pyrap.images.image(mask)
pixels = numpy.copy(img.getdata())
sh = numpy.shape(pixels)[3:4]
newsize = numpy.copy(sh[0])
sh = sh[0]
logging.debug(newsize)
trysizes = numpy.copy(sorted([6400,6144,5600,5400,5184,4800,4608,4320,4096,3840,3600,3200,3072,2880,2560,2304,2048, 1600, 1536, 1200, 1024, 800, 512]))
idx = numpy.where(trysizes < sh)
logging.debug(idx)
trysizes = numpy.copy(trysizes[idx]) # remove sizes larger than image
trysizes = numpy.copy(trysizes[::-1]) # reverse sorted
logging.debug(trysizes)
for size in trysizes:
logging.debug('Trying {}'.format(size))
cutedge = numpy.int((sh - size)/2.)
logging.debug(cutedge)
idx1 = numpy.size(numpy.where(pixels[0,0, 0:cutedge,0:sh] != 0))
idx2 = numpy.size(numpy.where(pixels[0,0, sh-cutedge:sh,0:sh] != 0))
idx3 = numpy.size(numpy.where(pixels[0,0, 0:sh,0:cutedge] != 0))
idx4 = numpy.size(numpy.where(pixels[0,0, 0:sh,sh-cutedge:sh] != 0))
logging.debug("{} {} {} {}".format(idx1, idx2, idx3, idx4))
if ((idx1) == 0) and ((idx2) == 0) and ((idx3) == 0) and ((idx4) == 0):
# UPDATE THE IMAGE SIZE
newsize = numpy.copy(size)
logging.debug('Found new size {} fits within the mask'.format(newsize))
return newsize
def runbbs(mslist, skymodel, parset, parmdb, replacesource, maxcpu=None):
"""
Run BBS on a list of MS.
Input:
* mslist - list of MS.
* skymodel
* parset
* parmdb
* replacesource - flag (True or False) to indicate if the parmdb has
to be replaced or not
"""
#NOTE WORK FROM MODEL_DATA (contains correct phase data from 10SB calibration)
b=bg(maxp=maxcpu)
for ms in mslist:
log = ms + '.bbslog'
if replacesource:
cmd = 'calibrate-stand-alone --replace-sourcedb --parmdb-name ' + parmdb + ' ' + ms + ' ' + parset + ' ' + skymodel + '>' + log + ' 2>&1'
else:
cmd = 'calibrate-stand-alone --parmdb-name ' + parmdb + ' ' + ms + ' ' + parset + ' ' + skymodel + '>' + log + ' 2>&1'
b.run(cmd)
time.sleep(10)
b.wait()
return
def create_subtract_parset_field_outlier(outputcolumn, TEC):
"""
Create a parset for the subtraction of outliers.
The name of the output parset is 'sub.parset'.
Input:
* outputcolumn - Output column.
* TEC - "True" or other, indicates if the TEC is enabled
Output:
* The name of the output parset
The chunksize is hardcoded to 200.
"""
bbs_parset = 'sub.parset'
os.system('rm -f ' + bbs_parset)
f=open(bbs_parset, 'w')
chunksize = 200
f.write('Strategy.InputColumn = MODEL_DATA\n')
f.write('Strategy.ChunkSize = %s\n' % chunksize)
f.write('Strategy.UseSolver = F\n')
f.write('Strategy.Steps = [subtract]\n\n\n')
f.write('Step.subtract.Model.Sources = []\n')
f.write('Step.subtract.Model.Cache.Enable = T\n')
f.write('Step.subtract.Model.Phasors.Enable = F\n')
f.write('Step.subtract.Model.DirectionalGain.Enable = F\n')
f.write('Step.subtract.Model.Gain.Enable = T\n')
f.write('Step.subtract.Model.Rotation.Enable = F\n')
f.write('Step.subtract.Model.CommonScalarPhase.Enable = T\n')
if TEC == "True":
f.write('Step.subtract.Model.TEC.Enable = T\n')
#if clock == "True":
# f.write('Step.subtract.Model.Clock.Enable = T\n')
f.write('Step.subtract.Model.CommonRotation.Enable = F\n')
f.write('Step.subtract.Operation = SUBTRACT\n')
f.write('Step.subtract.Model.Beam.Enable = F\n')
f.write('Step.subtract.Output.WriteCovariance = F\n')
f.write('Step.subtract.Output.Column = %s\n' % outputcolumn)
f.close()
return bbs_parset
def create_predict_parset(outputcolumn):
"""
Create a parset for to predict a model (for allbands.concat.source.ms).
The name of the output parset is 'predict.parset'.
Input:
* outputcolumn - Output column.
Output:
* The name of the output parset
The chunksize is hardcoded to 200.
"""
bbs_parset = 'predict.parset'
os.system('rm -f ' + bbs_parset)
f=open(bbs_parset, 'w')
chunksize = 200
f.write('Strategy.InputColumn = DATA\n')
f.write('Strategy.ChunkSize = %s\n' % chunksize)
f.write('Strategy.Steps = [predict]\n\n\n')
f.write('Step.subtract.Model.Sources = []\n')
f.write('Step.predict.Model.Cache.Enable = T\n')
f.write('Step.predict.Model.Phasors.Enable = F\n')
f.write('Step.predict.Model.DirectionalGain.Enable = F\n')
f.write('Step.predict.Model.Gain.Enable = F\n')
f.write('Step.predict.Model.Rotation.Enable = F\n')
f.write('Step.predict.Model.CommonScalarPhase.Enable = F\n')
f.write('Step.predict.Model.CommonRotation.Enable = F\n')
f.write('Step.predict.Operation = PREDICT\n')
f.write('Step.predict.Model.Beam.Enable = F\n')
f.write('Step.predict.Output.WriteCovariance = F\n')
f.write('Step.predict.Output.Column = %s\n' % outputcolumn)
f.close()
return bbs_parset
def runbbs_diffskymodel_addback(mslist, parmdb, replacesource, direction, imsize, output_template_im, do_ap,maxcpu=None):
"""
FIXME
"""
b=bg(maxp=maxcpu)
for ms in mslist:
log = ms + '.bbslog'
#set skymodel # ~weeren does not work in numpy.load
skymodel = ms.split('.')[0] + '.skymodel'
# find sources to add back, make parset
callist, callistarraysources = cal_return_slist(output_template_im +'.masktmp',skymodel, direction, imsize)
# cmd = 'python ' + SCRIPTPATH + '/cal_return_slist.py '+ output_template_im +'.masktmp ' +skymodel +' "'+str(direction) +'" ' + str(imsize)
# output = Popen(cmd, shell=True, stdout=PIPE).communicate()[0]
# callist = output.strip()
# callistarraysources = callist.split(',')
logging.debug('Adding back for calibration: '+str(callist))
if len(callist)>0: # otherwise do not have to add
parset = create_add_parset_ms(callist, ms, do_ap)
if replacesource:
cmd = 'calibrate-stand-alone --replace-sourcedb --parmdb-name ' + parmdb + ' ' + ms + ' ' + parset + ' ' + skymodel + '>' + log + ' 2>&1'
else:
cmd = 'calibrate-stand-alone --parmdb-name ' + parmdb + ' ' + ms + ' ' + parset + ' ' + skymodel + '>' + log + ' 2>&1'
b.run(cmd)
time.sleep(10) # otherwise add.parset is deleted (takes time for BBS to start up)
else:
logging.warning('No source to add back, are you sure the DDE position is correct?')
run("taql 'update " + ms + " set ADDED_DATA_SOURCE=SUBTRACTED_DATA_ALL'")
b.wait()
return
def runbbs_diffskymodel_addbackfield(mslist, parmdb, replacesource, direction, imsize, output_template_im, do_ap):
"""
FIXME
"""
b=bg()
for ms in mslist:
log = ms + '.bbslog'
#set skymodel
skymodel = ms.split('.')[0] + '.skymodel'
# find peeling sources (from previous step)
callist, callistarraysources = cal_return_slist(output_template_im +'.masktmp',skymodel, direction, imsize)
#cmd = 'python '+ SCRIPTPATH + '/cal_return_slist.py '+ output_template_im +'.masktmp ' +skymodel +' "'+str(direction) +'" ' + str(imsize)
#output = Popen(cmd, shell=True, stdout=PIPE).communicate()[0]
#callist = output.strip()
#callistarraysources = callist.split(',')
logging.debug('Add field back step 1')
# return the source list from the source to be added back surrounding the peeling source and which fall within the mask boundaries
# put in MODEL_DATA
addback_sourcelist,dummy = return_slist(output_template_im +'.masktmp', skymodel, callistarraysources)
logging.debug('Field source added back are: '+str(addback_sourcelist))
if len(addback_sourcelist) != 0: # otherwise do not have to add
parset = create_add_parset_field_ms(addback_sourcelist, ms, do_ap)
if replacesource:
cmd = 'calibrate-stand-alone --replace-sourcedb --parmdb-name ' + parmdb + ' ' + ms + ' ' + parset + ' ' + skymodel + '>' + log + ' 2>&1'
else:
cmd = 'calibrate-stand-alone --parmdb-name ' + parmdb + ' ' + ms + ' ' + parset + ' ' + skymodel + '>' + log + ' 2>&1'
b.run(cmd)
else:
run("taql 'update " + ms + " set MODEL_DATA=ADDED_DATA_SOURCE'") # in case no sources are put back
time.sleep(10) # otherwise addfield.parset is deleted (takes time for BBS to start up)
time.sleep(10)
b.wait()
return
def runbbs_2(mslist, msparmdb, skymodel, parset, parmdb):
"""
Second version of run BBS on a list of MS.
Input:
* mslist - list of MS.
* msparmdb - list of parmdbs.
* skymodel
* parset
* parmdb
"""
b=bg()
for ms_id, ms in enumerate(mslist):
log = ms + '.bbslog'
cmd = 'calibrate-stand-alone --parmdb ' + msparmdb[ms_id]+'/'+parmdb + ' ' + ms + ' ' + parset + ' ' + skymodel + '>' + log + ' 2>&1'
b.run(cmd)
time.sleep(10)
b.wait()
def create_phaseshift_parset_full(msin, msout, direction, column):
"""
Create a parset for the phase shift (for the combined MS? FIXME).
The name of the output parset is 'ndppp_phaseshiftfull.parset'.
Input:
* msin - Input MS
* msout - Output MS
* direction - Direction of the new phase center
* column - Output column.
Output:
* The name of the output parset
"""
ndppp_parset = 'ndppp_phaseshiftfull.parset'
os.system('rm -f ' + ndppp_parset)
f=open(ndppp_parset, 'w')
f.write('msin ="%s"\n' % msin)
f.write('msin.datacolumn = "%s"\n' % column)
f.write('msin.autoweight = false\n')
f.write('msout ="%s"\n' % msout)
f.write('msout.writefullresflag=False\n')
f.write('steps = [shift]\n')
f.write('shift.type = phaseshift\n')
f.write('shift.phasecenter = [%s]\n' % direction)
f.close()
return ndppp_parset
def create_phaseshift_parset(msin, msout, source, direction, imsize, dynamicrange, StefCal, numchanperms):
"""
Create a parset for the phase shift (for the individual MS? FIXME).
The name of the output parset depends on the input MS name and has
a suffix of '_ndppp_avgphaseshift.parset'.
Input:
* msin - Input MS
* msout - Output MS
* source - NOT USED but required input
* direction - Direction of the new phase center
* imsize - Size of the image. Used to select the frequency averaging.
* dynamicrange - "LD" or "HD". Used to select the frequency averaging.
* StefCal - True or False. Used to select the frequency averaging.
* numchanperms - Number of channels per ms. Required to compute the
correct averaging.
Output:
* The name of the output parset
"""
ndppp_parset = (msin.split('.')[0]) +'_ndppp_avgphaseshift.parset'
os.system('rm -f ' + ndppp_parset)
f=open(ndppp_parset, 'w')
f.write('msin ="%s"\n' % msin)
f.write('msin.datacolumn = ADDED_DATA_SOURCE\n')
f.write('msin.autoweight = false\n')
f.write('msout ="%s"\n' % msout)
f.write('msout.writefullresflag=False\n')
f.write('steps = [shift,avg1]\n')
f.write('shift.type = phaseshift\n')
f.write('shift.phasecenter = [%s]\n' % direction)
f.write('avg1.type = squash\n')
if dynamicrange == 'LD':
if StefCal:
if imsize <= 800:
f.write('avg1.freqstep = %s\n' % str(numchanperms))
else:
if imsize <= 1600:
f.write('avg1.freqstep = %s\n' % str(numchanperms/2))
else:
f.write('avg1.freqstep = %s\n' % str(numchanperms/5))
# we have a large image 2048 is more or less max expected
# divide by 5 because that allows datasets with 3 channels per SB (i.e., 30 channels per ms)
else:
f.write('avg1.freqstep = %s\n' % str(numchanperms))
else:
if dynamicrange != 'HD':
logging.error('dynamicrange {}'.format(dynamicrange))
raise Exception('Wrong dynamicrange code, use "LD" or "HD"')
logging.warning('High dynamic range DDE cycle, eveything will be slow...')
f.write('avg1.freqstep = %s\n' % str(numchanperms/10)) # one channel per SB
f.write('avg1.timestep = 1\n')
f.close()
return ndppp_parset
def create_phaseshift_parset_formasks(msin, msout, source, direction):
"""
Create a parset for the phase shift (for the individual MS? FIXME).
formasks version (FIXME). There is no averaging done and the input
column is "DATA".
The name of the output parset depends on the input MS name and has
a suffix of '_ndppp_avgphaseshift.parset'.
Input:
* msin - Input MS
* msout - Output MS
* source - NOT USED but required input
* direction - Direction of the new phase center
Output:
* The name of the output parset
"""
ndppp_parset = (msin.split('.')[0]) +'_ndppp_avgphaseshift.parset'
os.system('rm -f ' + ndppp_parset)
f=open(ndppp_parset, 'w')
f.write('msin ="%s"\n' % msin)
f.write('msin.datacolumn = DATA\n')
f.write('msin.autoweight = False\n')
f.write('msin.baseline = 0&1\n') # only one baseline
f.write('msout ="%s"\n' % msout)
f.write('msout.writefullresflag=False\n')
f.write('steps = [shift,avg1]\n')
f.write('shift.type = phaseshift\n')
f.write('shift.phasecenter = [%s]\n' % direction)
f.write('avg1.type = squash\n')
f.write('avg1.freqstep = 1\n')
f.write('avg1.timestep = 1\n')
f.close()
return ndppp_parset
def create_phaseshift_parset_field(msin, msout, source, direction, numchanperms, imsize):
"""
Create a parset for the phase shift (for the individual MS? FIXME).
field version (FIXME). The input column is "CORRECTED_DATA".
The name of the output parset depends on the input MS name and has
a suffix of '_ndppp_avgphaseshift_field.parset'.
Input:
* msin - Input MS
* msout - Output MS
* source - NOT USED but required input
* direction - Direction of the new phase center
* numchanperms - Number of channels per ms. Required to compute the
correct averaging.
Output:
* The name of the output parset
"""
ndppp_parset = msin.split('.')[0] +'ndppp_avgphaseshift_field.parset'
os.system('rm -f ' + ndppp_parset)
# start from 8192 and work down so the averaging is updated for smaller imsizes
if imsize <= 8192:
freqavg = numpy.int(numchanperms/20)
timeavg = 1
if imsize <= 4096:
freqavg = numpy.int(numchanperms/20)
timeavg = 2
if imsize <= 2048:
freqavg = numpy.int(numchanperms/10)
timeavg = 3
if imsize <= 1024:
freqavg = numpy.int(numchanperms/5)
timeavg = 6
f=open(ndppp_parset, 'w')
f.write('msin ="%s"\n' % msin)
f.write('msin.datacolumn = CORRECTED_DATA\n')
f.write('msin.autoweight = false\n')
f.write('msout ="%s"\n' % msout)
f.write('msout.writefullresflag=False\n')
f.write('steps = [shift,avg1]\n')
f.write('shift.type = phaseshift\n')
f.write('shift.phasecenter = [%s]\n' % direction)
f.write('avg1.type = squash\n')
f.write('avg1.freqstep = %s\n'% str(freqavg))
f.write('avg1.timestep = %s\n'% str(timeavg))
f.close()
return ndppp_parset
def create_add_parset_ms(source, ms, do_ap):
"""
Create a parset to add sources to the individual MSs.
The name of the output parset depends on the input MS name and has
a suffix of '_add.parset'. The input column is
"SUBTRACTED_DATA_ALL" and the output column is
"ADDED_DATA_SOURCE". The chunksize is hardcoded to 200.
Input:
* source - Source or sources to add.
* ms - Input MS. Used for the name of the parset.
* do_ap - True or False changes if the Gain is enabled or not.
Output:
* The name of the output parset
"""
bbs_parset = ms + '_add.parset'
os.system('rm -f ' + bbs_parset)
f=open(bbs_parset, 'w')
f.write('Strategy.InputColumn = SUBTRACTED_DATA_ALL\n')
f.write('Strategy.ChunkSize = 200\n')
f.write('Strategy.UseSolver = F\n')
f.write('Strategy.Steps = [add]\n\n\n')
f.write('Step.add.Model.Sources = [%s]\n' % source)
f.write('Step.add.Model.Cache.Enable = T\n')
f.write('Step.add.Model.Phasors.Enable = F\n')
f.write('Step.add.Model.DirectionalGain.Enable = F\n')
if do_ap:
f.write('Step.add.Model.Gain.Enable = T\n')
else:
f.write('Step.add.Model.Gain.Enable = F\n')
f.write('Step.add.Model.Rotation.Enable = F\n')
f.write('Step.add.Model.CommonScalarPhase.Enable = F\n')
f.write('Step.add.Model.CommonRotation.Enable = F\n')
f.write('Step.add.Operation = ADD\n')
f.write('Step.add.Model.Beam.Enable = F\n')
f.write('Step.add.Output.WriteCovariance = F\n')
f.write('Step.add.Output.Column = ADDED_DATA_SOURCE\n')
f.close()
return bbs_parset
def create_add_parset_field(source):
"""
Create a parset to add sources to the concatenated MS.
The name of the output parset is 'addfield.parset'. The input
column is "ADDED_DATA_SOURCE" and the output column is
"MODEL_DATA". The chunksize is hardcoded to 200.
Input:
* source - Source or sources to add.
Output:
* The name of the output parset
"""
bbs_parset = 'addfield.parset'
os.system('rm -f ' + bbs_parset)
f=open(bbs_parset, 'w')
f.write('Strategy.InputColumn = ADDED_DATA_SOURCE\n') # already contains peeling source
f.write('Strategy.ChunkSize = 200\n')
f.write('Strategy.UseSolver = F\n')
f.write('Strategy.Steps = [add]\n\n\n')
f.write('Step.add.Model.Sources = [%s]\n' % source)
f.write('Step.add.Model.Cache.Enable = T\n')
f.write('Step.add.Model.Phasors.Enable = F\n')
f.write('Step.add.Model.DirectionalGain.Enable = F\n')
f.write('Step.add.Model.Gain.Enable = T\n')
f.write('Step.add.Model.Rotation.Enable = F\n')
f.write('Step.add.Model.CommonScalarPhase.Enable = F\n')
f.write('Step.add.Model.CommonRotation.Enable = F\n')
f.write('Step.add.Operation = ADD\n')
f.write('Step.add.Model.Beam.Enable = F\n')
f.write('Step.add.Output.WriteCovariance = F\n')
f.write('Step.add.Output.Column = MODEL_DATA\n') # use use to save disk space
f.close()
return bbs_parset
def create_add_parset_field_ms(source, ms, do_ap):
"""
Create a parset to add sources to the individual MSs ? FIXME. field
version FIXME.
The name of the output parset depends on the input MS name and has
a suffix of '_add.parset'. The input column is
"ADDED_DATA_SOURCE" and the output column is
"MODEL_DATA". The chunksize is hardcoded to 200.
Input:
* source - Source or sources to add.
* ms - Input MS. Used for the name of the parset.
* do_ap - True or False changes if the Gain is enabled or not.
Output:
* The name of the output parset
"""
bbs_parset = ms + '_addfield.parset'
os.system('rm -f ' + bbs_parset)
f=open(bbs_parset, 'w')
f.write('Strategy.InputColumn = ADDED_DATA_SOURCE\n') # already contains peeling source
f.write('Strategy.ChunkSize = 200\n')
f.write('Strategy.UseSolver = F\n')
f.write('Strategy.Steps = [add]\n\n\n')
f.write('Step.add.Model.Sources = [%s]\n' % source)
f.write('Step.add.Model.Cache.Enable = T\n')
f.write('Step.add.Model.Phasors.Enable = F\n')
f.write('Step.add.Model.DirectionalGain.Enable = F\n')
if do_ap:
f.write('Step.add.Model.Gain.Enable = T\n')
else:
f.write('Step.add.Model.Gain.Enable = F\n')
f.write('Step.add.Model.Rotation.Enable = F\n')
f.write('Step.add.Model.CommonScalarPhase.Enable = F\n')
f.write('Step.add.Model.CommonRotation.Enable = F\n')
f.write('Step.add.Operation = ADD\n')
f.write('Step.add.Model.Beam.Enable = F\n')
f.write('Step.add.Output.WriteCovariance = F\n')
f.write('Step.add.Output.Column = MODEL_DATA\n') # use use to save disk space
f.close()
return bbs_parset
def create_subtract_parset(outputcolumn):
"""
Create a parset to subtract sources FIXME.
The name of the output parset is 'sub.parset'. The input
column is "ADDED_DATA_SOURCE". The chunksize is hardcoded to 100.
Input:
* outputcolumn - Output column.
Output:
* The name of the output parset
"""
bbs_parset = 'sub.parset'
os.system('rm -f ' + bbs_parset)
f=open(bbs_parset, 'w')
f.write('Strategy.InputColumn = ADDED_DATA_SOURCE\n')
f.write('Strategy.ChunkSize = 100\n')
f.write('Strategy.UseSolver = F\n')
f.write('Strategy.Steps = [subtract]\n\n\n')
f.write('Step.subtract.Model.Sources = []\n')
f.write('Step.subtract.Model.Cache.Enable = T\n')
f.write('Step.subtract.Model.Phasors.Enable = F\n')
f.write('Step.subtract.Model.DirectionalGain.Enable = F\n')
f.write('Step.subtract.Model.Gain.Enable = T\n')
f.write('Step.subtract.Model.Rotation.Enable = F\n')
f.write('Step.subtract.Model.CommonScalarPhase.Enable = T\n')
f.write('Step.subtract.Model.CommonRotation.Enable = F\n')
f.write('Step.subtract.Operation = SUBTRACT\n')
f.write('Step.subtract.Model.Beam.Enable = F\n')
f.write('Step.subtract.Output.WriteCovariance = F\n')
f.write('Step.subtract.Output.Column = %s\n' % outputcolumn)
f.close()
return bbs_parset
def create_subtract_parset_field(outputcolumn, TEC):
"""
Create a parset to subtract sources (previously added to the
"ADDED_DATA_SOURCE" column? FIXME). field version FIXME.
The name of the output parset is 'sub.parset'. The input
column is "MODEL_DATA". The chunksize is hardcoded to 175.
Input:
* outputcolumn - Output column.
* TEC - "True" or other.
Output:
* The name of the output parset
"""
bbs_parset = 'sub.parset'
os.system('rm -f ' + bbs_parset)
f=open(bbs_parset, 'w')
chunksize = 175
f.write('Strategy.InputColumn = MODEL_DATA\n')
f.write('Strategy.ChunkSize = %s\n' % chunksize)
f.write('Strategy.UseSolver = F\n')
f.write('Strategy.Steps = [subtract]\n\n\n')
f.write('Step.subtract.Model.Sources = [@ADDED_DATA_SOURCE]\n')
f.write('Step.subtract.Model.Cache.Enable = T\n')
f.write('Step.subtract.Model.Phasors.Enable = F\n')
f.write('Step.subtract.Model.DirectionalGain.Enable = F\n')
f.write('Step.subtract.Model.Gain.Enable = T\n')
f.write('Step.subtract.Model.Rotation.Enable = F\n')
f.write('Step.subtract.Model.CommonScalarPhase.Enable = T\n')
if TEC == "True":
f.write('Step.subtract.Model.TEC.Enable = T\n')
#if clock == "True":
# f.write('Step.subtract.Model.Clock.Enable = T\n')
f.write('Step.subtract.Model.CommonRotation.Enable = F\n')
f.write('Step.subtract.Operation = SUBTRACT\n')
f.write('Step.subtract.Model.Beam.Enable = F\n')
f.write('Step.subtract.Output.WriteCovariance = F\n')
f.write('Step.subtract.Output.Column = %s\n' % outputcolumn)
f.close()
return bbs_parset
def join_parmdb_stefcal(ms, parmdb_selfcal, parmdb_template, parmdb_out):
"""
FIXME
Transfer the parmdb values from the self_calibration using a
template?
"""
import lofar.parmdb
pdb_s = lofar.parmdb.parmdb(parmdb_selfcal)
pdb_t = lofar.parmdb.parmdb(parmdb_template)
parms_s = pdb_s.getValuesGrid("*")
parms_t = pdb_t.getValuesGrid("*")
keynames = parms_s.keys()
os.system('rm -rf ' + parmdb_out)
for key in keynames:
# copy over the selfcal solutions, can copy all (Real, Imag, CommonScalarPhase, TEC, clock)
parms_t[key]['values'][:,0] = numpy.copy(parms_s[key]['values'][:,0])
pol_list = ['0:0','1:1']
gain = 'Gain'
anttab = pt.table(ms + '/ANTENNA')
antenna_list = anttab.getcol('NAME')
anttab.close()
for pol in pol_list:
for antenna in antenna_list:
real2 = numpy.copy(parms_s[gain + ':' + pol + ':Real:'+ antenna]['values'][:, 0])
imag2 = numpy.copy(parms_s[gain + ':' + pol + ':Imag:'+ antenna]['values'][:, 0])
G2 = real2 + 1j*imag2
Gnew = numpy.copy(G2)
parms_t[gain + ':' + pol + ':Imag:'+ antenna]['values'][:, 0] = numpy.copy(numpy.imag(Gnew))
parms_t[gain + ':' + pol + ':Real:'+ antenna]['values'][:, 0] = numpy.copy(numpy.real(Gnew))
pdbnew = lofar.parmdb.parmdb(parmdb_out, create=True)
pdbnew.addValues(parms_t)
pdbnew.flush()
return
def join_parmdb(ms, parmdb_selfcal, parmdb_nondde, parmdb_template, parmdb_out, TEC, clock):
"""
FIXME
Transfer the parmdb values from the self_calibration using a
template?
"""
import lofar.parmdb
pdb_s = lofar.parmdb.parmdb(parmdb_selfcal)
pdb_p = lofar.parmdb.parmdb(parmdb_nondde)
pdb_t = lofar.parmdb.parmdb(parmdb_template)
parms_s = pdb_s.getValuesGrid("*")
parms_p = pdb_p.getValuesGrid("*")
parms_t = pdb_t.getValuesGrid("*")
keynames = parms_s.keys()
os.system('rm -rf ' + parmdb_out)
for key in keynames:
# copy over the selfcal solutions, can copy all (Real, Imag, CommonScalarPhase, TEC, clock)
parms_t[key]['values'][:,0] = numpy.copy(parms_s[key]['values'][:,0])
pol_list = ['0:0','1:1']
gain = 'Gain'
anttab = pt.table(ms + '/ANTENNA')
antenna_list = anttab.getcol('NAME')
anttab.close()
for pol in pol_list:
for antenna in antenna_list:
real1 = numpy.copy(parms_p[gain + ':' + pol + ':Real:'+ antenna]['values'][:, 0])
imag1 = numpy.copy(parms_p[gain + ':' + pol + ':Imag:'+ antenna]['values'][:, 0])
real2 = numpy.copy(parms_s[gain + ':' + pol + ':Real:'+ antenna]['values'][:, 0])
imag2 = numpy.copy(parms_s[gain + ':' + pol + ':Imag:'+ antenna]['values'][:, 0])
G1 = real1 + 1j*imag1
G2 = real2 + 1j*imag2
#G_new = G_nondde*G_selfcal
if TEC == "True":
Gnew = numpy.copy(G2)
else:
Gnew = numpy.copy(G1*G2)
parms_t[gain + ':' + pol + ':Imag:'+ antenna]['values'][:, 0] = numpy.copy(numpy.imag(Gnew))
parms_t[gain + ':' + pol + ':Real:'+ antenna]['values'][:, 0] = numpy.copy(numpy.real(Gnew))
#lofar.expion.parmdbmain.store_parms(parmdb_out, parms_t, create_new = True)
pdbnew = lofar.parmdb.parmdb(parmdb_out, create=True)
pdbnew.addValues(parms_t)
pdbnew.flush()
return
def normalize_parmdbs(mslist, parmdbname, parmdboutname):
"""
Normalice the gain solutions of a parmdb of a given name in a list
of MSs.
Input:
* mslist - List of MS with the solutons to normalize.
* parmdbname - Name of the parmdb used in all the MSs.
* parmdboutname - Name of the output parmdb with the normalized
gains.
"""
import lofar.parmdb
amplist = []
# create antenna list
pol_list = ['0:0','1:1']
gain = 'Gain'
anttab = pt.table(mslist[0] + '/ANTENNA')
antenna_list = anttab.getcol('NAME')
anttab.close()
for ms in mslist:
pdb = lofar.parmdb.parmdb(ms + '/' + parmdbname)
parms = pdb.getValuesGrid("*")
for pol in pol_list:
for antenna in antenna_list:
real = numpy.copy(parms[gain + ':' + pol + ':Real:'+ antenna]['values'][:, 0])
imag = numpy.copy(parms[gain + ':' + pol + ':Imag:'+ antenna]['values'][:, 0])
amp = numpy.copy(numpy.sqrt(real**2 + imag**2))
amplist.append(amp)
norm_factor = 1./(numpy.mean(amplist))
logging.debug('Normalizing gains: average gain value is {}'.format(1./norm_factor))
logging.debug('Multiplying gains by: {}'.format(norm_factor))
if (norm_factor > 1.5) or (norm_factor < (1./1.5)):
logging.error('Check normalization')
raise Exception('Wrong normalization')
# now normalize the parmdbs
for ms in mslist:
pdb = lofar.parmdb.parmdb(ms + '/' + parmdbname)
parms = pdb.getValuesGrid("*")
os.system('rm -rf ' + ms + '/' + parmdboutname)
for pol in pol_list:
for antenna in antenna_list:
real = numpy.copy(parms[gain + ':' + pol + ':Real:'+ antenna]['values'][:, 0])
imag = numpy.copy(parms[gain + ':' + pol + ':Imag:'+ antenna]['values'][:, 0])
parms[gain + ':' + pol + ':Imag:'+ antenna]['values'][:, 0] = numpy.copy(imag*norm_factor)
parms[gain + ':' + pol + ':Real:'+ antenna]['values'][:, 0] = numpy.copy(real*norm_factor)
pdbnew = lofar.parmdb.parmdb(ms + '/' +parmdboutname, create=True)
pdbnew.addValues(parms)
pdbnew.flush()
return numpy.mean(amplist)
def make_image(mslist, cluster, callnumber, threshpix, threshisl, nterms, atrous_do, imsize, inputmask, mscale, region):
"""
Make image using CASA for a list of MSs.
FIXME
"""
niter = numpy.int(2000 * (numpy.sqrt(numpy.float(len(mslist)))))
depth = 0.7 / (numpy.sqrt(numpy.float(len(mslist))))
cleandepth1 = str(depth*1.5) + 'mJy'
cleandepth2 = str(depth) + 'mJy'
# speed up the imaging if possible by reducing image size within the mask region
newsize = find_newsize(inputmask)
if newsize < imsize: # ok so we can use a smaller image size then
#make a new template
run('casapy --nogui -c '+ SCRIPTPATH +'/make_empty_image.py '+ str(mslist[0]) + ' ' + inputmask+'2' + ' ' + str(newsize) + ' ' +'1.5arcsec')
run('casapy --nogui -c '+ SCRIPTPATH +'/regrid_image.py ' + inputmask + ' ' + inputmask+'2' + ' ' + inputmask+'3')
# reset the imsize and the mask
imsize = newsize
inputmask = inputmask+'3'
ms = ''
for m in mslist:
ms = ms + ' ' + m
imout = 'im'+ callnumber +'_cluster'+cluster+'nm'
run('casapy --nogui -c ' + SCRIPTPATH + '/casapy_cleanv4.py ' + ms + ' ' + imout + ' ' + 'None' +
' ' + cleandepth1 + ' ' + str(niter) + ' ' + str(nterms) + ' ' + str(imsize) + ' ' + str(mscale))
# make mask
if nterms > 1:
do_makecleanmask_field(imout +'.image.tt0',threshpix,threshisl,atrous_do,ncores=getcpu())
# run('python ' + SCRIPTPATH +'/makecleanmask_field.py --threshpix '+str(threshpix)+
# ' --threshisl '+str(threshisl) +' --atrous_do '+ str(atrous_do) +'# ' +imout +'.image.tt0')
else:
do_makecleanmask_field(imout +'.image.tt0',threshpix,threshisl,atrous_do,ncores=getcpu())
# run('python ' + SCRIPTPATH +'/makecleanmask_field.py --threshpix '+str(threshpix)+
# ' --threshisl '+str(threshisl) +' --atrous_do '+ str(atrous_do) + ' ' + imout +'.image')
mask_sources = imout+'.cleanmask'
os.system('rm -rf ' + mask_sources + 'field')
os.system('cp -r ' + mask_sources + ' ' + mask_sources + 'field')
#Merge the two masks
img = pyrap.images.image(mask_sources+'field')
pixels = numpy.copy(img.getdata())
img2 = pyrap.images.image(inputmask)
pixels2 = numpy.copy(img2.getdata())
idx = numpy.where(pixels2 == 0.0)
pixels[idx] = 0.0
img.putdata(pixels)
img.unlock()
del img
del img2
niter = numpy.int(niter*1.2) # clean a bit deeper (will actually be quite a bit deeper because of mask)
imout = 'im'+ callnumber +'_cluster'+cluster
if region != 'empty': # in that case we have a extra region file for the clean mask
niter = niter*3 # increase niter, tune manually if needed
run('casapy --nogui -c ' + SCRIPTPATH +'/casapy_cleanv4.py '+ ms + ' ' + imout + ' ' + mask_sources+'field,'+region +
' ' + cleandepth2 + ' ' + str(niter) + ' ' + str(nterms) + ' ' + str(imsize) + ' ' + str(mscale))
else:
run('casapy --nogui -c '+ SCRIPTPATH + '/casapy_cleanv4.py '+ ms + ' ' + imout + ' ' + mask_sources+'field' +
' ' + cleandepth2 + ' ' + str(niter) + ' ' + str(nterms) + ' ' + str(imsize) + ' ' + str(mscale))
# convert to FITS
if nterms > 1:
run('image2fits in=' + imout +'.image.tt0' + ' ' + 'out='+ imout + '.fits')
else:
run('image2fits in=' + imout +'.image' + ' ' + 'out='+ imout + '.fits')
return imout, mask_sources+'field', imsize
def blank_facet(imagename,maskname):
imhdu=pyfits.open(imagename)
maskim=pyrap.images.image(maskname)
imdata=imhdu[0].data[0,0]
maskdata=maskim.getdata()[0,0]
assert(imdata.shape==maskdata.shape)
nanmask=numpy.ones_like(imdata)*numpy.nan
imdata=numpy.where(maskdata>0,imdata,nanmask)
imhdu[0].data[0,0]=imdata
outname=imagename.replace('.fits','.blanked.fits')
imhdu.writeto(outname,clobber=True)
return outname
def make_image_wsclean(mslist, cluster, callnumber, threshpix, threshisl,
nterms, atrous_do, imsize, inputmask, mscale,
region, cellsize, uvrange, wsclean, WSCleanRobust,
BlankField, WScleanWBgroup, numchanperms,path=None,tempdir=None):
"""
Make image using WSClean for a list of MSs.
FIXME
"""
# import if not already defined
try:
do_makecleanmask_field_wsclean
except NameError:
from makecleanmask_field_wsclean import do_makecleanmask_field_wsclean
if path is not None:
SCRIPTPATH=path
if imsize is None:
imsize = image_size_from_mask(inputmask)
niter = numpy.int(5000 * (numpy.sqrt(numpy.float(len(mslist)))))
cellsizeim = str(cellsize) +'arcsec'
depth = 1e-3*0.7 / (numpy.sqrt(numpy.float(len(mslist))))
cleandepth1 = str(depth*1.5) #+ 'mJy'
cleandepth2 = str(depth) #+ 'mJy'
wideband = False
if len(mslist) > WScleanWBgroup:
wideband = True
# speed up the imaging if possible by reducing image size within the mask region
#newsize = find_newsize(inputmask)
#if newsize < imsize: # ok so we can use a smaller image size then
# #make a new template
# run('casapy --nogui -c ' + SCRIPTPATH + '/make_empty_image.py '+ str(mslist[0]) + ' ' + inputmask+'2' + ' ' + str(newsize) + ' ' +'1.5arcsec')
# run('casapy --nogui -c ' + SCRIPTPATH + '/regrid_image.py ' + inputmask + ' ' + inputmask+'2' + ' ' + inputmask+'3')
#
# # reset the imsize and the mask
# imsize = newsize
# inputmask = inputmask+'3'
ms = ''
for m in mslist:
ms = ms + ' ' + m
imout = 'im'+ callnumber +'_cluster'+cluster+'nm'
os.system('rm -rf ' + imout + '-*')
# NDPPP concat
outms = 'field.ms'
parsetname = 'concatforwsclean.parset'
msinstr = ""
for ms_id, ms in enumerate(mslist):
msinstr = msinstr + "'" + ms + "'"
if ms_id < len(mslist)-1:
msinstr = msinstr + ", "
os.system('rm -rf ' + parsetname)
f=open(parsetname, 'w')
f.write('msin = [%s]\n' % msinstr)
f.write('msin.datacolumn = DATA\n')