forked from tammojan/facet-calibration
-
Notifications
You must be signed in to change notification settings - Fork 0
/
doDDE_reimage_v1_bootes_cep3.py
1415 lines (1107 loc) · 52.7 KB
/
doDDE_reimage_v1_bootes_cep3.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
import matplotlib
#matplotlib.use('GTK')
import numpy
import os
import sys
import lofar.parmdb
from scipy import interpolate
import time
#import subprocess
from subprocess import Popen, PIPE, STDOUT
import pyrap.tables as pt
import pyrap.images
import pwd
import logging
logging.basicConfig(filename='dde_reimage.log',level=logging.DEBUG, format='%(asctime)s - %(message)s', datefmt='%Y-%d-%m %H:%M:%S')
if len(sys.argv)<2:
raise Exception('Give the path to the setup code for the facet')
print 'Using',sys.argv[1],'as the setup code'
execfile(sys.argv[1])
print 'script path is',SCRIPTPATH
username = pwd.getpwuid(os.getuid())[0]
os.system('cp ' + SCRIPTPATH + '/coordinates_mode.py .')
os.system('cp ' + SCRIPTPATH + '/blank.py .')
os.system('cp ' + SCRIPTPATH + '/ftw.xml .')
os.system('cp ' + SCRIPTPATH + '/task_ftw.py .')
os.system(buildmytasks) # make casapy tasks
from coordinates_mode import *
pi = numpy.pi
# check high-DR
# check old selfcalv15
# check point source model
# TO DO
# - problem with e1 mask (sources not in clean mask)
# - problem with s3, diffuse source not in clean mask causes neg. bowl --> FIXED
# - check for mask gaps --> DONE
# - fit for clock in selfcal --> DONE
# - clean component overlap check -> avoid by giving up patches
# - reset phases to zero in selfcal part --> DONE
# - gain normalization --> DONE
# - HIGH-DYNAMIC RANGE (need to adjust merger/join parmdb, solution smoohting as well)
# - move m10 direction --> DONE
# - make normal template names files --> DONE
# - remove source list loading to prevent segfaults --> DONE
# - run the addback sources in seperate python script to avoid frequent Bus Errors DONE
# - run the addback sources FIELD in seperate python script to avoid frequent Bus Errors DONE
# - make sure parrallel FFT does not run out of memory (limit max. processes)/facets? DONE
# - automatic w-planes computation in imaging
# - how to deal with outlier sources low-freqs? # peel them first using low-freq bands only?
# - combine images into big image --> DONE
# - make fake avg pb images from mask to work with msss mosaic --> DONE
# - 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 remained the same, just better noise) or just proceed to the next field?
# - how to deal with Toothbrush, how to subtract it from the data properly (make low-res images for that?)
# - memory control in full resolution subtract step --> DONE
# v6
# - added SCRIPTPATH - makes it easier to switch between cep and para
# - added check of return values on some system calls (esp NDPPP which returns 0 on success)
# v7
# increase niter (for deeper clean)
# change scheme 2 to 3
#2. your new scheme
#- correct with solutions
#- phaseshift to updated position +avg
#- facet imaging
#3. proposed scheme
#- correct with solutions
#- phaseshift to selfcal center + avg
#- phaseshift to updated position (from selfcal center)
#- facet imaging
# v8
# go back... to scheme 2
# v9
# for difficult to low snr facet, but not so far from another facet try just using the other facet solutions
def ra_to_str(dra, ndec=2,delim=':'):
'''
converts a single decimal degrees ra to hh:mm:ss.s
'''
if delim == 'h':
delim1 = 'h'
delim2 = 'm'
else:
delim1 = delim
delim2 = delim
dra = dra/15.
dd = math.floor(dra)
dfrac = dra - dd
dmins = dfrac*60.
dm = math.floor(dmins)
dsec = (dmins-dm)*60.
if round(dsec, ndec) == 60.00:
dsec = 0.
dm += 1
if dm == 60.:
dm = 0.
dd += 1
sra = '%02d%s%02d%s%05.2f' %(dd,delim1,dm,delim2,dsec)
return sra
def dec_to_str(ddec,ndec=1,delim=':'):
'''
converts a single decimal degrees dec to dd:mm:ss.s
'''
if delim == 'd':
delim1 = 'd'
delim2 = 'm'
else:
delim1 = delim
delim2 = delim
dd = math.floor(ddec)
dfrac = ddec - dd
dmins = dfrac*60.
dm = math.floor(dmins)
dsec = (dmins-dm)*60.
if round(dsec, ndec) == 60.0:
dsec = 0.
dm += 1
if dm == 60.:
dm = 0.
dd += 1
sdec = '%02d%s%02d%s%04.1f' %(dd,delim1,dm,delim2,dsec)
return sdec
def find_newsize(mask):
img = pyrap.images.image(mask)
pixels = numpy.copy(img.getdata())
sh = numpy.shape(pixels)[3:4]
newsize = numpy.copy(sh[0])
sh = sh[0]
#print mask, newsize
trysizes = numpy.copy(sorted([6400,6144,5600,5400,5184,5000,4800,4608,4320,4096,3840,3600,3200,3072,2880,2560,2304,2048, 1600, 1536, 1200, 1024, 800, 512]))
#idx = numpy.where(trysizes < sh)
#print idx
#trysizes = numpy.copy(trysizes[idx]) # remove sizes larger than image
trysizes1 = numpy.copy(trysizes[::-1]) # reverse sorted
#print trysizes1
idx = numpy.where(pixels != 0)
idx_x = idx[2]
idx_y = idx[3]
span_x1 = 2*abs(max(idx_x) - sh/2)
span_x2 = 2*abs(sh/2 - min(idx_x))
span_y1 = 2*abs(max(idx_y)- sh/2)
span_y2 = 2*abs(sh/2 - min(idx_y))
max_span = max(span_x1, span_y1, span_x2, span_y2)
#print span_x1, span_x2
#print span_y1, span_y2
#print max_span
#print numpy.sum(trysizes1>= max_span)
this_size = trysizes1[numpy.sum(trysizes1>= max_span)-1]
#print "New size:", this_size
newsize = this_size
#trysizes = numpy.copy(sorted([6400,6144,5600,5400,5184,5000,4800,4608,4320,4096,3840,3600,3200,3072,2880,2560,2304,2048, 1600, 1536, 1200, 1024, 800, 512]))
#idx = numpy.where(trysizes < sh)
##print idx
#trysizes = numpy.copy(trysizes[idx]) # remove sizes larger than image
#trysizes = numpy.copy(trysizes[::-1]) # reverse sorted
#print trysizes
#for size in trysizes:
##print 'Trying', size
#cutedge = numpy.int((sh - size)/2.)
##print 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))
##print idx1, idx2, idx3, idx4
#if ((idx1) == 0) and ((idx2) == 0) and ((idx3) == 0) and ((idx4) == 0):
## UPDATE THE IMAGE SIZE
#newsize = numpy.copy(size)
#print 'Found new size', newsize, ' fits within the mask'
return newsize
def runbbs(mslist, skymodel, parset, parmdb, replacesource):
#NOTE WORK FROM MODEL_DATA (contains correct phase data from 10SB calibration)
for ms in mslist:
log = ms + '.bbslog'
if replacesource:
cmd = 'calibrate-stand-alone --replace-sourcedb --parmdb-name ' + parmdb + ' ' + ms + ' ' + parset + ' ' + skymodel + '>' + log + '&'
else:
cmd = 'calibrate-stand-alone --parmdb-name ' + parmdb + ' ' + ms + ' ' + parset + ' ' + skymodel + '>' + log + '&'
print cmd
os.system(cmd)
time.sleep(10)
done = 0
while(done < len(mslist)):
done = 0
for ms in mslist:
cmd = "grep 'INFO - bbs-reducer terminated successfully.' " + ms + ".bbslog"
output=Popen(cmd, shell=True, stdout=PIPE).communicate()[0]
if output[0:4] == 'INFO':
done = done + 1
print ms, 'is done'
time.sleep(5)
return
def runbbs16(mslist, skymodel, parset, parmdb, replacesource):
#NOTE WORK FROM MODEL_DATA (contains correct phase data from 10SB calibration)
mslist1 = mslist[0:15]
mslist2 = mslist[15:len(mslist)]
# PART1
for ms in mslist1:
log = ms + '.bbslog'
if replacesource:
cmd = 'calibrate-stand-alone --replace-sourcedb --parmdb-name ' + parmdb + ' ' + ms + ' ' + parset + ' ' + skymodel + '>' + log + '&'
else:
cmd = 'calibrate-stand-alone --parmdb-name ' + parmdb + ' ' + ms + ' ' + parset + ' ' + skymodel + '>' + log + '&'
print cmd
os.system(cmd)
time.sleep(10)
done = 0
while(done < len(mslist1)):
done = 0
for ms in mslist1:
cmd = "grep 'INFO - bbs-reducer terminated successfully.' " + ms + ".bbslog"
output=Popen(cmd, shell=True, stdout=PIPE).communicate()[0]
if output[0:4] == 'INFO':
done = done + 1
print ms, 'is done'
time.sleep(5)
# PART2
for ms in mslist2:
log = ms + '.bbslog'
if replacesource:
cmd = 'calibrate-stand-alone --replace-sourcedb --parmdb-name ' + parmdb + ' ' + ms + ' ' + parset + ' ' + skymodel + '>' + log + '&'
else:
cmd = 'calibrate-stand-alone --parmdb-name ' + parmdb + ' ' + ms + ' ' + parset + ' ' + skymodel + '>' + log + '&'
print cmd
os.system(cmd)
time.sleep(10)
done = 0
while(done < len(mslist2)):
done = 0
for ms in mslist2:
cmd = "grep 'INFO - bbs-reducer terminated successfully.' " + ms + ".bbslog"
output=Popen(cmd, shell=True, stdout=PIPE).communicate()[0]
if output[0:4] == 'INFO':
done = done + 1
print ms, 'is done'
time.sleep(5)
return
def create_subtract_parset_field_outlier(outputcolumn, TEC, clock):
bbs_parset = 'sub.parset'
os.system('rm -f ' + bbs_parset)
f=open(bbs_parset, 'w')
chunksize = 100
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 runbbs_diffskymodel_addback(mslist, parmdb, replacesource, direction, imsize, output_template_im):
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+' '+skymodel +' "'+str(direction) +'" ' + str(imsize)
output = Popen(cmd, shell=True, stdout=PIPE).communicate()[0]
callist = output.strip()
callistarraysources = callist.split(',')
print 'Adding back for calibration:', callist
parset = create_add_parset_ms(callist, ms)
if replacesource:
cmd = 'calibrate-stand-alone --replace-sourcedb --parmdb-name ' + parmdb + ' ' + ms + ' ' + parset + ' ' + skymodel + '>' + log + '&'
else:
cmd = 'calibrate-stand-alone --parmdb-name ' + parmdb + ' ' + ms + ' ' + parset + ' ' + skymodel + '>' + log + '&'
print cmd
os.system(cmd)
time.sleep(10) # otherwise add.parset is deleted (takes time for BBS to start up)
time.sleep(10)
done = 0
while(done < len(mslist)):
done = 0
for ms in mslist:
cmd = "grep 'INFO - bbs-reducer terminated successfully.' " + ms + ".bbslog"
output=Popen(cmd, shell=True, stdout=PIPE).communicate()[0]
if output[0:4] == 'INFO':
done = done + 1
print ms, 'is done'
time.sleep(5)
return
def runbbs_diffskymodel_addback16(mslist, parmdb, replacesource, direction, imsize, output_template_im):
mslist1 = mslist[0:16]
mslist2 = mslist[16:len(mslist)]
#part1
for ms in mslist1:
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+' '+skymodel +' "'+str(direction) +'" ' + str(imsize)
output = Popen(cmd, shell=True, stdout=PIPE).communicate()[0]
callist = output.strip()
callistarraysources = callist.split(',')
print 'Adding back for calibration:', callist
parset = create_add_parset_ms(callist, ms)
if replacesource:
cmd = 'calibrate-stand-alone --replace-sourcedb --parmdb-name ' + parmdb + ' ' + ms + ' ' + parset + ' ' + skymodel + '>' + log + '&'
else:
cmd = 'calibrate-stand-alone --parmdb-name ' + parmdb + ' ' + ms + ' ' + parset + ' ' + skymodel + '>' + log + '&'
print cmd
os.system(cmd)
time.sleep(10) # otherwise add.parset is deleted (takes time for BBS to start up)
time.sleep(10)
done = 0
while(done < len(mslist1)):
done = 0
for ms in mslist1:
cmd = "grep 'INFO - bbs-reducer terminated successfully.' " + ms + ".bbslog"
output=Popen(cmd, shell=True, stdout=PIPE).communicate()[0]
if output[0:4] == 'INFO':
done = done + 1
print ms, 'is done'
time.sleep(5)
#part2
for ms in mslist2:
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+' '+skymodel +' "'+str(direction) +'" ' + str(imsize)
output = Popen(cmd, shell=True, stdout=PIPE).communicate()[0]
callist = output.strip()
callistarraysources = callist.split(',')
print 'Adding back for calibration:', callist
parset = create_add_parset_ms(callist, ms)
if replacesource:
cmd = 'calibrate-stand-alone --replace-sourcedb --parmdb-name ' + parmdb + ' ' + ms + ' ' + parset + ' ' + skymodel + '>' + log + '&'
else:
cmd = 'calibrate-stand-alone --parmdb-name ' + parmdb + ' ' + ms + ' ' + parset + ' ' + skymodel + '>' + log + '&'
print cmd
os.system(cmd)
time.sleep(10) # otherwise add.parset is deleted (takes time for BBS to start up)
time.sleep(10)
done = 0
while(done < len(mslist2)):
done = 0
for ms in mslist2:
cmd = "grep 'INFO - bbs-reducer terminated successfully.' " + ms + ".bbslog"
output=Popen(cmd, shell=True, stdout=PIPE).communicate()[0]
if output[0:4] == 'INFO':
done = done + 1
print ms, 'is done'
time.sleep(5)
return
def runbbs_diffskymodel_addbackfield(mslist, parmdb, replacesource, direction, imsize, output_template_im):
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+' '+skymodel +' "'+str(direction) +'" ' + str(imsize)
output = Popen(cmd, shell=True, stdout=PIPE).communicate()[0]
callist = output.strip()
callistarraysources = callist.split(',')
print 'Add field back step 1'
# return the source list from the source to be added back sourrinding the peeling source and which fall within the mask boundaries
# put in MODEL_DATA
#addback_sourcelist = return_slist(output_template_im +'.masktmp', skymodel, callistarraysources)
cmd = 'python '+SCRIPTPATH+'/return_slist.py '+ output_template_im+' '+skymodel +' "'+str(callist)+'"'
output = Popen(cmd, shell=True, stdout=PIPE).communicate()[0]
addback_sourcelist = output.strip()
print 'Field source added back are: ', addback_sourcelist
if len(addback_sourcelist) != 0: # otherwise do not have to add
parset = create_add_parset_field_ms(addback_sourcelist, ms)
if replacesource:
cmd = 'calibrate-stand-alone --replace-sourcedb --parmdb-name ' + parmdb + ' ' + ms + ' ' + parset + ' ' + skymodel + '>' + log + '&'
else:
cmd = 'calibrate-stand-alone --parmdb-name ' + parmdb + ' ' + ms + ' ' + parset + ' ' + skymodel + '>' + log + '&'
print cmd
os.system(cmd)
else:
os.system("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)
done = 0
while(done < len(mslist)):
done = 0
for ms in mslist:
cmd = "grep 'INFO - bbs-reducer terminated successfully.' " + ms + ".bbslog"
output=Popen(cmd, shell=True, stdout=PIPE).communicate()[0]
if output[0:4] == 'INFO':
done = done + 1
print ms, 'is done'
time.sleep(5)
return
def runbbs_2(mslist, msparmdb, skymodel, parset, parmdb):
for ms_id, ms in enumerate(mslist):
log = ms + '.bbslog'
cmd = 'calibrate-stand-alone --parmdb ' + msparmdb[ms_id]+'/'+parmdb + ' ' + ms + ' ' + parset + ' ' + skymodel + '>' + log + '&'
print cmd
os.system(cmd)
time.sleep(10)
done = 0
while(done < len(mslist)):
done = 0
for ms in mslist:
cmd = "grep 'INFO - bbs-reducer terminated successfully.' " + ms + ".bbslog"
output=Popen(cmd, shell=True, stdout=PIPE).communicate()[0]
if output[0:4] == 'INFO':
done = done + 1
print ms, 'is done'
time.sleep(5)
return
def create_phaseshift_parset_full(msin, msout, direction, column):
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):
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')
# just to test
f.write('avg1.freqstep = 20\n')
f.write('avg1.timestep = 1\n')
f.close()
return ndppp_parset
def create_phaseshift_parset_formasks(msin, msout, source, direction):
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('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 = 20\n')
f.write('avg1.timestep = 1\n')
f.close()
return ndppp_parset
def create_phaseshift_parset_field(msin, msout, source, direction):
ndppp_parset = msin.split('.')[0] +'ndppp_avgphaseshift_field2.parset'
os.system('rm -f ' + ndppp_parset)
f=open(ndppp_parset, 'w')
f.write('msin ="%s"\n' % msin)
f.write('msin.datacolumn = DATA\n') # this is the second phaseshift
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_field_avg(msin, msout, source, direction):
ndppp_parset = msin.split('.')[0] +'ndppp_avgphaseshift_field1.parset'
os.system('rm -f ' + ndppp_parset)
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 = 5\n')
f.write('avg1.timestep = 3\n')
f.close()
return ndppp_parset
def create_add_parset_ms(source, ms):
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')
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 = ADDED_DATA_SOURCE\n')
f.close()
return bbs_parset
#def create_add_parset_field(source):
#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):
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')
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_subtract_parset(outputcolumn):
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, clock):
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 create_add_parset_field(outputcolumn, TEC, clock):
bbs_parset = 'add.parset'
os.system('rm -f ' + bbs_parset)
f=open(bbs_parset, 'w')
chunksize = 175
f.write('Strategy.InputColumn = SUBTRACTED_DATA_ALL\n')
f.write('Strategy.ChunkSize = %s\n' % chunksize)
f.write('Strategy.UseSolver = F\n')
f.write('Strategy.Steps = [add]\n\n\n')
f.write('Step.add.Model.Sources = [@ADDED_DATA_SOURCE]\n') ## comes from ft_allbands, then copy over columns
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 = T\n')
if TEC == "True":
f.write('Step.add.Model.TEC.Enable = T\n')
if clock == "True":
f.write('Step.add.Model.Clock.Enable = T\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 = %s\n' % outputcolumn)
f.close()
return bbs_parset
def join_parmdb(ms, parmdb_selfcal,parmdb_nondde, parmdb_template, parmdb_out, TEC, clock):
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):
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))
print 'Normalizing gains: average gain value is', 1./norm_factor
print 'Multiplying gains by:', norm_factor
if (norm_factor > 1.5) or (norm_factor < (1./1.5)):
print '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
def return_slist(imagename, skymodel, ref_source):
fluxweight = False
data = load_bbs_skymodel(skymodel)
if len(numpy.shape(data)) == 1: # in this case not issue and we do not use Pythonlibs
patchest,ra_patches,dec_patches, flux_patches = compute_patch_center(data,fluxweight)
print 'option 1'
if len(numpy.shape(data)) == 2:
patchest,ra_patches,dec_patches, flux_patches = compute_patch_center_libsproblem(data,fluxweight)
print 'option 2'
# remove sources already in the field and convert to radians
if len(ref_source) == 1:
idx = numpy.where(patchest != ref_source)
ralist = pi*(ra_patches[idx])/180.
declist = pi*(dec_patches[idx])/180.
patches = patchest[idx]
else:
idx = numpy.asarray([numpy.where(patchest == y)[0][0] for y in ref_source])
accept_idx = sorted(set(range(patchest.size)) - set(idx))
ralist = pi*(ra_patches[accept_idx])/180.
declist = pi*(dec_patches[accept_idx])/180.
patches = patchest[accept_idx]
img = pyrap.images.image(imagename)
pixels = numpy.copy(img.getdata())
plist = []
sh = numpy.shape(pixels)[2:4]
for patch_id,patch in enumerate(patches):
coor = [0,1,declist[patch_id],ralist[patch_id]]
pix = img.topixel(coor)[2:4]
if (pix[0] >= 0) and (pix[0] <= (sh[0]-1)) and \
(pix[1] >= 0) and (pix[1] <= (sh[1]-1)):
if pixels[0,0,pix[0],pix[1]] != 0.0: # only include if withtin the clean mask (==1)
plist.append(patches[patch_id])
sourcess = ''
if len(plist) == 1:
sourcess = str(plist[0])
else:
for patch in plist:
sourcess = sourcess+patch+','
sourcess = sourcess[:-1]
return sourcess
def angsep(ra1deg, dec1deg, ra2deg, dec2deg):
"""Returns angular separation between two coordinates (all in degrees)"""
import math
ra1rad=ra1deg*math.pi/180.0
dec1rad=dec1deg*math.pi/180.0
ra2rad=ra2deg*math.pi/180.0
dec2rad=dec2deg*math.pi/180.0
# calculate scalar product for determination
# of angular separation
x=math.cos(ra1rad)*math.cos(dec1rad)*math.cos(ra2rad)*math.cos(dec2rad)
y=math.sin(ra1rad)*math.cos(dec1rad)*math.sin(ra2rad)*math.cos(dec2rad)
z=math.sin(dec1rad)*math.sin(dec2rad)
if x+y+z >= 1: rad = 0
else: rad=math.acos(x+y+z)
# Angular separation
deg=rad*180/math.pi
return deg
def cal_return_slist(imagename,skymodel, direction, imsize):
factor = 0.8 # only add back in the center 80%
cut = 1.5*(imsize/2.)*factor/3600.
ra = direction.split(',')[0]
dec = direction.split(',')[1]
ra1 = float(ra.split('h')[0])*15.
ratmp = (ra.split('h')[1])
ra2 = float(ratmp.split('m')[0])*15./60
ra3 = float(ratmp.split('m')[1])*15./3600.
ref_ra= ra1 + ra2 +ra3
dec1 = float(dec.split('d')[0])
dectmp = (dec.split('d')[1])
dec2 = float(dectmp.split('m')[0])/60
dec3 = float(dectmp.split('m')[1])/3600.
ref_dec= dec1 + dec2 +dec3
fluxweight = False
data = load_bbs_skymodel(skymodel)
if len(numpy.shape(data)) == 1: # in this case not issue and we do not use Pythonlibs
patches,ra_patches,dec_patches, flux_patches = compute_patch_center(data,fluxweight)
print 'option 1'
if len(numpy.shape(data)) == 2:
patches,ra_patches,dec_patches, flux_patches = compute_patch_center_libsproblem(data,fluxweight)
print 'option 2'
ralist = pi*(ra_patches)/180.
declist = pi*(dec_patches)/180.
plist = []
print ref_ra, ref_dec