-
Notifications
You must be signed in to change notification settings - Fork 0
/
faust_imaging.py
3064 lines (2792 loc) · 117 KB
/
faust_imaging.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
#!/usr/bin/env python
"""
=======================
FAUST Archival Pipeline
=======================
This module contains the implementation for the CASA spectral line imaging
pipeline for the archival products of the ALMA Large Program FAUST. Please
see the README file for further information and the documentation, which
may be found under the `docs/` directory or online at:
https://faust-imaging.readthedocs.io
This script may be run under CASA v5 (Python 2) or CASA v6 (Python 3).
The current calibration pipeline release, CASA v5.6, is recommended as
it has received the most extensive testing. To use the script interactively,
execute the module by running at the CASA IPython prompt:
``execfile('<PATH>/<TO>/faust_imaging.py')``.
Authors
-------
Brian Svoboda and Claire Chandler.
Copyright 2020, 2021 Brian Svoboda under the MIT License.
"""
from __future__ import (print_function, division)
import gc
import os
import sys
import shutil
import datetime
import warnings
from glob import glob
from copy import deepcopy
from collections import (OrderedDict, Iterable)
import numpy as np
from scipy import special
from matplotlib import pyplot as plt
from matplotlib import patheffects as path_effects
# Python version information and v2/v3 specific imports.
is_python3 = sys.version_info >= (3, 0, 0)
if is_python3:
from configparser import ConfigParser
else:
from ConfigParser import ConfigParser
# Test whether the process is running from within a CASA environment.
try:
casalog.version
is_running_within_casa = True
except NameError:
is_running_within_casa = False
# The pipeline script currently supports being run under Python v2 and v3 under
# the CASA v5 and v6 branches, respectively. It may also be run under a user's
# system Python installation if the modules `casatasks` and `casatools` are
# installed (Python v3 only).
if is_running_within_casa and is_python3:
# The script is run under CASA 6 and Python 3. Rename task and tool names
# to follow the CASA 5 API.
from casatasks import MPIEnvironment
from casatasks.private.cleanhelper import cleanhelper
IS_MPI = MPIEnvironment.is_mpi_enabled
elif is_running_within_casa and not is_python3:
# The script is run under CASA 5 and Python 2.
from cleanhelper import cleanhelper
IS_MPI = MPIEnvironment.is_mpi_enabled
elif not is_running_within_casa and is_python3:
# The script is run under the user's system Python installation using
# Python 3. Use the CASA 5 API conventions.
from casatasks import (
casalog, exportfits, imhead, immath, impbcor,
imsmooth, imsmooth, imstat, makemask, rmtables, tclean,
mpi_env_found,
)
from casatasks.private.cleanhelper import cleanhelper
from casatools import image
from casatools import quanta
from casatools import coordsys
from casatools import msmetadata
ia = image()
im = image()
qa = quanta()
csys = coordsys()
msmd = msmetadata()
IS_MPI = mpi_env_found
elif not is_running_within_casa and not is_python3:
raise RuntimeError('Python v2 non-CASA environments are not supported.')
else:
raise RuntimeError('Invalid environment.')
# matplotlib configuration settings
plt.rc('font', size=10, family='serif')
plt.rc('xtick', direction='in')
plt.rc('ytick', direction='in')
plt.ioff() # turn off interactive GUI
###############################################################################
# Global configuration options
###############################################################################
# The configuration file `CONFIG_FILEN` must be present in the directory
# where CASA is started from as specified by `PROD_DIR`.
CONFIG_FILEN = 'faust_imaging.cfg'
cfg_parser = ConfigParser()
if not cfg_parser.read(CONFIG_FILEN):
warnings.warn('File "{0}" not found; falling back to CWD.'.format(CONFIG_FILEN))
# ConfigParser in Py3 does not have "fallback" parameter to "get" method.
# So set explicitly.
cfg_parser.add_section("Paths")
cfg_parser.set('Paths', 'DATA_DIR', os.getcwd())
cfg_parser.set('Paths', 'PROD_DIR', os.getcwd())
DATA_DIR = cfg_parser.get('Paths', 'DATA_DIR')
PROD_DIR = cfg_parser.get('Paths', 'PROD_DIR')
# Directories where specific products are read from or written.
IMAG_DIR = os.path.join(PROD_DIR, 'images/')
MOMA_DIR = os.path.join(PROD_DIR, 'moments/')
PLOT_DIR = os.path.join(PROD_DIR, 'plots/')
# Median-absolute-deviation conversion factor to Gaussian RMS
MAD_TO_RMS = 1 / (np.sqrt(2) * special.erfinv(0.5)) # approx. 1.4826
# Large `niter` value, hopefully not reached in actually executions.
NITERMAX = int(1e7)
# Primary beam limit to image down to. Values in the image are mainly dominated
# by 7m data outside of a pblimit=0.07 and will have a non-uniformly sized
# synthesized beam.
PBLIMIT = 0.2
# Sampling factor to determine cell size relative to target resolution (~0.3as,
# see values `ALL_TARGETS`). A relatively large value of 10 pix per synthesized
# HPBW is used for consistency with the continuum images.
OVERSAMPLE_FACT = 10
# Set of briggs uv-weightings to use by default in pipeline tasks
WEIGHTINGS = (0.5,)
# Default extension name for dirty images
DIRTY_EXT = 'dirty'
# Default extension name for unmasked clean model
NOMASK_EXT = 'nomask'
# Default extension name for small image stamps used to calculate the ".sumwt"
# files.
TINYIMG_EXT = 'tinyimg'
# perchanelweightdensity parameter in tclean, changing to False slightly
# improves the resolution at the expense of sensitivity and uniform RMS.
PERCHANWT = False
# See guide for discussion for of automasking parameters:
# https://casaguides.nrao.edu/index.php/Automasking_Guide
# These parameters have been tested to provide results that are
# frequently acceptable and are an overall compromise in masking compact
# and extended emission.
AUTOM_KWARGS = {
'usemask': 'auto-multithresh',
'noisethreshold': 5.0,
'sidelobethreshold': 2.0,
'lownoisethreshold': 1.5,
'minbeamfrac': 0.001,
'negativethreshold': 7.0,
'growiterations': 1000,
'dogrowprune': False,
'fastnoise': False,
'verbose': True,
}
# Default 7m values taken from the auto-masking CASA Guide above. Un-tested.
AUTOM_7M_KWARGS = {
'usemask': 'auto-multithresh',
'noisethreshold': 5.0,
'sidelobethreshold': 1.25,
'lownoisethreshold': 2.0,
'minbeamfrac': 0.1,
'negativethreshold': 10.0,
'growiterations': 1000,
'dogrowprune': False,
'fastnoise': False,
'verbose': True,
}
###############################################################################
# FAUST Target and SPW configuration
###############################################################################
class Target(object):
def __init__(self, name, res, vsys):
self.name = name
self.res = res
self.vsys = vsys
def vlsr_from_window(self, velo_width):
"""
Parameters
----------
velo_width : str
CASA quantity string, e.g. '10km/s'.
"""
assert qa.isquantity(velo_width)
half_vwin = qa.div(qa.quantity(velo_width), 2)
vsys = qa.quantity(self.vsys, 'km/s')
voffset = qa.sub(vsys, half_vwin)
return qa.tos(qa.convert(voffset, 'km/s'))
ALL_TARGETS = { t.name: t for t in [
Target('BHB07-11', 0.35, 3.6),
Target('CB68', 0.36, 5.0),
Target('Elias29', 0.36, 4.0),
Target('GSS30', 0.36, 3.2),
Target('IRAS_15398-3359', 0.32, 5.3),
Target('IRS63', 0.34, 2.75),
Target('L1527', 0.36, 5.85),
Target('L1551_IRS5', 0.34, 6.5),
Target('L483', 0.25, 5.5),
Target('NGC1333_IRAS4A1A2', 0.21, 7.0),
Target('NGC1333_IRAS4C', 0.21, 7.7),
Target('R_CrA_IRS7B', 0.37, 6.2),
Target('VLA1623A', 0.36, 3.8),
]}
ALL_FIELD_NAMES = list(ALL_TARGETS.keys())
class DataSet(object):
_ms_fmt = '{0}-Setup{1}/uid___*_target_lines_self_calibrated_continuum_subtracted_aligned.ms'
low_freqs = {1: 217, 2: 245, 3: 93} # GHz
high_freqs = {1: 235, 2: 262, 3: 108} # GHz
def __init__(self, field, setup=1, kind='joint'):
"""
Parameters
----------
field : str
FAUST target field name.
setup : int
FAUST Setup index number:
1 : Band 6, 220 GHz
2 : Band 6, 250 GHz
3 : Band 3, 90 GHz
kind : str
Datset descriptor for which measurement set files to use. Valid
values include: ('joint', '12m', '7m'). Note that only 12m data is
availabe for Setup 3.
"""
assert field in ALL_FIELD_NAMES
assert setup in (1, 2, 3)
if setup == 3 and kind != '12m':
log_post('-- Reverting `kind` to "12m" for Setup 3', priority='WARN')
kind = '12m'
kind = kind.lower()
self.field = field
self.target = ALL_TARGETS[field]
self.setup = setup
self.kind = kind
ms_glob_pattern = self.ms_fmt.format(field, setup)
vis_filen = sorted(glob(ms_glob_pattern))
if kind == 'joint':
self.vis = vis_filen
elif kind == '12m':
# use msmd to get array diameter size
self.vis = [
name for name in vis_filen
if ms_contains_diameter(name, diameter=12)
]
elif kind == '7m':
self.vis = [
name for name in vis_filen
if ms_contains_diameter(name, diameter=7)
]
else:
raise ValueError('Invalid dataset descriptor: "{0}"'.format(kind))
if len(self.vis) == 0:
raise IOError('MS files not found with pattern: {0}'.format(ms_glob_pattern))
self.check_if_product_dirs_exist()
@property
def ms_fmt(self):
return os.path.join(DATA_DIR, self._ms_fmt)
@property
def cell_12m(self):
cell = self.target.res / OVERSAMPLE_FACT
return '{0:.4f}arcsec'.format(cell)
@property
def cell_7m(self):
hi_nu = self.high_freqs[self.setup]
freq = qa.quantity(hi_nu, 'GHz')
diam = '50m' # max-baseline for ACA
angle = self.calc_res(freq, diam)
cell = angle['value'] / OVERSAMPLE_FACT
return '{0:.4f}arcsec'.format(cell)
@property
def cell(self):
if self.kind in ('joint', '12m'):
return self.cell_12m
elif self.kind == '7m':
return self.cell_7m
else:
raise ValueError
@property
def gridder(self):
if self.setup == 3:
return 'standard'
elif self.setup in (1, 2) and self.kind == 'joint':
return 'mosaic'
elif self.setup in (1, 2) and self.kind in ('7m', '12m'):
return 'standard'
else:
raise ValueError('Invalid setup, kind: ({0}, {1})'.format(self.setup, self.kind))
@property
def pblimit(self):
return PBLIMIT if self.kind == 'joint' else -0.01
@property
def imsize(self):
"""
Get the image size in pixels dynamically according to the lowest
frequency SPW of the Setup and antenna diameter (i.e., 12m or 7m).
The field size size is calculated as 10% larger than the full-width
at the 10%-maximum point of the primary beam (approximated as
$1.13 \lambda / D$).
"""
if self.kind in ('joint', '12m'):
ant_diam = '12m'
elif self.kind == '7m':
ant_diam = '7m'
else:
raise ValueError
diam = qa.div(ant_diam, 1.13) # account for tapered illumination
freq = qa.quantity(self.low_freqs[self.setup], 'GHz')
angle = self.calc_res(freq, diam)
angle = qa.mul(angle, 2.00) # 1.1 * [full-width at 10% maximum]
pix_width = qa.convert(qa.div(angle, self.cell), '')['value']
eff_width = cleanhelper.getOptimumSize(int(pix_width))
return [eff_width, eff_width]
def check_if_product_dirs_exist(self):
field_dir = os.path.join(IMAG_DIR, self.field)
try:
os.makedirs(field_dir)
except OSError:
if not os.path.isdir(field_dir):
raise
def calc_res(self, freq, diam):
"""Note that no factor of 1.028 is applied for FWHM of Airy pattern, just l/D."""
assert qa.isquantity(freq)
assert qa.isquantity(diam)
wavel = qa.convertfreq(freq, 'm')
angle = qa.convert(qa.mul(qa.div(wavel, diam), '1rad'), 'arcsec')
assert qa.isangle(angle)
return angle
def ms_contains_diameter(ms_filen, diameter=None, epsilon=0.5):
"""
Determine whether an MS contains an antenna with a given diameter.
Parameters
----------
diameter : number
Antenna diameter in meters.
epsilon : number, default 0.5
Fudge factor for querying the antennas min/max diameter.
"""
mindiameter = '{0}m'.format(diameter-epsilon)
maxdiameter = '{0}m'.format(diameter+epsilon)
msmd.open(ms_filen)
ant_ids = msmd.antennaids(mindiameter=mindiameter, maxdiameter=maxdiameter)
msmd.close()
# NOTE this will be incorrect if the MS files have been concat
return ant_ids.size > 0
class Spw(object):
def __init__(self, setup, restfreq, mol_name, name, ms_restfreq, spw_id,
ot_name, nchan, chan_width, tot_bw):
"""
Parameters
----------
setup : int
Setup ID number (1, 2, 3)
restfreq : str
Rest frequency of primary targeted line in the SPW, e.g. "93.17GHz".
mol_name : str
Molecule name of the primary targeted line in the SPW.
name : str
Name of the spectral line.
ms_restfreq : str
Line rest frequency listed in the measurement set, e.g. "93.17GHz".
Many of these values are not rest frequencies for specific molecular
transitions but shifted values meant to center the bandpass.
spw_id : int
ID number of the spectral window
ot_name : str
Ending of the OT SPW label, e.g. "#BB_1#SW-01". These are useful
for selecting the spectral window ID number if the correlator ID
numbers are inconsistent across 7M/12M datasets.
nchan : int
Total number of channels (before flagging).
chan_width : number
Channel width in TOPO frame.
**units**: kHz.
tot_bw : number
Total bandwidth in TOPO frame.
**units**: MHz
"""
assert setup in (1, 2, 3)
self.setup = setup
self.restfreq = restfreq
self.mol_name = mol_name
self.name = name
self.ms_restfreq = ms_restfreq
self.spw_id = spw_id
self.ot_name = ot_name
self.nchan = nchan
self.chan_width = chan_width
self.tot_bw = tot_bw
@property
def short_restfreq(self):
unit = 'GHz'
freq = qa.convert(self.restfreq, unit)
return '{0:.3f}{1}'.format(freq['value'], unit)
@property
def label(self):
return '{0}_{1}'.format(self.short_restfreq, self.mol_name)
def nchan_from_window(self, velo_width):
"""
Parameters
----------
velo_width : str
Full velocity width of window. CASA quantity string, e.g. '10km/s'.
"""
assert qa.isquantity(velo_width)
chan_fwidth = qa.quantity(self.chan_width, 'Hz')
chan_vwidth = qa.convertdop(qa.div(chan_fwidth, self.restfreq), 'km/s')
nchan = qa.convert(qa.div(velo_width, chan_vwidth), '')['value']
return int(np.ceil(nchan))
def copy(self):
return deepcopy(self)
def with_chunk(self, chunk):
"""
Parameters
----------
chunk : ChunkConfig, None
"""
if chunk is None:
return self
else:
spw = self.copy()
spw.mol_name = '{0}_chunk{1}'.format(self.mol_name, chunk.index)
return spw
def parse_spw_info_from_ms(ms_filen, field='CB68', out_filen=None):
# NOTE This function was only needed to write out the values that can now
# be found in the `Spw` objects. The resource configuration should be the
# same for all targets.
msmd.open(ms_filen)
# get source ID number
field_id = msmd.fieldsforname(field)[0]
# SPW data descriptor IDs just for science observations
sci_dds = msmd.spwsforintent('OBSERVE_TARGET#ON_SOURCE')
# list of SPW names from the science SPW DD IDs
spw_names = msmd.namesforspws(sci_dds)
spw_names = ['#'.join(n.split('#')[2:]) for n in spw_names]
spw_metadata = []
for ii, dd in enumerate(sci_dds):
# transitions
trans = msmd.transitions(field_id, dd)[0]
# restfreqs
freq_q = msmd.restfreqs(field_id, dd)['0']['m0']
freq_s = '{0}{1}'.format(freq_q['value'], freq_q['unit'])
# nchan
nchan = msmd.nchan(dd)
# channel resolution
chanres = abs(msmd.chanres(dd).mean()) # in Hz
# bandwidth
bandwidth = msmd.bandwidths(dd) # in Hz
spw_metadata.append(
(trans, freq_s, dd, spw_names[ii], nchan, chanres, bandwidth)
)
msmd.close()
if out_filen is not None:
with open(out_filen, 'w') as f:
for meta in spw_metadata:
f.write("Spw{0},\n".format(str(meta)))
return spw_metadata
def write_all_spw_info():
for setup_ix in range(1, 4):
log_post('-- Writing metadata for Setup-{0}'.format(setup_ix))
dset = DataSet(setup=setup_ix)
filen = dset.vis[-1]
out_filen = 'spw_info_Setup{0}.txt'.format(setup_ix)
parse_spw_info_from_ms(filen, out_filen=out_filen)
def spw_list_to_dict(spws):
return OrderedDict((s.label, s) for s in spws)
# NOTE These values are copy-pasted from the files generated by `write_all_spw_info`.
# They should be equivalent for all FAUST targets. The SPW ID numbers are for
# the 12m EBs, but these are only for reference. Actual SPW ID's are retrieved
# from each MS based on the "BB" name.
# SPWs for Setup 1 (Band 6 "a", 220 GHz)
SPW_S1 = spw_list_to_dict([
Spw(1, '216.1125822GHz', 'DCOp', 'DCO__v_0_J_3_2__HCOOCH3_19_2_18__18_2_17__A(ID=0)', '2.16112582e+11Hz', 25, 'BB_1#SW-01#FULL_RES', 480, 141113.28125, 58593750.0),
Spw(1, '216.5627160GHz', 'NH2D', 'NH2D_3_2_2_0s_3_1_2_0a__CH3CHO_v_t_0_11_1_10__10_1_9___E(ID=0)', '2.16562716e+11Hz', 27, 'BB_1#SW-02#FULL_RES', 480, 141113.28125, 58593750.0),
Spw(1, '217.1049190GHz', 'SiO', 'SiO_v_0_5_4(ID=0)', '2.17104919e+11Hz', 29, 'BB_1#SW-03#FULL_RES', 480, 141113.28125, 58593750.0),
Spw(1, '217.8221480GHz', 'c-C3H2', 'c_C3H2_v_0_6_0_6__5_1_5___6_1_6__5_0_5_(ID=0)', '2.17822148e+11Hz', 31, 'BB_1#SW-04#FULL_RES', 480, 141113.28125, 58593750.0),
Spw(1, '218.2221920GHz', 'H2CO', 'H2CO_3_0_3__2_0_2_(ID=0)', '2.18222192e+11Hz', 33, 'BB_2#SW-01#FULL_RES', 480, 141113.28125, 58593750.0),
Spw(1, '218.4400630GHz', 'CH3OH', 'CH3OH_v_t_0_4_2_2__3_1_2___NH2CHO_10_1_9__9_1_8___H2CO_3_2_2__2_2_1_(ID=0)', '2.18440063e+11Hz', 35, 'BB_2#SW-02#FULL_RES', 480, 141113.28125, 58593750.0),
Spw(1, '219.5603541GHz', 'C18O', 'C18O_2_1(ID=0)', '2.19560354e+11Hz', 37, 'BB_2#SW-03#FULL_RES', 480, 141113.28125, 58593750.0),
Spw(1, '219.9494420GHz', 'SO', 'SO_3__v_0_6_5__5_4_(ID=0)', '2.19949442e+11Hz', 39, 'BB_2#SW-04#FULL_RES', 480, 141113.28125, 58593750.0),
Spw(1, '231.0609934GHz', 'OCS', 'OCS_19_18(ID=0)', '2.31060993e+11Hz', 41, 'BB_3#SW-01#FULL_RES', 480, 141113.28125, 58593750.0),
Spw(1, '231.2206852GHz', '13CS', '13CS_v_0_5_4(ID=0)', '2.31220685e+11Hz', 43, 'BB_3#SW-02#FULL_RES', 480, 141113.28125, 58593750.0),
Spw(1, '231.3218283GHz', 'N2Dp', 'DN2__J_3_2__CH3CHO_4_lines(ID=0)', '2.313218283e+11Hz', 45, 'BB_3#SW-03#FULL_RES', 480, 141113.28125, 58593750.0),
Spw(1, '231.4102340GHz', 'D2CO', 'D2CO_4_0_4__3_0_3___CH3CHO_12_5_8__11_5_7__E(ID=0)', '2.31410234e+11Hz', 47, 'BB_3#SW-04#FULL_RES', 480, 141113.28125, 58593750.0),
Spw(1, '233.7957500GHz', 'cont', 'continuum(ID=0)', '2.3379575e+11Hz', 49, 'BB_4#SW-01#FULL_RES', 3840, 976562.5, 1875000000.0),
])
# SPWs for Setup 2 (Band 6 "b", 260 GHz)
SPW_S2 = spw_list_to_dict([
Spw(2, '243.9157880GHz', 'CH3OH', 'CH3OH_v_t_0_5_1_4__4_1_3____(ID=0)', '2.43915788e+11Hz', 25, 'BB_1#SW-01#FULL_RES', 480, 141113.28125, 58593750.0),
Spw(2, '244.0485044GHz', 'H2CS', 'H2CS_7_1_6__6_1_5_(ID=0)', '2.44048504e+11Hz', 27, 'BB_1#SW-02#FULL_RES', 480, 141113.28125, 58593750.0),
Spw(2, '244.9355565GHz', 'CS', 'CS_v_0_5_4(ID=0)', '2.44935557e+11Hz', 29, 'BB_1#SW-03#FULL_RES', 480, 141113.28125, 58593750.0),
Spw(2, '245.6063199GHz', 'HC3N', 'HC3N_v_0_J_27_26__SO2_10_3_7__10_2_8_(ID=0)', '2.4560632e+11Hz', 31, 'BB_1#SW-04#FULL_RES', 480, 141113.28125, 58593750.0),
Spw(2, '246.7000000GHz', 'cont', 'continuum(ID=0)', '2.467e+11Hz', 33, 'BB_2#SW-01#FULL_RES', 1920, 1128906.25, 1875000000.0),
Spw(2, '260.1890898GHz', 'NH2CHO', 'NH2CHO_12_2_10__11_2_9_(ID=0)', '2.60189848e+11Hz', 35, 'BB_3#SW-01#FULL_RES', 480, 141113.28125, 58593750.0),
Spw(2, '260.2553390GHz', 'H13COp', 'HCOOCH3_21_3_18__20_3_17_E__A__H13CO__J_3_2(ID=0)', '2.6025508e+11Hz', 37, 'BB_3#SW-02#FULL_RES', 480, 141113.28125, 58593750.0),
Spw(2, '261.6873662GHz', 'CH2DOH', 'CH2DOH_5_2_4__5_1_5___e0__HCOOCH3_21_7_14__20_7_13__E(ID=0)', '2.61692e+11Hz', 39, 'BB_3#SW-03#FULL_RES', 480, 141113.28125, 58593750.0),
Spw(2, '262.0042600GHz', 'CCH', 'CCH_v_0_N_3_2__J_7_2_5_2__F_4_3__3_2(ID=0)', '2.6200426e+11Hz', 41, 'BB_3#SW-04#FULL_RES', 480, 141113.28125, 58593750.0),
Spw(2, '257.8956727GHz', 'CH2DOH', 'CH2DOH_4_2_3__3_1_3___e1(ID=0)', '2.578956727e+11Hz', 43, 'BB_4#SW-01#FULL_RES', 480, 141113.28125, 58593750.0),
Spw(2, '258.2558259GHz', 'SO', 'SO_3__v_0_6_6__5_5_(ID=0)', '2.582558259e+11Hz', 45, 'BB_4#SW-02#FULL_RES', 480, 141113.28125, 58593750.0),
Spw(2, '258.5488190GHz', 'CH3OCH3', 'CH3OCH3_14_1_14__13_0_13__AE__EA__EE__AA(ID=0)', '2.58548819e+11Hz', 47, 'BB_4#SW-03#FULL_RES', 480, 141113.28125, 58593750.0),
Spw(2, '259.0349100GHz', 'HDCO', 'HDCO_4_2_2__3_2_1_(ID=0)', '2.5903491e+11Hz', 49, 'BB_4#SW-04#FULL_RES', 480, 141113.28125, 58593750.0),
])
# SPWs for Setup 3 (Band 3 "a", 90 GHz)
SPW_S3 = spw_list_to_dict([
Spw(3, '93.1762650GHz', 'N2Hp', 'N2H__v_0_J_1_0(ID=3925982)', '93180900000.0Hz', 25, 'BB_1#SW-01#FULL_RES', 960, 70556.640625, 58593750.0),
Spw(3, '94.4051630GHz', '13CH3OH', '13CH3OH_v_t_0_2__1_2__1__1_1___2_0_2__1_0_1______2__0_2__1__0_1___2__1_1__1__1_0_(ID=0)', '94407129000.0Hz', 27, 'BB_1#SW-02#FULL_RES', 960, 70556.640625, 58593750.0),
Spw(3, '94.9999080GHz', 'cont', 'Continuum(ID=0)', '94999908103.2Hz', 29, 'BB_2#SW-01#FULL_RES', 3840, 976562.5, 1875000000.0),
Spw(3, '107.0138310GHz', 'CH3OH', 'CH3OH_v_t_0_3_1_3__4_0_4____(ID=0)', '1.07013831e+11Hz', 31, 'BB_3#SW-01#FULL_RES', 960, 70556.640625, 58593750.0),
Spw(3, '108.0399860GHz', 'l-C3D', 'C3D_11_2_9_2_f__c_C3HD_5_5_1__5_4_2_(ID=0)', '1.08064e+11Hz', 33, 'BB_3#SW-02#FULL_RES', 960, 70556.640625, 58593750.0),
Spw(3, '104.2392952GHz', 'SO2', 'SO2_v_0_10_1_9__10_0_10_(ID=96928)', '1.042392952e+11Hz', 35, 'BB_4#SW-01#FULL_RES', 960, 70556.640625, 58593750.0),
Spw(3, '105.7991130GHz', 'H13CCCN', 'H13CCCN_J_12_11(ID=455557)', '1.05799113e+11Hz', 37, 'BB_4#SW-02#FULL_RES', 960, 70556.640625, 58593750.0),
])
ALL_SETUPS = (1, 2, 3)
SPWS_BY_SETUP = {1: SPW_S1, 2: SPW_S2, 3: SPW_S3}
ALL_SPWS = {}
ALL_SPWS.update(SPW_S1)
ALL_SPWS.update(SPW_S2)
ALL_SPWS.update(SPW_S3)
ALL_SPW_LABELS = list(ALL_SPWS.keys())
###############################################################################
# General utility functions
###############################################################################
class ImageManager(object):
def __init__(self, infile, cache=True):
"""
Safely open a CASA image by creating a context manager. The image tool
and file will be closed even if an error occurs while manipulating the
image tool. Note that multiple images can be opened in a nested
sequence.
Parameters
----------
infile : str
CASA image file name, including any file suffixes.
Examples
--------
The file is closed and the image tool destroyed when the scope of the
context manager is exited. The following example shows how two images
can be opened simulatenously in nested scopes.
>>> with ImageManager('foo.image') as tool1:
... print(tool1.shape())
... with ImageManager('bar.image') as tool2:
... print(tool2.shape())
... print(tool1.shape()) # Error! The image tool is closed.
"""
self.infile = infile
self.cache = cache
self.ia = iatool()
self.success = self.ia.open(infile, cache=cache)
def __enter__(self):
return self.ia
def __exit__(self, err_type, err_value, err_traceback):
self.ia.done()
self.ia.close()
def log_post(msg, priority='INFO'):
"""
Post a message to the CASA logger, logfile, and stdout/console.
Parameters
----------
msg : str
Message to post.
priority : str, default 'INFO'
Priority level. Includes 'INFO', 'WARN', 'SEVERE'.
"""
print(msg)
casalog.post(msg, priority, 'faust_pipe')
def check_delete_image_files(imagename, parallel=False, preserve_mask=False):
"""
Check for and remove (if they exist) files created by clean such as '.flux',
'.image', etc.
NOTE this function has issues with deleting tables made by clean in
parallel mode, probably because the directory structure is different.
Parameters
----------
imagename : str
The relative path name to the files to delete.
parallel : bool, default False
rmtables can't remove casa-images made with parallel=True, they must be
manually removed.
preserve_mask : bool, default False
Whether to preserve the `.mask` file extension
"""
log_post(':: Check for and remove existing files')
exts = [
'.flux', '.pb', '.image', '.alpha', '.alpha.error', '.weight',
'.model', '.pbcor', '.psf', '.sumwt', '.residual', '.flux.pbcoverage',
'.pb.tt0', '.image.tt0', '.weight.tt0', '.model.tt0', '.psf.tt0',
'.sumwt.tt0', '.residual.tt0',
]
if not preserve_mask:
exts += ['.mask']
# CASA image table directories
for ext in exts:
filen = imagename + ext
if os.path.exists(filen):
if parallel:
log_post('-- Hard delete {0}'.format(ext))
shutil.rmtree(filen)
else:
log_post('-- Removing {0}'.format(filen))
rmtables(filen)
# "Cannot delete X because it's not a table" -> so hard delete
for ext in ('.residual', '.workdirectory'):
filen = imagename + ext
if os.path.exists(filen):
log_post('-- Hard delete {0}'.format(ext))
shutil.rmtree(filen)
def safely_remove_file(filen):
if not os.path.exists(filen):
log_post('-- File not found: {0}'.format(filen), priority='WARN')
return
log_post(':: Removing: {0}'.format(filen))
if os.path.isdir(filen):
# The target is a directory, i.e., a CASA image. Use `rmtables` to
# safely release file locks within CASA on the internal tables.
rmtables(filen)
# The file will still exist if rmtables failed, such as for parallel
# images that have a directory structure that `rmtables` does not
# recognize.
try:
shutil.rmtree(filen)
log_post('-- Hard delete: {0}'.format(filen))
except OSError:
pass
else:
# Target is a file and not a directory (e.g., FITS).
os.remove(filen)
def if_exists_remove(filen):
if os.path.exists(filen):
safely_remove_file(filen)
def delete_all_extensions(imagename, keep_exts=None):
"""
Parameters
----------
imagename : str
keep_exts : None, iterable
A list of extensions to keep, example: ['mask', 'psf']
"""
for filen in glob(imagename+'.*'):
if keep_exts is not None and any(filen.endswith(ext) for ext in keep_exts):
continue
safely_remove_file(filen)
def delete_workdir(imagename):
workdir = '{0}.workdirectory'.format(imagename)
if os.path.exists(workdir):
shutil.rmtree(workdir)
def replace_existing_file_with_new(old_filen, new_filen):
"""
Replace an existing file with a new or temporary one.
`old_filen` will be removed and replaced by `new_filen`.
"""
if not os.path.exists(new_filen):
msg = 'File not found: "{0}"'.format(new_filen)
log_post(msg, priority='WARN')
raise IOError(msg)
rmtables(old_filen)
# If a parallel image, then will not be recognized as a table in the call
# to `rmtables`
if os.path.exists(old_filen):
log_post('-- Hard delete! "{0}"'.format(old_filen))
shutil.rmtree(old_filen)
os.rename(new_filen, old_filen)
def remove_end_from_pathname(filen, end='.image'):
"""
Retrieve the file name excluding an ending extension or terminating string.
Parameters
----------
filen : str
end : str
End to file name to remove. If an extension, include the period, e.g.
".image".
"""
if not filen.endswith(end):
raise ValueError('Path does not end in "{0}": {1}'.format(end, filen))
assert len(filen) > len(end)
stem = filen[:-len(end)]
return stem
def export_fits(imagename, velocity=False, overwrite=True):
log_post(':: Exporting fits')
exportfits(imagename, imagename+'.fits', dropstokes=True,
velocity=velocity, overwrite=overwrite)
def concat_parallel_image(imagename):
"""
Create a contiguous image cube file from a 'parallel image' generated from
a multiprocess `tclean` run with `parallel=True`. The function replaces the
original parallel image with the contiguous image.
"""
_, ext = os.path.splitext(imagename)
ext = ext.lstrip('.')
outfile = imagename + '.CONCAT_TEMP'
# parallel images generated by tclean have names formatted as:
# name.ext/name.n1.ext
infiles = glob(imagename+'/*.{0}'.format(ext))
if len(infiles) == 0:
log_post(':: Not a parallel image! Passing.')
return
log_post(':: Concatenating file "{0}"'.format(imagename))
if_exists_remove(outfile)
ia.open(imagename)
im_tool = ia.imageconcat(
outfile=outfile,
infiles=infiles,
reorder=True,
)
im_tool.close()
ia.done()
ia.close()
replace_existing_file_with_new(imagename, outfile)
def concat_parallel_all_extensions(imagebase):
exts = ['image', 'mask', 'model', 'pb', 'psf', 'residual', 'sumwt', 'weight']
for ext in exts:
imagename = '{0}.{1}'.format(imagebase, ext)
if os.path.exists(imagename):
concat_parallel_image(imagename)
def get_freq_axis_from_image(imagename):
"""
Compute the frequency axis from an image's header coordinate system
information.
Parameters
----------
imagename : str
Returns
-------
ndarray
Frequency axis.
str
Frequency axis unit (likely Hz).
"""
# Get coordinate system information.
ia.open(imagename)
csys = ia.coordsys()
csys_dict = csys.torecord()
shape = ia.shape()
ia.close()
ia.done()
# Validate the axes and get the number of channels.
try:
spec_index = csys.findaxisbyname('Frequency')
except RuntimeError:
raise ValueError('Image has no frequency axis, is in velocity?')
nchan = shape[spec_index]
csys.done()
# Compute the frequency axis indices to frequencies.
spec_sys = csys_dict['spectral2']
sunit = spec_sys['unit']
crpix = spec_sys['wcs']['crpix']
crval = spec_sys['wcs']['crval']
cdelt = spec_sys['wcs']['cdelt']
faxis = (np.arange(nchan) + crpix) * cdelt + crval
return faxis, sunit
def calc_common_coverage_range(imagebase):
"""
Calculate the common frequency coverage amongst a set of MSs/EBs. The
`.sumwt` image extension is used from an existing "dirty" cube.
Parameters
----------
imagebase : str
Image name without the ".sumwt" extension.
Returns
-------
str
The start frequency in the LSRK frame.
int
The number of channels from `start` at the native spectral resolution.
"""
sumwt_filen = '{0}.sumwt'.format(imagebase)
# get sum-of-the-weights values
ia.open(sumwt_filen)
sumwt = ia.getchunk().squeeze()
csys = ia.coordsys().torecord()
ia.close()
# determine lowest and highest channels to use
med_sumwt = np.nanmedian(sumwt)
good_chans = np.argwhere(sumwt > 0.95 * med_sumwt)
ix_lo = good_chans.min()
ix_hi = good_chans.max()
nchan = abs(ix_hi - ix_lo)
# convert indices to frequencies
faxis, sunit = get_freq_axis_from_image(sumwt_filen)
start_val = faxis[ix_lo:ix_hi].min()
start = '{0}{1}'.format(start_val, sunit)
log_post('-- start frequency: {0}'.format(start))
log_post('-- nchan: {0}'.format(nchan))
return start, nchan
def calc_chunk_freqs(imagebase, nchunks=1):
"""
Divide the spectral axis of an image into continuous chunks in frequency.
Returned frequencies specify the channel center frequency.
Parameters
----------
imagebase : str
Image name base without the ".sumwt" extension.
nchunks : int
Number of contiguous chunks to divide the frequency range into.
Returns
-------
[[str, int], ...]
(str) LSRK frequency of the bin left-edge of the first channel.
**units**: Hz.
(int) Number of channels in the chunk.
"""
nchunks = int(nchunks)
assert nchunks >= 1
freq_start, nchan_total = calc_common_coverage_range(imagebase)
assert nchunks <= nchan_total
# Convert start frequency unit string into a float.
spec_unit = 'Hz'
freq_start = qa.convert(freq_start, spec_unit)['value']
# Get frequency channel width.
imagename = '{0}.sumwt'.format(imagebase)
ia.open(imagename)
csys = ia.coordsys()
csys_dict = csys.torecord()
ia.close()
ia.done()
csys.done()
# Ensure that the delta and start frequency have the same units.
cdelt = csys_dict['spectral2']['wcs']['cdelt']
cunit = csys_dict['spectral2']['unit']
cdelt = qa.convert(qa.quantity(cdelt, cunit), spec_unit)['value']
cdelt = abs(cdelt)
# Calculate the number of channels per chunk. Distribute the channels the
# channel numbers that don't evenly divide uniformly among the remaining.
if nchan_total == nchunks:
chan_per_chunk = np.ones(nchunks, dtype=int)
else:
chan_per_chunk = np.zeros(nchunks, dtype=int)
chan_per_chunk[:] = nchan_total // nchunks
remainder = nchan_total % nchunks
if remainder > 0:
chan_per_chunk[-remainder:] += 1
assert chan_per_chunk.sum() == nchan_total
# Calculate the starting frequencies by iteratively adding the chunk
# bandwidth to the last starting frequency.
chunks = []
freq = freq_start
for n in chan_per_chunk:
freq_withunit = qa.tos(qa.quantity(freq, spec_unit))
chunks.append([freq_withunit, n])
freq += n * cdelt
return chunks
def primary_beam_correct(imagebase):
log_post(':: Primary beam correcting image: {0}'.format(imagebase))
impbcor(
imagename=imagebase+'.image',
pbimage=imagebase+'.pb',
outfile=imagebase+'.image.pbcor',
overwrite=True,
)
def hanning_smooth_image(imagename, overwrite=True):
"""
Hanning smooth an image. Produces a new file with the extension ".hanning".
Parameters
----------
filen : str
overwrite : bool
"""
log_post(':: Creating Hanning smoothed image')
outname = '{0}.hanning'.format(imagename)
ia.open(imagename)
ia.hanning(
outname, drop=False, dmethod='mean', overwrite=overwrite,
).done()
ia.done()
ia.close()
def smooth_cube_to_common_beam(imagename, beam=None):
"""
Use the ``imsmooth`` task to convert a cube with per-plane beams into one
with a single common beam.
Parameters
----------
imagename : str
Name of the image, including extension such as ".image".
beam : dict
Gaussian beam parameter dictionary (see ``imsmooth`` help).
"""
log_post(':: Smoothing cube to common beam scale')
outfile = imagename + '.common'
if beam is None:
imsmooth(imagename=imagename, kernel='commonbeam', outfile=outfile,
overwrite=True)
else:
imsmooth(imagename=imagename, kernel='gaussian', outfile=outfile,
beam=beam, targetres=True, overwrite=True)
def copy_pb_mask(imagename, pbimage):
"""
Copy primary beam T/F mask back into the image after being removed by a
task such as ``imsmooth``.
"""
log_post(':: Copying primary beam mask into: {0}'.format(imagename))
makemask(mode='copy', inpimage=pbimage, inpmask=pbimage+':mask0',
output=imagename+':mask0', overwrite=True)
def calc_rms_from_image(imagename, chan_expr=None):
"""
Calculate RMS values from the scaled MAD of all channels (unless given a
range) for the given full imagename.