-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathvtbin
executable file
·293 lines (223 loc) · 8.17 KB
/
vtbin
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-2020, 2023
# 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 3 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.
#
'Create bins based on voroni tesselation'
import os
import sys
import ciao_contrib.logger_wrapper as lw
__toolname__ = "vtbin"
__revision__ = "24 August 2023"
__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"],
delete=False, *args, **kwargs)
self.name = self.tmpfile.name
def __del__(self):
self.tmpfile.close()
if os.path.exists(self.name):
os.remove(self.name)
def find_local_max(infile, mask="box(0, 0, 5, 5)"):
"""
Identify the local peaks in the data. Value must be the max() valein the
mask region around the pixel (must be strictly > all surrounding pixels)
"""
from ciao_contrib.runtool import dmimgfilt
from ciao_contrib.runtool import dmimgblob
verb1("Finding local maxima")
t1 = CIAOTemporaryFile()
t2 = CIAOTemporaryFile()
nn = t2.name
dmimgfilt(infile, t1.name, function="peak", mask=mask, clobber=True)
dmimgblob(t1.name, nn, thresh=0, src=True, clobber=True)
return t2
def make_mask(shape, radius):
"""
This is the mask used to determine local max
"""
if "circle" == shape:
return f"circle(0, 0, {radius})"
if "box" == shape:
r = float(radius)*2.0
return f"box(0, 0, {r}, {r})"
raise RuntimeError(f"Unknown shape '{shape}'")
def cercle_circonscrit(T):
"""Find the center of a circle that circumscribes 3 points (triangle)
The 3 points cannot be colinear or this blows up.
https: //stackoverflow.com/questions/44231281/circumscribed-circle-of-a-triangle-in-2d
"""
import numpy as np
(x1, y1), (x2, y2), (x3, y3) = T
A = np.array([[x3-x1, y3-y1], [x3-x2, y3-y2]])
Y = np.array([(x3**2 + y3**2 - x1**2 - y1**2),
(x3**2+y3**2 - x2**2-y2**2)])
if np.linalg.det(A) == 0:
return False
Ainv = np.linalg.inv(A)
X = 0.5*np.dot(Ainv, Y)
x, y = X[0], X[1]
# r = sqrt((x-x1)**2+(y-y1)**2)
return (x, y) # , r
class Cell():
"""Class to hold Voronoi cells"""
def __init__(self, x, y):
'Hold info about cells'
self.x = x
self.y = y
self.neighbors = []
def calc_midpts(self):
'Convert center of triangles into voronoi cells'
from math import atan2
self.midpts = []
for n in self.neighbors:
(midx, midy) = n
ang = atan2(midy-self.y, midx-self.x)
# Do not add duplicate points
to_add = (ang, (midx, midy))
if to_add not in self.midpts:
self.midpts.append(to_add)
self.midpts.sort()
self.cellx = []
self.celly = []
for p in self.midpts:
self.cellx.append(p[1][0])
self.celly.append(p[1][1])
def make_vcells(x, y):
"""
Use matplotlib's Traiangulation to create Delauny triangulation,
then find centers of triangles to create Voronoi cells.
"""
import matplotlib.tri as mtri
tri = mtri.Triangulation(x, y)
pts = [Cell(_x, _y) for _x, _y in zip(x, y)]
for t in tri.get_masked_triangles():
# Find center of triangle; add center to list of
# neighbors at each vertex of the triangle
midx, midy = cercle_circonscrit(list(zip(x[t], y[t])))
pts[t[0]].neighbors.append((midx, midy))
pts[t[1]].neighbors.append((midx, midy))
pts[t[2]].neighbors.append((midx, midy))
for p in pts:
p.calc_midpts()
return pts
def make_polygon(cell, img_shape):
"Create polygon and compute extent bounded by image"
import numpy as np
from region import polygon
try:
p = polygon(cell.cellx, cell.celly)
if len(p) == 0:
raise RuntimeError("Bad polygon")
except Exception as bad:
print(f"Cellx: {cell.cellx}")
print(f"Celly: {cell.celly}")
raise bad
# Loop over pixels just inside extent of polygon
ext = p.extent()
xl = max([0, int(ext['x0'])])
xh = min([img_shape[1], int(ext['x1']+1)])
yl = max([0, int(ext['y0'])])
yh = min([img_shape[0], int(ext['y1']+1)])
_yrange = np.arange(yl, yh)
_xrange = np.arange(xl, xh)
return p, _xrange, _yrange
def compute_vcells(infile, sitesfile, outfile, clobber):
"""
Given a set of local max, grow the regions until they touch and
cover the image
"""
from crates_contrib.masked_image_crate import MaskedIMAGECrate
import numpy as np
verb1("Assigning pixels to maxima")
# Load data
img = MaskedIMAGECrate(sitesfile, mode="r")
imgd = img.get_image()
vv = imgd.values
# Open infile to get subspace
dss_img = MaskedIMAGECrate(infile, mode="r")
# get non-zero pixels
sites = np.argwhere(vv > 0)
# get pixel value at all non-zero pixels
sitesv = [vv[y, x] for y, x in sites]
# get x, y coords of non-zero pixels
xx = sites[:, 1]
yy = sites[:, 0]
# Compute V. cells.
cells = make_vcells(xx, yy)
# Now fill in the V. cells with the pixel value
outvv = np.zeros_like(vv)
for c, v in zip(cells, sitesv):
try:
p, _xrange, _yrange = make_polygon(c, vv.shape)
except Exception:
continue
for _y in _yrange:
for _x in _xrange:
# Pixel already assigned, skip it
if outvv[_y, _x] != 0:
continue
# Pixel not in subspace, skip it
if not dss_img.valid(_x, _y):
continue
# Do the hard work
if p.is_inside(_x, _y):
outvv[_y, _x] = v
# Save the values
imgd.values = outvv
img.name = "tess"
img.write(outfile, clobber=clobber)
@lw.handle_ciao_errors(__toolname__, __revision__)
def main():
"""
main routine
"""
# Load parameters
from ciao_contrib.param_soaker import get_params
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"])
mask = make_mask(pars["shape"], pars["radius"])
if len(pars["sitefile"]) == 0 or "none" == pars["sitefile"].lower():
tmpsitefile = find_local_max(pars["infile"], mask=mask)
sitefile = tmpsitefile.name
else:
sitefile = pars["sitefile"]
compute_vcells(pars["infile"], sitefile, pars["outfile"], pars["clobber"])
from ciao_contrib.runtool import add_tool_history
add_tool_history(pars["outfile"], __toolname__, pars,
toolversion=__revision__)
if len(pars["binimg"]) > 0 and "none" != pars["binimg"].lower():
from ciao_contrib.runtool import dmmaskbin
dmmaskbin(pars["infile"], pars["outfile"]+"[opt type=i4]",
pars["binimg"], clobber=True)
add_tool_history(pars["binimg"], __toolname__, pars,
toolversion=__revision__)
if __name__ == "__main__":
main()