| 1 |
""" |
| 2 |
(Mostly deprecated) code to handle coordinate systems and transform |
| 3 |
between them. |
| 4 |
|
| 5 |
Basically all of this should be taken over by stc and astropy |
| 6 |
""" |
| 7 |
|
| 8 |
#c Copyright 2008-2025, the GAVO project <[email protected]> |
| 9 |
#c |
| 10 |
#c This program is free software, covered by the GNU GPL. See the |
| 11 |
#c COPYING file in the source distribution. |
| 12 |
|
| 13 |
|
| 14 |
import math |
| 15 |
import types |
| 16 |
from math import sin, cos, pi #noflake: exported names |
| 17 |
import re |
| 18 |
|
| 19 |
import numpy |
| 20 |
from numpy import linalg |
| 21 |
|
| 22 |
from gavo import utils |
| 23 |
from gavo.base.unitconv import computeConversionFactor |
| 24 |
from gavo.utils import DEG |
| 25 |
from gavo.utils import pgsphere |
| 26 |
from gavo.utils import pyfits |
| 27 |
|
| 28 |
from gavo.utils.dachstypes import (Any, Callable, Dict, List, NDArray, |
| 29 |
Numeric, Optional, Sequence, TYPE_CHECKING, Tuple, Union) |
| 30 |
|
| 31 |
wcs = utils.DeferredImport("wcs", "from astropy import wcs") |
| 32 |
if TYPE_CHECKING: |
| 33 |
from astropy.wcs import WCS # type: ignore |
| 34 |
|
| 35 |
|
| 36 |
fitsKwPat = re.compile("[A-Z0-9_-]{1,8}$") |
| 37 |
|
| 38 |
def makePyfitsFromDict(d: Dict[str, Any]) -> pyfits.Header: |
| 39 |
"""returns a pyfits header with the cards of d.items(). |
| 40 |
|
| 41 |
Only keys "looking like" FITS header keywords are used, i.e. all-uppercase |
| 42 |
and shorter than 9 characters. |
| 43 |
""" |
| 44 |
res = pyfits.Header() |
| 45 |
res.update(dict((str(key), val) |
| 46 |
for key, val in d.items() |
| 47 |
if fitsKwPat.match(key) and val is not None)) |
| 48 |
return res |
| 49 |
|
| 50 |
|
| 51 |
_wcsTestDict = { |
| 52 |
"CRVAL1": 0, "CRVAL2": 0, "CRPIX1": 50, "CRPIX2": 50, |
| 53 |
"CD1_1": 0.01, "CD1_2": 0, "CD2_1": 0, "CD2_2": 0.01, |
| 54 |
"NAXIS1": 100, "NAXIS2": 100, "CUNIT1": "deg", "CUNIT2": "deg", |
| 55 |
"CTYPE1": 'RA---TAN-SIP', "CTYPE2": 'DEC--TAN-SIP', "LONPOLE": 180., |
| 56 |
} |
| 57 |
|
| 58 |
|
| 59 |
class Box(object): |
| 60 |
"""A 2D box. |
| 61 |
|
| 62 |
It can be constructed either with two tuples, giving two points |
| 63 |
delimiting the box, or with four arguments x0, x1, y0, y1. |
| 64 |
|
| 65 |
To access the thing, you can either access the x[01], y[01] attributes |
| 66 |
or use getitem to retrieve the upper right and lower left corner. |
| 67 |
|
| 68 |
The slightly silly ordering of the bounding points (larger values |
| 69 |
first) is for consistency with Postgresql. |
| 70 |
""" |
| 71 |
def __init__(self, |
| 72 |
x0: Union[Tuple[float, float], float], |
| 73 |
x1: Union[Tuple[float, float], float], |
| 74 |
y0: Optional[float] = None, |
| 75 |
y1: Optional[float] = None) -> None: |
| 76 |
if y0 is None: # explaining the signature to mypy is not worth it. |
| 77 |
x0, y0 = x0 #type: ignore |
| 78 |
x1, y1 = x1 #type: ignore |
| 79 |
lowerLeft: _2DPoint = (min(x0, x1), min(y0, y1)) # type: ignore |
| 80 |
upperRight: _2DPoint = (max(x0, x1), max(y0, y1)) # type: ignore |
| 81 |
self.x0: float = float(upperRight[0]) |
| 82 |
self.y0: float = float(upperRight[1]) |
| 83 |
self.x1: float = float(lowerLeft[0]) |
| 84 |
self.y1: float = float(lowerLeft[1]) |
| 85 |
|
| 86 |
def __getitem__(self, index: int) -> Tuple[float, float]: |
| 87 |
if index==0 or index==-2: |
| 88 |
return (self.x0, self.y0) |
| 89 |
elif index==1 or index==-1: |
| 90 |
return (self.x1, self.y1) |
| 91 |
else: |
| 92 |
raise IndexError("len(box) is always 2") |
| 93 |
|
| 94 |
def __str__(self) -> str: |
| 95 |
return "((%.4g,%.4g), (%.4g,%.4g))"%(self.x0, self.y0, self.x1, self.y1) |
| 96 |
|
| 97 |
def __repr__(self) -> str: |
| 98 |
return "Box((%g,%g), (%g,%g))"%(self.x0, self.y0, self.x1, self.y1) |
| 99 |
|
| 100 |
|
| 101 |
def getBbox(points: List[Tuple[float, float]]) -> Box: |
| 102 |
"""returns a bounding box for the sequence of 2-sequences points. |
| 103 |
|
| 104 |
The thing returned is a coords.Box. |
| 105 |
|
| 106 |
>>> getBbox([(0.25, 1), (-3.75, 1), (-2, 4)]) |
| 107 |
Box((0.25,4), (-3.75,1)) |
| 108 |
""" |
| 109 |
xCoos, yCoos = [[p[i] for p in points] for i in range(2)] |
| 110 |
return Box(min(xCoos), max(xCoos), min(yCoos), max(yCoos)) |
| 111 |
|
| 112 |
|
| 113 |
def clampAlpha(alpha: float) -> float: |
| 114 |
while alpha>360: |
| 115 |
alpha -= 360 |
| 116 |
while alpha<0: |
| 117 |
alpha += 360 |
| 118 |
return alpha |
| 119 |
|
| 120 |
|
| 121 |
def clampDelta(delta: float) -> float: |
| 122 |
return max(-90, min(90, delta)) |
| 123 |
|
| 124 |
|
| 125 |
def straddlesStitchingLine(minRA: Numeric, maxRA: Numeric) -> bool: |
| 126 |
"""returns true if something bordered by minRA and maxRA presumably straddles |
| 127 |
the stitching line. |
| 128 |
|
| 129 |
This assumes minRA<maxRA, and that "something" is less than 180 degrees in |
| 130 |
longitude. |
| 131 |
|
| 132 |
Angles are in degrees here. |
| 133 |
""" |
| 134 |
return float(maxRA)>270 and float(minRA)<90 |
| 135 |
|
| 136 |
|
| 137 |
def _calcFootprintMonkeypatch( |
| 138 |
self: "WCS", |
| 139 |
hdr: Optional[pyfits.Header] = None, |
| 140 |
undistort: bool = True) -> NDArray: |
| 141 |
"""returns the coordinates of the four corners of an image. |
| 142 |
|
| 143 |
This is for monkeypatching astropy.wcs. pywcs, at least up to 1.11 did |
| 144 |
really badly when non-spatial coordinates are present. TODO: see |
| 145 |
if there's astropy code that does this better. |
| 146 |
|
| 147 |
This method relies on the _monkey_naxis_lengths attribute left by getWCS to |
| 148 |
figure out the axis lengths. |
| 149 |
|
| 150 |
pywcs' hdr argument is always ignored here. |
| 151 |
""" |
| 152 |
naxis1, naxis2 = self._monkey_naxis_lengths |
| 153 |
corners = [[1,1],[1,naxis2], [naxis1,naxis2], [naxis1, 1]] |
| 154 |
|
| 155 |
# we want our polygons to have a counterclockwise winding direction, |
| 156 |
# and until I think about this a bit more deeply or get a sufficiently |
| 157 |
# capable library, I just revert my sense if the determinant of the |
| 158 |
# CD matrix is negative. That's gut feeling, not proven right. |
| 159 |
if linalg.det(self.pixel_scale_matrix)<0: |
| 160 |
corners.reverse() |
| 161 |
|
| 162 |
if undistort: |
| 163 |
return self.all_pix2world(corners, 1)*self.toDegVec |
| 164 |
else: |
| 165 |
return self.wcs_pix2world(corners, 1)*self.toDegVec |
| 166 |
|
| 167 |
|
| 168 |
def _monkeypatchWCS( |
| 169 |
wcsObj: "WCS", |
| 170 |
naxis: Sequence[int], |
| 171 |
wcsFields: pyfits.Header) -> None: |
| 172 |
"""monkeypatches wcs.WCS instances for DaCHS' purposes. |
| 173 |
""" |
| 174 |
wcsObj._dachs_header = wcsFields |
| 175 |
wcsObj.longAxis = naxis[0] |
| 176 |
if len(naxis)>1: |
| 177 |
wcsObj.latAxis = naxis[1] |
| 178 |
wcsObj._monkey_naxis_lengths = [wcsFields.get("NAXIS%d"%i) |
| 179 |
for i in naxis] |
| 180 |
wcsObj.toDegVec = numpy.array([ |
| 181 |
computeConversionFactor(wcsFields.get(f"CUNIT{naxis[1]}", "deg"), "deg"), |
| 182 |
computeConversionFactor(wcsFields.get(f"CUNIT{naxis[0]}", "deg"), "deg")]) |
| 183 |
wcsObj.calcFootprint = types.MethodType( |
| 184 |
_calcFootprintMonkeypatch, wcsObj) |
| 185 |
|
| 186 |
|
| 187 |
_PerhapsWCS = Union[Dict[str, Any], "WCS"] |
| 188 |
_2DPoint = Tuple[Numeric, Numeric] |
| 189 |
|
| 190 |
def getWCS( |
| 191 |
wcsFields: _PerhapsWCS, |
| 192 |
naxis: Sequence[int] = (1,2), |
| 193 |
relax: bool = True) -> "WCS": |
| 194 |
"""returns a WCS instance from wcsFields |
| 195 |
|
| 196 |
wcsFields can be either a dictionary or a pyfits header giving |
| 197 |
some kind of WCS information, or an wcs.WCS instance that is |
| 198 |
returned verbatim. |
| 199 |
|
| 200 |
This will return None if no (usable) WCS information is found in the header. |
| 201 |
|
| 202 |
We monkeypatch the resulting WCS structure quite a bit. Among |
| 203 |
others: |
| 204 |
|
| 205 |
* there's longAxis and latAxis attributes taken from naxis |
| 206 |
* there's _dachs_header, containing the incoming k-v pairs |
| 207 |
* there's _monkey_naxis_length, the lengths along the WCS axes. |
| 208 |
""" |
| 209 |
if isinstance(wcsFields, wcs.WCS): |
| 210 |
return wcsFields |
| 211 |
if isinstance(wcsFields, dict): |
| 212 |
wcsFields = makePyfitsFromDict(wcsFields) |
| 213 |
|
| 214 |
# pywcs used to invent identity transforms if no WCS keys are present. |
| 215 |
# Hence. we do some sanity checking up front to weed those out. |
| 216 |
if ("CD1_1" not in wcsFields |
| 217 |
and "CDELT1" not in wcsFields |
| 218 |
and "PC1_1" not in wcsFields |
| 219 |
and "CNPIX1" not in wcsFields): |
| 220 |
return None |
| 221 |
|
| 222 |
# workaround for a bug in pywcs 1.11: .*_ORDER=0 must not happen |
| 223 |
for key in ["AP_ORDER", "BP_ORDER", "A_ORDER", "B_ORDER"]: |
| 224 |
if wcsFields.get(key)==0: |
| 225 |
del wcsFields[key] |
| 226 |
|
| 227 |
# wcslib (at least in 5.16) wants to do DSS corrections if they see |
| 228 |
# either XPIXELSZ and YPIXELSZ; hide them, because that almost |
| 229 |
# never works. |
| 230 |
for key in ["XPIXELSZ", "YPIXELSZ"]: |
| 231 |
if key in wcsFields: |
| 232 |
del wcsFields[key] |
| 233 |
|
| 234 |
wcsObj = wcs.WCS(wcsFields, relax=relax, naxis=naxis) |
| 235 |
_monkeypatchWCS(wcsObj, naxis, wcsFields) |
| 236 |
|
| 237 |
return wcsObj |
| 238 |
|
| 239 |
|
| 240 |
def pix2foc(wcsFields: _PerhapsWCS, pixels: _2DPoint |
| 241 |
) -> _2DPoint: |
| 242 |
"""returns the focal plane coordinates for the 2-sequence pixels. |
| 243 |
|
| 244 |
(this is a thin wrapper intended to abstract for pix2world's funky |
| 245 |
calling convention; also, we fix on the silly "0 pixel is 1 convention") |
| 246 |
""" |
| 247 |
wcsObj = getWCS(wcsFields) |
| 248 |
val = wcsObj.pix2foc((pixels[0],), (pixels[1],), 1) |
| 249 |
return val[0][0], val[1][0] |
| 250 |
|
| 251 |
|
| 252 |
def pix2sky( |
| 253 |
wcsFields: _PerhapsWCS, |
| 254 |
pixels: _2DPoint) -> _2DPoint: |
| 255 |
"""returns the sky coordinates for the 2-sequence pixels. |
| 256 |
|
| 257 |
(this is a thin wrapper intended to abstract for pix2world's funky |
| 258 |
calling convention; also, we fix on the silly "0 pixel is 1 convention") |
| 259 |
""" |
| 260 |
wcsObj = getWCS(wcsFields) |
| 261 |
val = wcsObj.all_pix2world((pixels[0],), (pixels[1],), 1)*wcsObj.toDegVec |
| 262 |
return val[0][0], val[1][0] |
| 263 |
|
| 264 |
|
| 265 |
def sky2pix( |
| 266 |
wcsFields: _PerhapsWCS, |
| 267 |
longLat: _2DPoint) -> _2DPoint: |
| 268 |
"""returns the pixel coordinates for the 2-sequence longLad. |
| 269 |
|
| 270 |
(this is a thin wrapper intended to abstract for world2pix's funky |
| 271 |
calling convention; also, we fix on the silly "0 pixel is 1 convention") |
| 272 |
lonLat is supposed to be in degrees regardless of the units of the |
| 273 |
WCS. |
| 274 |
""" |
| 275 |
wcs = getWCS(wcsFields) |
| 276 |
val = wcs.wcs_world2pix( |
| 277 |
(longLat[0]/wcs.toDegVec[0],), (longLat[1]/wcs.toDegVec[1],), 1) |
| 278 |
return val[0][0], val[1][0] |
| 279 |
|
| 280 |
|
| 281 |
def getPixelSizeDeg(wcsFields: _PerhapsWCS) -> _2DPoint: |
| 282 |
"""returns the sizes of a pixel at roughly the center of the image for |
| 283 |
wcsFields. |
| 284 |
|
| 285 |
Near the pole, this gets a bit weird; we do some limitation of the width |
| 286 |
of RA pixels there. |
| 287 |
""" |
| 288 |
wcs = getWCS(wcsFields) |
| 289 |
width, height = wcs._dachs_header["NAXIS1"], wcs._dachs_header["NAXIS2"] |
| 290 |
cosDelta = max(0.01, math.cos(pix2sky(wcs, (width/2, height/2))[1]*DEG)) |
| 291 |
|
| 292 |
p0 = pix2sky(wcs, (width/2, height/2)) |
| 293 |
p1 = pix2sky(wcs, (width/2+1, height/2)) |
| 294 |
p2 = pix2sky(wcs, (width/2, height/2+1)) |
| 295 |
return abs(float(p1[0]-p0[0]))*cosDelta, abs(float(p2[1]-p0[1])) |
| 296 |
|
| 297 |
|
| 298 |
def getWCSTrafo(wcsFields: _PerhapsWCS |
| 299 |
) -> Callable[[Numeric, Numeric], Tuple[Numeric, Numeric]]: |
| 300 |
"""returns a callable transforming pixel to physical coordinates. |
| 301 |
|
| 302 |
wcsFields is passed to getWCS, see there for legal types. |
| 303 |
""" |
| 304 |
wcs = getWCS(wcsFields) |
| 305 |
return lambda x, y: pix2sky(wcs, (x, y)) |
| 306 |
|
| 307 |
|
| 308 |
def getInvWCSTrafo(wcsFields: _PerhapsWCS |
| 309 |
) -> Callable[[Numeric, Numeric], Tuple[Numeric, Numeric]]: |
| 310 |
"""returns a callable transforming physical to pixel coordinates. |
| 311 |
|
| 312 |
wcsFields is passed to getWCS, see there for legal types. |
| 313 |
""" |
| 314 |
wcs = getWCS(wcsFields) |
| 315 |
return lambda ra, dec: sky2pix(wcs, (ra,dec)) |
| 316 |
|
| 317 |
|
| 318 |
def getSpolyFromWCSFields(wcsFields: _PerhapsWCS) -> pgsphere.SPoly: |
| 319 |
"""returns a pgsphere spoly corresponding to wcsFields |
| 320 |
|
| 321 |
wcsFields is passed to getWCS, see there for legal types. |
| 322 |
|
| 323 |
The polygon returned is computed by using the four corner points |
| 324 |
assuming a rectangular image. This typically is only loosely related |
| 325 |
to a proper spherical polygon describing the shape, as image boundaries |
| 326 |
in the usual projects are not great circles. |
| 327 |
|
| 328 |
Also, the spoly will be in the coordinate system of the WCS. If that |
| 329 |
is not ICRS, you'll probably get something incompatible with most of the |
| 330 |
VO. |
| 331 |
""" |
| 332 |
wcs = getWCS(wcsFields) |
| 333 |
return pgsphere.SPoly([pgsphere.SPoint.fromDegrees(*p) # type: ignore |
| 334 |
for p in wcs.calcFootprint(wcs._dachs_header)]) |
| 335 |
|
| 336 |
|
| 337 |
def getCenterFromWCSFields( |
| 338 |
wcsFields: _PerhapsWCS, |
| 339 |
spatialAxes: Tuple[int, int] = (1,2)) -> _2DPoint: |
| 340 |
"""returns RA and Dec of the center of an image described by wcsFields. |
| 341 |
|
| 342 |
This will use the 1-based axes given by spatialAxes to figure out |
| 343 |
the pixel lengths of the axes. |
| 344 |
""" |
| 345 |
wcs = getWCS(wcsFields) |
| 346 |
if wcs is None: |
| 347 |
raise ValueError("No WCS solution found") |
| 348 |
|
| 349 |
center1 = wcs._dachs_header["NAXIS%s"%spatialAxes[0]]/2. |
| 350 |
center2 = wcs._dachs_header["NAXIS%s"%spatialAxes[1]]/2. |
| 351 |
return pix2sky(wcs, (center1, center2)) |
| 352 |
|
| 353 |
|
| 354 |
def getCoveringCircle( |
| 355 |
wcsFields: _PerhapsWCS, |
| 356 |
spatialAxes: Sequence[int] = (1,2) |
| 357 |
) -> Optional[pgsphere.SCircle]: |
| 358 |
"""returns a pgsphere.scircle large enough to cover the image |
| 359 |
described by wcsFields. |
| 360 |
""" |
| 361 |
wcs = getWCS(wcsFields) |
| 362 |
center = getCenterFromWCSFields(wcs) |
| 363 |
|
| 364 |
height, width = (wcs._dachs_header["NAXIS%s"%spatialAxes[0]], |
| 365 |
wcs._dachs_header["NAXIS%s"%spatialAxes[1]]) |
| 366 |
radius = max( |
| 367 |
getGCDist(center, pix2sky(wcs, corner)) |
| 368 |
for corner in [(0, 0), (height, 0), (0, width), (height, width)]) |
| 369 |
|
| 370 |
centerPoint = pgsphere.SPoint.fromDegrees(*center) |
| 371 |
if centerPoint is None: |
| 372 |
return None |
| 373 |
else: |
| 374 |
return pgsphere.SCircle(centerPoint, radius*DEG) |
| 375 |
|
| 376 |
|
| 377 |
def getSkyWCS(hdr: _PerhapsWCS) -> Tuple["WCS", List[int]]: |
| 378 |
"""returns a pair of a wcs.WCS instance and a sequence of |
| 379 |
the spatial axis indexes. |
| 380 |
|
| 381 |
This will be None, () if no WCS could be discerned. There's some |
| 382 |
heuristics involved in the identification of the spatial coordinates |
| 383 |
that will probably fail for unconventional datasets. |
| 384 |
""" |
| 385 |
wcsAxes = [] |
| 386 |
# heuristics: iterate through CTYPEn, anything that's got |
| 387 |
# a - is supposed to be a position (needs some refinement :-) |
| 388 |
for ind in range(1, hdr["NAXIS"]+1): |
| 389 |
if "-" in hdr.get("CTYPE%s"%ind, ""): |
| 390 |
wcsAxes.append(ind) |
| 391 |
|
| 392 |
if not wcsAxes: |
| 393 |
# more heuristics to be inserted here |
| 394 |
return None, [] |
| 395 |
|
| 396 |
if len(wcsAxes)!=2: |
| 397 |
raise utils.ValidationError("This FITS has !=2" |
| 398 |
" spatial WCS axes. Please contact the DaCHS authors and" |
| 399 |
" make them support it.", "PUBDID") |
| 400 |
|
| 401 |
return getWCS(hdr, naxis=wcsAxes), wcsAxes |
| 402 |
|
| 403 |
|
| 404 |
def getPixelLimits(cooPairs: List[_2DPoint], wcsFields: "WCS" |
| 405 |
) -> List[Tuple[int, Numeric, Numeric]]: |
| 406 |
"""returns pixel cutout slices for covering cooPairs in an image with |
| 407 |
wcsFields. |
| 408 |
|
| 409 |
cooPairs is a sequence of (ra, dec) tuples. wcsFields is a DaCHS-enhanced |
| 410 |
wcs.WCS instance. |
| 411 |
|
| 412 |
Behaviour if cooPairs use a different coordinate system from wcsFields |
| 413 |
is undefined at this point. |
| 414 |
|
| 415 |
Each cutout slice is a tuple of (FITS axis number, lower limit, upper limit). |
| 416 |
|
| 417 |
If cooPairs is off the wcsFields coverage, a null cutout on the longAxis |
| 418 |
is returned. |
| 419 |
""" |
| 420 |
latAxis = int(wcsFields.latAxis) |
| 421 |
longAxis = int(wcsFields.longAxis) |
| 422 |
latPixels = wcsFields._dachs_header["NAXIS%d"%latAxis] |
| 423 |
longPixels = wcsFields._dachs_header["NAXIS%d"%longAxis] |
| 424 |
|
| 425 |
# pywcs used to do really funny things when we "wrap around". Therefore, we |
| 426 |
# clamp values to be within the pywcs-safe region. Note that |
| 427 |
# due to spherical magic this is not enough to ensure +/-Inf behaviour |
| 428 |
# for SODA; TODO: re-evaluate this for astropy.wcs at some point. |
| 429 |
cooPairs = [( |
| 430 |
min(359.99999, max(-89.9999, ra)), # type: ignore |
| 431 |
min(89.9999, max(-89.9999, dec))) # type: ignore |
| 432 |
for ra, dec in cooPairs] |
| 433 |
|
| 434 |
# no, I will not try to understand why mypy is confused by the min()s |
| 435 |
|
| 436 |
slices: List[Tuple[int, Numeric, Numeric]] = [] |
| 437 |
pixelFootprint = numpy.asarray( |
| 438 |
numpy.round(wcsFields.wcs_world2pix(cooPairs, 1)), numpy.int32) |
| 439 |
pixelLimits = [ |
| 440 |
(min(pixelFootprint[:,0]), max(pixelFootprint[:,0])), # type: ignore |
| 441 |
(min(pixelFootprint[:,1]), max(pixelFootprint[:,1]))] # type: ignore |
| 442 |
|
| 443 |
# see if we're completely off coverage |
| 444 |
if pixelLimits[0][1]<0 or pixelLimits[1][1]<0: |
| 445 |
return [(longAxis, 0, 0)] |
| 446 |
if pixelLimits[0][0]>longPixels or pixelLimits[1][0]>latPixels: |
| 447 |
return [(longAxis, 0, 0)] |
| 448 |
|
| 449 |
# now crop to the actual pixel values |
| 450 |
pixelLimits = [ |
| 451 |
(max(pixelLimits[0][0], 1), min(pixelLimits[0][1], longPixels)), # type: ignore |
| 452 |
(max(pixelLimits[1][0], 1), min(pixelLimits[1][1], latPixels))] # type: ignore |
| 453 |
|
| 454 |
if pixelLimits[0]!=(1, longPixels): |
| 455 |
slices.append((longAxis,)+pixelLimits[0]) |
| 456 |
if pixelLimits[1]!=(1, latPixels): |
| 457 |
slices.append((latAxis,)+pixelLimits[1]) |
| 458 |
return slices |
| 459 |
|
| 460 |
|
| 461 |
def sgn(a: Numeric) -> int: |
| 462 |
if a<0: |
| 463 |
return -1 |
| 464 |
elif a>0: |
| 465 |
return 1 |
| 466 |
else: |
| 467 |
return 0 |
| 468 |
|
| 469 |
|
| 470 |
def dirVecToCelCoos(dirVec: NDArray) -> _2DPoint: |
| 471 |
"""returns alpha, delta in degrees for the direction vector dirVec. |
| 472 |
|
| 473 |
>>> utils.nprepr(dirVecToCelCoos(utils.spherToCart(25.25*DEG, 12.125*DEG))) |
| 474 |
'[25.25 12.12]' |
| 475 |
>>> utils.nprepr(dirVecToCelCoos(utils.spherToCart(25.25*DEG, 12.125*DEG)*16)) |
| 476 |
'[25.25 0.7522]' |
| 477 |
>>> utils.nprepr(dirVecToCelCoos(utils.spherToCart(25.25*DEG, 12.125*DEG)+ |
| 478 |
... utils.spherToCart(30.75*DEG, 20.0*DEG))) |
| 479 |
'[27.95 7.988]' |
| 480 |
""" |
| 481 |
dirVec = dirVec/numpy.inner(dirVec, dirVec) |
| 482 |
alpha = math.atan2(dirVec[1], dirVec[0]) |
| 483 |
if alpha<0: |
| 484 |
alpha += 2*math.pi |
| 485 |
return alpha*180./math.pi, math.asin(dirVec[2])*180./math.pi |
| 486 |
|
| 487 |
|
| 488 |
def getTangentialUnits(cPos: NDArray) -> Tuple[NDArray, NDArray]: |
| 489 |
"""returns the unit vectors for RA and Dec at the unit circle position cPos. |
| 490 |
|
| 491 |
We compute them by solving u_1*p_1+u_2*p_2=0 (we already know that |
| 492 |
u_3=0) simultaneously with u_1^2+u_2^2=1 for RA, and by computing the |
| 493 |
cross product of the RA unit and the radius vector for dec. |
| 494 |
|
| 495 |
This becomes degenerate at the poles. If we're exactly on a pole, |
| 496 |
we *define* the unit vectors as (1,0,0) and (0,1,0). |
| 497 |
|
| 498 |
Orientation is a pain -- the convention used here is that unit delta |
| 499 |
always points to the pole. |
| 500 |
|
| 501 |
>>> cPos = utils.spherToCart(45*DEG, -45*DEG) |
| 502 |
>>> ua, ud = getTangentialUnits(cPos) |
| 503 |
>>> print(numpy.dot(ua, ua), numpy.dot(ud, ud)) |
| 504 |
1.0 1.0 |
| 505 |
>>> utils.nprepr([numpy.dot(cPos, ua), numpy.dot(cPos, ud)]) |
| 506 |
'[0 0]' |
| 507 |
>>> utils.nprepr(ua), utils.nprepr(ud) |
| 508 |
('[-0.7071 0.7071 -0]', '[-0.5 -0.5 -0.7071]') |
| 509 |
>>> ua, ud = getTangentialUnits(utils.spherToCart(180*DEG, 60*DEG)) |
| 510 |
>>> utils.nprepr(ua), utils.nprepr(ud) |
| 511 |
('[-1.225e-16 -1 -0]', '[0.866 -1.061e-16 0.5]') |
| 512 |
>>> ua, ud = getTangentialUnits(utils.spherToCart(0*DEG, 60*DEG)) |
| 513 |
>>> utils.nprepr(ua), utils.nprepr(ud) |
| 514 |
('[-0 1 -0]', '[-0.866 -0 0.5]') |
| 515 |
>>> ua, ud = getTangentialUnits(utils.spherToCart(0, -60*DEG)) |
| 516 |
>>> utils.nprepr(ua), utils.nprepr(ud) |
| 517 |
('[-0 1 -0]', '[-0.866 -0 -0.5]') |
| 518 |
""" |
| 519 |
try: |
| 520 |
normalizer = 1/math.sqrt(cPos[0]**2+cPos[1]**2) |
| 521 |
except ZeroDivisionError: |
| 522 |
return numpy.array([1.,0.,0.]), numpy.array([0., 1., 0]) |
| 523 |
alphaUnit = normalizer*numpy.array([cPos[1], -cPos[0], 0.]) |
| 524 |
deltaUnit = normalizer*numpy.array( |
| 525 |
[cPos[0]*cPos[2], cPos[1]*cPos[2], -cPos[0]**2-cPos[1]**2]) |
| 526 |
|
| 527 |
# now orient the vectors: in delta, we always look towards the pole |
| 528 |
if sgn(cPos[2])!=sgn(deltaUnit[2]): |
| 529 |
deltaUnit = -1*deltaUnit # TODO this breaks on the equator |
| 530 |
|
| 531 |
# The orientation of alphaUnit depends on the hemisphere |
| 532 |
if cPos[2]<0: # south |
| 533 |
if numpy.inner(numpy.cross(deltaUnit, alphaUnit), cPos)<0: |
| 534 |
alphaUnit = -1*alphaUnit |
| 535 |
|
| 536 |
else: # north |
| 537 |
if numpy.inner(numpy.cross(deltaUnit, alphaUnit), cPos)>0: |
| 538 |
alphaUnit = -1*alphaUnit |
| 539 |
|
| 540 |
return alphaUnit, deltaUnit |
| 541 |
|
| 542 |
|
| 543 |
def movePm( |
| 544 |
alphaDeg: Numeric, |
| 545 |
deltaDeg: Numeric, |
| 546 |
pmAlpha: Numeric, |
| 547 |
pmDelta: Numeric, |
| 548 |
timeDiff: Numeric, |
| 549 |
foreshort: bool = False) -> _2DPoint: |
| 550 |
"""returns alpha and delta for an object with pm pmAlpha after timeDiff. |
| 551 |
|
| 552 |
pmAlpha has to have cos(delta) applied, everything is supposed to be |
| 553 |
in degrees, the time unit is yours to choose. |
| 554 |
""" |
| 555 |
alpha, delta = alphaDeg/180.*math.pi, deltaDeg/180.*math.pi |
| 556 |
pmAlpha, pmDelta = pmAlpha/180.*math.pi, pmDelta/180.*math.pi |
| 557 |
sd, cd = math.sin(delta), math.cos(delta) |
| 558 |
sa, ca = math.sin(alpha), math.cos(alpha) |
| 559 |
muAbs = math.sqrt(pmAlpha**2+pmDelta**2); |
| 560 |
muTot = muAbs+0.5*foreshort*timeDiff; |
| 561 |
|
| 562 |
if muAbs<1e-20: |
| 563 |
return alphaDeg, deltaDeg |
| 564 |
# this is according to Mueller, 115 (4.94) |
| 565 |
dirA = pmAlpha/muAbs; |
| 566 |
dirD = pmDelta/muAbs; |
| 567 |
sinMot = sin(muTot*timeDiff); |
| 568 |
cosMot = cos(muTot*timeDiff); |
| 569 |
|
| 570 |
dirVec = numpy.array([ |
| 571 |
-sd*ca*dirD*sinMot - sa*dirA*sinMot + cd*ca*cosMot, |
| 572 |
-sd*sa*dirD*sinMot + ca*dirA*sinMot + cd*sa*cosMot, |
| 573 |
+cd*dirD*sinMot + sd*cosMot]) |
| 574 |
return dirVecToCelCoos(dirVec) |
| 575 |
|
| 576 |
|
| 577 |
def getGCDist(pos1: _2DPoint, pos2: _2DPoint) -> float: |
| 578 |
"""returns the distance along a great circle between two points. |
| 579 |
|
| 580 |
The distance is in degrees, the input positions are in degrees. |
| 581 |
""" |
| 582 |
scalarprod = numpy.dot( |
| 583 |
utils.spherToCart(pos1[0]*DEG, pos1[1]*DEG), |
| 584 |
utils.spherToCart(pos2[0]*DEG, pos2[1]*DEG)) |
| 585 |
# cope with numerical trouble |
| 586 |
if scalarprod>=1: |
| 587 |
return 0 |
| 588 |
return math.acos(scalarprod)/DEG |
| 589 |
|
| 590 |
|
| 591 |
def _test(): # pragma: no cover |
| 592 |
import doctest |
| 593 |
doctest.testmod() |
| 594 |
|
| 595 |
|
| 596 |
if __name__=="__main__": # pragma: no cover |
| 597 |
_test() |