-
Notifications
You must be signed in to change notification settings - Fork 0
/
contour_map
executable file
·215 lines (164 loc) · 6.43 KB
/
contour_map
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
#!/usr/bin/env python
#
# Copyright (C) 2014 Smithsonian Astrophysical Observatory
#
# This program is free software; you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation; either version 2 of the License, or
# (at your option) any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License along
# with this program; if not, write to the Free Software Foundation, Inc.,
# 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.
#
from __future__ import print_function
toolname = "contour_map"
__revision__ = "16 January 2019"
import numpy as np
from math import sqrt
from pycrates import *
from ciao_contrib.runtool import dmimglasso
from ciao_contrib.runtool import dmstat
from ciao_contrib.runtool import dmimgcalc
from ciao_contrib.runtool import dmcoords
from ciao_contrib.runtool import dmmaskbin
import os
import sys
import shutil
import ciao_contrib.logger_wrapper as lw
lgr = lw.initialize_logger(toolname)
verb0 = lgr.verbose0
verb1 = lgr.verbose1
verb2 = lgr.verbose2
verb3 = lgr.verbose3
verb5 = lgr.verbose5
class CIAOTemporaryFile():
"""
A little class to make sure that tmpfiles are forcefully removed at end.
"""
def __init__( self, *args, **kwargs ):
from tempfile import NamedTemporaryFile
self.tmpfile = NamedTemporaryFile( dir=os.environ["ASCDS_WORK_PATH"], *args, **kwargs)
self.name = self.tmpfile.name
def __del__(self):
if os.path.exists( self.name ):
os.remove( self.name )
def make_temp_files():
t1 = CIAOTemporaryFile()
t2 = CIAOTemporaryFile()
t3 = CIAOTemporaryFile()
t4 = CIAOTemporaryFile()
t1.tmpfile.close()
t2.tmpfile.close()
t3.tmpfile.close()
t4.tmpfile.close()
return(t1,t2,t3,t4)
def make_grid(vals, levels, nlevels, scale ):
if "" == levels or "INDEF" == levels:
minval = np.min(vals[vals>0]) # no log of 0 please, we're keeping it real.
maxval = np.max(vals)
if "log" == scale:
lmin = np.log10(minval)
lmax = np.log10(maxval)
grid = np.logspace( lmin, lmax, num=nlevels, endpoint=False, base=10.0)
elif "linear" == scale:
grid = np.linspace( minval, maxval, num=nlevels, endpoint=False)
else:
raise ValueError("Unknown value for scale")
else: # use specific levels
import stk as stk
grid = stk.build( levels )
grid = np.array([float(x) for x in grid])
return grid
@lw.handle_ciao_errors( toolname, __revision__)
def main():
"""
"""
# get parameters
from ciao_contrib.param_soaker import get_params
from ciao_contrib.runtool import add_tool_history
# Load parameters
pars = get_params(toolname, "rw", sys.argv,
verbose={"set":lw.set_verbosity, "cmd":verb1} )
from ciao_contrib._tools.fileio import outfile_clobber_checks
outfile_clobber_checks(pars["clobber"], pars["outfile"] )
infile= pars["infile"] # "broad_gaus.img" # "abell2029_broad_thresh.img"
outfile = pars["outfile"] # "contour.map"
maxrad = float( pars["distance"] ) # 75
maxshape = pars["shape"] # "circle"
levels = pars["levels"]
nlevels = int( pars["nlevels"] )
scale = pars["scale"]
maxcntrs = int(pars["maxcontours"] ) # 1000
# Load input image
img2 = read_file(infile)
vals = img2.get_image().values*1.0
# Make list of contour levels
grid = make_grid( vals, levels, nlevels, scale )
# Create output file
out_mask = np.zeros_like( vals )
img2.get_image().values = out_mask
write_file( img2, outfile, clobber=True)
t1,t2,t3,t4 = make_temp_files()
use_img = infile
maxval = max(grid)
num_contours = 0
stopit = (np.nan, np.nan)
while num_contours < maxcntrs and maxval > min(grid):
# Trying to do some of this with crates left too many files open
dmstat( use_img, centroid=False, sigma=False, median=False)
maxval = float( dmstat.out_max )
if maxval <= min(grid):
break
# location of pixel == maxval
xc = dmstat.out_max_loc.split(",")[0]
yc = dmstat.out_max_loc.split(",")[1]
# convert to logical coords
dmcoords( infile, asol="", op="sky", x=xc, y=yc )
lx = int(float(dmcoords.logicalx)+0.5)
ly = int(float(dmcoords.logicaly)+0.5)
if stopit == (lx,ly):
# Hey,I've been here before. Didn't work the last time
# so just bail out.
break
else:
stopit = (lx,ly)
if "circle" == maxshape:
ff = "[sky=circle({},{},{})][opt full]".format( xc,yc,maxrad)
elif "box" == maxshape:
ff = "[sky=box({0},{1},{2},{2})][opt full]".format( xc,yc,maxrad*2.0)
else:
raise ValueError("Unknown shape")
low = grid[grid<maxval]
if len(low) == 0:
# pixels in image below lowest contour level, can't reach 'em
break
low = low[-1]
num_contours += 1
verb1("Contour lower limit: {} ({},{})".format(low,lx,ly))
dmimglasso( use_img+ff, t1.name, xpos=lx, ypos=ly, coord="logical",
low_val=low, value="absolute", clobber=True)
dmimgcalc( use_img+","+t1.name, "none", outfile=t3.name,
op="imgout=(img1-(img1*img2))", clobber=True)
shutil.move( t3.name, t2.name)
use_img = t2.name
dmimgcalc( outfile+","+t1.name, "none", outfile=t4.name+"[CONTMAP]",
op="imgout=(img1+(img2*{}))".format( num_contours), clobber=True)
shutil.move( t4.name, outfile)
# End while
add_tool_history( outfile, toolname, pars, toolversion=__revision__)
if len(pars["binimg"])>0 and "none" != pars["binimg"].lower():
dmmaskbin( pars["infile"], outfile+"[opt type=i4]", pars["binimg"], clobber=True)
add_tool_history( pars["binimg"], toolname, pars, toolversion=__revision__)
if __name__ == "__main__":
try:
main()
except Exception as E:
print("\n# "+toolname+" ("+__revision__+"): ERROR "+str(E)+"\n", file=sys.stderr)
sys.exit(1)
sys.exit(0)