-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathIRS5N_continuum_SB.py
752 lines (600 loc) · 31.8 KB
/
IRS5N_continuum_SB.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
"""
eDisk data reduction script
This script was written for CASA 6.1.1/6.2
Originally derived from DSHARP reduction scripts
Datasets calibrated (in order of date observed):
SB1: 2019.1.00261.L
LB1:
reducer: Merel van 't Hoff
"""
### Import statements
#sys.path.append('/home/casa/contrib/AIV/science/analysis_scripts/')
import analysisUtils as au
import analysisUtils as aU
import string
import os
import glob
import numpy as np
import sys
import pickle
execfile('../reduction_utils3.py', globals())
###############################################################
################ SETUP/METADATA SPECIFICATION #################
################ USERS NEED TO SET STUFF HERE #################
###############################################################
### Use MPI CASA for faster imaging (start casa with mpicasa -n XX CASA; where XX is the number of processes >= 2)
parallel=True
### if True, can run script non-interactively if later parameters properly set
skip_plots = True
### Add field names (corresponding to the field in the MS) here and prefix for
### filenameing (can be different but try to keep same)
### Only make different if, for example, the field name has a space
field = 'IRS5N'
prefix = 'IRS5N'
### always include trailing slashes!!
WD_path = '/lustre/cv/projects/edisk/IRS5N-validation/'
SB_path = WD_path+'SB/'
LB_path = WD_path+'LB/'
### scales for multi-scale clean
SB_scales = [0, 5] #[0, 5, 10, 20]
LB_scales = [0, 5, 30] #[0, 5, 30, 100, 200]
### Add additional dictionary entries if need, i.e., SB2, SB3, LB1, LB2, etc. for each execution
### Note that C18O and 13CO have different spws in the DDT vis LP os the spw ordering
### is different for data that were originally part of the DDT than the LP
### DDT 2019.A.00034.S SB data need 'spws': '25,31,29,27,33,35,37'
### LP 2019.1.00261.L SB data need 'spws': '25,27,29,31,33,35,37'
pl_data_params={'SB1': {'vis': SB_path+'uid___A002_Xebb7f0_X3680.ms',
'spws': '25,27,29,31,33,35,37'},
'SB2': {'vis': SB_path+'uid___A002_Xec0d12_X41ae.ms',
'spws': '25,27,29,31,33,35,37'},
}
### Dictionary defining necessary metadata for each execution
### SiO at 217.10498e9 excluded because of non-detection
### Only bother specifying simple species that are likely present in all datasets
### Hot corino lines (or others) will get taken care of by using the cont.dat
data_params = {'SB1': {'vis' : WD_path+prefix+'_SB1.ms',
'name' : 'SB1',
'field': field,
'line_spws': np.array([0,1,2,3,4,6,4,4,4,4,4]), # line SPWs, get from listobs
'line_freqs': np.array([218.76006600e9,220.39868420e9,219.94944200e9,219.56035410e9,
217.82215e9,230.538e9,217.94005e9,218.16044e9,217.2386e9,
218.22219200e9,218.47563200e9]), #restfreqs
'line_names': ['H2CO','13CO','SO','C18O','c-C3H2','12CO','c-C3H2','c-C3H2','DCN','H2CO','H2CO'], #restfreqs
'flagrange': np.array([[-5.5,14.5],[-5.5,14.5],[-5.5,14.5],[-5.5,14.5],
[-5.5,14.5],[-5.5,14.5],[-5.5,14.5],[-5.5,14.5],
[-5.5,14.5],[-5.5,14.5],[-5.5,14.5]]),
'orig_spw_map': {25:0, 27:1, 29:2, 31:3, 33:4, 35:5, 37:6}, # mapping of old spws to new spws (needed for cont.dat to work)
'cont_spws': np.array([0,1,2,3,4,5,6]), #spws to use for continuum
'cont_avg_width': np.array([480,480,480,480,60,60,60]), #n channels to average; approximately aiming for 30 MHz channels
'phasecenter': '',
'timerange': '2021/05/04/10:15:00~2021/05/04/11:15:00',
'contdotdat' : 'SB/cont-IRS5N.dat' # MvtH: continuum file has different name because of tracksharing with IRAS32
},
'SB2': {'vis' : WD_path+prefix+'_SB2.ms',
'name' : 'SB2',
'field': field,
'line_spws': np.array([0,1,2,3,4,6,4,4,4,4,4]), # line SPWs, get from listobs
'line_freqs': np.array([218.76006600e9,220.39868420e9,219.94944200e9,219.56035410e9,
217.82215e9,230.538e9,217.94005e9,218.16044e9,217.2386e9,
218.22219200e9,218.47563200e9]), #restfreqs
'line_names': ['H2CO','13CO','SO','C18O','c-C3H2','12CO','c-C3H2','c-C3H2','DCN','H2CO','H2CO'], #restfreqs
'flagrange': np.array([[-5.5,14.5],[-5.5,14.5],[-5.5,14.5],[-5.5,14.5],
[-5.5,14.5],[-5.5,14.5],[-5.5,14.5],[-5.5,14.5],
[-5.5,14.5],[-5.5,14.5],[-5.5,14.5]]),
'orig_spw_map': {25:0, 27:1, 29:2, 31:3, 33:4, 35:5, 37:6}, # mapping of old spws to new spws (needed for cont.dat to work)
'cont_spws': np.array([0,1,2,3,4,5,6]), #spws to use for continuum
'cont_avg_width': np.array([480,480,480,480,60,60,60]), #n channels to average; approximately aiming for 30 MHz channels
'phasecenter': '',
'timerange': '2021/05/15/08:45:00~2021/05/15/10:00:00',
'contdotdat' : 'SB/cont-IRS5N.dat' # MvtH: continuum file has different name because of tracksharing with IRAS32
},
}
'''
No LB yet
'LB1': {'vis' : LB1_path,
'name' : 'LB1',
'field' : 'Ced110IRS4',
'line_spws': np.array([]), # CO SPWs
'line_freqs': np.array([]),
'flagrange': np.array([]),
'cont_spws': np.array([]), # CO SPWs
'cont_avg_width': np.array([]),
'phasecenter': ' ',
'timerange': '2015/11/01/00:00:00~2015/11/02/00:00:00',
}
}
'''
### Flag range corresponds to velocity range in each spw that should be flagged.
### Velocity range should correspond to
### approximate width of the line contamination
#save data params to a pickle
with open(prefix+'.pickle', 'wb') as handle:
pickle.dump(data_params, handle, protocol=pickle.HIGHEST_PROTOCOL)
###############################################################
#################### DATA PREPARATION #########################
###############################################################
### split out each pipeline-calibrated dataset into an MS only containing the target data
for i in pl_data_params.keys():
if os.path.exists(prefix+'_'+i+'.ms'):
flagmanager(vis=prefix+'_'+i+'.ms', mode="restore", \
versionname="starting_flags")
else:
split(vis=pl_data_params[i]['vis'],outputvis=prefix+'_'+i+'.ms',spw=pl_data_params[i]['spws'],field=field,datacolumn='corrected')
### Backup the the flagging state at start of reduction
for i in data_params.keys():
if not os.path.exists(data_params[i]['vis']+\
".flagversions/flags.starting_flags"):
flagmanager(vis=data_params[i]['vis'], mode = 'save', versionname = 'starting_flags', comment = 'Flag states at start of reduction')
### Inspect data in each spw for each dataset
#### OPTIONAL #####
if not skip_plots:
for i in data_params.keys():
plotms(vis=data_params[i]['vis'], xaxis='frequency', yaxis='amplitude',
field=data_params[i]['field'], ydatacolumn='data',
avgtime='1e8', avgscan=True, avgbaseline=True, iteraxis='spw',
transform=True,freqframe='LSRK')
input("Press Enter key to advance to next MS/Caltable...")
#### END OPTIONAL ###
### Flag spectral regions around lines and do spectral averaging to make a smaller continuum MS
for i in data_params.keys():
flagchannels_string = get_flagchannels(data_params[i], prefix)
s=' ' # work around for Python 3 port of following string generating for loops
print(i)
avg_cont(data_params[i], prefix, flagchannels=flagchannels_string,contspws=s.join(str(elem) for elem in data_params[i]['cont_spws'].tolist()).replace(' ',','),width_array=data_params[i]['cont_avg_width'])
data_params[i]['vis_avg']=prefix+'_'+i+'_initcont.ms'
###############################################################
############## INITIAL IMAGING FOR ALIGNMENT ##################
###############################################################
### Image each dataset individually to get source position in each image
### Images are saved in the format prefix+'_name_initcont_exec#.ms'
outertaper='2000klambda' # taper if necessary to align using larger-scale uv data, small-scale may have subtle shifts from phase noise
for i in data_params.keys():
print('Imaging SB: ',i)
if 'LB' in i:
image_each_obs(data_params[i], prefix, scales=LB_scales, uvtaper=outertaper,
nsigma=5.0, sidelobethreshold=2.5, smoothfactor=1.5,interactive=False,parallel=parallel)
else:
image_each_obs(data_params[i], prefix, scales=SB_scales,
nsigma=5.0, sidelobethreshold=2.5, interactive=False,parallel=parallel)
#check masks to ensure you are actually masking the image, lower sidelobethreshold if needed
""" Fit Gaussians to roughly estimate centers, inclinations, PAs """
""" Loops through each dataset specified """
###default fit region is blank for an obvious single source
fit_region=''
###specify manual mask on brightest source if Gaussian fitting fails due to confusion
'''
mask_ra = '12h01m34.007s'.replace('h',':').replace('m',':').replace('s','')
mask_dec = '-65d08m48.101s'.replace('d','.').replace('m','.').replace('s','')
mask_pa = 90.0 # position angle of mask in degrees
mask_maj = 0.76 # semimajor axis of mask in arcsec
mask_min = 0.75 # semiminor axis of mask in arcsec
fit_region = 'ellipse[[%s, %s], [%.1farcsec, %.1farcsec], %.1fdeg]' % \
(mask_ra, mask_dec, mask_maj, mask_min, mask_pa)
'''
for i in data_params.keys():
print(i)
data_params[i]['phasecenter']=fit_gaussian(prefix+'_'+i+'_initcont_exec0.image', region=fit_region,mask=prefix+'_'+i+'_initcont_exec0.mask')
### Check phase center fits in viewer, if centers appear too shifted from the Gaussian fit,
### manually set the phase center dictionary entry by eye
""" The emission centers are slightly misaligned. So we split out the
individual executions, shift the peaks to the phase center, and reassign
the phase centers to a common direction. """
### Set common direction for each EB using one as reference (typically best looking LB image)
### MvtH: used SB2 as reference, because higher resolution than SB1.
for i in data_params.keys():
#################### MANUALLY SET THIS ######################
data_params[i]['common_dir']='J2000 19h01m48.479616s -36d57m15.38531s'
### save updated data params to a pickle
with open(prefix+'.pickle', 'wb') as handle:
pickle.dump(data_params, handle, protocol=pickle.HIGHEST_PROTOCOL)
###############################################################
#################### SHIFT PHASE CENTERS ######################
###############################################################
for i in data_params.keys():
print(i)
data_params[i]['vis_avg_shift']=prefix+'_'+i+'_initcont_shift.ms'
os.system('rm -rf '+data_params[i]['vis_avg_shift'])
fixvis(vis=data_params[i]['vis_avg'], outputvis=data_params[i]['vis_avg_shift'],
field=data_params[i]['field'],
phasecenter='J2000 '+data_params[i]['phasecenter'])
### fix planets may throw an error, usually safe to ignore
fixplanets(vis=data_params[i]['vis_avg_shift'], field=data_params[i]['field'],
direction=data_params[i]['common_dir'])
###############################################################
############### REIMAGING TO CHECK ALIGNMENT ##################
###############################################################
for i in data_params.keys():
print(i)
if 'SB' in i:
scales=SB_scales
else:
scales=LB_scales
for suffix in ['image','mask','mode','psf','pb','residual','sumwt']:
os.system('rm -rf '+prefix+'_'+i+'_initcont_shift.'+suffix)
image_each_obs_shift(data_params[i]['vis_avg_shift'], prefix, scales=scales,
nsigma=5.0, sidelobethreshold=2.5, interactive=False,parallel=parallel)
"""
MvtH: this is giving some errors?
SB1
2021-09-22 21:17:49 SEVERE image::open (file binding/tools/image/image_cmpt.cc, line 4125) Exception Reported: Exception: Unable to open image IRS5N_SB1_initcont_shift.ms.
2021-09-22 21:17:49 SEVERE image::open (file binding/tools/image/image_cmpt.cc, line 4125)+ ... thrown by static casa::ITUPLE casa::ImageFactory::fromFile(const casa6core::String&, casa6core::Bool) at File: casa-source/code/imageanalysis/ImageAnalysis/ImageFactory2.cc, line: 289
Each observation saved in the format IRS5N_SB1_initcont_shift
SB2
2021-09-22 21:19:26 SEVERE image::open (file binding/tools/image/image_cmpt.cc, line 4125) Exception Reported: Exception: Unable to open image IRS5N_SB2_initcont_shift.ms.
2021-09-22 21:19:26 SEVERE image::open (file binding/tools/image/image_cmpt.cc, line 4125)+ ... thrown by static casa::ITUPLE casa::ImageFactory::fromFile(const casa6core::String&, casa6core::Bool) at File: casa-source/code/imageanalysis/ImageAnalysis/ImageFactory2.cc, line: 289
Each observation saved in the format IRS5N_SB2_initcont_shift
"""
for i in data_params.keys():
print(i)
data_params[i]['phasecenter_new']=fit_gaussian(prefix+'_'+i+'_initcont_shift.image',\
region=fit_region,mask=prefix+'_'+i+'_initcont_shift.mask')
print('Phasecenter new: ',data_params[i]['phasecenter_new'])
print('Phasecenter old: ',data_params[i]['phasecenter'])
"""
MvtH:
SB1
19h01m48.479602s -36d57m15.38541s
#Peak of Gaussian component identified with imfit: J2000 19h01m48.479602s -36d57m15.38541s
#PA of Gaussian component: 82.31 deg
#Inclination of Gaussian component: 64.02 deg
#Pixel coordinates of peak: x = 450.014 y = 450.006
Phasecenter new: 19h01m48.479602s -36d57m15.38541s
Phasecenter old: 19h01m48.47824s -036d57m15.389905s
SB2
19h01m48.479618s -36d57m15.38529s
#Peak of Gaussian component identified with imfit: J2000 19h01m48.479618s -36d57m15.38529s
#PA of Gaussian component: 81.00 deg
#Inclination of Gaussian component: 64.12 deg
#Pixel coordinates of peak: x = 450.008 y = 450.010
Phasecenter new: 19h01m48.479618s -36d57m15.38529s
Phasecenter old: 19h01m48.47969s -036d57m15.383165s
"""
### save updated data params to a pickle
with open(prefix+'.pickle', 'wb') as handle:
pickle.dump(data_params, handle, protocol=pickle.HIGHEST_PROTOCOL)
###############################################################
############### PLOT UV DATA TO CHECK SCALING #################
###############################################################
### Assign rough emission geometry parameters; keep 0, 0
PA, incl = 0, 0
### Export MS contents into Numpy save files
export_vislist=[]
for i in data_params.keys():
export_MS(data_params[i]['vis_avg_shift'])
export_vislist.append(data_params[i]['vis_avg_shift'].replace('.ms','.vis.npz'))
if not skip_plots:
### Plot deprojected visibility profiles for all data together """
plot_deprojected(export_vislist,
fluxscale=[1.0]*len(export_vislist), PA=PA, incl=incl,
show_err=False)
### Now inspect offsets by comparing against a reference
### Set reference data using the dictionary key.
### MvtH: use SB2, but both SBs look quite good
#################### MANUALLY SET THIS ######################
refdata='SB2'
reference=prefix+'_'+refdata+'_initcont_shift.vis.npz'
for i in data_params.keys():
print(i)
if i != refdata:
data_params[i]['gencal_scale']=estimate_flux_scale(reference=reference,
comparison=prefix+'_'+i+'_initcont_shift.vis.npz',
incl=incl, PA=PA)
else:
data_params[i]['gencal_scale']=1.0
print(' ')
#No rescaling here since just one dataset
#Go ahead with rescaling anyway to keep the flow of the script
'''
MvtH: CASA output:
#The ratio of the fluxes of IRS5N_SB1_initcont_shift.vis.npz to IRS5N_SB2_initcont_shift.vis.npz is 1.02775
#The scaling factor for gencal is 1.014 for your comparison measurement
#The error on the weighted mean ratio is 5.051e-04, although it's likely that the weights in the measurement sets are off by some constant factor
'''
###############################################################
############### SCALE DATA RELATIVE TO ONE EB #################
###############################################################
os.system('rm -rf *_rescaled.ms')
for i in data_params.keys():
rescale_flux(data_params[i]['vis_avg_shift'], [data_params[i]['gencal_scale']])
rescale_flux(data_params[i]['vis_avg'], [data_params[i]['gencal_scale']])
data_params[i]['vis_avg_shift_rescaled']=data_params[i]['vis_avg_shift'].replace('.ms','_rescaled.ms')
data_params[i]['vis_avg_rescaled']=data_params[i]['vis_avg'].replace('.ms','_rescaled.ms')
###############################################################
############## PLOT UV DATA TO CHECK RE-SCALING ###############
###############################################################
if not skip_plots:
### Assign rough emission geometry parameters; keep 0, 0
PA, incl = 0, 0
### Check that rescaling did what we expect
export_vislist_rescaled=[]
for i in data_params.keys():
export_MS(data_params[i]['vis_avg_shift_rescaled'])
export_vislist_rescaled.append(data_params[i]['vis_avg_shift_rescaled'].replace('.ms','.vis.npz'))
plot_deprojected(export_vislist_rescaled,
fluxscale=[1.0]*len(export_vislist_rescaled), PA=PA, incl=incl,
show_err=False)
### Make sure differences are no longer significant
refdata='SB2' # MvtH: I assume this should be SB2 here as well now??
reference=prefix+'_'+refdata+'_initcont_shift.vis.npz'
for i in data_params.keys():
if i != refdata:
estimate_flux_scale(reference=reference,
comparison=prefix+'_'+i+'_initcont_shift_rescaled.vis.npz',
incl=incl, PA=PA)
'''
MvtH: CASA output:
#The ratio of the fluxes of IRS5N_SB1_initcont_shift_rescaled.vis.npz to IRS5N_SB2_initcont_shift.vis.npz is 1.00000
#The scaling factor for gencal is 1.000 for your comparison measurement
#The error on the weighted mean ratio is 4.915e-04, although it's likely that the weights in the measurement sets are off by some constant factor
'''
### Save data params to a pickle
with open(prefix+'.pickle', 'wb') as handle:
pickle.dump(data_params, handle, protocol=pickle.HIGHEST_PROTOCOL)
###############################################################
################ SELF-CALIBRATION PREPARATION #################
###############################################################
selectedVis='vis_avg_rescaled'
#selectedVis='vis_avg_shift_rescaled'
### determine best reference antennas based on geometry and flagging
for i in data_params.keys():
data_params[i]["refant"] = rank_refants(data_params[i][selectedVis])
'''Find reference antenna, pick 2 near array center'''
'''
if not skip_plots:
for i in data_params.keys():
if 'LB' in i:
continue
listobs(data_params[i]['vis'])
plotants(data_params[i]['vis'])
input("Press Enter key to advance to next MS/Caltable...")
'''
'''antenna name is DV/DA/PMXX'''
'''pad number is @AXXX '''
'''want antenna that is on the same pad if possible, list multiple in case one drops out'''
'''check listobs and fill in the SB_refant field '''
'''with the antenna name (DAXX, DVXX, or PMXX) @ pad number (AXXX)'''
'''so make a comma separated list like: DA43@A035,DV07@A011,...'''
#################### MANUALLY SET THIS ######################
#SB_refant = 'DA43@A035,DV07@A011,DV05@A042'
############### CHECK THESE, SHOULD BE FINE #################
SB_spwmap=[0,0,0,0,0,0,0]
SB_contspws = ''
### Make a list of EBs to image
vislist=[]
for i in data_params.keys():
if ('LB' in i): # skip over LB EBs if in SB-only mode
continue
vislist.append(data_params[i][selectedVis])
""" Set up a clean mask """
mask_ra = data_params[i]['common_dir'].split()[1].replace('h',':').replace('m',':').replace('s','')
mask_dec = data_params[i]['common_dir'].split()[2].replace('d','.').replace('m','.').replace('s','')
mask_pa = 90.0 # position angle of mask in degrees
mask_maj = 1.01 # semimajor axis of mask in arcsec
mask_min = 1.0 # semiminor axis of mask in arcsec
common_mask = 'ellipse[[%s, %s], [%.1farcsec, %.1farcsec], %.1fdeg]' % \
(mask_ra, mask_dec, mask_maj, mask_min, mask_pa)
""" Define a noise annulus, measure the peak SNR in map """
noise_annulus = "annulus[[%s, %s],['%.2farcsec', '8.0arcsec']]" % \
(mask_ra, mask_dec, 2.0*mask_maj)
###############################################################
###################### SELF-CALIBRATION #######################
###############################################################
### Initial dirty map to assess DR
tclean_wrapper(vis=vislist, imagename=prefix+'_dirty',
scales=SB_scales, niter=0,parallel=parallel,cellsize='0.025arcsec',imsize=1600)
estimate_SNR(prefix+'_dirty.image.tt0', disk_mask=common_mask,
noise_mask=noise_annulus)
#IRS5N_dirty.image.tt0
#Beam 0.228 arcsec x 0.152 arcsec (88.50 deg)
#Flux inside disk mask: 165.48 mJy
#Peak intensity of source: 37.55 mJy/beam
#rms: 2.54e-01 mJy/beam
#Peak SNR: 147.93
### Image produced by iter 0 has not selfcal applied, it's used to set the initial model
### only images >0 have self-calibration applied
### Run self-calibration command set
### 0. Split off corrected data from previous selfcal iteration (except iteration 0)
### 1. Image data to specified nsigma depth, set model column
### 2. Calculate self-cal gain solutions
### 3. Apply self-cal gain solutions to MS
### 4. Check S/N before and after
############# USERS MAY NEED TO ADJUST NSIGMA AND SOLINT FOR EACH SELF-CALIBRATION ITERATION ##############
iteration=0
self_calibrate(prefix,data_params,selectedVis,mode='SB-only',iteration=iteration,selfcalmode='p',nsigma=50.0,solint='inf',
noisemasks=[common_mask,noise_annulus],
SB_contspws=SB_contspws,SB_spwmap=SB_spwmap,parallel=parallel)
### Plot gain corrections, loop through each
if not skip_plots:
for i in data_params.keys():
plotms(vis=data_params[i][selectedVis].replace('.ms','_SB-only_p'+str(iteration)+'.g'),
xaxis='time', yaxis='phase',gridrows=4,gridcols=1,iteraxis='antenna', xselfscale=True, plotrange=[0,0,-180,180])
input("Press Enter key to advance to next MS/Caltable...")
### Make note of key metrics of image in each round
#IRS5N_SB-only_p0.image.tt0
#Beam 0.228 arcsec x 0.152 arcsec (88.50 deg)
#Flux inside disk mask: 112.46 mJy
#Peak intensity of source: 35.40 mJy/beam
#rms: 7.82e-02 mJy/beam
#Peak SNR: 452.58
#IRS5N_SB-only_p0_post.image.tt0
#Beam 0.228 arcsec x 0.152 arcsec (88.50 deg)
#Flux inside disk mask: 114.03 mJy
#Peak intensity of source: 36.34 mJy/beam
#rms: 5.43e-02 mJy/beam
#Peak SNR: 669.12
iteration=1
self_calibrate(prefix,data_params,selectedVis,mode='SB-only',iteration=iteration,selfcalmode='p',nsigma=25.0,solint='30s',
noisemasks=[common_mask,noise_annulus],
SB_contspws=SB_contspws,SB_spwmap=SB_spwmap,parallel=parallel)
if not skip_plots:
for i in data_params.keys():
plotms(vis=data_params[i][selectedVis].replace('.ms','_SB-only_p'+str(iteration)+'.g'),
xaxis='time', yaxis='phase',gridrows=4,gridcols=1,iteraxis='antenna', xselfscale=True, plotrange=[0,0,-180,180])
input("Press Enter key to advance to next MS/Caltable...")
#IRS5N_SB-only_p1.image.tt0
#Beam 0.228 arcsec x 0.152 arcsec (88.50 deg)
#Flux inside disk mask: 105.57 mJy
#Peak intensity of source: 35.41 mJy/beam
#rms: 3.92e-02 mJy/beam
#Peak SNR: 902.33
#IRS5N_SB-only_p1_post.image.tt0
#Beam 0.228 arcsec x 0.152 arcsec (88.50 deg)
#Flux inside disk mask: 105.81 mJy
#Peak intensity of source: 35.76 mJy/beam
#rms: 3.91e-02 mJy/beam
#Peak SNR: 914.00
iteration=2
self_calibrate(prefix,data_params,selectedVis,mode='SB-only',iteration=iteration,selfcalmode='p',nsigma=5.0,solint='6s',
noisemasks=[common_mask,noise_annulus],
SB_contspws=SB_contspws,SB_spwmap=SB_spwmap,parallel=parallel)
if not skip_plots:
for i in data_params.keys():
plotms(vis=data_params[i][selectedVis].replace('.ms','_SB-only_p'+str(iteration)+'.g'),
xaxis='time', yaxis='phase',gridrows=4,gridcols=1,iteraxis='antenna', xselfscale=True,plotrange=[0,0,-180,180])
input("Press Enter key to advance to next MS/Caltable...")
# Some solutions now get flagged due to SNR < 2.
#IRS5N_SB-only_p2.image.tt0
#Beam 0.228 arcsec x 0.152 arcsec (88.50 deg)
#Flux inside disk mask: 102.09 mJy
#Peak intensity of source: 35.43 mJy/beam
#rms: 3.66e-02 mJy/beam
#Peak SNR: 968.10
#IRS5N_SB-only_p2_post.image.tt0
#Beam 0.228 arcsec x 0.152 arcsec (88.50 deg)
#Flux inside disk mask: 102.50 mJy
#Peak intensity of source: 35.73 mJy/beam
#rms: 3.67e-02 mJy/beam
#Peak SNR: 972.23
iteration=3
self_calibrate(prefix,data_params,selectedVis,mode='SB-only',iteration=iteration,selfcalmode='p',nsigma=3.0,solint='int',
noisemasks=[common_mask,noise_annulus],
SB_contspws=SB_contspws,SB_spwmap=SB_spwmap,parallel=parallel)
if not skip_plots:
for i in data_params.keys():
plotms(vis=data_params[i][selectedVis].replace('.ms','_SB-only_p'+str(iteration)+'.g'),
xaxis='time', yaxis='phase',gridrows=4,gridcols=1,iteraxis='antenna', xselfscale=True,plotrange=[0,0,-180,180])
input("Press Enter key to advance to next MS/Caltable...")
#IRS5N_SB-only_p3.image.tt0
#Beam 0.228 arcsec x 0.152 arcsec (88.50 deg)
#Flux inside disk mask: 101.65 mJy
#Peak intensity of source: 35.66 mJy/beam
#rms: 3.65e-02 mJy/beam
#Peak SNR: 976.39
#IRS5N_SB-only_p3_post.image.tt0
#Beam 0.228 arcsec x 0.152 arcsec (88.50 deg)
#Flux inside disk mask: 101.65 mJy
#Peak intensity of source: 35.71 mJy/beam
#rms: 3.65e-02 mJy/beam
#Peak SNR: 978.47
### Changing self-cal mode here to ap, see use of prevselfcalmode to ensure proper split
iteration=4
self_calibrate(prefix,data_params,selectedVis,mode='SB-only',iteration=iteration,selfcalmode='ap',prevselfcalmode='p',nsigma=3.0,solint='inf',
noisemasks=[common_mask,noise_annulus],
SB_contspws=SB_contspws,SB_spwmap=SB_spwmap,parallel=parallel)
if not skip_plots:
for i in data_params.keys():
plotms(vis=data_params[i][selectedVis].replace('.ms','_SB-only_ap'+str(iteration)+'.g'), xaxis='time',
yaxis='amp',gridrows=4,gridcols=1,iteraxis='antenna', xselfscale=True,plotrange=[0,0,0,2])
input("Press Enter key to advance to next MS/Caltable...")
#IRS5N_SB-only_p4.image.tt0
#Beam 0.228 arcsec x 0.152 arcsec (88.50 deg)
#Flux inside disk mask: 101.65 mJy
#Peak intensity of source: 35.70 mJy/beam
#rms: 3.65e-02 mJy/beam
#Peak SNR: 978.87
#IRS5N_SB-only_p4_post.image.tt0
#Beam 0.232 arcsec x 0.156 arcsec (-89.95 deg)
#Flux inside disk mask: 99.54 mJy
#Peak intensity of source: 36.43 mJy/beam
#rms: 3.63e-02 mJy/beam
#Peak SNR: 1002.28
'''
iteration=5
self_calibrate(prefix,data_params,selectedVis,mode='SB-only',iteration=iteration,selfcalmode='ap',nsigma=3.0,solint='18s',
noisemasks=[common_mask,noise_annulus],
SB_contspws=SB_contspws,SB_spwmap=SB_spwmap,parallel=parallel)
if not skip_plots:
for i in data_params.keys():
plotms(vis=data_params[i][selectedVis].replace('.ms','_SB-only_ap'+str(iteration)+'.g'), xaxis='time',
yaxis='amp',gridrows=4,gridcols=1,iteraxis='antenna', xselfscale=True,plotrange=[0,0,0,2])
input("Press Enter key tto advance to next MS/Caltable...")
'''
#IRS5N_SB-only_ap5.image.tt0
#Beam 0.232 arcsec x 0.156 arcsec (-89.95 deg)
#Flux inside disk mask: 100.10 mJy
#Peak intensity of source: 36.44 mJy/beam
#rms: 3.64e-02 mJy/beam
#Peak SNR: 1000.50
#IRS5N_SB-only_ap5_post.image.tt0
#Beam 0.233 arcsec x 0.156 arcsec (-88.72 deg)
#Flux inside disk mask: 100.40 mJy
#Peak intensity of source: 36.70 mJy/beam
#rms: 3.67e-02 mJy/beam
#Peak SNR: 1000.19
# This is getting worse, so skip iteration this iteration.
### Make the final image, will not run another self-calibration
### MvtH: set solint='inf', as in last self-calibration iteration.
iteration=5
self_calibrate(prefix,data_params,selectedVis,mode='SB-only',iteration=iteration,selfcalmode='ap',nsigma=3.0,solint='inf',
noisemasks=[common_mask,noise_annulus],SB_contspws=SB_contspws,SB_spwmap=SB_spwmap,
parallel=parallel,finalimageonly=True)
#IRS5N_SB-only_ap5.image.tt0
#Beam 0.232 arcsec x 0.156 arcsec (-89.95 deg)
#Flux inside disk mask: 100.10 mJy
#Peak intensity of source: 36.44 mJy/beam
#rms: 3.64e-02 mJy/beam
#Peak SNR: 1000.50
###############################################################
################# SPLIT OFF FINAL CONT DATA ###################
###############################################################
for i in data_params.keys():
os.system('rm -rf '+prefix+'_'+i+'_continuum.ms '+prefix+'_'+i+'_continuum.ms.tgz')
split(vis=data_params[i]['vis_avg_selfcal'], outputvis=prefix+'_'+i+'_continuum.ms',
datacolumn='data')
data_params[i]['vis_final']=prefix+'_'+i+'_continuum.ms'
os.system('tar cvzf '+prefix+'_'+i+'_continuum.ms.tgz '+prefix+'_'+i+'_continuum.ms')
#save data params to a pickle
with open(prefix+'.pickle', 'wb') as handle:
pickle.dump(data_params, handle, protocol=pickle.HIGHEST_PROTOCOL)
###############################################################
################## RUN A FINAL IMAGE SET ######################
###############################################################
### Generate a vislist
vislist=[]
for i in data_params.keys():
vislist.append(data_params[i]['vis_final'])
scales = SB_scales
cellsize='0.025arcsec'
imsize=1600
for robust in [2.0,1.0,0.5,0.0,-0.5,-1.0,-2.0]:
imagename=prefix+'_SB_continuum_robust_'+str(robust)
os.system('rm -rf '+imagename+'*')
sigma = get_sensitivity(data_params, specmode='mfs',robust=robust,cellsize=cellsize, imsize=imsize)
if robust == 2.0 or robust == 1.0:
sigma=sigma*1.75
tclean_wrapper(vis=vislist, imagename=imagename, sidelobethreshold=2.0,
smoothfactor=1.5, scales=scales, threshold=3.0*sigma,
noisethreshold=3.0, robust=robust, parallel=parallel,
cellsize=cellsize, imsize=imsize,phasecenter=data_params['SB1']['common_dir'].replace('J2000','ICRS'))
imagename=imagename+'.image.tt0'
exportfits(imagename=imagename, fitsimage=imagename+'.fits',overwrite=True,dropdeg=True)
###############################################################
########################### CLEANUP ###########################
###############################################################
### Remove extra image products
os.system('rm -rf *.residual* *.psf* *.model* *dirty* *.sumwt* *.gridwt* *.workdirectory')
### put selfcalibration intermediate images somewhere safe
os.system('rm -rf initial_images')
os.system('mkdir initial_images')
os.system('mv *initcont*.image *_p*.image* *_ap*.image* initial_images')
os.system('mv *initcont*.mask *_p*.mask *_ap*.mask initial_images')
os.system('rm -rf *_p*.alpha* *_p*.pb.tt0 *_ap*.alpha* *_ap*.pb.tt0')
### Remove intermediate selfcal MSfiles
os.system("rm -rf *p{0..99}.ms")
os.system("rm -rf *p{0..99}.ms.flagversions")
### Remove rescaled selfcal MSfiles
os.system('rm -rf *rescaled.ms')
os.system('rm -rf *rescaled.ms.flagversions')
### Remove rescaled selfcal MSfiles
os.system('rm -rf *initcont*.ms')
os.system('rm -rf *initcont*.ms.flagversions')