-
Notifications
You must be signed in to change notification settings - Fork 7
/
enplot_old
executable file
·212 lines (201 loc) · 8.71 KB
/
enplot_old
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
#!/usr/bin/env python
import numpy as np, argparse, time, sys, warnings
from enlib import enmap, colorize, mpi
warnings.filterwarnings("ignore")
parser = argparse.ArgumentParser()
parser.add_argument("ifiles", nargs="+")
parser.add_argument("-o", "--oname", default="{pre}{base}{suf}{comp}.{ext}")
parser.add_argument("-c", "--color", default="wmap")
parser.add_argument("-r", "--range", type=str)
parser.add_argument("--min", type=str)
parser.add_argument("--max", type=str)
parser.add_argument("-q", "--quantile", type=float, default=0.01)
parser.add_argument("-v", dest="verbosity", action="count")
parser.add_argument("-s", "-u", "--scale", "--upgrade", type=str, default="1")
parser.add_argument("--verbosity", dest="verbosity", type=int)
parser.add_argument("--method", default="fast")
parser.add_argument("--slice", type=str)
parser.add_argument("--sub", type=str)
parser.add_argument("--op", type=str)
parser.add_argument("-d", "--downgrade", type=str, default="1")
parser.add_argument("--prefix", type=str, default="")
parser.add_argument("--suffix", type=str, default="")
parser.add_argument("--ext", type=str, default="png")
parser.add_argument("-m", "--mask", type=float)
parser.add_argument("--mask-tol", type=float, default=1e-14)
parser.add_argument("-g", "--grid", action="count", default=1)
parser.add_argument("--grid-color", type=str, default="00000020")
parser.add_argument("-t", "--ticks", type=str, default="1")
parser.add_argument("--nolabels", action="store_true")
parser.add_argument("--nstep", type=int, default=200)
parser.add_argument("--subticks", type=float, default=0)
parser.add_argument("--font", type=str, default="arial.ttf")
parser.add_argument("--font-size", type=int, default=20)
parser.add_argument("--font-color", type=str, default="000000")
parser.add_argument("-D", "--driver", type=str, default="pil")
parser.add_argument("--mpl-dpi", type=float, default=75)
parser.add_argument("--mpl-pad", type=float, default=1.6)
parser.add_argument("--rgb", action="store_true")
parser.add_argument("-a", "--autocrop", action="store_true")
parser.add_argument("-A", "--autocrop-each", action="store_true")
args = parser.parse_args()
if args.verbosity >= 3:
try:
import os, psutil
p = psutil.Process(os.getpid())
t1 = p.create_time()
sys.stderr.write("%6.2f %s\n" % (time.time()-t1,"startup"))
except ImportError:
pass
class dprint:
def __init__(self, desc):
self.desc = desc
def __enter__(self):
self.t1 = time.time()
def __exit__(self, type, value, traceback):
if args.verbosity >= 3:
sys.stderr.write("%6.2f %s\n" % (time.time()-self.t1,self.desc))
comm = mpi.COMM_WORLD
ticks = np.full(2,1.0); ticks[:] = [float(w) for w in args.ticks.split(",")]
ngroup = 3 if args.rgb else 1
for fi in range(comm.rank,len(args.ifiles),comm.size):
ifile = args.ifiles[fi]
# Allow slicing of input argument
with dprint("read %s" % ifile):
toks = ifile.split(":")
ifile, slice = toks[0], ":".join(toks[1:])
m0 = enmap.read_map(ifile)
m = m0
if args.sub is not None:
default = [[-90,-180],[90,180]]
sub = np.array([[(default[j][i] if q == '' else float(q))*np.pi/180 for j,q in enumerate(w.split(":"))]for i,w in enumerate(args.sub.split(","))]).T
m = m.submap(sub)
if args.autocrop:
m = enmap.autocrop(m)
downgrade = [int(w) for w in args.downgrade.split(",")]
m = enmap.downgrade(m, downgrade)
m = eval("m"+slice)
if args.slice is not None:
m = eval("m"+args.slice)
flip = (m.wcs.wcs.cdelt*m0.wcs.wcs.cdelt)[::-1]<0
assert m.ndim >= 2, "Image must have at least 2 dimensions"
if args.op is not None:
m = eval(args.op, {"m":m},np.__dict__)
# Scale if requested
scale = [int(w) for w in args.scale.split(",")]
if np.any(np.array(scale)>1):
m = enmap.upgrade(m, scale)
# Flatten pre-dimensions
mf = m.reshape((-1,)+m.shape[-2:])
ncomp = mf.shape[0]
with dprint("ranges"):
# Construct color ranges
def parse_range(desc,n):
res = np.array([float(w) for w in desc.split(":")])[:n]
return np.concatenate([res,np.repeat([res[-1]],n-len(res))])
crange = np.zeros((2,ncomp))+np.nan
# Try explicit limits if given
if args.range is not None:
crange[1] = parse_range(args.range,ncomp)
crange[0] = -crange[1]
if args.min is not None: crange[0] = parse_range(args.min,ncomp)
if args.max is not None: crange[1] = parse_range(args.max,ncomp)
# Fall back on quantile otherwise
if np.any(np.isnan(crange)):
vals = np.sort(mf[np.isfinite(mf)])
n = len(vals)
v1,v2 = vals[int(round(n*args.quantile))], vals[min(n-1,int(round(n*(1-args.quantile))))]
crange[0,np.isnan(crange[0])] = v1
crange[1,np.isnan(crange[1])] = v2
if args.verbosity >= 4:
for ci, cr in enumerate(crange.T):
sys.stderr.write("color range %d: %15.7e to %15.7e\n" % (ci, cr[0], cr[1]))
# Construct default out format
ndigit = int(np.log10(ncomp))+1
# Find the extension. Using the last dot does not work for .fits.gz.
# Using the first dot in basename does not work for foo2.5_bar.fits.
# Will therefore handle .gz as a special case.
if ifile.endswith(".gz"):
dot = ifile[:-3].rfind(".")
else:
dot = ifile.rfind(".")
if dot < 0: dot = len(ifile)
# Loop over fields
for i in range(0, ncomp, ngroup):
istr = ("%%0%dd/%%d" % ndigit) % (i+1,ncomp)
# We want dec to increase upwards (negative pixel diretion)
# and ra to increae leftwards (negative pixel direction).
mdata = mf[i:i+ngroup]
if mdata.wcs.wcs.cdelt[1] > 0: mdata = mdata[:,::-1,:]
if mdata.wcs.wcs.cdelt[0] > 0: mdata = mdata[:,:,::-1]
if flip[0]: mdata = mdata[:,::-1,:]
if flip[1]: mdata = mdata[:,:,::-1]
# Build output file name
fields = {"base":ifile[:dot], "iext":ifile[dot+1:], "fi":fi, "fn":len(args.ifiles),
"ci":i, "cn":ncomp, "pi":comm.rank, "pn":comm.size, "pre":args.prefix,
"suf":args.suffix, "comp": "_%0*d" % (ndigit,i) if m.ndim > 2 else "",
"ext":args.ext}
oname = args.oname.format(**fields)
if args.autocrop_each:
mdata = enmap.autocrop(mdata)
if args.mask is not None:
if not np.isfinite(args.mask): mdata[mdata==args.mask] = np.nan
else: mdata[np.abs(mdata-args.mask)<=args.mask_tol] = np.nan
with dprint("%s rescale" % istr):
mdata = (mdata-crange[0,i])/(crange[1,i]-crange[0,i])
with dprint("%s colorize" % istr):
if args.rgb: m_color = colorize.colorize(mdata, desc=args.color, method="direct")
else: m_color = colorize.colorize(mdata[0], desc=args.color, method=args.method)
if args.driver.lower() == "pil":
import PIL.Image, enlib.cgrid
with dprint("%s to image" % istr):
m_img = PIL.Image.fromarray(m_color).convert('RGBA')
if args.grid % 2:
with dprint("draw grid"):
ginfo = enlib.cgrid.calc_gridinfo(mdata.shape, mdata.wcs, steps=ticks, nstep=args.nstep)
m_img = enlib.cgrid.draw_grid(ginfo, color=args.grid_color, background=m_img)
if not args.nolabels:
linfo = []
for gi in [ginfo.lat, ginfo.lon]:
linfo += enlib.cgrid.calc_label_pos(gi, m_img.size)
m_img, bounds = enlib.cgrid.draw_labels(m_img, linfo, fname=args.font, fsize=args.font_size, color=args.font_color, return_bounds=True)
padding = np.array([-bounds[0,::-1],bounds[1,::-1]-mdata.shape[-2:]],dtype=int)
else: padding = np.zeros([2,2])
with dprint("padded by %d %d %d %d" % tuple(padding.reshape(-1))):
pass
with dprint("%s write to %s" % (istr,oname)):
m_img.save(oname)
elif args.driver.lower() in ["matplotlib","mpl"]:
import matplotlib, warnings
matplotlib.use("Agg")
from matplotlib import pyplot, ticker
warnings.filterwarnings('ignore')
matplotlib.rcParams.update({'font.size': 10})
with dprint("%s to image" % istr):
dpi, pad = args.mpl_dpi, args.mpl_pad
winch, hinch = mdata.shape[1]/dpi, mdata.shape[0]/dpi
fig = pyplot.figure(figsize=(winch+pad,hinch+pad))
box = mdata.box()*180/np.pi
pyplot.imshow(m_color, extent=[box[0,1],box[1,1],box[1,0],box[0,0]])
# Make conformal in center of image
pyplot.axes().set_aspect(1/np.cos(np.mean(mdata.box()[:,0])))
if args.grid % 2:
ax = pyplot.axes()
ax.xaxis.set_major_locator(ticker.MultipleLocator(ticks[1]))
ax.yaxis.set_major_locator(ticker.MultipleLocator(ticks[0]))
if args.subticks:
ax.xaxis.set_minor_locator(ticker.MultipleLocator(args.sub))
ax.yaxis.set_minor_locator(ticker.MultipleLocator(args.sub))
pyplot.minorticks_on()
pyplot.grid(True, which="major", linewidth=2)
pyplot.grid(True, which="minor", linewidth=1)
else:
pyplot.grid(True)
with dprint("%s write to %s" % (istr,oname)):
pyplot.tight_layout(pad=0.0,h_pad=0.0,w_pad=0.0)
pyplot.savefig(oname,bbox_inches="tight",dpi=dpi)
# Progress report
if args.verbosity == 2:
sys.stderr.write("\r%s %5d/%d" % (ifile, i+1,ncomp))
if args.verbosity == 2: sys.stderr.write("\n")
if args.verbosity == 1: sys.stderr.write("%s\n" % ifile)