Coverage for pygeodesy/utily.py: 90%
321 statements
« prev ^ index » next coverage.py v7.2.2, created at 2023-08-23 12:10 -0400
« prev ^ index » next coverage.py v7.2.2, created at 2023-08-23 12:10 -0400
2# -*- coding: utf-8 -*-
4u'''Various utility functions.
6After I{(C) Chris Veness 2011-2015} published under the same MIT Licence**, see
7U{Latitude/Longitude<https://www.Movable-Type.co.UK/scripts/latlong.html>} and
8U{Vector-based geodesy<https://www.Movable-Type.co.UK/scripts/latlong-vectors.html>}.
9'''
10# make sure int/int division yields float quotient, see .basics
11from __future__ import division as _; del _ # PYCHOK semicolon
13from pygeodesy.basics import copysign0, isint, isstr
14from pygeodesy.constants import EPS, EPS0, INF, NAN, NEG0, NINF, PI, PI2, PI_2, R_M, \
15 _float as _F, _isfinite, isnan, isnear0, isneg0, _M_KM, \
16 _M_NM, _M_SM, _0_0, _1__90, _0_5, _1_0, _N_1_0, _2__PI, \
17 _10_0, _90_0, _N_90_0, _180_0, _N_180_0, _360_0, _400_0
18from pygeodesy.errors import _ValueError, _xkwds, _xkwds_get
19from pygeodesy.interns import _edge_, _radians_, _semi_circular_, _SPACE_
20from pygeodesy.lazily import _ALL_LAZY, _ALL_MODS as _MODS
21from pygeodesy.units import Degrees, Feet, Float, Lam, Lam_, Meter, Meter2, Radians
23from math import acos, asin, atan2, cos, degrees, fabs, radians, sin, tan # pow
25__all__ = _ALL_LAZY.utily
26__version__ = '23.08.15'
28# read constant name "_M_Unit" as "meter per Unit"
29_M_CHAIN = _F( 20.1168) # yard2m(1) * 22
30_M_FATHOM = _F( 1.8288) # yard2m(1) * 2 or _M_NM * 1e-3
31_M_FOOT = _F( 0.3048) # Int'l (1 / 3.2808398950131 = 10_000 / (254 * 12))
32_M_FOOT_GE = _F( 0.31608) # German Fuss (1 / 3.1637560111364)
33_M_FOOT_FR = _F( 0.3248406) # French Pied-du-Roi or pied (1 / 3.0784329298739)
34_M_FOOT_USVY = _F( 0.3048006096012192) # US Survey (1200 / 3937)
35_M_FURLONG = _F( 201.168) # 220 * yard2m(1) == 10 * m2chain(1)
36# _M_KM = _F(1000.0) # kilo meter
37# _M_NM = _F(1852.0) # nautical mile
38# _M_SM = _F(1609.344) # statute mile
39_M_TOISE = _F( 1.9490436) # French toise, 6 pieds (6 / 3.0784329298739)
40_M_YARD_UK = _F( 0.9144) # 254 * 12 * 3 / 10_000 == 3 * ft2m(1) Int'l
43def acos1(x):
44 '''Return C{math.acos(max(-1, min(1, B{x})))}.
45 '''
46 return acos(x) if fabs(x) < _1_0 else (PI if x < 0 else _0_0)
49def acre2ha(acres):
50 '''Convert acres to hectare.
52 @arg acres: Value in acres (C{scalar}).
54 @return: Value in C{hectare} (C{float}).
56 @raise ValueError: Invalid B{C{acres}}.
57 '''
58 # 0.40468564224 == acre2m2(1) / 10_000
59 return Float(ha=Float(acres) * 0.40468564224)
62def acre2m2(acres):
63 '''Convert acres to I{square} meter.
65 @arg acres: Value in acres (C{scalar}).
67 @return: Value in C{meter^2} (C{float}).
69 @raise ValueError: Invalid B{C{acres}}.
70 '''
71 # 4046.8564224 == chain2m(1) * furlong2m(1)
72 return Meter2(Float(acres) * 4046.8564224)
75def asin1(x):
76 '''Return C{math.asin(max(-1, min(1, B{x})))}.
77 '''
78 return asin(x) if fabs(x) < _1_0 else (PI_2 if x > 0 else -PI_2) # not PI3_2!
81def atand(y_x):
82 '''Return C{atan(B{y_x})} angle in C{degrees}.
84 @see: Function L{pygeodesy.atan2d}.
85 '''
86 return atan2d(y_x, _1_0)
89def atan2b(y, x):
90 '''Return C{atan2(B{y}, B{x})} in degrees M{[0..+360]}.
92 @see: Function L{pygeodesy.atan2d}.
93 '''
94 d = atan2d(y, x)
95 if d < 0:
96 d += _360_0
97 return d
100def atan2d(y, x, reverse=False):
101 '''Return C{atan2(B{y}, B{x})} in degrees M{[-180..+180]},
102 optionally reversed (by 180 degrees for C{azi2}).
104 @see: I{Karney}'s C++ function U{Math.atan2d
105 <https://GeographicLib.SourceForge.io/C++/doc/classGeographicLib_1_1Math.html>}.
106 '''
107 if fabs(y) > fabs(x) > 0:
108 if y < 0: # q = 3
109 d = degrees(atan2(x, -y)) - _90_0
110 else: # q = 2
111 d = _90_0 - degrees(atan2(x, y))
112 elif x < 0: # q = 1
113 d = copysign0(_180_0, y) - degrees(atan2(y, -x))
114 elif x > 0: # q = 0
115 d = degrees(atan2(y, x)) if y else _0_0
116 elif isnan(x) or isnan(y):
117 return NAN
118 else: # x == 0
119 d = _N_90_0 if y < 0 else (_90_0 if y > 0 else _0_0)
120 if reverse:
121 d += _180_0 if d < 0 else _N_180_0
122 return d
125def chain2m(chains):
126 '''Convert I{UK} chains to meter.
128 @arg chains: Value in chains (C{scalar}).
130 @return: Value in C{meter} (C{float}).
132 @raise ValueError: Invalid B{C{chains}}.
133 '''
134 return Meter(Float(chains=chains) * _M_CHAIN)
137def circle4(earth, lat):
138 '''Get the equatorial or a parallel I{circle of latitude}.
140 @arg earth: The earth radius, ellipsoid or datum
141 (C{meter}, L{Ellipsoid}, L{Ellipsoid2},
142 L{Datum} or L{a_f2Tuple}).
143 @arg lat: Geodetic latitude (C{degrees90}, C{str}).
145 @return: A L{Circle4Tuple}C{(radius, height, lat, beta)}
146 instance.
148 @raise RangeError: Latitude B{C{lat}} outside valid range and
149 L{pygeodesy.rangerrors} set to C{True}.
151 @raise TypeError: Invalid B{C{earth}}.
153 @raise ValueError: B{C{earth}} or B{C{lat}}.
154 '''
155 E = _MODS.datums._spherical_datum(earth).ellipsoid
156 return E.circle4(lat)
159def cot(rad, **error_kwds):
160 '''Return the C{cotangent} of an angle in C{radians}.
162 @arg rad: Angle (C{radians}).
163 @kwarg error_kwds: Error to raise (C{ValueError}).
165 @return: C{cot(B{rad})}.
167 @raise ValueError: L{pygeodesy.isnear0}C{(sin(B{rad})}.
168 '''
169 s, c = sincos2(rad)
170 if isnear0(s):
171 raise _valueError(cot, rad, **error_kwds)
172 return c / s
175def cot_(*rads, **error_kwds):
176 '''Return the C{cotangent} of angle(s) in C{radiansresection}.
178 @arg rads: One or more angles (C{radians}).
179 @kwarg error_kwds: Error to raise (C{ValueError}).
181 @return: Yield the C{cot(B{rad})} for each angle.
183 @raise ValueError: See L{pygeodesy.cot}.
184 '''
185 try:
186 for r in rads:
187 yield cot(r)
188 except ValueError:
189 raise _valueError(cot_, r, **error_kwds)
192def cotd(deg, **error_kwds):
193 '''Return the C{cotangent} of an angle in C{degrees}.
195 @arg deg: Angle (C{degrees}).
196 @kwarg error_kwds: Error to raise (C{ValueError}).
198 @return: C{cot(B{deg})}.
200 @raise ValueError: L{pygeodesy.isnear0}C{(sin(B{deg})}.
201 '''
202 s, c = sincos2d(deg)
203 if isnear0(s):
204 raise _valueError(cotd, deg, **error_kwds)
205 return c / s
208def cotd_(*degs, **error_kwds):
209 '''Return the C{cotangent} of angle(s) in C{degrees}.
211 @arg degs: One or more angles (C{degrees}).
212 @kwarg error_kwds: Error to raise (C{ValueError}).
214 @return: Yield the C{cot(B{deg})} for each angle.
216 @raise ValueError: See L{pygeodesy.cotd}.
217 '''
218 try:
219 for d in degs:
220 yield cotd(d)
221 except ValueError:
222 raise _valueError(cotd_, d, **error_kwds)
225def degrees90(rad):
226 '''Convert radians to degrees and wrap M{[-270..+90]}.
228 @arg rad: Angle (C{radians}).
230 @return: Angle, wrapped (C{degrees90}).
231 '''
232 return _wrap(degrees(rad), _90_0, _360_0)
235def degrees180(rad):
236 '''Convert radians to degrees and wrap M{[-180..+180]}.
238 @arg rad: Angle (C{radians}).
240 @return: Angle, wrapped (C{degrees180}).
241 '''
242 return _wrap(degrees(rad), _180_0, _360_0)
245def degrees360(rad):
246 '''Convert radians to degrees and wrap M{[0..+360)}.
248 @arg rad: Angle (C{radians}).
250 @return: Angle, wrapped (C{degrees360}).
251 '''
252 return _wrap(degrees(rad), _360_0, _360_0)
255def degrees2grades(deg):
256 '''Convert degrees to I{grades} (aka I{gons} or I{gradians}).
258 @arg deg: Angle (C{degrees}).
260 @return: Angle (C{grades}).
261 '''
262 return Degrees(deg) * _400_0 / _360_0
265def degrees2m(deg, radius=R_M, lat=0):
266 '''Convert an angle to a distance along the equator or
267 along the parallel at an other (geodetic) latitude.
269 @arg deg: The angle (C{degrees}).
270 @kwarg radius: Mean earth radius, ellipsoid or datum
271 (C{meter}, L{Ellipsoid}, L{Ellipsoid2},
272 L{Datum} or L{a_f2Tuple}).
273 @kwarg lat: Parallel latitude (C{degrees90}, C{str}).
275 @return: Distance (C{meter}, same units as B{C{radius}}
276 or equatorial and polar radii) or C{0.0} for
277 near-polar B{C{lat}}.
279 @raise RangeError: Latitude B{C{lat}} outside valid range and
280 L{pygeodesy.rangerrors} set to C{True}.
282 @raise TypeError: Invalid B{C{radius}}.
284 @raise ValueError: Invalid B{C{deg}}, B{C{radius}} or
285 B{C{lat}}.
287 @see: Function L{radians2m} and L{m2degrees}.
288 '''
289 return _radians2m(Lam_(deg=deg, clip=0), radius, lat)
292def fathom2m(fathoms):
293 '''Convert I{Imperial} fathom to meter.
295 @arg fathoms: Value in fathoms (C{scalar}).
297 @return: Value in C{meter} (C{float}).
299 @raise ValueError: Invalid B{C{fathoms}}.
301 @see: Function L{toise2m}, U{Fathom<https://WikiPedia.org/wiki/Fathom>}
302 and U{Klafter<https://WikiPedia.org/wiki/Klafter>}.
303 '''
304 return Meter(Float(fathoms=fathoms) * _M_FATHOM)
307def ft2m(feet, usurvey=False, pied=False, fuss=False):
308 '''Convert I{International}, I{US Survey}, I{French} or I{German}
309 B{C{feet}} to C{meter}.
311 @arg feet: Value in feet (C{scalar}).
312 @kwarg usurvey: If C{True}, convert I{US Survey} foot else ...
313 @kwarg pied: If C{True}, convert French I{pied-du-Roi} else ...
314 @kwarg fuss: If C{True}, convert German I{Fuss}, otherwise
315 I{International} foot to C{meter}.
317 @return: Value in C{meter} (C{float}).
319 @raise ValueError: Invalid B{C{feet}}.
320 '''
321 return Meter(Feet(feet) * (_M_FOOT_USVY if usurvey else
322 (_M_FOOT_FR if pied else
323 (_M_FOOT_GE if fuss else _M_FOOT))))
326def furlong2m(furlongs):
327 '''Convert a furlong to meter.
329 @arg furlongs: Value in furlongs (C{scalar}).
331 @return: Value in C{meter} (C{float}).
333 @raise ValueError: Invalid B{C{furlongs}}.
334 '''
335 return Meter(Float(furlongs=furlongs) * _M_FURLONG)
338def grades(rad):
339 '''Convert radians to I{grades} (aka I{gons} or I{gradians}).
341 @arg rad: Angle (C{radians}).
343 @return: Angle (C{grades}).
344 '''
345 return Float(grades=Float(rad=rad) * _400_0 / PI2)
348def grades400(rad):
349 '''Convert radians to I{grades} (aka I{gons} or I{gradians}) and wrap M{[0..+400)}.
351 @arg rad: Angle (C{radians}).
353 @return: Angle, wrapped (C{grades}).
354 '''
355 return Float(grades400=_wrap(grades(rad), _400_0, _400_0))
358def grades2degrees(gon):
359 '''Convert I{grades} (aka I{gons} or I{gradians}) to C{degrees}.
361 @arg gon: Angle (C{grades}).
363 @return: Angle (C{degrees}).
364 '''
365 return Degrees(Float(gon=gon) * _360_0 / _400_0)
368def grades2radians(gon):
369 '''Convert I{grades} (aka I{gons} or I{gradians}) to C{radians}.
371 @arg gon: Angle (C{grades}).
373 @return: Angle (C{radians}).
374 '''
375 return Radians(Float(gon=gon) * PI2 / _400_0)
378def km2m(km):
379 '''Convert kilo meter to meter (m).
381 @arg km: Value in kilo meter (C{scalar}).
383 @return: Value in meter (C{float}).
385 @raise ValueError: Invalid B{C{km}}.
386 '''
387 return Meter(Float(km=km) * _M_KM)
390def m2chain(meter):
391 '''Convert meter to I{UK} chains.
393 @arg meter: Value in meter (C{scalar}).
395 @return: Value in C{chains} (C{float}).
397 @raise ValueError: Invalid B{C{meter}}.
398 '''
399 return Float(chain=Meter(meter) / _M_CHAIN) # * 0.049709695378986715
402def m2degrees(distance, radius=R_M, lat=0):
403 '''Convert a distance to an angle along the equator or
404 along the parallel at an other (geodetic) latitude.
406 @arg distance: Distance (C{meter}, same units as B{C{radius}}).
407 @kwarg radius: Mean earth radius, ellipsoid or datum (C{meter},
408 an L{Ellipsoid}, L{Ellipsoid2}, L{Datum} or
409 L{a_f2Tuple}).
410 @kwarg lat: Parallel latitude (C{degrees90}, C{str}).
412 @return: Angle (C{degrees}) or C{INF} for near-polar B{C{lat}}.
414 @raise RangeError: Latitude B{C{lat}} outside valid range and
415 L{pygeodesy.rangerrors} set to C{True}.
417 @raise TypeError: Invalid B{C{radius}}.
419 @raise ValueError: Invalid B{C{distance}}, B{C{radius}}
420 or B{C{lat}}.
422 @see: Function L{m2radians} and L{degrees2m}.
423 '''
424 return degrees(m2radians(distance, radius=radius, lat=lat))
427def m2fathom(meter):
428 '''Convert meter to I{Imperial} fathoms.
430 @arg meter: Value in meter (C{scalar}).
432 @return: Value in C{fathoms} (C{float}).
434 @raise ValueError: Invalid B{C{meter}}.
436 @see: Function L{m2toise}, U{Fathom<https://WikiPedia.org/wiki/Fathom>}
437 and U{Klafter<https://WikiPedia.org/wiki/Klafter>}.
438 '''
439 return Float(fathom=Meter(meter) / _M_FATHOM) # * 0.546806649
442def m2ft(meter, usurvey=False, pied=False, fuss=False):
443 '''Convert meter to I{International}, I{US Survey}, I{French} or
444 or I{German} feet (C{ft}).
446 @arg meter: Value in meter (C{scalar}).
447 @kwarg usurvey: If C{True}, convert to I{US Survey} foot else ...
448 @kwarg pied: If C{True}, convert to French I{pied-du-Roi} else ...
449 @kwarg fuss: If C{True}, convert to German I{Fuss}, otherwise to
450 I{International} foot.
452 @return: Value in C{feet} (C{float}).
454 @raise ValueError: Invalid B{C{meter}}.
455 '''
456 # * 3.2808333333333333, US Survey 3937 / 1200
457 # * 3.2808398950131235, Int'l 10_000 / (254 * 12)
458 return Float(feet=Meter(meter) / (_M_FOOT_USVY if usurvey else
459 (_M_FOOT_FR if pied else
460 (_M_FOOT_GE if fuss else _M_FOOT))))
463def m2furlong(meter):
464 '''Convert meter to furlongs.
466 @arg meter: Value in meter (C{scalar}).
468 @return: Value in C{furlongs} (C{float}).
470 @raise ValueError: Invalid B{C{meter}}.
471 '''
472 return Float(furlong=Meter(meter) / _M_FURLONG) # * 0.00497096954
475def m2km(meter):
476 '''Convert meter to kilo meter (Km).
478 @arg meter: Value in meter (C{scalar}).
480 @return: Value in Km (C{float}).
482 @raise ValueError: Invalid B{C{meter}}.
483 '''
484 return Float(km=Meter(meter) / _M_KM)
487def m2NM(meter):
488 '''Convert meter to nautical miles (NM).
490 @arg meter: Value in meter (C{scalar}).
492 @return: Value in C{NM} (C{float}).
494 @raise ValueError: Invalid B{C{meter}}.
495 '''
496 return Float(NM=Meter(meter) / _M_NM) # * 5.39956804e-4
499def m2radians(distance, radius=R_M, lat=0):
500 '''Convert a distance to an angle along the equator or
501 along the parallel at an other (geodetic) latitude.
503 @arg distance: Distance (C{meter}, same units as B{C{radius}}).
504 @kwarg radius: Mean earth radius, ellipsoid or datum (C{meter},
505 an L{Ellipsoid}, L{Ellipsoid2}, L{Datum} or
506 L{a_f2Tuple}).
507 @kwarg lat: Parallel latitude (C{degrees90}, C{str}).
509 @return: Angle (C{radians}) or C{INF} for near-polar B{C{lat}}.
511 @raise RangeError: Latitude B{C{lat}} outside valid range and
512 L{pygeodesy.rangerrors} set to C{True}.
514 @raise TypeError: Invalid B{C{radius}}.
516 @raise ValueError: Invalid B{C{distance}}, B{C{radius}}
517 or B{C{lat}}.
519 @see: Function L{m2degrees} and L{radians2m}.
520 '''
521 m = circle4(radius, lat).radius
522 return INF if m < EPS0 else Radians(Float(distance=distance) / m)
525def m2SM(meter):
526 '''Convert meter to statute miles (SM).
528 @arg meter: Value in meter (C{scalar}).
530 @return: Value in C{SM} (C{float}).
532 @raise ValueError: Invalid B{C{meter}}.
533 '''
534 return Float(SM=Meter(meter) / _M_SM) # * 6.21369949e-4 == 1 / 1609.344
537def m2toise(meter):
538 '''Convert meter to French U{toises<https://WikiPedia.org/wiki/Toise>}.
540 @arg meter: Value in meter (C{scalar}).
542 @return: Value in C{toises} (C{float}).
544 @raise ValueError: Invalid B{C{meter}}.
546 @see: Function L{m2fathom}.
547 '''
548 return Float(toise=Meter(meter) / _M_TOISE) # * 0.513083632632119
551def m2yard(meter):
552 '''Convert meter to I{UK} yards.
554 @arg meter: Value in meter (C{scalar}).
556 @return: Value in C{yards} (C{float}).
558 @raise ValueError: Invalid B{C{meter}}.
559 '''
560 return Float(yard=Meter(meter) / _M_YARD_UK) # * 1.0936132983377078
563def NM2m(nm):
564 '''Convert nautical miles to meter (m).
566 @arg nm: Value in nautical miles (C{scalar}).
568 @return: Value in meter (C{float}).
570 @raise ValueError: Invalid B{C{nm}}.
571 '''
572 return Meter(Float(nm=nm) * _M_NM)
575def _passarg(arg): # in .auxilats.auxLat, .formy
576 '''(INTERNAL) Helper, no-op.
577 '''
578 return arg
581def _passargs(*args): # in .formy
582 '''(INTERNAL) Helper, no-op.
583 '''
584 return args
587def radians2m(rad, radius=R_M, lat=0):
588 '''Convert an angle to a distance along the equator or
589 along the parallel at an other (geodetic) latitude.
591 @arg rad: The angle (C{radians}).
592 @kwarg radius: Mean earth radius, ellipsoid or datum
593 (C{meter}, L{Ellipsoid}, L{Ellipsoid2},
594 L{Datum} or L{a_f2Tuple}).
595 @kwarg lat: Parallel latitude (C{degrees90}, C{str}).
597 @return: Distance (C{meter}, same units as B{C{radius}}
598 or equatorial and polar radii) or C{0.0} for
599 near-polar B{C{lat}}.
601 @raise RangeError: Latitude B{C{lat}} outside valid range and
602 L{pygeodesy.rangerrors} set to C{True}.
604 @raise TypeError: Invalid B{C{radius}}.
606 @raise ValueError: Invalid B{C{rad}}, B{C{radius}} or
607 B{C{lat}}.
609 @see: Function L{degrees2m} and L{m2radians}.
610 '''
611 return _radians2m(Lam(rad=rad, clip=0), radius, lat)
614def _radians2m(rad, radius, lat):
615 '''(INTERNAL) Helper for C{degrees2m} and C{radians2m}.
616 '''
617 m = circle4(radius, lat).radius
618 return _0_0 if m < EPS0 else (rad * m)
621def radiansPI(deg):
622 '''Convert and wrap degrees to radians M{[-PI..+PI]}.
624 @arg deg: Angle (C{degrees}).
626 @return: Radians, wrapped (C{radiansPI})
627 '''
628 return _wrap(radians(deg), PI, PI2)
631def radiansPI2(deg):
632 '''Convert and wrap degrees to radians M{[0..+2PI)}.
634 @arg deg: Angle (C{degrees}).
636 @return: Radians, wrapped (C{radiansPI2})
637 '''
638 return _wrap(radians(deg), PI2, PI2)
641def radiansPI_2(deg):
642 '''Convert and wrap degrees to radians M{[-3PI/2..+PI/2]}.
644 @arg deg: Angle (C{degrees}).
646 @return: Radians, wrapped (C{radiansPI_2})
647 '''
648 return _wrap(radians(deg), PI_2, PI2)
651def _sin0cos2(q, r, sign):
652 '''(INTERNAL) 2-tuple (C{sin(r), cos(r)}) in quadrant C{0 <= B{q} <= 3}
653 and C{sin} zero I{signed} with B{C{sign}}.
654 '''
655 if r < PI_2:
656 s, c = sin(r), cos(r)
657 t = s, c, -s, -c, s
658 else: # r == PI_2
659 t = _1_0, _0_0, _N_1_0, _0_0, _1_0
660# else: # r == 0, testUtility failures
661# t = _0_0, _1_0, _0_0, _N_1_0, _0_0
662# q &= 3
663 s = t[q] or (NEG0 if sign < 0 else _0_0)
664 c = t[q + 1] or _0_0
665 return s, c
668def sincos2(rad):
669 '''Return the C{sine} and C{cosine} of an angle in C{radians}.
671 @arg rad: Angle (C{radians}).
673 @return: 2-Tuple (C{sin(B{rad})}, C{cos(B{rad})}).
675 @see: U{GeographicLib<https://GeographicLib.SourceForge.io/C++/doc/
676 classGeographicLib_1_1Math.html#sincosd>} function U{sincosd
677 <https://SourceForge.net/p/geographiclib/code/ci/release/tree/
678 python/geographiclib/geomath.py#l155>} and C++ U{sincosd
679 <https://SourceForge.net/p/geographiclib/code/ci/release/tree/
680 include/GeographicLib/Math.hpp#l558>}.
681 '''
682 if _isfinite(rad):
683 q = int(rad * _2__PI) # int(math.floor)
684 if q < 0:
685 q -= 1
686 t = _sin0cos2(q & 3, rad - q * PI_2, rad)
687 else:
688 t = NAN, NAN
689 return t
692def sincos2_(*rads):
693 '''Return the C{sine} and C{cosine} of angle(s) in C{radians}.
695 @arg rads: One or more angles (C{radians}).
697 @return: Yield the C{sin(B{rad})} and C{cos(B{rad})} for each angle.
699 @see: function L{sincos2}.
700 '''
701 for r in rads:
702 s, c = sincos2(r)
703 yield s
704 yield c
707def sincos2d(deg, **adeg):
708 '''Return the C{sine} and C{cosine} of an angle in C{degrees}.
710 @arg deg: Angle (C{degrees}).
711 @kwarg adeg: Optional correction (C{degrees}).
713 @return: 2-Tuple (C{sin(B{deg_})}, C{cos(B{deg_})}, C{B{deg_} =
714 B{deg} + B{adeg}}).
716 @see: U{GeographicLib<https://GeographicLib.SourceForge.io/C++/doc/
717 classGeographicLib_1_1Math.html#sincosd>} function U{sincosd
718 <https://SourceForge.net/p/geographiclib/code/ci/release/tree/
719 python/geographiclib/geomath.py#l155>} and C++ U{sincosd
720 <https://SourceForge.net/p/geographiclib/code/ci/release/tree/
721 include/GeographicLib/Math.hpp#l558>}.
722 '''
723 if _isfinite(deg):
724 q = int(deg * _1__90) # int(math.floor)
725 if q < 0:
726 q -= 1
727 d = deg - q * _90_0
728 if adeg:
729 t = _xkwds_get(adeg, adeg=_0_0)
730 d = _MODS.karney._around(d + t)
731 t = _sin0cos2(q & 3, radians(d), deg)
732 else:
733 t = NAN, NAN
734 return t
737def SinCos2(x):
738 '''Get C{sin} and C{cos} of I{typed} angle.
740 @arg x: Angle (L{Degrees}, L{Radians} or C{radians}).
742 @return: 2-Tuple (C{sin(B{x})}, C{cos(B{x})}).
743 '''
744 return sincos2d(x) if isinstance(x, Degrees) else (
745 sincos2(x) if isinstance(x, Radians) else
746 sincos2(float(x))) # assume C{radians}
749def sincos2d_(*degs):
750 '''Return the C{sine} and C{cosine} of angle(s) in C{degrees}.
752 @arg degs: One or more angles (C{degrees}).
754 @return: Yield the C{sin(B{deg})} and C{cos(B{deg})} for each angle.
756 @see: Function L{sincos2d}.
757 '''
758 for d in degs:
759 s, c = sincos2d(d)
760 yield s
761 yield c
764def sincostan3(rad):
765 '''Return the C{sine}, C{cosine} and C{tangent} of an angle in C{radians}.
767 @arg rad: Angle (C{radians}).
769 @return: 3-Tuple (C{sin(B{rad})}, C{cos(B{rad})}, C{tan(B{rad})}).
771 @see: Function L{sincos2}.
772 '''
773 rad %= PI2 # see ._wrap comments
774 if rad:
775 s, c = sincos2(rad)
776 t = (s / c) if c else (NINF if s < 0
777 else (INF if s > 0 else s))
778 else: # sin(-0.0) == tan(-0.0) = -0.0
779 c = _1_0
780 s = t = NEG0 if isneg0(rad) else _0_0
781 return s, c, t
784def SM2m(sm):
785 '''Convert statute miles to meter (m).
787 @arg sm: Value in statute miles (C{scalar}).
789 @return: Value in meter (C{float}).
791 @raise ValueError: Invalid B{C{sm}}.
792 '''
793 return Meter(Float(sm=sm) * _M_SM)
796def tan_2(rad, **semi): # edge=1
797 '''Compute the tangent of half angle.
799 @arg rad: Angle (C{radians}).
800 @kwarg semi: Angle or edge name and index
801 for semi-circular error.
803 @return: M{tan(rad / 2)} (C{float}).
805 @raise ValueError: If B{C{rad}} is semi-circular
806 and B{C{semi}} is given.
807 '''
808 # .formy.excessKarney_, .sphericalTrigonometry.areaOf
809 if semi and isnear0(fabs(rad) - PI):
810 for n, v in semi.items():
811 break
812 n = _SPACE_(n, _radians_) if not isint(v) else \
813 _SPACE_(_MODS.streprs.Fmt.SQUARE(**semi), _edge_)
814 raise _ValueError(n, rad, txt=_semi_circular_)
816 return tan(rad * _0_5)
819def tand(deg, **error_kwds):
820 '''Return the C{tangent} of an angle in C{degrees}.
822 @arg deg: Angle (C{degrees}).
823 @kwarg error_kwds: Error to raise (C{ValueError}).
825 @return: C{tan(B{deg})}.
827 @raise ValueError: If L{pygeodesy.isnear0}C{(cos(B{deg})}.
828 '''
829 s, c = sincos2d(deg)
830 if isnear0(c):
831 raise _valueError(tand, deg, **error_kwds)
832 return s / c
835def tand_(*degs, **error_kwds):
836 '''Return the C{tangent} of angle(s) in C{degrees}.
838 @arg degs: One or more angles (C{degrees}).
839 @kwarg error_kwds: Error to raise (C{ValueError}).
841 @return: Yield the C{tan(B{deg})} for each angle.
843 @raise ValueError: See L{pygeodesy.tand}.
844 '''
845 for d in degs:
846 yield tand(d, **error_kwds)
849def tanPI_2_2(rad):
850 '''Compute the tangent of half angle, 90 degrees rotated.
852 @arg rad: Angle (C{radians}).
854 @return: M{tan((rad + PI/2) / 2)} (C{float}).
855 '''
856 return tan((rad + PI_2) * _0_5)
859def toise2m(toises):
860 '''Convert French U{toises<https://WikiPedia.org/wiki/Toise>} to meter.
862 @arg toises: Value in toises (C{scalar}).
864 @return: Value in C{meter} (C{float}).
866 @raise ValueError: Invalid B{C{toises}}.
868 @see: Function L{fathom2m}.
869 '''
870 return Meter(Float(toises=toises) * _M_TOISE)
873def truncate(x, ndigits=None):
874 '''Truncate to the given number of digits.
876 @arg x: Value to truncate (C{scalar}).
877 @kwarg ndigits: Number of digits (C{int}),
878 aka I{precision}.
880 @return: Truncated B{C{x}} (C{float}).
882 @see: Python function C{round}.
883 '''
884 if isint(ndigits):
885 p = _10_0**ndigits
886 x = int(x * p) / p
887 return x
890def unroll180(lon1, lon2, wrap=True):
891 '''Unroll longitudinal delta and wrap longitude in degrees.
893 @arg lon1: Start longitude (C{degrees}).
894 @arg lon2: End longitude (C{degrees}).
895 @kwarg wrap: If C{True}, wrap and unroll to the M{(-180..+180]}
896 range (C{bool}).
898 @return: 2-Tuple C{(B{lon2}-B{lon1}, B{lon2})} unrolled (C{degrees},
899 C{degrees}).
901 @see: Capability C{LONG_UNROLL} in U{GeographicLib
902 <https://GeographicLib.SourceForge.io/html/python/interface.html#outmask>}.
903 '''
904 d = lon2 - lon1
905 if wrap and fabs(d) > _180_0:
906 u = _wrap(d, _180_0, _360_0)
907 if u != d:
908 return u, (lon1 + u)
909 return d, lon2
912def _unrollon(p1, p2, wrap=False): # unroll180 == .karney._unroll2
913 '''(INTERNAL) Wrap/normalize, unroll and replace longitude.
914 '''
915 lat, lon = p2.lat, p2.lon
916 if wrap and _Wrap.normal:
917 lat, lon = _Wrap.latlon(lat, lon)
918 _, lon = unroll180(p1.lon, lon, wrap=True)
919 if lat != p2.lat or fabs(lon - p2.lon) > EPS:
920 p2 = p2.dup(lat=lat, lon=wrap180(lon))
921 # p2 = p2.copy(); p2.latlon = lat, wrap180(lon)
922 return p2
925def _unrollon3(p1, p2, p3, wrap=False):
926 '''(INTERNAL) Wrap/normalize, unroll 2 points.
927 '''
928 w = wrap
929 if w:
930 w = _Wrap.normal
931 p2 = _unrollon(p1, p2, wrap=w)
932 p3 = _unrollon(p1, p3, wrap=w)
933 p2 = _unrollon(p2, p3)
934 return p2, p3, w # was wrapped?
937def unrollPI(rad1, rad2, wrap=True):
938 '''Unroll longitudinal delta and wrap longitude in radians.
940 @arg rad1: Start longitude (C{radians}).
941 @arg rad2: End longitude (C{radians}).
942 @kwarg wrap: If C{True}, wrap and unroll to the M{(-PI..+PI]}
943 range (C{bool}).
945 @return: 2-Tuple C{(B{rad2}-B{rad1}, B{rad2})} unrolled
946 (C{radians}, C{radians}).
948 @see: Capability C{LONG_UNROLL} in U{GeographicLib
949 <https://GeographicLib.SourceForge.io/html/python/interface.html#outmask>}.
950 '''
951 r = rad2 - rad1
952 if wrap and fabs(r) > PI:
953 u = _wrap(r, PI, PI2)
954 if u != r:
955 return u, (rad1 + u)
956 return r, rad2
959def _valueError(where, x, **kwds):
960 '''(INTERNAL) Return a C{_ValueError}.
961 '''
962 x = _MODS.streprs.Fmt.PAREN(where.__name__, x)
963 return _ValueError(x, **kwds)
966class _Wrap(object):
968 _normal = False # default
970 @property
971 def normal(self):
972 '''Get the current L{normal} setting (C{True},
973 C{False} or C{None}).
974 '''
975 return self._normal
977 @normal.setter # PYCHOK setter!
978 def normal(self, setting):
979 '''Set L{normal} to C{True}, C{False} or C{None}.
980 '''
981 t = {True: (_MODS.formy.normal, _MODS.formy.normal_),
982 False: (self.wraplatlon, self.wraphilam),
983 None: (_passargs, _passargs)}.get(setting, ())
984 if t:
985 self.latlon, self.philam = t
986 self._normal = setting
988 def latlonDMS2(self, lat, lon, **DMS2_kwds):
989 if isstr(lat) or isstr(lon):
990 kwds = _xkwds(DMS2_kwds, clipLon=0, clipLat=0)
991 lat, lon = _MODS.dms.parseDMS2(lat, lon, **kwds)
992 return self.latlon(lat, lon)
994# def normalatlon(self, *latlon):
995# return _MODS.formy.normal(*latlon)
997# def normalamphi(self, *philam):
998# return _MODS.formy.normal_(*philam)
1000 def wraplatlon(self, lat, lon):
1001 return wrap90(lat), wrap180(lon)
1003 latlon = wraplatlon # default
1005 def latlon3(self, lon1, lat2, lon2, wrap):
1006 if wrap:
1007 lat2, lon2 = self.latlon(lat2, lon2)
1008 lon21, lon2 = unroll180(lon1, lon2)
1009 else:
1010 lon21 = lon2 - lon1
1011 return lon21, lat2, lon2
1013 def _latlonop(self, wrap):
1014 if wrap and self._normal is not None:
1015 return self.latlon
1016 else:
1017 return _passargs
1019 def wraphilam(self, phi, lam):
1020 return wrapPI_2(phi), wrapPI(lam)
1022 philam = wraphilam # default
1024 def philam3(self, lam1, phi2, lam2, wrap):
1025 if wrap:
1026 phi2, lam2 = self.philam(phi2, lam2)
1027 lam21, lam2 = unrollPI(lam1, lam2)
1028 else:
1029 lam21 = lam2 - lam1
1030 return lam21, phi2, lam2
1032 def _philamop(self, wrap):
1033 if wrap and self._normal is not None:
1034 return self.philam
1035 else:
1036 return _passargs
1038 def wraphilam(self, phi, lam):
1039 return wrapPI_2(phi), wrapPI(lam)
1041 def point(self, ll, wrap=True): # in .points._fractional, -.PointsIter.iterate, ...
1042 '''Return C{ll} or a copy, I{normalized} or I{wrap}'d.
1043 '''
1044 if wrap and self._normal is not None:
1045 lat, lon = ll.latlon
1046 if fabs(lon) > 180 or fabs(lat) > 90:
1047 _n = self.latlon
1048 ll = ll.copy(name=_n.__name__)
1049 ll.latlon = _n(lat, lon)
1050 return ll
1052_Wrap = _Wrap() # PYCHOK singleton
1055def _wrap(angle, wrap, modulo):
1056 '''(INTERNAL) Angle wrapper M{((wrap-modulo)..+wrap]}.
1058 @arg angle: Angle (C{degrees}, C{radians} or C{grades}).
1059 @arg wrap: Range (C{degrees}, C{radians} or C{grades}).
1060 @arg modulo: Upper limit (360 C{degrees}, PI2 C{radians} or 400 C{grades}).
1062 @return: The B{C{angle}}, wrapped (C{degrees}, C{radians} or C{grades}).
1063 '''
1064 a = float(angle)
1065 if not (wrap - modulo) <= a < wrap:
1066 # math.fmod(-1.5, 3.14) == -1.5, but -1.5 % 3.14 == 1.64
1067 # math.fmod(-1.5, 360) == -1.5, but -1.5 % 360 == 358.5
1068 a %= modulo
1069 if a > wrap:
1070 a -= modulo
1071 return a
1074def wrap90(deg):
1075 '''Wrap degrees to M{[-270..+90]}.
1077 @arg deg: Angle (C{degrees}).
1079 @return: Degrees, wrapped (C{degrees90}).
1080 '''
1081 return _wrap(deg, _90_0, _360_0)
1084def wrap180(deg):
1085 '''Wrap degrees to M{[-180..+180]}.
1087 @arg deg: Angle (C{degrees}).
1089 @return: Degrees, wrapped (C{degrees180}).
1090 '''
1091 return _wrap(deg, _180_0, _360_0)
1094def wrap360(deg): # see .streprs._umod_360
1095 '''Wrap degrees to M{[0..+360)}.
1097 @arg deg: Angle (C{degrees}).
1099 @return: Degrees, wrapped (C{degrees360}).
1100 '''
1101 return _wrap(deg, _360_0, _360_0)
1104def wrapPI(rad):
1105 '''Wrap radians to M{[-PI..+PI]}.
1107 @arg rad: Angle (C{radians}).
1109 @return: Radians, wrapped (C{radiansPI}).
1110 '''
1111 return _wrap(rad, PI, PI2)
1114def wrapPI2(rad):
1115 '''Wrap radians to M{[0..+2PI)}.
1117 @arg rad: Angle (C{radians}).
1119 @return: Radians, wrapped (C{radiansPI2}).
1120 '''
1121 return _wrap(rad, PI2, PI2)
1124def wrapPI_2(rad):
1125 '''Wrap radians to M{[-3PI/2..+PI/2]}.
1127 @arg rad: Angle (C{radians}).
1129 @return: Radians, wrapped (C{radiansPI_2}).
1130 '''
1131 return _wrap(rad, PI_2, PI2)
1134def wrap_normal(*normal):
1135 '''Define the operation for the keyword argument C{B{wrap}=True},
1136 across L{pygeodesy}: I{wrap}, I{normalize} or I{no-op}. For
1137 backward compatibility, the default is I{wrap}.
1139 @arg normal: If C{True}, I{normalize} lat- and longitude using
1140 L{normal} or L{normal_}, if C{False}, I{wrap} the
1141 lat- and longitude individually by L{wrap90} or
1142 L{wrapPI_2} respectively L{wrap180}, L{wrapPI} or
1143 if C{None}, leave lat- and longitude I{unchanged}.
1144 Do not supply any value to get the current setting.
1146 @return: The previous L{wrap_normal} setting (C{bool} or C{None}).
1147 '''
1148 t = _Wrap.normal
1149 if normal:
1150 _Wrap.normal = normal[0]
1151 return t
1154def yard2m(yards):
1155 '''Convert I{UK} yards to meter.
1157 @arg yards: Value in yards (C{scalar}).
1159 @return: Value in C{meter} (C{float}).
1161 @raise ValueError: Invalid B{C{yards}}.
1162 '''
1163 return Float(yards=yards) * _M_YARD_UK
1165# **) MIT License
1166#
1167# Copyright (C) 2016-2023 -- mrJean1 at Gmail -- All Rights Reserved.
1168#
1169# Permission is hereby granted, free of charge, to any person obtaining a
1170# copy of this software and associated documentation files (the "Software"),
1171# to deal in the Software without restriction, including without limitation
1172# the rights to use, copy, modify, merge, publish, distribute, sublicense,
1173# and/or sell copies of the Software, and to permit persons to whom the
1174# Software is furnished to do so, subject to the following conditions:
1175#
1176# The above copyright notice and this permission notice shall be included
1177# in all copies or substantial portions of the Software.
1178#
1179# THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS
1180# OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
1181# FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL
1182# THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR
1183# OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE,
1184# ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR
1185# OTHER DEALINGS IN THE SOFTWARE.