-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathOphIRS43_continuum_SB.py
653 lines (518 loc) · 28.2 KB
/
OphIRS43_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
"""
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 05/26/2021
SB2: '' 06/08/2021
LB1:
reducer:
"""
### 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 = 'OphIRS43'
prefix = 'OphIRS43'
### always include trailing slashes!!
WD_path = '/lustre/cv/projects/edisk/OphIRS43/'
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_Xec5832_X8bec.ms',
'spws': '25,27,29,31,33,35,37'},
'SB2': {'vis': SB_path+'uid___A002_Xecbc07_X5972.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/26/07:00:00~2021/05/26/09:00:00',
'contdotdat' : 'SB/cont.dat'
},
'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/06/08/05:00:00~2021/06/08/06:00:00',
'contdotdat' : 'SB/cont.dat'
},
}
'''
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
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...")
### 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'
### save updated data params to a pickle
with open(prefix+'.pickle', 'wb') as handle:
pickle.dump(data_params, handle, protocol=pickle.HIGHEST_PROTOCOL)
###############################################################
############## 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 """
#specify manual fitting mask due to binary source
mask_ra = '16h27m26.908s'.replace('h',':').replace('m',':').replace('s','')
mask_dec = '-24d40m50.85s'.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', mask=prefix+'_'+i+'_initcont_exec0.mask',region=fit_region)
### Check phase center fits in viewer, tf 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)
for i in data_params.keys():
#################### MANUALLY SET THIS ######################
data_params[i]['common_dir']='J2000 16h27m26.90669s -024d40m50.79877s'
### 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)
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'])
### 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.
### Using SB1 as reference because it looks the nicest by far
#################### 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)
#difference seems to be due to decorrelation, let self-calibration fix it
data_params['SB1']['gencal_scale']=1.0
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
###############################################################
############### 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'
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)
### 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,...'''
############### 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)
#OphIRS43_dirty.image.tt0
#Beam 0.221 arcsec x 0.143 arcsec (-67.24 deg)
#Flux inside disk mask: 35.82 mJy
#Peak intensity of source: 10.18 mJy/beam
#rms: 1.26e-01 mJy/beam
#Peak SNR: 80.75
### 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
############# 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=40.0,solint='inf',
noisemasks=[common_mask,noise_annulus],
SB_contspws=SB_contspws,SB_spwmap=SB_spwmap)
### 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...")
#OphIRS43_SB-only_p0.image.tt0
#Beam 0.221 arcsec x 0.143 arcsec (-67.24 deg)
#Flux inside disk mask: 27.62 mJy
#Peak intensity of source: 10.19 mJy/beam
#rms: 9.38e-02 mJy/beam
#Peak SNR: 108.60
iteration=1
self_calibrate(prefix,data_params,selectedVis,mode='SB-only',iteration=iteration,selfcalmode='p',nsigma=20.0,solint='30s',
noisemasks=[common_mask,noise_annulus],
SB_contspws=SB_contspws,SB_spwmap=SB_spwmap)
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...")
#OphIRS43_SB-only_p1.image.tt0
#Beam 0.221 arcsec x 0.143 arcsec (-67.24 deg)
#Flux inside disk mask: 25.68 mJy
#Peak intensity of source: 11.59 mJy/beam
#rms: 8.44e-02 mJy/beam
#Peak SNR: 137.31
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...")
#OphIRS43_SB-only_p2.image.tt0
#Beam 0.221 arcsec x 0.143 arcsec (-67.24 deg)
#Flux inside disk mask: 22.56 mJy
#Peak intensity of source: 12.20 mJy/beam
#rms: 8.26e-02 mJy/beam
#Peak SNR: 147.68
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...")
#OphIRS43_SB-only_p3.image.tt0
#Beam 0.221 arcsec x 0.143 arcsec (-67.24 deg)
#Flux inside disk mask: 20.95 mJy
#Peak intensity of source: 12.04 mJy/beam
#rms: 7.97e-02 mJy/beam
#Peak SNR: 151.10
### 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...")
#Peak SNR: 1229.56
#OphIRS43_SB-only_p4.image.tt0
#Beam 0.221 arcsec x 0.143 arcsec (-67.24 deg)
#Flux inside disk mask: 21.04 mJy
#Peak intensity of source: 12.08 mJy/beam
#rms: 7.98e-02 mJy/beam
#Peak SNR: 151.25
### Make the final image, will not run another self-calibration
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)
#OphIRS43_SB-only_ap5.image.tt0
#Beam 0.228 arcsec x 0.147 arcsec (-66.85 deg)
#Flux inside disk mask: 19.87 mJy
#Peak intensity of source: 12.26 mJy/beam
#rms: 8.23e-02 mJy/beam
#Peak SNR: 148.94
###############################################################
################# 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)
###############################################################
############### CHECK SCALING AFTER SELFCAL ###################
###############################################################
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_final'])
export_vislist.append(data_params[i]['vis_final'].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)
refdata='SB2'
reference=prefix+'_'+refdata+'_continuum.vis.npz'
for i in data_params.keys():
print(i)
if i != refdata:
estimate_flux_scale(reference=reference,comparison=prefix+'_'+i+'_continuum.vis.npz',incl=incl, PA=PA)
#The ratio of the fluxes of OphIRS43_SB1_continuum.vis.npz to OphIRS43_SB2_continuum.vis.npz is 0.89689
#The scaling factor for gencal is 0.947 for your comparison measurement
#The error on the weighted mean ratio is 2.101e-03, although it's likely that the weights in the measurement sets are off by some constant factor
#Overall small difference and will not worry about it.
###############################################################
################## 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
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')
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='0.025arcsec', imsize=1600,phasecenter=data_params['SB1']['common_dir'].replace('J2000','ICRS'))
#imagename=imagename+'.image.tt0'
#exportfits(imagename=imagename, fitsimage=imagename+'.fits',overwrite=True,dropdeg=True)
#impbcor(imagename=imagename,pbimage=imagename.replace('image','pb'),outfile=imagename.replace('image','pbcor'))
#exportfits(imagename=imagename.replace('image','pbcor'), fitsimage=imagename.replace('image','pbcor')+'.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')