| 1 |
""" |
| 2 |
Bindings for the pgsphere library and psycopg2. |
| 3 |
|
| 4 |
Basically, once per program run, you need to call preparePgSphere(connection), |
| 5 |
and you're done. |
| 6 |
|
| 7 |
All native representation is in rad. |
| 8 |
""" |
| 9 |
|
| 10 |
#c Copyright 2008-2025, the GAVO project <[email protected]> |
| 11 |
#c |
| 12 |
#c This program is free software, covered by the GNU GPL. See the |
| 13 |
#c COPYING file in the source distribution. |
| 14 |
|
| 15 |
|
| 16 |
from __future__ import annotations |
| 17 |
|
| 18 |
import io |
| 19 |
import math |
| 20 |
import re |
| 21 |
import tempfile |
| 22 |
|
| 23 |
from astropy import units as u # type: ignore |
| 24 |
import numpy |
| 25 |
|
| 26 |
from gavo.utils import codetricks |
| 27 |
from gavo.utils import excs |
| 28 |
from gavo.utils import mathtricks |
| 29 |
from gavo.utils import misctricks |
| 30 |
from gavo.utils import texttricks |
| 31 |
from gavo.utils.fitstools import pyfits |
| 32 |
from gavo.utils.mathtricks import DEG |
| 33 |
|
| 34 |
from gavo.utils.dachstypes import (Any, Dict, List, Optional, Sequence, |
| 35 |
Union, Tuple, TYPE_CHECKING, cast) |
| 36 |
if TYPE_CHECKING: |
| 37 |
Component = Union[float, u.Quantity] |
| 38 |
from astropy.coordinates import ( # type: ignore |
| 39 |
UnitSphericalRepresentation) |
| 40 |
|
| 41 |
|
| 42 |
_TRAILING_ZEROES = re.compile(r"0+(\s|$)") |
| 43 |
def removeTrailingZeroes(s: str) -> str: |
| 44 |
"""remove zeroes in front of whitespace or the string end. |
| 45 |
|
| 46 |
This is used for cosmetics in STC-S strings. |
| 47 |
|
| 48 |
>>> removeTrailingZeroes("23.3420 21.2 12.00000") |
| 49 |
'23.342 21.2 12.' |
| 50 |
""" |
| 51 |
return _TRAILING_ZEROES.sub(r"\1", s) |
| 52 |
|
| 53 |
|
| 54 |
class PgSAdapter(object): |
| 55 |
"""A base class for objects adapting pgSphere objects. |
| 56 |
|
| 57 |
The all need a pgType attribute and two static methods |
| 58 |
``_adaptToPgSphere(obj)`` and ``_castFromPgSphere(value, cursor)``. |
| 59 |
|
| 60 |
You must also define a sequence checkedAttributes; all attributes |
| 61 |
mentioned there must be equal for two adapted values to be equal (equality |
| 62 |
testing here really is mainly for unit tests with hand-crafted values). |
| 63 |
|
| 64 |
Also, all subclasses you should provide an asPoly returning a spherical |
| 65 |
polygon. This is used when uploading VOTables with REGION columns. |
| 66 |
|
| 67 |
In practice, you also want: |
| 68 |
|
| 69 |
:fromDALI(cls, daliSeq): |
| 70 |
a classmethod turning the DALI votable representation (typically, |
| 71 |
float arrays in degrees) into a corresponding object. |
| 72 |
:asDALI(self): |
| 73 |
the inverse of fromDALI |
| 74 |
:asSODA(self): |
| 75 |
returns a representation of the geometry as used in SODA parameters. |
| 76 |
""" |
| 77 |
pgType: Optional[str] = None |
| 78 |
checkedAttributes: List[str] = [] |
| 79 |
|
| 80 |
def __eq__(self, other: Any): |
| 81 |
if self.__class__!=other.__class__: |
| 82 |
return False |
| 83 |
for attName in self.checkedAttributes: |
| 84 |
if getattr(self, attName)!=getattr(other, attName): |
| 85 |
return False |
| 86 |
return True |
| 87 |
|
| 88 |
def __ne__(self, other: Any): |
| 89 |
return not self==other |
| 90 |
|
| 91 |
def __repr__(self): |
| 92 |
return "<pgsphere %s>"%self.asSTCS("Unknown") |
| 93 |
|
| 94 |
def asPoly(self): |
| 95 |
raise ValueError("%s objects cannot be turned into polygons."% |
| 96 |
self.__class__) |
| 97 |
|
| 98 |
def asSODA(self): |
| 99 |
"""returns the "SODA-form" for this circle. |
| 100 |
|
| 101 |
This is a string containing blank-separated float literals; the |
| 102 |
floats are what asDALI returns, and hence this is built on top of |
| 103 |
asDALI. We don't worry about the fact that the coordinates just |
| 104 |
*might* be non-ICRS. |
| 105 |
""" |
| 106 |
return removeTrailingZeroes( |
| 107 |
" ".join("%.10f"%v for v in self.asDALI())) |
| 108 |
|
| 109 |
|
| 110 |
class SPoint(PgSAdapter): |
| 111 |
"""A point on a sphere from pgSphere. |
| 112 |
|
| 113 |
>>> SPoint(1, 1).asSTCS("ICRS") |
| 114 |
'Position ICRS 57.2957795131 57.2957795131' |
| 115 |
>>> SPoint.fromDegrees(1, -1).asSTCS("ICRS") |
| 116 |
'Position ICRS 1. -1.' |
| 117 |
""" |
| 118 |
pgType = "spoint" |
| 119 |
checkedAttributes = ["x", "y"] |
| 120 |
pattern = re.compile(r"\s*\(\s*([0-9.eNa-]+)\s*,\s*([0-9.eNa-]+)\s*\)") |
| 121 |
|
| 122 |
def __init__(self, x: Component, y: Component): |
| 123 |
if isinstance(x, u.Quantity) and isinstance(y, u.Quantity): |
| 124 |
self.x, self.y = x.to(u.rad).value, y.to(u.rad).value |
| 125 |
else: |
| 126 |
self.x, self.y = float(x), float(y) |
| 127 |
|
| 128 |
def __repr__(self) -> str: |
| 129 |
return "SPoint(%r, %r)"%(self.x, self.y) |
| 130 |
|
| 131 |
@staticmethod |
| 132 |
def _adaptToPgSphere(spoint: SPoint) -> AsIs: |
| 133 |
return AsIs("spoint '(%.10f,%.10f)'"%(spoint.x, spoint.y)) |
| 134 |
|
| 135 |
@classmethod |
| 136 |
def _castFromPgSphere(cls, value: Optional[str], cursor: Any |
| 137 |
) -> 'Optional[SPoint]': |
| 138 |
if value is not None: |
| 139 |
return cls(*[float(v) |
| 140 |
for v in cls.pattern.match(value).groups()]) # type: ignore |
| 141 |
return None |
| 142 |
|
| 143 |
@classmethod |
| 144 |
def fromDegreesP(cls, x: Component, y: Component) -> SPoint: |
| 145 |
"""fromDegrees when it's certain that there's no None x and y. |
| 146 |
""" |
| 147 |
return cls(x*DEG, y*DEG) |
| 148 |
|
| 149 |
@classmethod |
| 150 |
def fromDegrees(cls, x: Optional[Component], y: Optional[Component] |
| 151 |
) -> Optional[SPoint]: |
| 152 |
if x is None or y is None: |
| 153 |
return None |
| 154 |
return cls.fromDegreesP(x, y) |
| 155 |
|
| 156 |
@classmethod |
| 157 |
def fromUnitVector(cls, uvec: UnitSphericalRepresentation) -> SPoint: |
| 158 |
"""returns an SPoint for a 3-unit sphere vector. |
| 159 |
""" |
| 160 |
return cls(*mathtricks.cartToSpher(uvec)) |
| 161 |
|
| 162 |
def asCooPair(self) -> Tuple[float, float]: |
| 163 |
"""returns this point as (long, lat) in degrees. |
| 164 |
""" |
| 165 |
return (self.x/DEG, self.y/DEG) |
| 166 |
|
| 167 |
def asSTCS(self, systemString: str) -> str: |
| 168 |
return removeTrailingZeroes( |
| 169 |
"Position %s %.10f %.10f"%(systemString, self.x/DEG, self.y/DEG)) |
| 170 |
|
| 171 |
def asPgSphere(self) -> str: |
| 172 |
return "spoint '(%.10f,%.10f)'"%(self.x, self.y) |
| 173 |
|
| 174 |
def p(self) -> str: # helps below |
| 175 |
return "(%r, %r)"%(self.x, self.y) |
| 176 |
|
| 177 |
def asUnitSphereVec(self) -> UnitSphericalRepresentation: |
| 178 |
"""returns self as a triple of cx, cy, cz on the unit sphere. |
| 179 |
""" |
| 180 |
return mathtricks.spherToCart(self.x, self.y) |
| 181 |
|
| 182 |
def asDALI(self) -> Tuple[float, float]: |
| 183 |
return self.asCooPair() |
| 184 |
|
| 185 |
@classmethod |
| 186 |
def fromDALI(cls, coos: Sequence[Component]): |
| 187 |
return cls.fromDegrees(*coos) |
| 188 |
|
| 189 |
|
| 190 |
class SCircle(PgSAdapter): |
| 191 |
"""A spherical circle from pgSphere. |
| 192 |
|
| 193 |
The constructor accepts an SPoint center and a radius in rad. |
| 194 |
""" |
| 195 |
pgType = "scircle" |
| 196 |
checkedAttributes = ["center", "radius"] |
| 197 |
pattern = re.compile(r"<(\([^)]*\))\s*,\s*([0-9.e-]+)>") |
| 198 |
|
| 199 |
def __init__(self, center: SPoint, radius: Component): |
| 200 |
self.center, self.radius = center, float(radius) |
| 201 |
|
| 202 |
@staticmethod |
| 203 |
def _adaptToPgSphere(sc: SCircle): |
| 204 |
return AsIs("scircle '< %s, %r >'"%(sc.center.p(), sc.radius)) |
| 205 |
|
| 206 |
@classmethod |
| 207 |
def _castFromPgSphere(cls, value: Optional[str], cursor: Any |
| 208 |
) -> Optional[SCircle]: |
| 209 |
if value is not None: |
| 210 |
pt, radius = cls.pattern.match(value).groups() # type: ignore |
| 211 |
if pt is not None: |
| 212 |
return cls(SPoint._castFromPgSphere(pt, cursor), radius) # type: ignore |
| 213 |
return None |
| 214 |
|
| 215 |
def asDALI(self) -> Tuple[float, float, float]: |
| 216 |
"""returns the "DALI-form" for this circle. |
| 217 |
|
| 218 |
This is an array containing the center coordinates and the radius |
| 219 |
in degrees. |
| 220 |
""" |
| 221 |
return (self.center.x/DEG, self.center.y/DEG, self.radius/DEG) |
| 222 |
|
| 223 |
@classmethod |
| 224 |
def fromDALI(cls, daliSeq: Sequence[Optional[Component]] |
| 225 |
) -> Optional[SCircle]: |
| 226 |
"""returns a circle from its DALI float sequence. |
| 227 |
|
| 228 |
Any None in daliSeq makes this a None to help with VOTable null value |
| 229 |
handling. |
| 230 |
""" |
| 231 |
if None in daliSeq: |
| 232 |
return None |
| 233 |
ra, dec, radius = [float(s) for s in daliSeq] # type: ignore |
| 234 |
center = SPoint.fromDegreesP(ra, dec) |
| 235 |
return cls(center, radius*DEG) |
| 236 |
|
| 237 |
@classmethod |
| 238 |
def fromPointSet(cls, points: Sequence[SPoint]) -> SCircle: |
| 239 |
"""returns an SCircle covering all the SPoints in points. |
| 240 |
|
| 241 |
(max radius: pi/2). |
| 242 |
""" |
| 243 |
uvecs = [numpy.array(p.asUnitSphereVec()) for p in points] |
| 244 |
center = sum(uvecs)/len(uvecs) |
| 245 |
radius = max(center.dot(v) for v in uvecs) # type: ignore |
| 246 |
return cls( |
| 247 |
SPoint.fromUnitVector(center), |
| 248 |
math.acos(radius)) |
| 249 |
|
| 250 |
def asSTCS(self, systemString: str) -> str: |
| 251 |
return removeTrailingZeroes("Circle %s %s"%( |
| 252 |
systemString, self.asSODA())) |
| 253 |
|
| 254 |
def asPgSphere(self) -> str: |
| 255 |
return "scircle '< (%.10f, %.10f), %.10f >'"%( |
| 256 |
self.center.x, self.center.y, self.radius) |
| 257 |
|
| 258 |
def asPoly(self, nSegments: int=32) -> SPoly: |
| 259 |
# approximate the circle with 32 line segments and don't worry about |
| 260 |
# circles with radii larger than 90 degrees. |
| 261 |
# We compute the circle around the north pole and then rotate |
| 262 |
# the resulting points such that the center ends up at the |
| 263 |
# circle's center. |
| 264 |
r = math.sin(self.radius) |
| 265 |
innerOffset = math.cos(self.radius) |
| 266 |
rotationMatrix = mathtricks.getRotZ(math.pi/2-self.center.x |
| 267 |
)@mathtricks.getRotX(math.pi/2-self.center.y) |
| 268 |
|
| 269 |
points = [] |
| 270 |
for i in range(nSegments): |
| 271 |
angle = 2.*i*math.pi/nSegments |
| 272 |
dx, dy = r*math.sin(angle), r*math.cos(angle) |
| 273 |
points.append(SPoint( |
| 274 |
*mathtricks.cartToSpher( |
| 275 |
[email protected]([dx, dy, innerOffset])))) |
| 276 |
return SPoly(points) |
| 277 |
|
| 278 |
def asSMoc(self, order: int=6, inclusive: bool=False): |
| 279 |
"""returns an SMoc instance for this circle. |
| 280 |
|
| 281 |
order is the maximum order of the moc returned. |
| 282 |
""" |
| 283 |
import healpy # type: ignore |
| 284 |
pixels = healpy.query_disc(vec=self.center.asUnitSphereVec(), |
| 285 |
radius=self.radius, |
| 286 |
nside=2**order, nest=True, inclusive=inclusive) |
| 287 |
return SMoc.fromCells(order, pixels, maxOrder=order) |
| 288 |
|
| 289 |
|
| 290 |
class SPoly(PgSAdapter): |
| 291 |
"""A spherical polygon from pgSphere. |
| 292 |
|
| 293 |
The constructor accepts a list points of SPoints. |
| 294 |
""" |
| 295 |
pgType = "spoly" |
| 296 |
checkedAttributes = ["points"] |
| 297 |
pattern = re.compile(r"\([^)]+\)") |
| 298 |
|
| 299 |
def __init__(self, points: Sequence[SPoint]): |
| 300 |
self.points = tuple(points) |
| 301 |
|
| 302 |
@staticmethod |
| 303 |
def _adaptToPgSphere(spoly: SPoly) -> AsIs: |
| 304 |
return AsIs("spoly '{%s}'"%(", ".join(p.p() for p in spoly.points))) |
| 305 |
|
| 306 |
@classmethod |
| 307 |
def _castFromPgSphere(cls, value: Optional[str], cursor: Any |
| 308 |
) -> Optional[SPoly]: |
| 309 |
if value is not None: |
| 310 |
return cls([SPoint._castFromPgSphere(ptLit, cursor) # type: ignore |
| 311 |
for ptLit in cls.pattern.findall(value)]) |
| 312 |
return None |
| 313 |
|
| 314 |
def asDALI(self) -> List[float]: |
| 315 |
"""returns the DALI form of this polygon. |
| 316 |
|
| 317 |
This is a sequence of floats of the vertex coordinates in degrees. |
| 318 |
""" |
| 319 |
res = [] |
| 320 |
for p in self.points: |
| 321 |
res.extend([p.x/DEG, p.y/DEG]) |
| 322 |
return res |
| 323 |
|
| 324 |
@classmethod |
| 325 |
def fromDALI(cls, daliSeq: List[Component]) -> Optional[SPoly]: |
| 326 |
"""returns a polygon from a DALI float-sequence |
| 327 |
|
| 328 |
This returns None for empty daliSeqs to help with VOTable NULL value |
| 329 |
handling. |
| 330 |
""" |
| 331 |
if not daliSeq: |
| 332 |
return None |
| 333 |
if len(daliSeq)<6 or len(daliSeq)%2: |
| 334 |
raise ValueError("Need an even-numbered number (>=6) of floats" |
| 335 |
" in a DALI polygon representation, got %s floats."%len(daliSeq)) |
| 336 |
|
| 337 |
return cls([SPoint.fromDegreesP(*tuple(p)) |
| 338 |
for p in misctricks.grouped(2, daliSeq)]) |
| 339 |
|
| 340 |
def asCooPairs(self) -> List[Tuple[float, float]]: |
| 341 |
"""returns the vertices as a sequence of (long, lat) pairs in |
| 342 |
degrees. |
| 343 |
|
| 344 |
This form is required by some functions from base.coords. |
| 345 |
""" |
| 346 |
return [p.asCooPair() for p in self.points] |
| 347 |
|
| 348 |
def asSTCS(self, systemString: str) -> str: |
| 349 |
return removeTrailingZeroes("Polygon %s %s"%(systemString, |
| 350 |
self.asSODA())) |
| 351 |
|
| 352 |
def asPgSphere(self) -> str: |
| 353 |
return "spoly '{%s}'"%(",".join("(%.10f,%.10f)"%(p.x, p.y) |
| 354 |
for p in self.points)) |
| 355 |
|
| 356 |
def asPoly(self) -> SPoly: |
| 357 |
return self |
| 358 |
|
| 359 |
def asSMoc(self, order: int=6, inclusive: bool=False) -> SMoc: |
| 360 |
"""returns an SMoc instance for this polygon. |
| 361 |
|
| 362 |
order is the maximum order of the moc returned. |
| 363 |
""" |
| 364 |
import healpy |
| 365 |
vertices = [p.asUnitSphereVec() for p in self.points] |
| 366 |
pixels = healpy.query_polygon(vertices=vertices, |
| 367 |
nside=2**order, nest=True, inclusive=inclusive) |
| 368 |
return SMoc.fromCells(order, pixels, maxOrder=order) |
| 369 |
|
| 370 |
def getCenter(self) -> List[float]: |
| 371 |
# This probably should return an SPoint, but let's first see where |
| 372 |
# this is used. |
| 373 |
"""returns an estimate for some sort of center of this polygon. |
| 374 |
|
| 375 |
This is computed as the mean of the vertices (in unit sphere |
| 376 |
representation), which, depending on the polygon, may be very far from the |
| 377 |
polygon's center of mass. Also, you can kill this by having all points |
| 378 |
sit on a great circle, etc. |
| 379 |
|
| 380 |
So: handle with care. Doing this properly is hard. |
| 381 |
""" |
| 382 |
vertices = [numpy.array(mathtricks.spherToCart(p.x, p.y)) |
| 383 |
for p in self.points] |
| 384 |
center = numpy.average(vertices, axis=0) |
| 385 |
center = center/(center@center) |
| 386 |
return mathtricks.cartToSpher(center) |
| 387 |
|
| 388 |
|
| 389 |
class SBox(PgSAdapter): |
| 390 |
"""A spherical box from pgSphere. |
| 391 |
|
| 392 |
The constructor accepts the two corner points. |
| 393 |
""" |
| 394 |
pgType = "sbox" |
| 395 |
checkedAttributes = ["corner1", "corner2"] |
| 396 |
pattern = re.compile(r"\([^()]+\)") |
| 397 |
|
| 398 |
def __init__(self, corner1: SPoint, corner2: SPoint): |
| 399 |
self.corner1, self.corner2 = corner1, corner2 |
| 400 |
|
| 401 |
@staticmethod |
| 402 |
def _adaptToPgSphere(sbox: SBox) -> AsIs: |
| 403 |
return AsIs("sbox '(%s, %s)'"%(sbox.corner1.p(), sbox.corner2.p())) |
| 404 |
|
| 405 |
@classmethod |
| 406 |
def _castFromPgSphere(cls, value: Optional[str], cursor: Any |
| 407 |
) -> Optional[SBox]: |
| 408 |
if value is not None: |
| 409 |
return cls(*[SPoint._castFromPgSphere(ptLit, cursor) # type: ignore |
| 410 |
for ptLit in cls.pattern.findall(value)]) |
| 411 |
return None |
| 412 |
|
| 413 |
@classmethod |
| 414 |
def fromSIAPPars(cls, ra: float, dec: float, raSize: float, decSize: float |
| 415 |
) -> SBox: |
| 416 |
"""returns an SBox corresponding to what SIAP passes in. |
| 417 |
|
| 418 |
In particular, all values are in degrees, and a cartesian projection |
| 419 |
is assumed. |
| 420 |
|
| 421 |
This is for use with SIAP and tries to partially implement that silly |
| 422 |
prescription of "folding" over at the poles. If that happens, |
| 423 |
a TwoSBoxes exception is raised. It contains two SBoxes that |
| 424 |
should be ORed. I agree that sucks. Let's fix SIAP. |
| 425 |
""" |
| 426 |
if 90-abs(dec)<0.1: # Special handling at the pole |
| 427 |
raSize = 360 |
| 428 |
else: |
| 429 |
raSize = raSize/math.cos(dec*DEG) |
| 430 |
decSize = abs(decSize) # inhibit auto swapping of points |
| 431 |
minRA, maxRA = ra-raSize/2., ra+raSize/2. |
| 432 |
bottom, top = dec-decSize/2., dec+decSize/2. |
| 433 |
# folding over at the poles: raise an exception with two boxes, |
| 434 |
# and let upstream handle it. Foldover on both poles is not supported. |
| 435 |
# All this isn't really thought out and probably doesn't work in |
| 436 |
# many interesting cases. |
| 437 |
# I hate that folding over. |
| 438 |
if bottom<-90 and top>90: |
| 439 |
raise ValueError("Cannot fold over at both poles") |
| 440 |
elif bottom<-90: |
| 441 |
raise TwoSBoxes( |
| 442 |
cls( |
| 443 |
SPoint.fromDegreesP(minRA, -90), |
| 444 |
SPoint.fromDegreesP(maxRA, top)), |
| 445 |
cls( |
| 446 |
SPoint.fromDegreesP(180+minRA, -90), |
| 447 |
SPoint.fromDegreesP(180+maxRA, top))) |
| 448 |
elif top>90: |
| 449 |
raise TwoSBoxes( |
| 450 |
cls( |
| 451 |
SPoint.fromDegreesP(minRA, bottom), |
| 452 |
SPoint.fromDegreesP(maxRA, 90)), |
| 453 |
cls( |
| 454 |
SPoint.fromDegreesP(180+minRA, bottom), |
| 455 |
SPoint.fromDegreesP(180+maxRA, 90))) |
| 456 |
return cls(SPoint.fromDegreesP(minRA, bottom), |
| 457 |
SPoint.fromDegreesP(maxRA, top)) |
| 458 |
|
| 459 |
def asSTCS(self, systemString: str) -> str: |
| 460 |
return removeTrailingZeroes("PositionInterval %s %s %s"%(systemString, |
| 461 |
"%.10f %.10f"%(self.corner1.x/DEG, self.corner1.y/DEG), |
| 462 |
"%.10f %.10f"%(self.corner2.x/DEG, self.corner2.y/DEG))) |
| 463 |
|
| 464 |
def asPoly(self) -> SPoly: |
| 465 |
x1, y1 = self.corner1.x, self.corner1.y |
| 466 |
x2, y2 = self.corner2.x, self.corner2.y |
| 467 |
minX, maxX = min(x1, x2), max(x1, x2) |
| 468 |
minY, maxY = min(y1, y2), max(y1, y2) |
| 469 |
return SPoly(( |
| 470 |
SPoint(minX, minY), |
| 471 |
SPoint(minX, maxY), |
| 472 |
SPoint(maxX, maxY), |
| 473 |
SPoint(maxX, minY))) |
| 474 |
|
| 475 |
@classmethod |
| 476 |
def fromDALI(cls, daliSeq: Sequence[Component]) -> SBox: |
| 477 |
# see asDALI() |
| 478 |
return cls( |
| 479 |
SPoint.fromDALI(daliSeq[:2]), |
| 480 |
SPoint.fromDALI(daliSeq[2:])) |
| 481 |
|
| 482 |
def asDALI(self) -> Tuple[float, float, float, float]: |
| 483 |
# we're cheating a bit here; there's no official DALI representation |
| 484 |
# yet. This is for our private xtype x-box |
| 485 |
return self.corner1.asDALI()+self.corner2.asDALI() |
| 486 |
|
| 487 |
|
| 488 |
class TwoSBoxes(excs.ExecutiveAction): |
| 489 |
"""is raised when an SBox is constructed from center and size such that |
| 490 |
it overlaps the pole. |
| 491 |
""" |
| 492 |
def __init__(self, box1: SBox, box2: SBox): |
| 493 |
self.box1, self.box2 = box1, box2 |
| 494 |
|
| 495 |
|
| 496 |
try: |
| 497 |
import pymoc # type: ignore |
| 498 |
except ImportError: |
| 499 |
# we're trying to work without pymoc, too |
| 500 |
pass |
| 501 |
|
| 502 |
class SMoc(PgSAdapter): |
| 503 |
"""a MOC with a pgsphere interface. |
| 504 |
|
| 505 |
The default constructor accepts a pymoc.MOC instance, which is |
| 506 |
accessible as the moc attribute. The database interface uses |
| 507 |
the ASCII serialisation, for which there's the fromASCII constructor. |
| 508 |
""" |
| 509 |
pgType = "smoc" |
| 510 |
checkedAttributes = ["moc"] |
| 511 |
|
| 512 |
def __init__(self, moc: pymoc.MOC): |
| 513 |
self.moc = moc |
| 514 |
if not hasattr(self.moc, "explicitMaxOrder"): |
| 515 |
self.moc.explicitMaxOrder = None |
| 516 |
|
| 517 |
_orderHeadRE = re.compile(r"(\d+)/") |
| 518 |
_rangeRE = re.compile(r"\s*(\d+)(?:-(\d+))?\s*$") |
| 519 |
|
| 520 |
@property |
| 521 |
def maxOrder(self) -> int: |
| 522 |
if self.moc.explicitMaxOrder is None: |
| 523 |
return self.moc.order |
| 524 |
else: |
| 525 |
return self.moc.explicitMaxOrder |
| 526 |
|
| 527 |
@classmethod |
| 528 |
def _parseCells(cls, cellLiteral: str, firstPos: int |
| 529 |
) -> List[int]: |
| 530 |
"""returns a sequence of cells from a MOC cell literal. |
| 531 |
|
| 532 |
firstPos is the string position of the beginning of cellLiteral |
| 533 |
for error messages. |
| 534 |
""" |
| 535 |
curPos = 0 |
| 536 |
cells = [] |
| 537 |
|
| 538 |
for item in re.split("[, \n\t]", cellLiteral): |
| 539 |
if not item.strip(): |
| 540 |
continue |
| 541 |
|
| 542 |
mat = cls._rangeRE.match(item) |
| 543 |
if not mat: |
| 544 |
raise ValueError("MOC literal syntax error at char %s"% |
| 545 |
(firstPos+curPos)) |
| 546 |
|
| 547 |
if mat.group(2) is None: |
| 548 |
cells.append(int(mat.group(1))) |
| 549 |
else: |
| 550 |
cells.extend(list(range(int(mat.group(1)), int(mat.group(2))+1))) |
| 551 |
|
| 552 |
curPos += len(item)+1 |
| 553 |
|
| 554 |
return cells |
| 555 |
|
| 556 |
@classmethod |
| 557 |
def fromASCII(cls, literal: str) -> SMoc: |
| 558 |
"""returns an SMoc from a quasi-standard ASCII serialisation. |
| 559 |
""" |
| 560 |
# we do the parsing ourselves -- the pymoc interface is too clumsy, |
| 561 |
# and the rigidity of the parser doesn't look good. |
| 562 |
seps = cast(List[re.Match], |
| 563 |
list(cls._orderHeadRE.finditer(literal))+[re.search("$", literal)]) |
| 564 |
|
| 565 |
if len(seps)==1: |
| 566 |
raise ValueError("No order separator visible in MOC literal '%s'"% |
| 567 |
texttricks.makeEllipsis(literal, 40)) |
| 568 |
if not re.match(r"\s*$", literal[:seps[0].start()]): |
| 569 |
raise ValueError("MOC literal '%s' does not start with order spec"% |
| 570 |
texttricks.makeEllipsis(literal, 40)) |
| 571 |
|
| 572 |
moc = pymoc.MOC() |
| 573 |
moc.explicitMaxOrder = None |
| 574 |
|
| 575 |
for openMat, closeMat in cast( # TODO: why do I need this cast? |
| 576 |
Sequence[Tuple[re.Match, re.Match]], codetricks.iterRanges(seps)): |
| 577 |
order = int(openMat.group(1)) |
| 578 |
cells = cls._parseCells( |
| 579 |
literal[openMat.end():closeMat.start()], |
| 580 |
openMat.end()) |
| 581 |
if cells: |
| 582 |
moc.add(order, cells) |
| 583 |
else: |
| 584 |
moc.explicitMaxOrder = order |
| 585 |
|
| 586 |
return cls(moc) |
| 587 |
|
| 588 |
@classmethod |
| 589 |
def fromCells(cls, |
| 590 |
order: int, |
| 591 |
pixels: List[int], |
| 592 |
maxOrder: Optional[int]=None) -> SMoc: |
| 593 |
"""returns a SMoc instance from a collection of pixels at order. |
| 594 |
|
| 595 |
Pass maxOrder to set an explicit max order for the resulting MOC. |
| 596 |
""" |
| 597 |
moc = pymoc.MOC(order=order, cells=pixels) |
| 598 |
moc.explicitMaxOrder = maxOrder |
| 599 |
moc.normalize() |
| 600 |
return cls(moc) |
| 601 |
|
| 602 |
@staticmethod |
| 603 |
def _formatASCIIRange(minCell: int, maxCell: int) -> str: |
| 604 |
"""returns a cell literal for a MOC. |
| 605 |
""" |
| 606 |
if minCell==maxCell: |
| 607 |
return str(minCell) |
| 608 |
else: |
| 609 |
return "%d-%d"%(minCell, maxCell) |
| 610 |
|
| 611 |
def asASCII(self) -> str: |
| 612 |
"""returns an ascii serialisation of this MOC. |
| 613 |
""" |
| 614 |
# this is essentially the pymoc code, but again saving the file |
| 615 |
# interface that we don't want here. |
| 616 |
parts = [] |
| 617 |
for order, cells in self.moc: |
| 618 |
ranges = [] |
| 619 |
rmin, rmax = -1, -1 |
| 620 |
|
| 621 |
for cell in sorted(cells): |
| 622 |
if rmin==-1: |
| 623 |
rmin = rmax = cell |
| 624 |
elif rmax==cell-1: |
| 625 |
rmax = cell |
| 626 |
else: |
| 627 |
ranges.append(self._formatASCIIRange(rmin, rmax)) |
| 628 |
rmin = rmax = cell |
| 629 |
|
| 630 |
ranges.append(self._formatASCIIRange(rmin, rmax)) |
| 631 |
parts.append("%d/%s"%(order, " ".join(ranges))) |
| 632 |
|
| 633 |
if self.moc.explicitMaxOrder is not None: |
| 634 |
parts.append(f"{self.moc.explicitMaxOrder}/") |
| 635 |
|
| 636 |
return " ".join(parts) |
| 637 |
|
| 638 |
@classmethod |
| 639 |
def fromFITS(cls, literal: bytes) -> SMoc: |
| 640 |
"""returns an SMoc from a string containing a FITS-serialised MOC. |
| 641 |
""" |
| 642 |
from pymoc.io.fits import read_moc_fits_hdu # type: ignore |
| 643 |
|
| 644 |
moc = pymoc.MOC() |
| 645 |
read_moc_fits_hdu(moc, |
| 646 |
pyfits.open(io.BytesIO(literal))[1]) |
| 647 |
return cls(moc) |
| 648 |
|
| 649 |
@staticmethod |
| 650 |
def _adaptToPgSphere(smoc: SMoc) -> AsIs: |
| 651 |
return AsIs("smoc '%s'"%(smoc.asASCII())) |
| 652 |
|
| 653 |
@classmethod |
| 654 |
def _castFromPgSphere(cls, value: Optional[str], cursor: Any |
| 655 |
) -> Optional[SMoc]: |
| 656 |
if value is not None: |
| 657 |
return cls.fromASCII(value) |
| 658 |
return None |
| 659 |
|
| 660 |
def asPoly(self) -> SPoly: |
| 661 |
raise TypeError("MOCs cannot be represented as polygons") |
| 662 |
|
| 663 |
def asSTCS(self, frame: str) -> str: |
| 664 |
# no STCS for MOCs, but this is really just for old-style VOTable |
| 665 |
# serialisation, so let's cheat |
| 666 |
return "MOC "+self.asASCII() |
| 667 |
|
| 668 |
def asSMoc(self, order: int=6) -> SMoc: |
| 669 |
"""returns a copy of self, normalised for order. |
| 670 |
""" |
| 671 |
moc = self.moc.copy() |
| 672 |
moc.normalize(order) |
| 673 |
|
| 674 |
if self.moc.explicitMaxOrder is not None: |
| 675 |
moc.explicitMaxOrder = min(self.moc.explicitMaxOrder, order) |
| 676 |
|
| 677 |
return self.__class__(moc) |
| 678 |
|
| 679 |
def getPlot(self, **kwargs) -> bytes: |
| 680 |
"""returns a png string with a plot visualising this moc. |
| 681 |
""" |
| 682 |
from pymoc.util.plot import plot_moc # type: ignore |
| 683 |
with tempfile.NamedTemporaryFile(suffix=".png") as f: |
| 684 |
plot_moc(self.moc, filename=f.name, projection="moll", **kwargs) |
| 685 |
return f.read() |
| 686 |
|
| 687 |
def asFITS(self) -> bytes: |
| 688 |
"""returns a standard FITS (table) representation of this MOC. |
| 689 |
""" |
| 690 |
from pymoc.io.fits import write_moc_fits |
| 691 |
|
| 692 |
with tempfile.NamedTemporaryFile(suffix=".fits") as f: |
| 693 |
write_moc_fits(self.moc, f) |
| 694 |
f.seek(0) |
| 695 |
return f.read() |
| 696 |
|
| 697 |
def asDALI(self) -> str: |
| 698 |
"""returns the string representation of this MOC. |
| 699 |
|
| 700 |
This isn't what DALI actually says at this point, but we suspect |
| 701 |
it will say that at some point. |
| 702 |
""" |
| 703 |
return self.asASCII() |
| 704 |
|
| 705 |
@classmethod |
| 706 |
def fromDALI(cls, literal: str) -> SMoc: |
| 707 |
"""returns an SMoc from a MOC string. |
| 708 |
|
| 709 |
(see asDALI) |
| 710 |
""" |
| 711 |
return cls.fromASCII(literal) |
| 712 |
|
| 713 |
def asNUNIQs(self) -> List[int]: |
| 714 |
"""returns a list of integers usable as nuniqs. |
| 715 |
""" |
| 716 |
res: List[int] = [] |
| 717 |
for order, cells in self.moc: |
| 718 |
shiftedOrder = 4 * (4 ** order) |
| 719 |
res.extend(pix+shiftedOrder for pix in cells) |
| 720 |
return res |
| 721 |
|
| 722 |
|
| 723 |
try: |
| 724 |
import psycopg2 |
| 725 |
from psycopg2.extensions import (register_adapter, AsIs, register_type, |
| 726 |
new_type) |
| 727 |
if TYPE_CHECKING: |
| 728 |
from psycopg2.extensions import connection as Connection |
| 729 |
|
| 730 |
def _query(conn: Connection, |
| 731 |
query: str, |
| 732 |
pars: Optional[Dict[str, Any]]=None) -> List[Tuple]: |
| 733 |
c = conn.cursor() |
| 734 |
c.execute(query, pars) |
| 735 |
return list(c) |
| 736 |
|
| 737 |
_getPgSClass = codetricks.buildClassResolver( |
| 738 |
PgSAdapter, |
| 739 |
list(globals().values()), |
| 740 |
key=lambda obj: obj.pgType, default=PgSAdapter) # type: ignore |
| 741 |
|
| 742 |
|
| 743 |
def preparePgSphere(conn: Connection) -> None: |
| 744 |
if hasattr(psycopg2, "_pgsphereLoaded"): # type: ignore |
| 745 |
return |
| 746 |
try: |
| 747 |
oidmap = _query(conn, |
| 748 |
"SELECT typname, oid" |
| 749 |
" FROM pg_type" |
| 750 |
" WHERE typname ~ " |
| 751 |
" '^s(point|trans|circle|line|ellipse|poly|path|box|moc)'") |
| 752 |
for typeName, oid in oidmap: |
| 753 |
cls = _getPgSClass(typeName) |
| 754 |
if cls is not PgSAdapter: # base class is null value |
| 755 |
register_adapter(cls, cls._adaptToPgSphere) |
| 756 |
register_type( |
| 757 |
new_type((oid,), "spoint", cls._castFromPgSphere)) |
| 758 |
psycopg2._pgsphereLoaded = True # type: ignore |
| 759 |
conn.commit() |
| 760 |
except: |
| 761 |
psycopg2._pgsphereLoaded = False # type: ignore |
| 762 |
|
| 763 |
except ImportError: # pragma: no cover |
| 764 |
# psycopg2 not installed. Since preparsePgSphere can only be |
| 765 |
# called from code depending on psycopg2, there's no harm if |
| 766 |
# we don't define it. |
| 767 |
pass |
| 768 |
|
| 769 |
|
| 770 |
if __name__=="__main__": # pragma: no cover |
| 771 |
import doctest |
| 772 |
doctest.testmod() |