-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathregion.py
More file actions
400 lines (342 loc) · 12.3 KB
/
Copy pathregion.py
File metadata and controls
400 lines (342 loc) · 12.3 KB
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
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
# Licensed under a 3-clause BSD style license - see LICENSE.rst
from __future__ import division
import abc
from astropy.utils import OrderedDict
import os
import numpy as np
import json
#from jwstlib.models.lib import jsonschema
import jsonschema
from . import schema
class ValidationError(Exception):
def __init__(self, message):
self._message = message
def __str__(self):
return self._message
def create_region_mask_from_json(mshape, regions, regschema=None, validate=False):
"""
Create a regions byte mask from regions defined in a json file
Assumes the regions are not overlapping
Parameters
----------
mshape : tuple
shape of mask array
regions: string or a JSON list of regions
path to a json file with regions
regschema : string Or None
path to json file with schema
if None, the default schema in gwsc/schema is used
validate : boolean
if True, validate th eregions file against the schema
Returns
-------
mask : array of shape=mshape
a byte array where pixels, internal to each region
have a value, equal to the region's ID.
Example
-------
mask = region.create_regions_mask_from_json((300,300), 'regions.json',
'region_schema.json')
"""
if isinstance(regions[0]['id'], basestring):
np_dtype = 'a7'
else:
np_dtype = np.byte
mask = np.zeros(mshape, dtype=np_dtype)
if validate:
##TODO: Use validate_reference_file
if not validate_json(regions, regschema):
message = "Regions file {0} fdid not validate".format(regions)
raise ValidationError(message)
for polygon in regions:
pol = Polygon(polygon['id'], polygon['vertices'], 'Cartesian')
mask = pol.scan(mask)
return mask
def validate_json(json_def, json_schema):
if json_schema is None:
path = os.path.abspath(schema.__path__[0])
json_schema = os.path.join(path, 'region_schema.json')
with open(json_def) as defs:
try:
defs = json.load(defs)
except:
print("Unable to load json file {0} in json".format(json_file))
raise
json_schema = os.path.join(path, json_schema)
with open(json_schema) as json_schema:
try:
json_schema = json.load(json_schema)
except:
print("Unable to load schema file in json").format(json_schema)
raise
result = jsonschema.validate(defs, json_schema)
if result is None:
return True
else:
return False
class Region(object):
"""
Base class for regions.
Parameters
-------------
rid : int or string
region ID
coordinate_system : astropy.wcs.CoordinateSystem instance or a string
in the context of WCS this would be an instance of wcs.CoordinateSysem
"""
__metaclass__ = abc.ABCMeta
def __init__(self, rid, coordinate_system):
self._coordinate_system = coordinate_system
self._rid = rid
@abc.abstractmethod
def __contains__(self, x, y):
"""
Determines if a pixel is within a region.
Parameters
----------
x, y : float
x , y values of a pixel
Returns
-------
True or False
Subclasses must define this method.
"""
def scan(self, mask):
"""
Sets mask values to region id for all pixels within the region.
Subclasses must define this method.
Parameters
----------
mask : ndarray
a byte array with the shape of the observation to be used as a mask
Returns
-------
mask : array where the value of the elements is the region ID or 0 (for
pixels which are not included in any region).
"""
class Polygon(Region):
"""
Represents a 2D polygon region with multiple vertices
Parameters
----------
rid : string
polygon id
vertices : list of (x,y) tuples or lists
The list is ordered in such a way that when traversed in a
counterclockwise direction, the enclosed area is the polygon.
The last vertex must coincide with the first vertex, minimum
4 vertices are needed to define a triangle
coord_system : string
coordinate system
"""
def __init__(self, rid, vertices, coord_system="Cartesian"):
assert len(vertices) >= 4, ("Expected vertices to be "
"a list of minimum 4 tuples (x,y)")
super(Polygon, self).__init__(rid, coord_system)
self._vertices = np.asarray(vertices)
self._bbox = self._get_bounding_box()
self._scan_line_range=range(self._bbox[1], self._bbox[3]+self._bbox[1]+1)
#constructs a Global Edge Table (GET) in bbox coordinates
self._GET = self._construct_ordered_GET()
def _get_bounding_box(self):
x = self._vertices[:,0].min()
y = self._vertices[:,1].min()
w = self._vertices[:,0].max() - x
h = self._vertices[:,1].max() - y
return (x, y, w, h)
def _construct_ordered_GET(self):
"""
Construct a Global Edge Table (GET)
The GET is an OrderedDict. Keys are scan line numbers,
ordered from bbox.ymin to bbox.ymax, where bbox is the
bounding box of the polygon.
Values are lists of edges for which edge.ymin==scan_line_number.
Returns
-------
GET: OrderedDict
{scan_line: [edge1, edge2]}
"""
# edges is a list of Edge objects which define a polygon
# with these vertices
edges = self.get_edges()
GET = OrderedDict.fromkeys(self._scan_line_range)
ymin=np.asarray([e._ymin for e in edges])
for i in self._scan_line_range:
ymin_ind = (ymin == i).nonzero()[0]
if ymin_ind.any():
GET[i] = [edges[ymin_ind[0]]]
for j in ymin_ind[1:]:
GET[i].append(edges[j])
return GET
def get_edges(self):
"""
Create a list of Edge objects from vertices
"""
edges = []
for i in range(1, len(self._vertices)):
name = 'E'+str(i-1)
edges.append(Edge(name=name, start=self._vertices[i-1], stop=self._vertices[i]))
return edges
def scan(self, data):
"""
This is the main function which scans the polygon and creates the mask
Parameters
----------
data : array
the mask array
it has all zeros initially, elements within a region are set to
the region's ID
Algorithm:
- Set the Global Edge Table (GET)
- Set y to be the smallest y coordinate that has an entry in GET
- Initialize the Active Edge Table (AET) to be empty
- For each scan line:
1. Add edges from GET to AET for which ymin==y
2. Remove edges from AET fro which ymax==y
3. Compute the intersection of the current scan line with all edges in the AET
4. Sort on X of intersection point
5. Set elements between pairs of X in the AET to the Edge's ID
"""
##TODO: 1.This algorithm does not mark pixels in the top row and left most column.
## Pad the initial pixel description on top and left with 1 px to prevent this.
## 2. Currently it uses intersection of the scan line with edges. If this is
## too slow it should use the 1/m increment (replace 3 above) (or the increment
## should be removed from the GET entry).
y = np.min(self._GET.keys())
AET = []
scline = self._scan_line_range[-1]
while y <=scline:
AET = self.update_AET(y, AET)
scan_line = Edge('scan_line', start=[self._bbox[0], y],
stop=[self._bbox[0]+self._bbox[2], y])
x = [np.ceil(e.compute_AET_entry(scan_line)[1]) for e in AET if e is not None]
xnew=np.sort(x)
for i,j in zip(xnew[::2], xnew[1::2]):
data[y][i:j+1] = self._rid
y = y+1
return data
def update_AET(self, y, AET):
"""
Update the Active Edge Table (AET)
Add edges from GET to AET for which ymin of the edge is
equal to the y of the scan line.
Remove edges from AET for which ymax of the edge is
equal to y of the scan line.
"""
edge_cont = self._GET[y]
if edge_cont is not None:
for edge in edge_cont:
if edge._start[1] != edge._stop[1] and edge._ymin == y:
AET.append(edge)
for edge in AET[::-1]:
if edge is not None:
if edge._ymax == y:
AET.remove(edge)
return AET
def __contains__(self, px):
"""even-odd algorithm or smth else better sould be used"""
minx = self._vertices[:,0].min()
maxx = self._vertices[:,0].max()
miny = self._vertices[:,1].min()
maxy = self._vertices[:,1].max()
return px[0] >= self._bbox[0] and px[0] <= self._bbox[0]+self._bbox[2] and \
px[1] >=self._bbox[1] and px[1] <=self._bbox[1]+self._bbox[3]
class Edge(object):
"""
Edge representation
An edge has a "start" and "stop" (x,y) vertices and an entry in the
GET table of a polygon. The GET entry is a list of these values:
[ymax, x_at_ymin, delta_x/delta_y]
"""
def __init__(self, name=None, start=None, stop=None, next=None):
self._start = None
if start is not None:
self._start = np.asarray(start)
self._name= name
self._stop = stop
if stop is not None:
self._stop = np.asarray(stop)
self._next=next
if self._stop is not None and self._start is not None:
if self._start[1] < self._stop[1]:
self._ymin = self._start[1]
self._yminx = self._start[0]
else:
self._ymin = self._stop[1]
self._yminx = self._stop[0]
self._ymax = max(self._start[1], self._stop[1])
self._xmin = min(self._start[0], self._stop[0])
self._xmax = max(self._start[0], self._stop[1])
else:
self._ymin = None
self._yminx = None
self._ymax = None
self._xmin = None
self._xmax = None
self.GET_entry = self.compute_GET_entry()
@property
def ymin(self):
return self._ymin
@property
def start(self):
return self._start
@property
def stop(self):
return self._stop
@property
def ymax(self):
return self._ymax
def compute_GET_entry(self):
"""
Compute the entry in the Global Edge Table
[ymax, x@ymin, 1/m]
"""
if self._start is None:
entry = None
else:
earr = np.asarray([self._start, self._stop])
entry=[self._ymax, self._yminx, (np.diff(earr[:,0]) / np.diff(earr[:,1])).item(), None]
return entry
def compute_AET_entry(self, edge):
"""
Compute the entry for an edge in the current Active Edge Table
[ymax, x_intersect, 1/m]
note: currently 1/m is not used
"""
x = self.intersection(edge)[0]
return [self._ymax, x, self.GET_entry[2]]
def __repr__(self):
fmt = ""
if self._name is not None:
fmt += self._name
next=self.next
while next is not None:
fmt += "-->"
fmt += next._name
next = next.next
return fmt
@property
def next(self):
return self._next
@next.setter
def next(self, edge):
if self._name is None:
self._name = edge._name
self._stop = edge._stop
self._start = edge._start
self._next = edge.next
else:
self._next = edge
def intersection(self, edge):
u = self._stop - self._start
v = edge._stop - edge._start
w = self._start - edge._start
D = np.cross(u, v)
return np.cross(v, w)/D * u + self._start
def is_parallel(self, edge):
u = self._stop - self._start
v = edge._stop - edge._start
if np.cross(u, v):
return False
else:
return True