Debian Codegraph @

gavo/stc/bboxes.py

raw
1 """
2 Computing bboxes for STC geometries.
3
4 A bbox coming out of this module is a 4-tuple of (ra0, de0, ra1, de1) in
5 ICRS degrees.
6
7 (You're right, this should be part of the dm classes; but it's enough
8 messy custom code that I found it nicer to break it out).
9 """
10
11 #c Copyright 2008-2025, the GAVO project <[email protected]>
12 #c
13 #c This program is free software, covered by the GNU GPL. See the
14 #c COPYING file in the source distribution.
15
16
17 import functools
18 import math
19 from math import sin, cos, tan, atan, acos
20
21 try:
22 from astropy.coordinates import angular_separation
23 except ImportError:
24 from astropy.coordinates.angle_utilities import angular_separation
25
26 from astropy import units as u
27
28 from gavo import utils
29 from gavo.stc import common
30 from gavo.stc import conform
31 from gavo.stc import stcsast
32
33 from gavo.utils import DEG
34
35 ############### Some spherical geometry calculations
36 # (most due to Chamberlain and Duquette, "Some Algorithms for Polygons on
37 # a sphere", http://hdl.handle.net/2014/40409)
38
39
40 def getHeading(long1, lat1, long2, lat2):
41 """returns the initial heading when going from one spherical position to
42 another along a great circle.
43
44 Everything is in rad, angle is counted north over east.
45 """
46 if abs(long1-long2)<=1e-10:
47 # along a meridian
48 if lat1<lat2:
49 return 0
50 else:
51 return math.pi
52
53 if lat1<=-math.pi/2+1e-10:
54 # starting on south pole
55 return 0
56 elif lat1>=math.pi/2-1e-10:
57 # starting on north pole
58 return math.pi
59
60 zeta = angular_separation(
61 long1*u.rad, lat1*u.rad,
62 long2*u.rad, lat2*u.rad).to(u.rad).value
63 cosPhi = (sin(lat2)-sin(lat1)*cos(zeta))/(sin(zeta)*cos(lat1))
64 if abs(cosPhi-1)<1e-10:
65 return 0
66 elif abs(cosPhi+1)<1e-10:
67 return math.pi
68 elif sin(long2-long1)>0:
69 return acos(cosPhi)
70 else:
71 return common.TWO_PI-acos(cosPhi)
72
73
74 class GCSegment(object):
75 """A great circle segment on a sphere. It is assumed that it's no larger
76 than pi.
77
78 Construction is long,lat, long, lat in rad (or use the fromDegrees
79 class method.
80
81 Very small (<1e-8 rad, say) segments are not supported. You should
82 probably work in the tangential plane on that kind of scale.
83 """
84 def __init__(self, long1, lat1, long2, lat2):
85 self.long1, self.lat1 = long1, lat1
86 self.long2, self.lat2 = long2, lat2
87 self._normalize()
88 if self.long1>self.long2:
89 self.long1, self.long2 = self.long2, self.long1
90 self.lat1, self.lat2 = self.lat2, self.lat1
91
92 vertical = abs(self.long1-self.long2)<1e-10
93 if vertical and abs(self.lat1-self.lat2)<1e-10:
94 raise ValueError("Null segment: start and end are identical")
95
96 self.overPole = vertical or cos(lat1)*cos(lat2)<1e-10
97 self.overStich = 2*math.pi<=self.long1+self.long2<3*math.pi
98
99 @classmethod
100 def fromDegrees(cls, long1, lat1, long2, lat2):
101 return cls(long1*DEG, lat1*DEG, long2*DEG, lat2*DEG)
102
103 def __str__(self):
104 return "<Great Circle through (%f %f), (%f %f)"%(
105 self.long1/DEG, self.lat1/DEG, self.long2/DEG, self.lat2/DEG)
106
107 def _normalize(self):
108 """makes sure all longitudes are in [0, 2 pi[ and all latitudes between
109 [-pi, pi].
110 """
111 self.long1 = common.clampLong(self.long1)
112 self.long2 = common.clampLong(self.long2)
113 self.lat1 = common.clampLat(self.lat1)
114 self.lat2 = common.clampLat(self.lat2)
115
116 def _computeBBFor(self, long1, lat1, long2, lat2):
117 """returns a 4-tuple bounding box for a great circle segment.
118
119 This is restricted to GCs not crossing the stitch line; furthermore, it
120 still depends on self.
121 """
122 if self.overPole:
123 latMin, latMax = min(lat1, lat2), max(lat1, lat2)
124 if cos(lat1)*cos(lat2)<1e-10:
125 # the pole is part of the segment
126 long1, long2 = 0, common.TWO_PI
127
128 else:
129 # compute headings at both ends
130 theta1 = getHeading(long1, lat1, long2, lat2)
131 theta2 = getHeading(long2, lat2, long1, lat1)
132
133 # if the headings are two quadrants apart, the limits are at
134 # the corners
135 quad1, quad2 = int(2*theta1/math.pi), int(2*theta2/math.pi)
136 if abs(quad1-quad2)==2:
137 latExt = lat1
138 else:
139 # the limit is somewhere in between.
140 latExt = acos(abs(sin(theta1))*cos(lat1))
141 # acos has two branches; inspecting lat1 for the sign is
142 # enough since latExt won't be extreme when sgn(lat1)!=sgn(lat2).
143 if lat1<0:
144 latExt = -latExt
145
146 latMin = min(latExt, lat1, lat2)
147 latMax = max(latExt, lat1, lat2)
148 return (long1, latMin, long2, latMax)
149
150 def latForLong(self, long):
151 """returns the latitude the great circle is on for a given longitude.
152
153 Input and output is in rad.
154
155 If the pole is part of the great circle, a constant (but fairly
156 meaningless) value is returned.
157 """
158 if self.overPole:
159 return self.long1
160 return atan(
161 tan(self.lat1)*(sin(long-self.long2)/sin(self.long1-self.long2))
162 -tan(self.lat2)*(sin(long-self.long1)/sin(self.long1-self.long2)))
163
164 def getBBs(self):
165 """returns a sequence of bounding boxes for this great circle segment.
166
167 Actually, the sequence contains one box for a segment that does not
168 cross the stitching line, two boxes for those that do.
169 """
170 if not self.overPole and common.TWO_PI<=self.long1+self.long2<3*math.pi:
171 # segment crosses stitch line, split it up
172 latAtStich = self.latForLong(0)
173 return [
174 self._computeBBFor(0, latAtStich, self.long1, self.lat1),
175 self._computeBBFor(self.long2, self.lat2, 2*math.pi, latAtStich)]
176 else:
177 return [
178 self._computeBBFor(self.long1, self.lat1, self.long2, self.lat2)]
179
180
181 #############################################################
182 # Actual bbox hacks. I'm pretty sure there's loads of bad
183 # corner cases in here. In particular in the vicinity of the
184 # pole, *much* more thought and testing is required (I'm hoping
185 # astropy will come to the rescue at some point).
186
187 @functools.lru_cache(1)
188 def getStandardFrame():
189 return stcsast.parseSTCS("Position ICRS unit deg")
190
191
192 def _makeSphericalBbox(minRA, minDec, maxRA, maxDec):
193 """yields one or two bboxes from for spherical coordinates.
194
195 This handles crossing the stich line as well as shooting over the pole.
196
197 Everything here is in degrees.
198
199 This function assumes that -360<minRA<maxRA<720 and that at least one
200 of minRA, maxRA is between 0 and 360.
201 """
202 if minDec<-90:
203 # fold over the pole
204 maxDec = max(maxDec, -minDec-180)
205 minDec = -90
206 minRA, maxRA = 0, 360
207
208 if maxDec>90:
209 # fold over the pole
210 minDec = min(minDec, 180-maxDec)
211 maxDec = 90
212 minRA, maxRA = 0, 360
213
214 if minRA<0:
215 yield (0, minDec, maxRA, maxDec)
216 yield (360+minRA, minDec, 360, maxDec)
217 elif maxRA>360:
218 yield (0, minDec, maxRA-360, maxDec)
219 yield (minRA, minDec, 360, maxDec)
220 else:
221 yield (minRA, minDec, maxRA, maxDec)
222
223
224 def _intersectBboxes(bbox1, bbox2):
225 """returns the intersection of the two bboxes.
226 """
227 return (
228 max(bbox1[0], bbox2[0]),
229 max(bbox1[1], bbox2[1]),
230 min(bbox1[2], bbox2[2]),
231 min(bbox1[3], bbox2[3]))
232
233
234 def _isEmpty(bbox):
235 """returns true if bbox is empty.
236 """
237 return bbox[0]>=bbox[2] or bbox[1]>=bbox[3]
238
239
240 def _computeIntersectionForSequence(seq1, seq2):
241 """helps _computeIntersection; see comment there.
242 """
243 if seq1 is None:
244 return seq2
245 if seq2 is None:
246 return seq1
247
248 commonBoxes = []
249 for box1 in seq1:
250 for box2 in seq2:
251 commonBox = _intersectBboxes(box1, box2)
252 if not _isEmpty(commonBox):
253 commonBoxes.append(commonBox)
254 return commonBoxes
255
256
257 def _computeCircleBbox(circle):
258 """helps _getBboxesFor.
259 """
260 return _makeSphericalBbox(
261 circle.center[0]-circle.radius,
262 circle.center[1]-circle.radius,
263 circle.center[0]+circle.radius,
264 circle.center[1]+circle.radius)
265
266
267 def _computeEllipseBbox(ellipse):
268 """helps _getBboxesFor.
269
270 TODO: Make tighter by actually using minor axis.
271 """
272 return _makeSphericalBbox(
273 ellipse.center[0]-ellipse.smajAxis,
274 ellipse.center[1]-ellipse.smajAxis,
275 ellipse.center[0]+ellipse.smajAxis,
276 ellipse.center[1]+ellipse.smajAxis)
277
278
279 def _computeBoxBbox(box):
280 """helps _getBboxesFor.
281
282 Note that the box boundaries are great circles.
283 """
284 maxDec = max(-90, min(90, box.center[1]+box.boxsize[1]))
285 minDec = max(-90, min(90, box.center[1]-box.boxsize[1]))
286
287 if maxDec>90-1e-10:
288 yield (0, minDec, 360, 90)
289 return
290 if minDec<-90+1e-10:
291 yield (0, -90, 360, maxDec)
292 return
293
294 upperBBs = GCSegment.fromDegrees(
295 box.center[0]-box.boxsize[0], maxDec,
296 box.center[0]+box.boxsize[0], maxDec
297 ).getBBs()
298 lowerBBs = GCSegment.fromDegrees(
299 box.center[0]-box.boxsize[0], minDec,
300 box.center[0]+box.boxsize[0], minDec
301 ).getBBs()
302
303 for bbox in _makeSphericalBbox(
304 *joinBboxes(fromRad(upperBBs[0]), fromRad(lowerBBs[0]))):
305 yield bbox
306 if len(upperBBs)==2: # stitching required
307 assert len(lowerBBs)==2
308 for bbox in _makeSphericalBbox(
309 *joinBboxes(fromRad(upperBBs[1]), fromRad(lowerBBs[1]))):
310 yield bbox
311
312
313 def _computePolygonBbox(poly):
314 """helps _getBboxesFor.
315 """
316 leftBoxes, rightBoxes = [], []
317
318 def addBoxes(b):
319 rightBoxes.append(fromRad(b[0]))
320 if len(b)>1:
321 leftBoxes.append(fromRad(b[1]))
322
323 firstPoint = lastPoint = poly.vertices[0]
324 for point in poly.vertices[1:]:
325 curSegment = GCSegment.fromDegrees(
326 lastPoint[0], lastPoint[1], point[0], point[1])
327 addBoxes(list(curSegment.getBBs()))
328 lastPoint = point
329
330 try:
331 curSegment = GCSegment.fromDegrees(
332 lastPoint[0], lastPoint[1], firstPoint[0], firstPoint[1])
333 except ValueError: # probably a null segment since the authors
334 # closed the polygon. Ignore this.
335 pass
336 else:
337 addBoxes(list(curSegment.getBBs()))
338
339 yield joinBboxes(*rightBoxes)
340 if leftBoxes:
341 yield joinBboxes(*leftBoxes)
342
343
344 def _computeAllSkyBbox(geo):
345 """helps _getBboxesFor.
346 """
347 yield (0, -90, 360, 90)
348
349
350 def _computeSpaceIntervalBbox(geo):
351 """helps _getBboxesFor.
352
353 PositionInterval could have all kinds of weird coordinate systems.
354 We only check there's exactly two dimensions and otherwise hope for the
355 best.
356 """
357 if geo.frame.nDim!=2:
358 raise ValueError("Only PositionsIntervals with nDim=2 are supported"
359 " for bboxes.")
360
361 lowerLimit = geo.lowerLimit
362 if lowerLimit is None:
363 lowerLimit = (0, -90)
364
365 upperLimit = geo.upperLimit
366 if upperLimit is None:
367 upperLimit = (360, 90)
368 return _makeSphericalBbox(lowerLimit[0], lowerLimit[1],
369 upperLimit[0], upperLimit[1])
370
371
372 def _computeUnionBbox(geo):
373 """helps _getBboxesFor.
374
375 Union is just returning all bboxes from our child geometries.
376 """
377 for child in geo.children:
378 for bbox in _getBboxesFor(child):
379 yield bbox
380
381
382 def _computeIntersectionBbox(geo):
383 """helps _getBboxesFor.
384 """
385 # This is surprisingly involved, since our children may yield an arbitrary
386 # number of part boxes; each of those could contribute to an intersection.
387 # To figure out the intersection, we need to intersect each part bbox with
388 # each other part bbox and keep whatever is non-empty.
389 commonBboxes = None
390 for child in geo.children:
391 commonBboxes = _computeIntersectionForSequence(commonBboxes,
392 list(_getBboxesFor(child)))
393 for bbox in commonBboxes:
394 yield bbox
395
396 def _computeDifferenceBbox(geo):
397 """helps _getBboxesFor.
398
399 (we ignore the cut-out).
400 """
401 return _getBboxesFor(geo.children[0])
402
403 def _computeNotBbox(geo):
404 """helps _getBboxesFor.
405
406 (we ignore the cut-out and always return the entire sky)
407 """
408 # of course, we could provide a saner implementation of _computeIntersection
409 # which then would make up to eight bboxes out of such a thing.
410 # Never mind, people shouldn't do this anyway.
411 return _computeAllSkyBbox(geo)
412
413
414
415 _BBOX_COMPUTERS = {
416 "Circle": _computeCircleBbox,
417 "Ellipse": _computeEllipseBbox,
418 "Box": _computeBoxBbox,
419 "Polygon": _computePolygonBbox,
420 "AllSky": _computeAllSkyBbox,
421 "SpaceInterval": _computeSpaceIntervalBbox,
422 "Union": _computeUnionBbox,
423 "Intersection": _computeIntersectionBbox,
424 "Difference": _computeDifferenceBbox,
425 "Not": _computeNotBbox,
426 }
427
428
429 def _getBboxesFor(geo):
430 """yields one or two bboxes for a conformed geometry.
431
432 Two bboxes are returned when the geometry overlaps the stitching point.
433
434 A geometry is conformed if it's been conformed to what's coming back
435 from getStandardFrame() above.
436 """
437 geoName = geo.__class__.__name__
438 if geoName not in _BBOX_COMPUTERS:
439 raise common.STCInternalError("Do now know how to compute the bbox of"
440 " %s."%geoName)
441
442 for bbox in _BBOX_COMPUTERS[geoName](geo):
443 yield bbox
444
445
446 def fromRad(bbox):
447 return tuple(a/utils.DEG for a in bbox)
448
449
450 def joinBboxes(*bboxes):
451 """returns a bounding box encompassing all the the bboxes passed in.
452
453 No input bbox must cross the stitching line; they must be normalized,
454 i.e., lower left and upper right corners.
455 """
456 if not bboxes:
457 raise common.InternalError("bbox join without bbox")
458 minRA, maxRA = utils.Supremum, utils.Infimum
459 minDec, maxDec = utils.Supremum, utils.Infimum
460
461 for ra0, dec0, ra1, dec1 in bboxes:
462 minRA = min(minRA, ra0)
463 minDec = min(minDec, dec0)
464 maxRA = max(maxRA, ra1)
465 maxDec = max(maxDec, dec1)
466
467 return (minRA, minDec, maxRA, maxDec)
468
469
470 def getBboxes(ast):
471 """iterates over the bboxes of the areas within ast.
472
473 bboxes are (ra0, de0, ra1, de1) in ICRS degrees.
474 """
475 astc = conform.conform(ast, getStandardFrame())
476 for area in astc.areas:
477 for bbox in _getBboxesFor(area):
478 yield bbox
479