| 1 |
""" |
| 2 |
Math-related helper functions. |
| 3 |
""" |
| 4 |
|
| 5 |
#c Copyright 2008-2025, the GAVO project <[email protected]> |
| 6 |
#c |
| 7 |
#c This program is free software, covered by the GNU GPL. See the |
| 8 |
#c COPYING file in the source distribution. |
| 9 |
|
| 10 |
|
| 11 |
import functools |
| 12 |
import math |
| 13 |
|
| 14 |
from astropy.coordinates import ( # type: ignore |
| 15 |
UnitSphericalRepresentation, CartesianRepresentation) |
| 16 |
from astropy import units as u # type: ignore |
| 17 |
import numpy |
| 18 |
|
| 19 |
from gavo.utils.dachstypes import ( |
| 20 |
Callable, Dict, NDArray, Numeric, Optional, Union) |
| 21 |
|
| 22 |
DEG = math.pi/180 |
| 23 |
ARCSEC = DEG/3600 |
| 24 |
|
| 25 |
|
| 26 |
def nprepr(npobj: Union[Numeric, NDArray]): |
| 27 |
"""formats a simple numpy array of value avoiding excessive digits. |
| 28 |
|
| 29 |
This, realistically, is mainly for doctests. |
| 30 |
""" |
| 31 |
if isinstance(npobj, (numpy.ndarray, tuple, list)): |
| 32 |
return "[{}]".format(" ".join("%.4g"%float(v) for v in npobj)) |
| 33 |
else: |
| 34 |
return str(float(npobj)) |
| 35 |
|
| 36 |
|
| 37 |
def findMinimum( |
| 38 |
f: Callable[[float], float], |
| 39 |
left: float, |
| 40 |
right: float, |
| 41 |
minInterval: float=3e-8) -> float: |
| 42 |
"""returns an estimate for the minimum of the single-argument function f |
| 43 |
on (left,right). |
| 44 |
|
| 45 |
minInterval is a fourth of the smallest test interval considered. |
| 46 |
|
| 47 |
For constant functions, a value close to left will be returned. |
| 48 |
|
| 49 |
This function should only be used on functions having exactly |
| 50 |
one minimum in the interval. |
| 51 |
""" |
| 52 |
# replace this at some point by some better method (Num. Recip. in C, 394f) |
| 53 |
# -- this is easy to fool and massively suboptimal. |
| 54 |
mid = (right+left)/2. |
| 55 |
offset = (right-left)/4. |
| 56 |
if offset<minInterval: |
| 57 |
return mid |
| 58 |
if f(left+offset)<=f(mid+offset): |
| 59 |
return findMinimum(f, left, mid, minInterval) |
| 60 |
else: |
| 61 |
return findMinimum(f, mid, right, minInterval) |
| 62 |
|
| 63 |
|
| 64 |
@functools.cache |
| 65 |
def getHexToBin() -> Dict[str, str]: |
| 66 |
"""returns a dictionary mapping hex chars to their binary expansions. |
| 67 |
""" |
| 68 |
return dict(list(zip( |
| 69 |
"0123456789abcdef", |
| 70 |
["0000", "0001", "0010", "0011", "0100", "0101", "0110", "0111", |
| 71 |
"1000", "1001", "1010", "1011", "1100", "1101", "1110", "1111",]))) |
| 72 |
|
| 73 |
|
| 74 |
def toBinary(anInt: int, desiredLength: Optional[int]=None) -> str: |
| 75 |
"""returns anInt as a string with its binary digits, MSB first. |
| 76 |
|
| 77 |
If desiredLength is given and the binary expansion is shorter, |
| 78 |
the value will be padded with zeros. |
| 79 |
|
| 80 |
>>> toBinary(349) |
| 81 |
'101011101' |
| 82 |
>>> toBinary(349, 10) |
| 83 |
'0101011101' |
| 84 |
""" |
| 85 |
h2b = getHexToBin() |
| 86 |
res = "".join(h2b[c] for c in "%x"%anInt).lstrip("0") |
| 87 |
if desiredLength is not None: |
| 88 |
res = "0"*(desiredLength-len(res))+res |
| 89 |
return res |
| 90 |
|
| 91 |
|
| 92 |
def roundO2M(num: float) -> int: |
| 93 |
"""returns a plausible rounding of num. |
| 94 |
|
| 95 |
This will round up the last couple of digits. For now, this will only |
| 96 |
do cardinals. |
| 97 |
>>> roundO2M(0) |
| 98 |
0 |
| 99 |
>>> roundO2M(2.5) |
| 100 |
2 |
| 101 |
>>> roundO2M(15) |
| 102 |
20 |
| 103 |
>>> roundO2M(9900) |
| 104 |
10000 |
| 105 |
>>> roundO2M(8321) |
| 106 |
8400 |
| 107 |
>>> roundO2M(3.2349302e9) |
| 108 |
3300000000 |
| 109 |
""" |
| 110 |
if num<10: |
| 111 |
return int(round(num)) |
| 112 |
mant = ("%f"%num).split(".")[0] |
| 113 |
|
| 114 |
if len(mant)==2: |
| 115 |
nextVal = int(mant[0])+1 |
| 116 |
return int("%s0"%nextVal) |
| 117 |
|
| 118 |
nextVal = int(mant[:2])+1 |
| 119 |
return int("%s%s"%(nextVal, "0"*(len(mant)-2))) |
| 120 |
|
| 121 |
|
| 122 |
def getRotX(angle): |
| 123 |
"""returns a 3-rotation matrix for rotating angle radians around x. |
| 124 |
""" |
| 125 |
c, s = math.cos(angle), math.sin(angle) |
| 126 |
return numpy.array([(1, 0, 0), (0, c, s), (0, -s, c)]) |
| 127 |
|
| 128 |
|
| 129 |
def getRotY(angle): |
| 130 |
"""returns a 3-rotation matrix for rotating angle radians around y. |
| 131 |
""" |
| 132 |
c, s = math.cos(angle), math.sin(angle) |
| 133 |
return numpy.array([[c, 0, -s], [0, 1, 0], [s, 0, c]]) |
| 134 |
|
| 135 |
|
| 136 |
def getRotZ(angle): |
| 137 |
"""returns a 3-rotation matrix for rotating angle radians around z. |
| 138 |
""" |
| 139 |
c, s = math.cos(angle), math.sin(angle) |
| 140 |
return numpy.array([(c, s, 0), (-s, c, 0), (0, 0, 1)]) |
| 141 |
|
| 142 |
|
| 143 |
def spherToCart(theta:Numeric, phi:Numeric) -> NDArray: |
| 144 |
"""returns a 3-cartesian unit vector pointing to longitude theta, |
| 145 |
latitude phi. |
| 146 |
|
| 147 |
The angles are in rad. |
| 148 |
|
| 149 |
>>> print(spherToCart(0,0)) |
| 150 |
[1. 0. 0.] |
| 151 |
>>> nprepr(spherToCart(0, 90*DEG)) |
| 152 |
'[6.123e-17 0 1]' |
| 153 |
>>> nprepr(spherToCart(90*DEG, 90*DEG)) |
| 154 |
'[3.749e-33 6.123e-17 1]' |
| 155 |
>>> nprepr(spherToCart(90*DEG, 0)) |
| 156 |
'[6.123e-17 1 0]' |
| 157 |
>>> nprepr(spherToCart(180*DEG, -45*DEG)) |
| 158 |
'[-0.7071 8.66e-17 -0.7071]' |
| 159 |
""" |
| 160 |
return UnitSphericalRepresentation(theta*u.rad, phi*u.rad |
| 161 |
).represent_as(CartesianRepresentation).xyz.value |
| 162 |
|
| 163 |
|
| 164 |
def cartToSpher(unitvector): |
| 165 |
"""returns spherical coordinates for a 3-unit vector. |
| 166 |
|
| 167 |
We do not check if unitvector actually *is* a unit vector. The returned |
| 168 |
angles are in rad. |
| 169 |
""" |
| 170 |
spherical = CartesianRepresentation(*unitvector |
| 171 |
).represent_as(UnitSphericalRepresentation) |
| 172 |
return [spherical.lon.to(u.rad).value, spherical.lat.to(u.rad).value] |
| 173 |
|
| 174 |
|
| 175 |
def floorInt(flt: float) -> float: |
| 176 |
"""returns the largest integer smaller than flt, except if flt is a |
| 177 |
special float, in which case flt is returned. |
| 178 |
""" |
| 179 |
if math.isfinite(flt): |
| 180 |
return int(math.floor(flt)) |
| 181 |
return flt |
| 182 |
|
| 183 |
|
| 184 |
def ceilInt(flt: float) -> float: |
| 185 |
"""returns the smallest integer largest than flt, except if flt is a |
| 186 |
special float, in which case flt is returned. |
| 187 |
""" |
| 188 |
if math.isfinite(flt): |
| 189 |
return int(math.ceil(flt)) |
| 190 |
return flt |
| 191 |
|
| 192 |
|
| 193 |
if __name__=="__main__": # pragma: no cover |
| 194 |
import doctest |
| 195 |
doctest.testmod() |