aboutsummaryrefslogtreecommitdiffstats
path: root/astro/marx/marx_pntsrc.py
blob: 97b157521e889a6c47143fe9b741493ad5fe682a (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
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
#
# Aaron LI
# 2015/06/16

"""
Run MARX simulation on a given list of point sources, merge the
output simulation results, and finally convert into FITS image.
"""

__version__ = "0.1.0"
__date__ = "2015/06/16"

import sys
import argparse
import subprocess
import re
import os


def marx_pntsrc(pfile, ra, dec, flux, outdir):
    """
    Run MARX simulation for the provided point source.
    """
    cmd = "marx @@%(pfile)s SourceRA=%(ra)s " % {"pfile": pfile, "ra": ra} + \
            "SourceDEC=%(dec)s SourceFlux=%(flux)s OutputDir=%(outdir)s" % \
            {"dec": dec, "flux": flux, "outdir": outdir}
    print("CMD: %s" % cmd, file=sys.stderr)
    subprocess.call(cmd, shell=True)


def marxcat(indirs, outdir):
    """
    Concatenate a list of MARX simulation results.

    Note: the number of MARX results to be concatenated at *one* time
          can not be to many, otherwise the 'marxcat' tool will failed.
    """
    if isinstance(indirs, list):
        pass
    elif isinstance(indirs, str):
        indirs = indirs.split()
    else:
        raise ValueError("invalid indirs type: %s" % indirs)
    pid = os.getpid()
    tempdir = "_marx_tmp%d" % pid
    cmd = "cp -a %(marxdir)s %(tempdir)s" % \
            {"marxdir": indirs[0], "tempdir": tempdir}
    print("CMD: %s" % cmd, file=sys.stderr)
    subprocess.call(cmd, shell=True)
    del indirs[0]
    while len(indirs) > 0:
        # concatenated 10 directories each time
        catdirs = indirs[:9]
        del indirs[:9]
        catdirs = tempdir + " " + " ".join(catdirs)
        # concatenate MARX results
        cmd = "marxcat %(catdirs)s %(outdir)s" % \
                {"catdirs": catdirs, "outdir": outdir}
        print("CMD: %s" % cmd, file=sys.stderr)
        subprocess.call(cmd, shell=True)
        # move output results to temporary directory
        cmd = "rm -rf %(tempdir)s && mv %(outdir)s %(tempdir)s" % \
                {"tempdir": tempdir, "outdir": outdir}
        print("CMD: %s" % cmd, file=sys.stderr)
        subprocess.call(cmd, shell=True)
    cmd = "mv %(tempdir)s %(outdir)s" % \
            {"tempdir": tempdir, "outdir": outdir}
    print("CMD: %s" % cmd, file=sys.stderr)
    subprocess.call(cmd, shell=True)


def marx2fits(indir, outfile, params=""):
    """
    Convert the results of MARX simulation into FITS image.
    """
    cmd = "marx2fits %(params)s %(indir)s %(outfile)s" % \
            {"params": params, "indir": indir, "outfile": outfile}
    print("CMD: %s" % cmd, file=sys.stderr)
    subprocess.call(cmd, shell=True)


def main():
    parser = argparse.ArgumentParser(
            description="Run MARX on a given list of point sources")
    parser.add_argument("-V", "--version", action="version",
            version="%(prog)s " + "%s (%s)" % (__version__, __date__))
    parser.add_argument("pfile", help="marx paramter file")
    parser.add_argument("srclist", help="point source list file")
    parser.add_argument("outprefix", help="prefix of output directories")
    args = parser.parse_args()

    outdirs = []
    i = 0
    for line in open(args.srclist, "r"):
        if re.match(r"^\s*$", line):
            # skip blank line
            continue
        elif re.match(r"^\s*#", line):
            # skip comment line
            continue
        i += 1
        ra, dec, flux = map(float, line.split())
        print("INFO: ra = %g, dec = %g, flux = %g" % (ra, dec, flux),
                file=sys.stderr)
        outdir = "%sp%03d" % (args.outprefix, i)
        print("INFO: outdir = %s" % outdir, file=sys.stderr)
        outdirs.append(outdir)
        marx_pntsrc(args.pfile, ra, dec, flux, outdir)
    # merge results
    merged = args.outprefix + "merged"
    marxcat(outdirs, merged)
    # convert to FITS image
    merged_fits = merged + ".fits"
    marx2fits(merged, merged_fits)


if __name__ == "__main__":
    main()