aboutsummaryrefslogtreecommitdiffstats
path: root/astro/oskar/wsclean.py
blob: 05899b4baf2efa3f468e375c7d8d22840705fda3 (plain)
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
#!/usr/bin/env python3
#
# Copyright (c) 2017 Aaron LI
# MIT license
#
# Create image from OSKAR simulated visibility data using `WSClean`.
# WSClean: https://sourceforge.net/p/wsclean/
#
# 2017-09-01
#


import os
import re
import argparse
import subprocess
import time


def wsclean(args, dryrun=False):
    # NOTE: Convert all arguments to strings
    cmd = ["wsclean"] + [str(arg) for arg in args]
    print("CMD: %s" % " ".join(cmd))
    if dryrun:
        print(">>> DRY RUN MODE <<<")
        return

    t1 = time.perf_counter()
    subprocess.check_call(cmd)
    t2 = time.perf_counter()
    print("-----------------------------------------------------------")
    print("WSClean Elapsed time: %.1f [min]" % ((t2-t1)/60))
    print("-----------------------------------------------------------")


def main():
    parser = argparse.ArgumentParser(
        description="Run WSClean with more handy arguments")
    parser.add_argument("-a", "--args", dest="args",
                        help="additional arguments for WSClean, " +
                        "in a quoted string separated by space, e.g.," +
                        "' -simulate-noise 0.001' (NOTE the beginning space!)")
    parser.add_argument("-d", "--dirty", dest="dirty", action="store_true",
                        help="only create dirty images (by setting niter=0)")
    parser.add_argument("-n", "--dry-run", dest="dryrun", action="store_true",
                        help="do not actually run WSClean")
    parser.add_argument("--update-model", dest="update_model",
                        action="store_true",
                        help="write/update the MODEL_DATA column in MS")
    parser.add_argument("--save-weights", dest="save_weights",
                        action="store_true",
                        help="save gridded weights in <name>-weights.fits")
    parser.add_argument("--save-uv", dest="save_uv",
                        action="store_true",
                        help="save gridded uv plane (i.e., FFT of the " +
                        "residual image) in <name>-uv-{real,imag}.fits")
    parser.add_argument("--uv-range", dest="uv_range", default=":",
                        help="uv range [lambda] (i.e., baseline lengths) " +
                        "used for imaging; syntax: '<min>:<max>' " +
                        "(default: ':', i.e., all uv/baselines)")
    parser.add_argument("-w", "--weight", dest="weight", default="uniform",
                        choices=["uniform", "natural", "briggs"],
                        help="weighting method (default: 'briggs')")
    parser.add_argument("-B", "--briggs", dest="briggs",
                        type=float, default=0.0,
                        help="Briggs robustness parameter (default: 0); " +
                        "-1 (uniform) -> 1 (natural)")
    parser.add_argument("-#", "--niter", dest="niter",
                        type=int, default=200000,
                        help="maximum number of CLEAN iterations " +
                        "(default: 200,000)")
    parser.add_argument("--gain", dest="gain", type=float, default=0.1,
                        help="CLEAN gain for each minor iteration " +
                        "(default: 0.1)")
    parser.add_argument("--mgain", dest="mgain", type=float, default=0.85,
                        help="CLEAN gain for major iterations " +
                        "(default: 0.85)")
    parser.add_argument("-s", "--size", dest="size", type=int,
                        required=True,
                        help="output image size (pixel number on a side)")
    parser.add_argument("-p", "--pixelsize", dest="pixelsize", type=float,
                        required=True,
                        help="output image pixel size [arcsec]")
    parser.add_argument("-G", "--taper-gaus", dest="taper_gaus", type=float,
                        help="taper the weights with a Gaussian function " +
                        "to reduce the contribution of long baselines. " +
                        "Gaussian beam size in [arcsec].")
    parser.add_argument("--fit-spec-order", dest="fit_spec_order", type=int,
                        help="do joined-channel CLEAN by fitting the " +
                        "spectra with [order] polynomial in normal-space")
    #
    exgrp = parser.add_mutually_exclusive_group()
    exgrp.add_argument("-S", "--threshold-nsigma", dest="threshold_nsigma",
                       type=float, default=2.0,
                       help="estimate the noise level <sigma> and stop at " +
                       "nsigma*<sigma> (default: 2.0 <sigma>)")
    exgrp.add_argument("-t", "--threshold", dest="threshold", type=float,
                       help="stopping CLEAN threshold [mJy]")
    #
    parser.add_argument("-N", "--name", dest="name", required=True,
                        help="filename prefix for the output files")
    parser.add_argument("-m", "--ms", nargs="+", help="input visibility MSs")
    args = parser.parse_args()

    nms = len(args.ms)  # i.e., number of MS == number of channels

    cmdargs = [
        "-verbose",
        "-log-time",
        "-pol", "XX",  # OSKAR "Scalar" simulation only give "XX" component
        "-make-psf",  # always make the PSF, even no cleaning performed
        "-tempdir", "/tmp",
    ]

    if args.dirty:
        cmdargs += ["-niter", 0]  # make dirty image only
    else:
        cmdargs += ["-niter", args.niter]

    if args.weight == "uniform":
        cmdargs += ["-weight", "uniform",
                    "-weighting-rank-filter", 3]
    elif args.weight == "briggs":
        cmdargs += ["-weight", "briggs", args.briggs]
    else:
        cmdargs += ["-weight", args.weight]  # natural
    cmdargs += ["-gain", args.gain]
    cmdargs += ["-mgain", args.mgain]
    cmdargs += ["-size", args.size, args.size]
    cmdargs += ["-scale", "{0}asec".format(args.pixelsize)]

    if args.fit_spec_order:
        cmdargs += ["-joinchannels", "-channelsout", nms,
                    "-fit-spectral-pol", args.fit_spec_order+1]

    if args.update_model:
        cmdargs += ["-update-model-required"]
    else:
        cmdargs += ["-no-update-model-required"]

    if args.save_weights:
        cmdargs += ["-saveweights"]
    if args.save_uv:
        cmdargs += ["-saveuv"]

    # uv/baseline range
    uvmin, uvmax = args.uv_range.strip().split(":")
    if uvmin:
        cmdargs += ["-minuv-l", float(uvmin)]
    if uvmax:
        cmdargs += ["-maxuv-l", float(uvmax)]

    if args.threshold:
        cmdargs += ["-threshold", args.threshold*1e-3]  # [mJy] -> [Jy]
    else:
        cmdargs += ["-auto-threshold", args.threshold_nsigma]

    if args.taper_gaus:
        cmdargs += ["-taper-gaussian", args.taper_gaus]

    # additional WSClean arguments
    if args.args:
        extra_args = re.split(r"\s+", args.args.strip())
        print("Additional WSClean arguments:", extra_args)
        cmdargs += extra_args

    nameprefix = args.name.rstrip("-_")
    cmdargs += ["-name", nameprefix]
    cmdargs += args.ms

    wsclean(cmdargs, dryrun=args.dryrun)

    if args.dirty and not args.dryrun:
        # Remove the output "-image" since it is identical to "-dirty"
        os.remove(nameprefix+"-image.fits")


if __name__ == "__main__":
    main()