-
Notifications
You must be signed in to change notification settings - Fork 0
/
dragon_scales
executable file
·296 lines (223 loc) · 8.33 KB
/
dragon_scales
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
#!/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 = "dragon_scales"
__revision__ = "15 January 2019"
import os
import sys
import numpy as np
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
from cxcdm import *
class OverlappingShapes():
invalid_pixel = 12345678
def __init__(self, infile, psffile, gradient ):
"""
"""
from crates_contrib.masked_image_crate import MaskedIMAGECrate
self.img = MaskedIMAGECrate(infile,mode="r")
self.vals = self.img.get_image().values
self.infile = infile
try:
self.pmap = np.zeros_like( self.vals ) + float( psffile )
except Exception as e:
self.pmap = MaskedIMAGECrate( psffile, mode="r").get_image().values
self.nullval = -999
self.mask = None
if gradient:
gx,gy = np.gradient( self.vals)
self.angle = np.arctan2(gy,gx) # radians, keep it like that
else:
self.angle = np.zeros_like(self.vals)
def get_psfsize( self, xx, yy):
"""
"""
import numpy as np
p = self.pmap[yy,xx]
return p if np.isfinite(p) else 0
@staticmethod
def inside( dx, dy, rad ):
raise NotImplementedError("Please implement this in the subclass")
def set_mask( self, xx, yy, maskval ):
"""
"""
rad = int(self.get_psfsize( xx, yy )+0.5)
rad_2 = 2*rad # allow for rotation of shapes
def rotate( _x, _y ):
aa = -self.angle[yy,xx]
cos_a = np.cos(aa)
sin_a = np.sin(aa)
ox = cos_a * _x + sin_a * _y
oy = -sin_a * _x + cos_a * _y
return(ox,oy)
for _y in range( yy-rad_2-1, yy+rad_2+1, 1):
if _y < 0 or _y >= self.mask.shape[0]:
continue
dy = _y-yy
for _x in range( xx-rad_2-1, xx+rad_2+1, 1):
if _x < 0 or _x >= self.mask.shape[1]:
continue
if self.mask[_y,_x] != 0:
continue
if not self.img.valid(_x,_y):
self.mask[_y, _x] = self.invalid_pixel
self.vals[_y, _x] = self.nullval
continue
dx = _x-xx
rx,ry = rotate(dx,dy)
if self.inside( rx,ry, rad):
self.mask[_y, _x] = maskval
self.vals[_y, _x] = self.nullval
def get_loc_max(self):
"""
"""
ll = np.where( self.vals == np.max( self.vals ) )
ly = ll[0][0]
lx = ll[1][0]
self.vals[ly,lx] = self.nullval
return (ly,lx)
def doit(self):
"""
"""
self.mask = np.zeros_like(self.vals).astype(np.int32)
maskval = 0
while 0 == np.min(self.mask):
maskval = maskval + 1
verb3(str(maskval))
ly,lx = self.get_loc_max()
self.set_mask( lx, ly, maskval )
for iy in range(self.mask.shape[0]):
for ix in range(self.mask.shape[1]):
if self.mask[iy][ix] == self.invalid_pixel:
self.mask[iy][ix] = 0
def save( self, outfile ):
"""
"""
if os.path.exists( outfile ):
os.remove( outfile) # clobber check already done
dm_img = dmImageOpen(self.infile+"[opt type=i4]")
out_img = dmBlockCreateCopy( dmDatasetCreate(outfile), "GRID", dm_img)
out_dd = dmImageGetDataDescriptor( out_img )
dmImageSetData( out_dd, self.mask )
dmImageClose( out_img )
dmImageClose( dm_img)
class RegionTiles( OverlappingShapes ):
"""
Use cxcRegion for shapes
"""
def make_region(self, radius):
raise NotImplementedError("Implement in the subclass")
def inside( self, dx, dy, rad ):
if not hasattr(self, "region"):
self.make_region(rad)
return self.region.is_inside( dx,dy)
class HexTiles( RegionTiles):
"""
"""
def make_region(self, radius):
import region as cxcregion
s60 = np.sin(np.deg2rad(60.0))
c60 = np.cos(np.deg2rad(60.0))
px = np.array( [ -1.0, -c60, c60, 1.0, c60, -c60, -1.0 ] )*radius
py = np.array( [ 0.0, s60, s60, 0.0, -s60, -s60, 0.0 ] )*radius
self.region = cxcregion.polygon(px,py)
class TriangleTiles( RegionTiles):
"""
"""
def make_region(self, radius):
import region as cxcregion
px = np.array( [ -0.5, 0.5, 0 ] )*radius
py = np.array( [ -0.5, -0.5, 0.5 ] )*radius
self.region = cxcregion.polygon(px,py)
class InvertedTriangleTiles( RegionTiles):
"""
"""
def make_region(self, radius):
import region as cxcregion
px = np.array( [ -0.5, 0.5, 0 ] )*radius
py = np.array( [ 0.5, 0.5, -0.5 ] )*radius
self.region = cxcregion.polygon(px,py)
class RoofingTiles( OverlappingShapes ):
"""
Use square shapes
"""
@staticmethod
def inside( dx, dy, rad ):
return (max( [abs(dx),abs(dy)] ) <= rad)
class DragonScales( OverlappingShapes ):
"""
Use circular shapes
"""
@staticmethod
def inside( dx, dy, rad ):
from math import hypot
return (hypot( dx, dy) <= rad)
class Diamonds( OverlappingShapes ):
"""
Use city-block distance
"""
@staticmethod
def inside( dx, dy, rad ):
return (abs(dx)+abs(dy) <= rad)
@lw.handle_ciao_errors( toolname, __revision__)
def main():
"""
"""
from ciao_contrib.param_soaker import get_params
from ciao_contrib.runtool import dmmaskbin
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"] )
outfile_clobber_checks(pars["clobber"], pars["binimg"] )
gradient = ("yes" == pars["gradient"])
if "circle" == pars["shape"]:
dragon = DragonScales( pars["infile"], pars["radius"], gradient )
elif "box" == pars["shape"]:
dragon = RoofingTiles( pars["infile"], pars["radius"], gradient )
elif "diamond" == pars["shape"]:
dragon = Diamonds( pars["infile"], pars["radius"], gradient )
elif "hexagon" == pars["shape"]:
dragon = HexTiles( pars["infile"], pars["radius"], gradient )
elif "triangle" == pars["shape"]:
dragon = TriangleTiles( pars["infile"], pars["radius"], gradient )
elif "itriangle" == pars["shape"]:
dragon = InvertedTriangleTiles( pars["infile"], pars["radius"], gradient )
else:
raise ValueError("Unknown shape value {}".format(pars["shape"]))
dragon.doit()
dragon.save( pars["outfile"] )
add_tool_history( pars["outfile"], toolname, pars, toolversion=__revision__)
if len(pars["binimg"])>0 and "none" != pars["binimg"].lower():
dmmaskbin( pars["infile"], pars["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)