-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathreduction_utils3.py
2081 lines (1799 loc) · 92.2 KB
/
reduction_utils3.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
"""
Functions useful for data reduction
Derived from DSHARP reduction utils
modified for eDisk project
"""
import os
import matplotlib.pyplot as plt
import numpy as np
import numpy
from casatools import table as tbtool
from casatools import ms as mstool
def LSRKvel_to_chan(msfile, field, spw, restfreq, LSRKvelocity):
"""
Identifies the channel(s) corresponding to input LSRK velocities.
Useful for choosing which channels to split out or flag if a line is expected to be present
Parameters
==========
msfile: Name of measurement set (string)
spw: Spectral window number (int)
obsid: Observation ID corresponding to the selected spectral window
restfreq: Rest frequency in Hz (float)
LSRKvelocity: input velocity in LSRK frame in km/s (float or array of floats)
Returns
=======
Channel number most closely corresponding to input LSRK velocity
"""
cc = 299792458. #speed of light in m/s
tb.open(msfile)
spw_col = tb.getcol('DATA_DESC_ID')
obs_col = tb.getcol('OBSERVATION_ID')
tb.close()
obsid = np.unique(obs_col[np.where(spw_col==spw)])
tb.open(msfile+'/SPECTRAL_WINDOW')
chanfreqs = tb.getcol('CHAN_FREQ', startrow = spw, nrow = 1)
tb.close()
tb.open(msfile+'/FIELD')
fieldnames = tb.getcol('NAME')
tb.close()
tb.open(msfile+'/OBSERVATION')
obstime = np.squeeze(tb.getcol('TIME_RANGE', startrow = obsid, nrow = 1))[0]
tb.close()
nchan = len(chanfreqs)
ms.open(msfile)
lsrkfreqs = ms.cvelfreqs(spwids = [spw], fieldids = int(np.where(fieldnames==field)[0][0]), mode = 'channel', nchan = nchan, obstime = str(obstime)+'s', start = 0, outframe = 'LSRK')
chanvelocities = (restfreq-lsrkfreqs)/restfreq*cc/1.e3 #converted to LSRK velocities in km/s
ms.close()
if type(LSRKvelocity)==np.ndarray:
outchans = np.zeros_like(LSRKvelocity)
for i in range(len(LSRKvelocity)):
outchans[i] = np.argmin(np.abs(chanvelocities - LSRKvelocity[i]))
return outchans
else:
return np.argmin(np.abs(chanvelocities - LSRKvelocity))
def LSRKfreq_to_chan(msfile, field, spw, LSRKfreq):
"""
Identifies the channel(s) corresponding to input LSRK frequencies.
Useful for choosing which channels to split out or flag if a line has been identified by the pipeline.
Parameters
==========
msfile: Name of measurement set (string)
spw: Spectral window number (int)
obsid: Observation ID corresponding to the selected spectral window
restfreq: Rest frequency in Hz (float)
LSRKvelocity: input velocity in LSRK frame in km/s (float or array of floats)
Returns
=======
Channel number most closely corresponding to input LSRK frequency.
"""
tb.open(msfile)
spw_col = tb.getcol('DATA_DESC_ID')
obs_col = tb.getcol('OBSERVATION_ID')
tb.close()
obsid = np.unique(obs_col[np.where(spw_col==spw)])
tb.open(msfile+'/SPECTRAL_WINDOW')
chanfreqs = tb.getcol('CHAN_FREQ', startrow = spw, nrow = 1)
tb.close()
tb.open(msfile+'/FIELD')
fieldnames = tb.getcol('NAME')
tb.close()
tb.open(msfile+'/OBSERVATION')
obstime = np.squeeze(tb.getcol('TIME_RANGE', startrow = obsid, nrow = 1))[0]
tb.close()
nchan = len(chanfreqs)
ms.open(msfile)
lsrkfreqs = ms.cvelfreqs(spwids = [spw], fieldids = int(np.where(fieldnames==field)[0][0]), mode = 'channel', nchan = nchan, \
obstime = str(obstime)+'s', start = 0, outframe = 'LSRK') / 1e9
ms.close()
if type(LSRKfreq)==np.ndarray:
outchans = np.zeros_like(LSRKfreq)
for i in range(len(LSRKfreq)):
outchans[i] = np.argmin(np.abs(lsrkfreqs - LSRKfreq[i]))
return outchans
else:
return np.argmin(np.abs(lsrkfreqs - LSRKfreq))
def parse_contdotdat(contdotdat_file, orig_spw_map):
"""
Parses the cont.dat file that includes line emission automatically identified by the ALMA pipeline.
Parameters
==========
msfile: Name of the cont.dat file (string)
Returns
=======
Dictionary with the boundaries of the frequency range including line emission. The dictionary keys correspond to the spectral windows identified
in the cont.dat file, and the entries include numpy arrays with shape (nline, 2), with the 2 corresponding to min and max frequencies identified.
"""
f = open(contdotdat_file,'r')
lines = f.readlines()
f.close()
while '\n' in lines:
lines.remove('\n')
contdotdat = {}
for i, line in enumerate(lines):
if 'Field' in line:
continue
elif 'SpectralWindow' in line:
spw = int(line.split()[-1])
contdotdat[orig_spw_map[spw]] = []
else:
contdotdat[orig_spw_map[spw]] += [line.split()[0].split("G")[0].split("~")]
for spw in contdotdat:
contdotdat[spw] = np.array(contdotdat[spw], dtype=float)
return contdotdat
def flagchannels_from_contdotdat(ms_dict):
"""
Generates a string with the list of lines identified by the cont.dat file from the ALMA pipeline, that need to be flagged.
Parameters
==========
ms_dict: Dictionary of information about measurement set
Returns
=======
String of channels to be flagged, in a format that can be passed to the spw parameter in CASA's flagdata task.
"""
contdotdat = parse_contdotdat(ms_dict['contdotdat'], ms_dict['orig_spw_map'])
flagchannels_string = ''
for j,spw in enumerate(contdotdat):
flagchannels_string += '%d:' % (spw)
tb.open(ms_dict['vis']+'/SPECTRAL_WINDOW')
nchan = tb.getcol('CHAN_FREQ', startrow = spw, nrow = 1).size
tb.close()
chans = np.array([])
for k in range(contdotdat[spw].shape[0]):
print(spw, contdotdat[spw][k])
chans = np.concatenate((LSRKfreq_to_chan(ms_dict['vis'], ms_dict['field'], spw, contdotdat[spw][k]),chans))
"""
if flagchannels_string == '':
flagchannels_string+='%d:%d~%d' % (spw, np.min([chans[0], chans[1]]), np.max([chans[0], chans[1]]))
else:
flagchannels_string+=', %d:%d~%d' % (spw, np.min([chans[0], chans[1]]), np.max([chans[0], chans[1]]))
"""
chans = np.sort(chans)
flagchannels_string += '0~%d;' % (chans[0])
for i in range(1,chans.size-1,2):
flagchannels_string += '%d~%d;' % (chans[i], chans[i+1])
flagchannels_string += '%d~%d, ' % (chans[-1], nchan-1)
print("# Flagchannels input string for %s from cont.dat file: \'%s\'" % (ms_dict['name'], flagchannels_string))
return flagchannels_string
def get_fitspw(msdict,output_prefix):
if 'contdotdat' in ms_dict:
print("# cont.dat file found, adding lines identified by the ALMA pipeline.")
contdot_dat_fitspw_string = fitspw_from_contdotdat(ms_dict)
# Merge the two strings together properly. First create (N,2) arrays of (start flagging, stop flagging) channels and store them in
# dictionaries where the keys are the SPWs.
basic_dict = dict([line.split(":") for line in flagchannels_string.split()])
for spw in basic_dict:
basic_dict[spw] = basic_dict[spw].split(',')[0].split(';')
for i in range(len(basic_dict[spw])):
basic_dict[spw][i] = basic_dict[spw][i].split('~')
basic_dict[spw] = numpy.array(basic_dict[spw], dtype=int)
cont_dict = dict([line.split(":") for line in contdot_dat_flagchannels_string.split()])
for spw in cont_dict:
cont_dict[spw] = cont_dict[spw].split(',')[0].split(';')
for i in range(len(cont_dict[spw])):
cont_dict[spw][i] = cont_dict[spw][i].split('~')
cont_dict[spw] = numpy.array(cont_dict[spw], dtype=int)
# Now merge those two dictionaries into one.
keys = np.unique(np.concatenate((np.array(list(basic_dict.keys())), np.array(list(cont_dict.keys())))))
merged_dict = {}
for key in keys:
if key in basic_dict and key not in cont_dict:
merged_dict[key] = basic_dict[key].flatten()
elif key in cont_dict and key not in basic_dict:
merged_dict[key] = cont_dict[key].flatten()
else:
merged_dict[key] = numpy.concatenate((basic_dict[key],cont_dict[key]), axis=0)
# Now make sure we remove any overlap in (start, stop) channels. E.g. if we have (0, 10) and (6, 11) we want to replace that with
# just (0, 11).
chans = list(merged_dict[key][merged_dict[key][:,0].argsort(),:].flatten())
i = 1
while True:
if i >= len(chans)-1 or len(chans) == 2:
break
if chans[i] > chans[i+1]:
chans.pop(i + 1)
if chans[i+1] > chans[i]:
chans.pop(i)
else:
chans.pop(i+1)
else:
i += 2
merged_dict[key] = chans
# Finally, recreate the string.
flagchannels_string = ''
for key in merged_dict.keys():
flagchannels_string += key+":"
for i in range(0,len(merged_dict[key]),2):
if i > 0:
flagchannels_string += ';'
flagchannels_string += '%d~%d' % (merged_dict[key][i], merged_dict[key][i+1])
flagchannels_string += ", "
flagchannels_string=flagchannels_string[:-2]
print("# Flagchannels input string for %s: \'%s\'" % (ms_dict['name'], flagchannels_string))
return flagchannels_string
def fitspw_from_contdotdat(ms_dict):
"""
Generates a string with the list of lines identified by the cont.dat file from the ALMA pipeline, that need to be flagged.
Parameters
==========
ms_dict: Dictionary of information about measurement set
Returns
=======
String of channels to be flagged, in a format that can be passed to the spw parameter in CASA's flagdata task.
"""
contdotdat = parse_contdotdat(ms_dict['contdotdat'], ms_dict['orig_spw_map'])
fitspw_string = ''
for j,spw in enumerate(contdotdat):
#fitspw_string += '%d:' % (spw)
if fitspw_string !='':
fitspw_string=fitspw_string[:-1]
fitspw_string += ',%d:' % (spw)
else:
fitspw_string += '%d:' % (spw)
tb.open(ms_dict['vis']+'/SPECTRAL_WINDOW')
nchan = tb.getcol('CHAN_FREQ', startrow = spw, nrow = 1).size
tb.close()
chans = np.array([])
for k in range(contdotdat[spw].shape[0]):
print(spw, contdotdat[spw][k])
chans = np.concatenate((LSRKfreq_to_chan(ms_dict['vis'], ms_dict['field'], spw, contdotdat[spw][k]),chans))
"""
if flagchannels_string == '':
flagchannels_string+='%d:%d~%d' % (spw, np.min([chans[0], chans[1]]), np.max([chans[0], chans[1]]))
else:
flagchannels_string+=', %d:%d~%d' % (spw, np.min([chans[0], chans[1]]), np.max([chans[0], chans[1]]))
"""
chans = np.sort(chans)
for i in range(0,chans.size-1,2):
fitspw_string += '%d~%d;' % (chans[i], chans[i+1])
fitspw_string=fitspw_string[:-1]
print("# Flagchannels input string for %s from cont.dat file: \'%s\'" % (ms_dict['name'], fitspw_string))
return fitspw_string
def get_flagchannels(ms_dict, output_prefix):
"""
Identify channels to flag based on provided velocity range of the line emission
Parameters
==========
ms_dict: Dictionary of information about measurement set
output_prefix: Prefix for all output file names (string)
velocity_range: Velocity range (in km/s) over which line emission has been identified, in the format np.array([min_velocity, max_velocity])
velocity_range: turned into part of the ms dictionary to specify individual ranges around particular lines
Returns
=======
String of channels to be flagged, in a format that can be passed to the spw parameter in CASA's flagdata task.
"""
flagchannels_string = ''
for spw in np.unique(ms_dict['line_spws']):
flagchannels_string += '%d:' % (spw)
for count, j in enumerate(np.where(ms_dict['line_spws'] == spw)[0]):
print(ms_dict['flagrange'][j],'spw:',ms_dict['line_spws'][j],j)
if count==0:
chans = LSRKvel_to_chan(ms_dict['vis'], ms_dict['field'], spw, ms_dict['line_freqs'][j] , \
ms_dict['flagrange'][j]).reshape((1,ms_dict['flagrange'][j].size))
#flagchannels_string+='%d~%d' % (np.min([chans[0], chans[1]]), np.max([chans[0], chans[1]]))
else:
chans = np.concatenate((LSRKvel_to_chan(ms_dict['vis'], ms_dict['field'], spw, ms_dict['line_freqs'][j] , \
ms_dict['flagrange'][j]).reshape((1,ms_dict['flagrange'][j].size)), chans), axis=0)
#flagchannels_string+=';%d~%d' % (np.min([chans[0], chans[1]]), np.max([chans[0], chans[1]]))
# Check that there's no overlap in their ranges.
chans.sort(axis=1)
chans = list(chans[chans[:,0].argsort(),:].flatten())
i = 1
while True:
if i >= len(chans)-1 or len(chans) == 2:
break
if chans[i] > chans[i+1]:
chans.pop(i + 1)
if chans[i+1] > chans[i]:
chans.pop(i)
else:
chans.pop(i+1)
else:
i += 2
# Now add these ranges to the string.
for i in range(0,len(chans),2):
if i == 0:
flagchannels_string+='%d~%d' % (chans[i], chans[i+1])
else:
flagchannels_string+=';%d~%d' % (chans[i], chans[i+1])
flagchannels_string += ", "
if 'contdotdat' in ms_dict:
print("# cont.dat file found, adding lines identified by the ALMA pipeline.")
contdot_dat_flagchannels_string = flagchannels_from_contdotdat(ms_dict)
# Merge the two strings together properly. First create (N,2) arrays of (start flagging, stop flagging) channels and store them in
# dictionaries where the keys are the SPWs.
basic_dict = dict([line.split(":") for line in flagchannels_string.split()])
for spw in basic_dict:
basic_dict[spw] = basic_dict[spw].split(',')[0].split(';')
for i in range(len(basic_dict[spw])):
basic_dict[spw][i] = basic_dict[spw][i].split('~')
basic_dict[spw] = numpy.array(basic_dict[spw], dtype=int)
cont_dict = dict([line.split(":") for line in contdot_dat_flagchannels_string.split()])
for spw in cont_dict:
cont_dict[spw] = cont_dict[spw].split(',')[0].split(';')
for i in range(len(cont_dict[spw])):
cont_dict[spw][i] = cont_dict[spw][i].split('~')
cont_dict[spw] = numpy.array(cont_dict[spw], dtype=int)
# Now merge those two dictionaries into one.
keys = np.unique(np.concatenate((np.array(list(basic_dict.keys())), np.array(list(cont_dict.keys())))))
merged_dict = {}
for key in keys:
if key in basic_dict and key not in cont_dict:
merged_dict[key] = basic_dict[key].flatten()
elif key in cont_dict and key not in basic_dict:
merged_dict[key] = cont_dict[key].flatten()
else:
merged_dict[key] = numpy.concatenate((basic_dict[key],cont_dict[key]), axis=0)
# Now make sure we remove any overlap in (start, stop) channels. E.g. if we have (0, 10) and (6, 11) we want to replace that with
# just (0, 11).
chans = list(merged_dict[key][merged_dict[key][:,0].argsort(),:].flatten())
i = 1
while True:
if i >= len(chans)-1 or len(chans) == 2:
break
if chans[i] > chans[i+1]:
chans.pop(i + 1)
if chans[i+1] > chans[i]:
chans.pop(i)
else:
chans.pop(i+1)
else:
i += 2
merged_dict[key] = chans
# Finally, recreate the string.
flagchannels_string = ''
for key in merged_dict.keys():
flagchannels_string += key+":"
for i in range(0,len(merged_dict[key]),2):
if i > 0:
flagchannels_string += ';'
flagchannels_string += '%d~%d' % (merged_dict[key][i], merged_dict[key][i+1])
flagchannels_string += ", "
flagchannels_string=flagchannels_string[:-2]
print("# Flagchannels input string for %s: \'%s\'" % (ms_dict['name'], flagchannels_string))
return flagchannels_string
def get_flagchannels_withcont(ms_dict, output_prefix):
"""
Identify channels to flag based on provided velocity range of the line emission
Parameters
==========
ms_dict: Dictionary of information about measurement set
output_prefix: Prefix for all output file names (string)
velocity_range: Velocity range (in km/s) over which line emission has been identified, in the format np.array([min_velocity, max_velocity])
velocity_range: turned into part of the ms dictionary to specify individual ranges around particular lines
Returns
=======
String of channels to be flagged, in a format that can be passed to the spw parameter in CASA's flagdata task.
"""
flagchannels_string = ''
for j,spw in enumerate(ms_dict['line_spws']):
print(ms_dict['flagrange'][j],j)
chans = LSRKvel_to_chan(ms_dict['vis'], ms_dict['field'], spw, ms_dict['line_freqs'][j] , ms_dict['flagrange'][j])
if j==0:
flagchannels_string+='%d:%d~%d' % (spw, np.min([chans[0], chans[1]]), np.max([chans[0], chans[1]]))
else:
flagchannels_string+=', %d:%d~%d' % (spw, np.min([chans[0], chans[1]]), np.max([chans[0], chans[1]]))
for j,spw in enumerate(ms_dict['cont_spws_orig']):
if flagchannels_string != '':
flagchannels_string+=', %d:%d~%d' % (spw, 0,0)
else:
flagchannels_string+='%d:%d~%d' % (spw, 0,0)
print("# Flagchannels input string for %s: \'%s\'" % (ms_dict['name'], flagchannels_string))
return flagchannels_string
def get_flagchannels_concat(ms_dict, output_prefix):
"""
Identify channels to flag based on provided velocity range of the line emission
Parameters
==========
ms_dict: Dictionary of information about measurement set
output_prefix: Prefix for all output file names (string)
velocity_range: Velocity range (in km/s) over which line emission has been identified, in the format np.array([min_velocity, max_velocity])
velocity_range: turned into part of the ms dictionary to specify individual ranges around particular lines
Returns
=======
String of channels to be flagged, in a format that can be passed to the spw parameter in CASA's flagdata task.
"""
flagchannels_string = ''
for j,spw in enumerate(ms_dict['contsub_spws_concat']):
print(ms_dict['flagrange'][j],j)
chans = LSRKvel_to_chan(ms_dict['vis'], ms_dict['field'], ms_dict['line_spws'][j], ms_dict['line_freqs'][j] , ms_dict['flagrange'][j])
if j==0:
flagchannels_string+='%d:%d~%d' % (spw, np.min([chans[0], chans[1]]), np.max([chans[0], chans[1]]))
else:
flagchannels_string+=', %d:%d~%d' % (spw, np.min([chans[0], chans[1]]), np.max([chans[0], chans[1]]))
for j,spw in enumerate(ms_dict['cont_spws']):
if flagchannels_string != '':
flagchannels_string+=', %d:%d~%d' % (spw, 0,0)
else:
flagchannels_string+='%d:%d~%d' % (spw, 0,0)
print("# Flagchannels input string for %s: \'%s\'" % (ms_dict['name'], flagchannels_string))
return flagchannels_string
def get_contsub_spws(ms_dict, output_prefix):
"""
Identify channels to flag based on provided velocity range of the line emission
Parameters
==========
ms_dict: Dictionary of information about measurement set
output_prefix: Prefix for all output file names (string)
velocity_range: Velocity range (in km/s) over which line emission has been identified, in the format np.array([min_velocity, max_velocity])
velocity_range: turned into part of the ms dictionary to specify individual ranges around particular lines
Returns
=======
String of channels to be flagged, in a format that can be passed to the spw parameter in CASA's flagdata task.
"""
flagchannels_string = ''
for j,spw in enumerate(ms_dict['contsub_spws_concat']):
print(ms_dict['flagrange'][j],j)
chans = LSRKvel_to_chan(ms_dict['vis'], ms_dict['field'], ms_dict['line_spws'][j], ms_dict['line_freqs'][j] , ms_dict['flagrange'][j])
if j==0:
flagchannels_string+='%d' % (spw)
else:
flagchannels_string+=', %d' % (spw)
for j,spw in enumerate(ms_dict['cont_spws']):
if flagchannels_string != '':
flagchannels_string+=', %d' % (spw)
#flagchannels_string+=', %d:%d~%d' % (spw, 0,0)
else:
flagchannels_string+='%d' % (spw)
print("# Contsub spw selection for %s: \'%s\'" % (ms_dict['name'], flagchannels_string))
return flagchannels_string
def get_contsub_spws_indivdual_ms(ms_dict, output_prefix,only_cont_spws=True):
"""
Identify channels to flag based on provided velocity range of the line emission
Parameters
==========
ms_dict: Dictionary of information about measurement set
output_prefix: Prefix for all output file names (string)
velocity_range: Velocity range (in km/s) over which line emission has been identified, in the format np.array([min_velocity, max_velocity])
velocity_range: turned into part of the ms dictionary to specify individual ranges around particular lines
Returns
=======
String of channels to be flagged, in a format that can be passed to the spw parameter in CASA's flagdata task.
"""
flagchannels_string = ''
if only_cont_spws == False:
for j,spw in enumerate(ms_dict['line_spws']):
print(ms_dict['flagrange'][j],j)
chans = LSRKvel_to_chan(ms_dict['vis'], ms_dict['field'], ms_dict['line_spws'][j], ms_dict['line_freqs'][j] , ms_dict['flagrange'][j])
if j==0:
flagchannels_string+='%d' % (spw)
else:
flagchannels_string+=', %d' % (spw)
for j,spw in enumerate(ms_dict['cont_spws']):
if flagchannels_string != '':
flagchannels_string+=', %d' % (spw)
#flagchannels_string+=', %d:%d~%d' % (spw, 0,0)
else:
flagchannels_string+='%d' % (spw)
print("# Contsub spw selection for %s: \'%s\'" % (ms_dict['name'], flagchannels_string))
return flagchannels_string
def avg_cont(ms_dict, output_prefix, flagchannels = '', maxchanwidth = 125, datacolumn = 'data', contspws = None, width_array = None):
"""
Produce spectrally averaged continuum measurement sets
Parameters
==========
ms_dict: Dictionary of information about measurement set
output_prefix: Prefix for all output file names (string)
flagchannels: Argument to be passed for flagchannels parameter in flagdata task
maxchanwidth: Maximum width of channel (MHz). This is the value recommended by ALMA for Band 6 to avoid bandwidth smearing
datacolumn: Column to pull from for continuum averaging (usually will be 'data', but may sometimes be 'corrected' if there was flux rescaling applied)
contspws: Argument to be passed to CASA for the spw parameter in split. If not set, all SPWs will be selected by default. (string)
width_array: Argument to be passed to CASA for the width parameter in split. If not set, all SPWs will be selected by default. (array)
"""
msfile = ms_dict['vis']
tb.open(msfile+'/SPECTRAL_WINDOW')
total_bw = tb.getcol('TOTAL_BANDWIDTH')
num_chan = tb.getcol('NUM_CHAN')
tb.close()
if width_array is None and contspws is None:
width_array = (num_chan/np.ceil(total_bw/(1.e6*maxchanwidth))).astype('int').tolist() #array of number of channels to average to form an output channel (to be passed to mstransform)
contspws = '%d~%d' % (0, len(total_bw)-1)#by default select all SPWs
elif (width_array is not None and contspws is None) or (width_array is None and contspws is not None):
print("If either contspws or width_array is set to a value, the other parameter has to be manually set as well")
return
#not doing any time binning for now.
if 'LB' in ms_dict['name']:
timebin = '0s'
else:
timebin = '0s' #default in CASA
#start of CASA commands
if len(flagchannels)==0:
outputvis = output_prefix+'_'+ms_dict['name']+'_initcont.ms'
os.system('rm -rf '+outputvis)
split(vis=msfile,
field = ms_dict['field'],
spw = contspws,
outputvis = outputvis,
width = width_array,
timebin = timebin,
datacolumn=datacolumn,
intent = 'OBSERVE_TARGET#ON_SOURCE',
keepflags = True)
else:
if os.path.isdir(msfile+'.flagversions/flags.before_cont_flags'):
flagmanager(vis = msfile, mode = 'delete', versionname = 'before_cont_flags') # clear out old versions of the flags
if os.path.isdir(msfile+'.flagversions/flags.cont_flags'):
flagmanager(vis = msfile, mode = 'delete', versionname = 'cont_flags') # clear out old versions of the flags
flagmanager(vis = msfile, mode = 'save', versionname = 'before_cont_flags', comment = 'Flag states before spectral lines are flagged') #save flag state before flagging spectral lines
flagdata(vis=msfile, mode='manual', spw=flagchannels, flagbackup=False, field = ms_dict['field']) #flag spectral lines
flagmanager(vis = msfile, mode = 'save', versionname = 'cont_flags', comment = 'Flag state after line flagging')
outputvis = output_prefix+'_'+ms_dict['name']+'_initcont.ms'
os.system('rm -rf '+outputvis)
split(vis=msfile,
field = ms_dict['field'],
spw = contspws,
outputvis = outputvis,
width = width_array,
timebin = timebin,
datacolumn=datacolumn,
intent = 'OBSERVE_TARGET#ON_SOURCE',
keepflags = True)
flagmanager(vis = msfile, mode = 'restore', versionname = 'before_cont_flags') #restore flagged spectral line channels
print("#Averaged continuum dataset saved to %s" % outputvis)
def split_spec(ms_dict, output_prefix, datacolumn = 'data'):
"""
Produce spectrally averaged continuum measurement sets
Parameters
==========
ms_dict: Dictionary of information about measurement set
output_prefix: Prefix for all output file names (string)
flagchannels: Argument to be passed for flagchannels parameter in flagdata task
maxchanwidth: Maximum width of channel (MHz). This is the value recommended by ALMA for Band 6 to avoid bandwidth smearing
datacolumn: Column to pull from for continuum averaging (usually will be 'data', but may sometimes be 'corrected' if there was flux rescaling applied)
contspws: Argument to be passed to CASA for the spw parameter in split. If not set, all SPWs will be selected by default. (string)
width_array: Argument to be passed to CASA for the width parameter in split. If not set, all SPWs will be selected by default. (array)
"""
msfile = ms_dict['vis']
tb.open(msfile+'/SPECTRAL_WINDOW')
total_bw = tb.getcol('TOTAL_BANDWIDTH')
num_chan = tb.getcol('NUM_CHAN')
tb.close()
if 'LB' in ms_dict['name']:
timebin = '6s'
else:
timebin = '0s' #default in CASA
split(vis=msfile,field = ms_dict['field'],outputvis=prefix+'_initspec.ms')
def contsub(msfile, output_prefix, spw='',flagchannels = '', datacolumn = 'data', excludechans = True,combine=''):
"""
Produce spectrally averaged continuum measurement sets
Parameters
==========
ms_dict: Dictionary of information about measurement set
output_prefix: Prefix for all output file names (string)
flagchannels: Argument to be passed for flagchannels parameter in flagdata task
maxchanwidth: Maximum width of channel (MHz). This is the value recommended by ALMA for Band 6 to avoid bandwidth smearing
datacolumn: Column to pull from for continuum averaging (usually will be 'data', but may sometimes be 'corrected' if there was flux rescaling applied)
contspws: Argument to be passed to CASA for the spw parameter in split. If not set, all SPWs will be selected by default. (string)
width_array: Argument to be passed to CASA for the width parameter in split. If not set, all SPWs will be selected by default. (array)
"""
#start of CASA commands
uvcontsub(vis=msfile, fitspw=flagchannels, spw=spw,field = '',fitorder=1,solint='int',combine=combine,excludechans=excludechans) #flag spectral lines
print("#Continuum subtracted dataset saved to %s" % msfile+'.contsub')
def tclean_wrapper(vis, imagename, scales, smallscalebias = 0.6, mask = '', nsigma=5.0, imsize = None, cellsize = None, interactive = False, robust = 0.5, gain = 0.1, niter = 50000, cycleniter = 300, uvtaper = [], savemodel = 'none', sidelobethreshold=3.0,smoothfactor=1.0,noisethreshold=5.0,lownoisethreshold=1.5,parallel=False,nterms=2,
cyclefactor=3,uvrange='',threshold='0.0Jy',phasecenter='',startmodel='',pblimit=0.1,pbmask=0.1):
"""
Wrapper for tclean with keywords set to values desired for the Large Program imaging
See the CASA 6.1.1 documentation for tclean to get the definitions of all the parameters
"""
if 'LB' in vis and sidelobethreshold>3.0:
sidelobethreshold=2.0
if mask == '':
usemask='auto-multithresh'
else:
usemask='user'
if threshold != '0.0Jy':
nsigma=0.0
if imsize is None:
if 'LB' in vis or 'combined' in vis or 'continuum' in vis:
imsize = 6000
elif 'SB' in vis:
imsize = 1600
else:
print("Error: need to set imsize manually")
if cellsize is None:
if 'LB' in vis or 'combined' in vis or 'continuum' in vis:
cellsize = '.003arcsec'
elif 'SB' in vis:
cellsize = '.03arcsec'
else:
print("Error: need to set cellsize manually")
for ext in ['.image*', '.mask', '.model*', '.pb*', '.psf*', '.residual*', '.sumwt*','.gridwt*']:
os.system('rm -rf '+ imagename + ext)
tclean(vis= vis,
imagename = imagename,
specmode = 'mfs',
deconvolver = 'mtmfs',
scales = scales,
weighting='briggs',
robust = robust,
gain = gain,
imsize = imsize,
cell = cellsize,
smallscalebias = smallscalebias, #set to CASA's default of 0.6 unless manually changed
niter = niter, #we want to end on the threshold
interactive = interactive,
nsigma=nsigma,
cycleniter = cycleniter,
cyclefactor = cyclefactor,
uvtaper = uvtaper,
savemodel = 'none',
mask=mask,
usemask=usemask,
sidelobethreshold=sidelobethreshold,
smoothfactor=smoothfactor,
pbmask=pbmask,
pblimit=pblimit,
nterms = nterms,
uvrange=uvrange,
threshold=threshold,
parallel=parallel,
phasecenter=phasecenter,
startmodel=startmodel)
#this step is a workaround a bug in tclean that doesn't always save the model during multiscale clean. See the "Known Issues" section for CASA 5.1.1 on NRAO's website
if savemodel=='modelcolumn':
print("")
print("Running tclean a second time to save the model...")
tclean(vis= vis,
imagename = imagename,
specmode = 'mfs',
deconvolver = 'mtmfs',
scales = scales,
weighting='briggs',
robust = robust,
gain = gain,
imsize = imsize,
cell = cellsize,
smallscalebias = smallscalebias, #set to CASA's default of 0.6 unless manually changed
niter = 0,
interactive = False,
nsigma=nsigma,
cycleniter = cycleniter,
cyclefactor = cyclefactor,
uvtaper = uvtaper,
usemask='auto-multithresh',
savemodel = savemodel,
sidelobethreshold=sidelobethreshold,
smoothfactor=smoothfactor,
pbmask=pbmask,
pblimit=pblimit,
calcres = False,
calcpsf = False,
nterms = nterms,
uvrange=uvrange,
threshold=threshold,
parallel=False,
phasecenter=phasecenter)
def tclean_fill_model_column(vis, imagename, scales, smallscalebias = 0.6, mask = '', nsigma=5.0, imsize = None, cellsize = None, interactive = False, robust = 0.5, gain = 0.1, niter = 50000, cycleniter = 300, uvtaper = [], savemodel = 'none', sidelobethreshold=3.0,smoothfactor=1.0,noisethreshold=5.0,lownoisethreshold=1.5,parallel=False,nterms=2,
cyclefactor=3,uvrange='',threshold='0.0Jy',phasecenter='',startmodel='',pblimit=0.1,pbmask=0.1):
print("Running tclean to fill the model column...")
tclean(vis= vis,
imagename = imagename,
specmode = 'mfs',
deconvolver = 'mtmfs',
scales = scales,
weighting='briggs',
robust = robust,
gain = gain,
imsize = imsize,
cell = cellsize,
smallscalebias = smallscalebias, #set to CASA's default of 0.6 unless manually changed
niter = 0,
interactive = False,
nsigma=0.0,
cycleniter = cycleniter,
cyclefactor = cyclefactor,
uvtaper = uvtaper,
usemask='user',
savemodel = 'modelcolumn',
sidelobethreshold=sidelobethreshold,
smoothfactor=smoothfactor,
pbmask=pbmask,
pblimit=pblimit,
calcres = False,
calcpsf = False,
restart = True,
nterms = nterms,
uvrange=uvrange,
threshold=threshold,
parallel=False,
phasecenter=phasecenter)
def tclean_spectral_line_wrapper(vis, imagename, start, width, nchan, restfreq, spw, scales, smallscalebias = 0.6, mask = '', nsigma=5.0, imsize = None, cellsize = None, interactive = False, robust = 0.5, gain = 0.1, niter = 50000, cycleniter = 300, uvtaper = [], savemodel = 'none', sidelobethreshold=3.0,smoothfactor=1.0,noisethreshold=5.0,lownoisethreshold=1.5,
parallel=False,cyclefactor=3,threshold='0.0Jy',uvrange='',weighting='briggsbwtaper',phasecenter=''):
"""
Wrapper for tclean with keywords set to values desired for the Large Program imaging
See the CASA 6.1.1 documentation for tclean to get the definitions of all the parameters
"""
if 'LB' in vis and sidelobethreshold>3.0:
sidelobethreshold=2.0
if mask == '':
usemask='auto-multithresh'
else:
usemask='user'
if threshold != '0.0Jy':
nsigma=0.0
if imsize is None:
if 'LB' in vis or 'combined' in vis or 'continuum' in vis:
imsize = 3000
elif 'SB' in vis:
imsize = 1600
else:
print("Error: need to set imsize manually")
if cellsize is None:
if 'LB' in vis or 'combined' in vis or 'continuum' in vis:
cellsize = '.003arcsec'
elif 'SB' in vis:
cellsize = '.03arcsec'
else:
print("Error: need to set cellsize manually")
for ext in ['.image*', '.mask', '.model*', '.pb*', '.psf*', '.residual*', '.sumwt*', '.workdirectory*']:
os.system('rm -rf '+ imagename + ext)
tclean(vis= vis,
imagename = imagename,
specmode = 'cube',
deconvolver = 'multiscale',
scales = scales,
weighting=weighting,
robust = robust,
gain = gain,
start=start,
width=width,
spw=spw,
nchan=nchan,
veltype='radio',
outframe='LSRK',
imsize = imsize,
cell = cellsize,
smallscalebias = smallscalebias, #set to CASA's default of 0.6 unless manually changed
niter = niter, #we want to end on the threshold
interactive = interactive,
nsigma=nsigma,
cycleniter = cycleniter,
cyclefactor = cyclefactor,
uvtaper = uvtaper,
savemodel = 'none',
mask=mask,
usemask=usemask,
sidelobethreshold=sidelobethreshold,
lownoisethreshold=lownoisethreshold,
noisethreshold=noisethreshold,
smoothfactor=smoothfactor,
pbmask=0.1,
pblimit=0.1,
restoringbeam='common',
threshold=threshold,
uvrange=uvrange,
restfreq=restfreq,
parallel=parallel,
phasecenter=phasecenter)
def image_each_obs(ms_dict, prefix, scales, smallscalebias = 0.6, mask = '', nsigma=5.0, imsize = None, cellsize = None, interactive = False, robust = 0.5, gain = 0.3, niter = 50000, cycleniter = 300,sidelobethreshold=3.0,smoothfactor=1.0,noisethreshold=5.0,uvtaper='',parallel=False):
"""
Wrapper for tclean that will loop through all the observations in a measurement set and image them individual
Parameters
==========
ms_dict: Dictionary of information about measurement set
prefix: Prefix for all output file names (string)
See the CASA 5.1.1 documentation for tclean to get the definitions of all other parameters
"""
msfile = prefix+'_'+ms_dict['name']+'_initcont.ms'
tb.open(msfile+'/OBSERVATION')
num_observations = (tb.getcol('TIME_RANGE')).shape[1] #picked an arbitrary column to count the number of observations
tb.close()
if imsize is None:
if 'LB' in ms_dict['name']:
imsize = 3000
else:
imsize = 1024
if cellsize is None:
if 'LB' in ms_dict['name']:
cellsize = '0.003arcsec'
else:
imsize = 900
cellsize = '0.03arcsec'
if 'LB' in ms_dict['name'] and sidelobethreshold>3.0:
sidelobethreshold=2.0
#start of CASA commands
for i in range(num_observations):
observation = '%d' % i
imagename = prefix+'_'+ms_dict['name']+'_initcont_exec%s' % observation
for ext in ['.image', '.mask', '.model', '.pb', '.psf', '.residual', '.sumwt']:
os.system('rm -rf '+ imagename + ext)
tclean(vis= msfile,
imagename = imagename,
observation = observation,
specmode = 'mfs',
deconvolver = 'multiscale',
scales = scales,
weighting='briggs',
robust = robust,
gain = gain,
imsize = imsize,
cell = cellsize,
smallscalebias = smallscalebias, #set to CASA's default of 0.6 unless manually changed
niter = niter, #we want to end on the threshold
interactive = interactive,
nsigma=nsigma,
cycleniter = cycleniter,
cyclefactor = 1,
usemask='auto-multithresh',
sidelobethreshold=sidelobethreshold,
smoothfactor=smoothfactor,
noisethreshold=noisethreshold,
nterms = 1,
uvtaper=[uvtaper],parallel=parallel)
print("Each observation saved in the format %sOBSERVATIONNUMBER.image" % (prefix+'_'+ms_dict['name']+'_initcont_exec',))
def image_each_obs_shift(msfile, prefix, scales, smallscalebias = 0.6, mask = '', nsigma=5.0, imsize = None, cellsize = None, interactive = False, robust = 0.5, gain = 0.3, niter = 50000, cycleniter = 300,sidelobethreshold=3.0,smoothfactor=1.0,uvtaper='',parallel=False):
"""
Wrapper for tclean that will loop through all the observations in a measurement set and image them individual
Parameters
==========
ms_dict: Dictionary of information about measurement set
prefix: Prefix for all output file names (string)
See the CASA 5.1.1 documentation for tclean to get the definitions of all other parameters
"""
baselinename=''
if 'SB1' in msfile:
baseline_name='SB1'
elif 'SB2' in msfile:
baseline_name='SB2'
elif 'SB3' in msfile:
baseline_name='SB3'
elif 'LB1' in msfile:
baseline_name='LB1'
elif 'LB2' in msfile:
baseline_name='LB2'
elif 'LB3' in msfile:
baseline_name='LB3'
elif 'LB4' in msfile:
baseline_name='LB4'
elif 'LB5' in msfile:
baseline_name='LB5'
if imsize is None:
if 'LB' in msfile:
imsize = 3000
else:
imsize = 1024
if cellsize is None: