Coverage for pygeodesy/basics.py: 91%
268 statements
« prev ^ index » next coverage.py v7.6.1, created at 2025-04-09 11:05 -0400
« prev ^ index » next coverage.py v7.6.1, created at 2025-04-09 11:05 -0400
2# -*- coding: utf-8 -*-
4u'''Some, basic definitions, functions and dependencies.
6Use env variable C{PYGEODESY_XPACKAGES} to avoid import of dependencies
7C{geographiclib}, C{numpy} and/or C{scipy}. Set C{PYGEODESY_XPACKAGES}
8to a comma-separated list of package names to be excluded from import.
9'''
10# make sure int/int division yields float quotient
11from __future__ import division
12division = 1 / 2 # .albers, .azimuthal, .constants, etc., .utily
13if not division:
14 raise ImportError('%s 1/2 == %s' % ('division', division))
15del division
17# from pygeodesy.cartesianBase import CartesianBase # _MODS
18# from pygeodesy.constants import isneg0, NEG0 # _MODS
19from pygeodesy.errors import _AttributeError, _ImportError, _NotImplementedError, \
20 _TypeError, _TypesError, _ValueError, _xAssertionError, \
21 _xkwds_get1
22# from pygeodesy.fsums import _isFsum_2Tuple # _MODS
23from pygeodesy.internals import _0_0, _enquote, _getenv, _passarg, _PYGEODESY, \
24 _version_info
25from pygeodesy.interns import MISSING, NN, _1_, _by_, _COMMA_, _DOT_, _DEPRECATED_, \
26 _ELLIPSIS4_, _EQUAL_, _in_, _invalid_, _N_A_, _not_, \
27 _not_scalar_, _odd_, _SPACE_, _UNDER_, _version_
28# from pygeodesy.latlonBase import LatLonBase # _MODS
29from pygeodesy.lazily import _ALL_LAZY, _ALL_MODS as _MODS, LazyImportError
30# from pygeodesy.named import classname, modulename, _name__ # _MODS
31# from pygeodesy.nvectorBase import NvectorBase # _MODS
32# from pygeodesy.props import _update_all # _MODS
33# from pygeodesy.streprs import Fmt # _MODS
35from copy import copy as _copy, deepcopy as _deepcopy
36from math import copysign as _copysign
37# import inspect as _inspect # _MODS
39__all__ = _ALL_LAZY.basics
40__version__ = '25.01.17'
42_below_ = 'below'
43_list_tuple_types = (list, tuple)
44_required_ = 'required'
46try: # Luciano Ramalho, "Fluent Python", O'Reilly, 2016 p. 395, 2022 p. 577+
47 from numbers import Integral as _Ints, Real as _Scalars # .units
48except ImportError:
49 try:
50 _Ints = int, long # int objects (C{tuple})
51 except NameError: # Python 3+
52 _Ints = int, # int objects (C{tuple})
53 _Scalars = (float,) + _Ints
55try:
56 try: # use C{from collections.abc import ...} in Python 3.9+
57 from collections.abc import Sequence as _Sequence # in .points
58 except ImportError: # no .abc in Python 3.8- and 2.7-
59 from collections import Sequence as _Sequence # in .points
60 if isinstance([], _Sequence) and isinstance((), _Sequence):
61 # and isinstance(range(1), _Sequence):
62 _Seqs = _Sequence
63 else:
64 raise ImportError() # _AssertionError
65except ImportError:
66 _Sequence = tuple # immutable for .points._Basequence
67 _Seqs = list, _Sequence # range for function len2 below
69try:
70 _Bytes = unicode, bytearray # PYCHOK in .internals
71 _Strs = basestring, str # XXX str == bytes
72 str2ub = ub2str = _passarg # avoids UnicodeDecodeError
74 def _Xstr(exc): # PYCHOK no cover
75 '''I{Invoke only with caught ImportError} B{C{exc}}.
77 C{... "can't import name _distributor_init" ...}
79 only for C{numpy}, C{scipy} import errors occurring
80 on arm64 Apple Silicon running macOS' Python 2.7.16?
81 '''
82 t = str(exc)
83 if '_distributor_init' in t:
84 from sys import exc_info
85 from traceback import extract_tb
86 tb = exc_info()[2] # 3-tuple (type, value, traceback)
87 t4 = extract_tb(tb, 1)[0] # 4-tuple (file, line, name, 'import ...')
88 t = _SPACE_("can't", t4[3] or _N_A_)
89 del tb, t4
90 return t
92except NameError: # Python 3+
93 from pygeodesy.interns import _utf_8_
95 _Bytes = bytes, bytearray # in .internals
96 _Strs = str, # tuple
97 _Xstr = str
99 def str2ub(sb):
100 '''Convert C{str} to C{unicode bytes}.
101 '''
102 if isinstance(sb, _Strs):
103 sb = sb.encode(_utf_8_)
104 return sb
106 def ub2str(ub):
107 '''Convert C{unicode bytes} to C{str}.
108 '''
109 if isinstance(ub, _Bytes):
110 ub = str(ub.decode(_utf_8_))
111 return ub
114# def _args_kwds_count2(func, exelf=True): # in .formy
115# '''(INTERNAL) Get a C{func}'s args and kwds count as 2-tuple
116# C{(nargs, nkwds)}, including arg C{self} for methods.
117#
118# @kwarg exelf: If C{True}, exclude C{self} in the C{args}
119# of a method (C{bool}).
120# '''
121# i = _MODS.inspect
122# try:
123# a = k = 0
124# for _, p in i.signature(func).parameters.items():
125# if p.kind is p.POSITIONAL_OR_KEYWORD:
126# if p.default is p.empty:
127# a += 1
128# else:
129# k += 1
130# except AttributeError: # Python 2-
131# s = i.getargspec(func)
132# k = len(s.defaults or ())
133# a = len(s.args) - k
134# if exelf and a > 0 and i.ismethod(func):
135# a -= 1
136# return a, k
139def _args_kwds_names(func, splast=False):
140 '''(INTERNAL) Get a C{func}'s args and kwds names, including
141 C{self} for methods.
143 @kwarg splast: If C{True}, split the last keyword argument
144 at UNDERscores (C{bool}).
146 @note: Python 2 may I{not} include the C{*args} nor the
147 C{**kwds} names.
148 '''
149 i = _MODS.inspect
150 try:
151 args_kwds = i.signature(func).parameters.keys()
152 except AttributeError: # Python 2-
153 args_kwds = i.getargspec(func).args
154 if splast and args_kwds: # PYCHOK no cover
155 args_kwds = list(args_kwds)
156 t = args_kwds[-1:]
157 if t:
158 s = t[0].strip(_UNDER_).split(_UNDER_)
159 if len(s) > 1 or s != t:
160 args_kwds += s
161 return tuple(args_kwds)
164def clips(sb, limit=50, white=NN, length=False):
165 '''Clip a string to the given length limit.
167 @arg sb: String (C{str} or C{bytes}).
168 @kwarg limit: Length limit (C{int}).
169 @kwarg white: Optionally, replace all whitespace (C{str}).
170 @kwarg length: If C{True}, append the original I{[length]} (C{bool}).
172 @return: The clipped or unclipped B{C{sb}}.
173 '''
174 T, n = type(sb), len(sb)
175 if n > limit > 8:
176 h = limit // 2
177 sb = T(_ELLIPSIS4_).join((sb[:h], sb[-h:]))
178 if length:
179 n = _MODS.streprs.Fmt.SQUARE(n)
180 sb = T(NN).join((sb, n))
181 if white: # replace whitespace
182 sb = T(white).join(sb.split())
183 return sb
186def copysign0(x, y):
187 '''Like C{math.copysign(x, y)} except C{zero}, I{unsigned}.
189 @return: C{math.copysign(B{x}, B{y})} if B{C{x}} else
190 C{type(B{x})(0)}.
191 '''
192 return _copysign(x, (y if y else 0)) if x else copytype(0, x)
195def copytype(x, y):
196 '''Return the value of B{x} as C{type} of C{y}.
198 @return: C{type(B{y})(B{x})}.
199 '''
200 return type(y)(x if x else _0_0)
203def _enumereverse(iterable):
204 '''(INTERNAL) Reversed C{enumberate}.
205 '''
206 for j in _reverange(len(iterable)):
207 yield j, iterable[j]
210try:
211 from math import gcd as _gcd
212except ImportError: # 3.4-
214 def _gcd(a, b): # PYCHOK redef
215 # <https://WikiPedia.org/wiki/Greatest_common_divisor>
216 a, b = int(a), int(b)
217 if b > a:
218 a, b = b, a
219# if b <= 0:
220# return 1
221 while b:
222 a, b = b, (a % b)
223 return a
226def halfs2(str2):
227 '''Split a string in 2 halfs.
229 @arg str2: String to split (C{str}).
231 @return: 2-Tuple C{(_1st, _2nd)} half (C{str}).
233 @raise ValueError: Zero or odd C{len(B{str2})}.
234 '''
235 h, r = divmod(len(str2), 2)
236 if r or not h:
237 raise _ValueError(str2=str2, txt=_odd_)
238 return str2[:h], str2[h:]
241def _integer_ratio2(x): # PYCHOK no cover
242 '''(INTERNAL) Return C{B{x}.as_interger_ratio()}.
243 '''
244 try: # int.as_integer_ratio in 3.8+
245 return x.as_integer_ratio()
246 except (AttributeError, OverflowError, TypeError, ValueError):
247 return (x if isint(x) else float(x)), 1
250def int1s(x): # PYCHOK no cover
251 '''Count the number of 1-bits in an C{int}, I{unsigned}.
253 @note: C{int1s(-B{x}) == int1s(abs(B{x}))}.
254 '''
255 try:
256 return x.bit_count() # Python 3.10+
257 except AttributeError:
258 # bin(-x) = '-' + bin(abs(x))
259 return bin(x).count(_1_)
262def isbool(obj):
263 '''Is B{C{obj}}ect a C{bool}ean?
265 @arg obj: The object (any C{type}).
267 @return: C{True} if C{bool}ean, C{False} otherwise.
268 '''
269 return isinstance(obj, bool) # and (obj is False
270# or obj is True)
272assert not (isbool(1) or isbool(0) or isbool(None)) # PYCHOK 2
275def isCartesian(obj, ellipsoidal=None):
276 '''Is B{C{obj}}ect some C{Cartesian}?
278 @arg obj: The object (any C{type}).
279 @kwarg ellipsoidal: If C{None}, return the type of any C{Cartesian},
280 if C{True}, only an ellipsoidal C{Cartesian type}
281 or if C{False}, only a spherical C{Cartesian type}.
283 @return: C{type(B{obj}} if a C{Cartesian} of the required type, C{False}
284 if a C{Cartesian} of an other type or {None} otherwise.
285 '''
286 if ellipsoidal is not None:
287 try:
288 return obj.ellipsoidalCartesian if ellipsoidal else obj.sphericalCartesian
289 except AttributeError:
290 return None
291 return isinstanceof(obj, _MODS.cartesianBase.CartesianBase)
294def isclass(obj): # XXX avoid epydoc Python 2.7 error
295 '''Is B{C{obj}}ect a C{Class} or C{type}?
296 '''
297 return _MODS.inspect.isclass(obj)
300def iscomplex(obj, both=False):
301 '''Is B{C{obj}}ect a C{complex} or complex literal C{str}?
303 @arg obj: The object (any C{type}).
304 @kwarg both: If C{True}, check complex C{str} (C{bool}).
306 @return: C{True} if C{complex}, C{False} otherwise.
307 '''
308 try: # hasattr('conjugate', 'real' and 'imag')
309 return isinstance(obj, complex) or bool(both and isstr(obj) and
310 isinstance(complex(obj), complex)) # numbers.Complex?
311 except (TypeError, ValueError):
312 return False
315def isDEPRECATED(obj):
316 '''Is B{C{obj}}ect a C{DEPRECATED} class, method or function?
318 @return: C{True} if C{DEPRECATED}, {False} if not or
319 C{None} if undetermined.
320 '''
321 try: # XXX inspect.getdoc(obj) or obj.__doc__
322 doc = obj.__doc__.lstrip()
323 return bool(doc and doc.startswith(_DEPRECATED_))
324 except AttributeError:
325 return None
328def isfloat(obj, both=False):
329 '''Is B{C{obj}}ect a C{float} or float literal C{str}?
331 @arg obj: The object (any C{type}).
332 @kwarg both: If C{True}, check float C{str} (C{bool}).
334 @return: C{True} if C{float}, C{False} otherwise.
335 '''
336 try:
337 return isinstance(obj, float) or bool(both and
338 isstr(obj) and isinstance(float(obj), float))
339 except (TypeError, ValueError):
340 return False
343try:
344 isidentifier = str.isidentifier # Python 3, must be str
345except AttributeError: # Python 2-
347 def isidentifier(obj):
348 '''Is B{C{obj}}ect a Python identifier?
349 '''
350 return bool(obj and isstr(obj)
351 and obj.replace(_UNDER_, NN).isalnum()
352 and not obj[:1].isdigit())
355def isinstanceof(obj, *Classes):
356 '''Is B{C{obj}}ect an instance of one of the C{Classes}?
358 @arg obj: The object (any C{type}).
359 @arg Classes: One or more classes (C{Class}).
361 @return: C{type(B{obj}} if one of the B{C{Classes}},
362 C{None} otherwise.
363 '''
364 return type(obj) if isinstance(obj, Classes) else None
367def isint(obj, both=False):
368 '''Is B{C{obj}}ect an C{int} or integer C{float} value?
370 @arg obj: The object (any C{type}).
371 @kwarg both: If C{True}, check C{float} and L{Fsum}
372 type and value (C{bool}).
374 @return: C{True} if C{int} or I{integer} C{float}
375 or L{Fsum}, C{False} otherwise.
377 @note: Both C{isint(True)} and C{isint(False)} return
378 C{False} (and no longer C{True}).
379 '''
380 if isinstance(obj, _Ints):
381 return not isbool(obj)
382 elif both: # and isinstance(obj, (float, Fsum))
383 try: # NOT , _Scalars) to include Fsum!
384 return obj.is_integer()
385 except AttributeError:
386 pass # XXX float(int(obj)) == obj?
387 return False
390def isiterable(obj, strict=False):
391 '''Is B{C{obj}}ect C{iterable}?
393 @arg obj: The object (any C{type}).
394 @kwarg strict: If C{True}, check class attributes (C{bool}).
396 @return: C{True} if C{iterable}, C{False} otherwise.
397 '''
398 # <https://PyPI.org/project/isiterable/>
399 return bool(isiterabletype(obj)) if strict else hasattr(obj, '__iter__') # map, range, set
402def isiterablen(obj, strict=False):
403 '''Is B{C{obj}}ect C{iterable} and has C{len}gth?
405 @arg obj: The object (any C{type}).
406 @kwarg strict: If C{True}, check class attributes (C{bool}).
408 @return: C{True} if C{iterable} with C{len}gth, C{False} otherwise.
409 '''
410 _has = isiterabletype if strict else hasattr
411 return bool(_has(obj, '__len__') and _has(obj, '__getitem__'))
414def isiterabletype(obj, method='__iter__'):
415 '''Is B{C{obj}}ect an instance of an C{iterable} class or type?
417 @arg obj: The object (any C{type}).
418 @kwarg method: The name of the required method (C{str}).
420 @return: The C{base-class} if C{iterable}, C{None} otherwise.
421 '''
422 try: # <https://StackOverflow.com/questions/73568964>
423 for b in type(obj).__mro__[:-1]: # ignore C{object}
424 try:
425 if callable(b.__dict__[method]):
426 return b
427 except (AttributeError, KeyError):
428 pass
429 except (AttributeError, TypeError):
430 pass
431 return None
434try:
435 from keyword import iskeyword # Python 2.7+
436except ImportError:
438 def iskeyword(unused):
439 '''Not Implemented, C{False} always.
440 '''
441 return False
444def isLatLon(obj, ellipsoidal=None):
445 '''Is B{C{obj}}ect some C{LatLon}?
447 @arg obj: The object (any C{type}).
448 @kwarg ellipsoidal: If C{None}, return the type of any C{LatLon},
449 if C{True}, only an ellipsoidal C{LatLon type}
450 or if C{False}, only a spherical C{LatLon type}.
452 @return: C{type(B{obj}} if a C{LatLon} of the required type, C{False}
453 if a C{LatLon} of an other type or {None} otherwise.
454 '''
455 if ellipsoidal is not None:
456 try:
457 return obj.ellipsoidalLatLon if ellipsoidal else obj.sphericalLatLon
458 except AttributeError:
459 return None
460 return isinstanceof(obj, _MODS.latlonBase.LatLonBase)
463def islistuple(obj, minum=0):
464 '''Is B{C{obj}}ect a C{list} or C{tuple} with non-zero length?
466 @arg obj: The object (any C{type}).
467 @kwarg minum: Minimal C{len} required C({int}).
469 @return: C{True} if a C{list} or C{tuple} with C{len} at
470 least B{C{minum}}, C{False} otherwise.
471 '''
472 return isinstance(obj, _list_tuple_types) and len(obj) >= minum
475def isNvector(obj, ellipsoidal=None):
476 '''Is B{C{obj}}ect some C{Nvector}?
478 @arg obj: The object (any C{type}).
479 @kwarg ellipsoidal: If C{None}, return the type of any C{Nvector},
480 if C{True}, only an ellipsoidal C{Nvector type}
481 or if C{False}, only a spherical C{Nvector type}.
483 @return: C{type(B{obj}} if an C{Nvector} of the required type, C{False}
484 if an C{Nvector} of an other type or {None} otherwise.
485 '''
486 if ellipsoidal is not None:
487 try:
488 return obj.ellipsoidalNvector if ellipsoidal else obj.sphericalNvector
489 except AttributeError:
490 return None
491 return isinstanceof(obj, _MODS.nvectorBase.NvectorBase)
494def isodd(x):
495 '''Is B{C{x}} odd?
497 @arg x: Value (C{scalar}).
499 @return: C{True} if odd, C{False} otherwise.
500 '''
501 return bool(int(x) & 1) # == bool(int(x) % 2)
504def isscalar(obj, both=False):
505 '''Is B{C{obj}}ect an C{int} or integer C{float} value?
507 @arg obj: The object (any C{type}).
508 @kwarg both: If C{True}, check L{Fsum} and L{Fsum2Tuple}
509 residuals.
511 @return: C{True} if C{int}, C{float} or C{Fsum/-2Tuple}
512 with zero residual, C{False} otherwise.
513 '''
514 if isinstance(obj, _Scalars):
515 return not isbool(obj) # exclude bool
516 elif both and _MODS.fsums._isFsum_2Tuple(obj):
517 return bool(obj.residual == 0)
518 return False
521def issequence(obj, *excls):
522 '''Is B{C{obj}}ect some sequence type?
524 @arg obj: The object (any C{type}).
525 @arg excls: Classes to exclude (C{type}), all positional.
527 @note: Excluding C{tuple} implies excluding C{namedtuple}.
529 @return: C{True} if a sequence, C{False} otherwise.
530 '''
531 return isinstance(obj, _Seqs) and not (excls and isinstance(obj, excls))
534def isstr(obj):
535 '''Is B{C{obj}}ect some string type?
537 @arg obj: The object (any C{type}).
539 @return: C{True} if a C{str}, C{bytes}, ...,
540 C{False} otherwise.
541 '''
542 return isinstance(obj, _Strs)
545def issubclassof(Sub, *Supers):
546 '''Is B{C{Sub}} a class and sub-class of some other class(es)?
548 @arg Sub: The sub-class (C{Class}).
549 @arg Supers: One or more C(super) classes (C{Class}).
551 @return: C{True} if a sub-class of any B{C{Supers}}, C{False}
552 if not (C{bool}) or C{None} if not a class or if no
553 B{C{Supers}} are given or none of those are a class.
554 '''
555 if isclass(Sub):
556 t = tuple(S for S in Supers if isclass(S))
557 if t:
558 return bool(issubclass(Sub, t)) # built-in
559 return None
562def itemsorted(adict, *items_args, **asorted_reverse):
563 '''Return the items of C{B{adict}} sorted I{alphabetically,
564 case-insensitively} and in I{ascending} order.
566 @arg items_args: Optional positional argument(s) for method
567 C{B{adict}.items(B*{items_args})}.
568 @kwarg asorted_reverse: Use C{B{asorted}=False} for I{alphabetical,
569 case-sensitive} sorting and C{B{reverse}=True} for
570 sorting in C{descending} order.
571 '''
572 def _ins(item): # functools.cmp_to_key
573 k, v = item
574 return k.lower()
576 def _reverse_key(asorted=True, reverse=False):
577 return dict(reverse=reverse, key=_ins if asorted else None)
579 items = adict.items(*items_args) if items_args else adict.items()
580 return sorted(items, **_reverse_key(**asorted_reverse))
583def len2(items):
584 '''Make built-in function L{len} work for generators, iterators,
585 etc. since those can only be started exactly once.
587 @arg items: Generator, iterator, list, range, tuple, etc.
589 @return: 2-Tuple C{(n, items)} of the number of items (C{int})
590 and the items (C{list} or C{tuple}).
591 '''
592 if not isinstance(items, _Seqs): # NOT hasattr(items, '__len__'):
593 items = list(items)
594 return len(items), items
597def map1(fun1, *xs): # XXX map_
598 '''Call a single-argument function to each B{C{xs}}
599 and return a C{tuple} of results.
601 @arg fun1: 1-Arg function (C{callable}).
602 @arg xs: Arguments (C{any positional}).
604 @return: Function results (C{tuple}).
605 '''
606 return tuple(map(fun1, xs))
609def map2(fun, *xs, **strict):
610 '''Like Python's B{C{map}} but returning a C{tuple} of results.
612 Unlike Python 2's built-in L{map}, Python 3+ L{map} returns a
613 L{map} object, an iterator-like object which generates the
614 results only once. Converting the L{map} object to a tuple
615 maintains the Python 2 behavior.
617 @arg fun: Function (C{callable}).
618 @arg xs: Arguments (C{all positional}).
619 @kwarg strict: See U{Python 3.14+ map<https://docs.Python.org/
620 3.14/library/functions.html#map>} (C{bool}).
622 @return: Function results (C{tuple}).
623 '''
624 return tuple(map(fun, *xs, **strict) if strict else map(fun, *xs))
627def max2(*xs):
628 '''Return 2-tuple C{(max(xs), xs.index(max(xs)))}.
629 '''
630 return _max2min2(xs, max, max2)
633def _max2min2(xs, _m, _m2):
634 '''(INTERNAL) Helper for C{max2} and C{min2}.
635 '''
636 if len(xs) == 1:
637 x = xs[0]
638 if isiterable(x) or isiterablen(x):
639 x, i = _m2(*x)
640 else:
641 i = 0
642 else:
643 x = _m(xs) # max or min
644 i = xs.index(x)
645 return x, i
648def min2(*xs):
649 '''Return 2-tuple C{(min(xs), xs.index(min(xs)))}.
650 '''
651 return _max2min2(xs, min, min2)
654def neg(x, neg0=None):
655 '''Negate C{x} and optionally, negate C{0.0} and C{-0.0}.
657 @kwarg neg0: Defines the return value for zero C{B{x}}: if C{None}
658 return C{0.0}, if C{True} return C{NEG0 if B{x}=0.0}
659 and C{0.0 if B{x}=NEG0} or if C{False} return C{B{x}}
660 I{as-is} (C{bool} or C{None}).
662 @return: C{-B{x} if B{x} else 0.0, NEG0 or B{x}}.
663 '''
664 return (-x) if x else (
665 _0_0 if neg0 is None else (
666 x if not neg0 else (
667 _0_0 if signBit(x) else _MODS.constants.
668 NEG0))) # PYCHOK indent
671def neg_(*xs):
672 '''Negate all C{xs} with L{neg}.
674 @return: A C{map(neg, B{xs})}.
675 '''
676 return map(neg, xs)
679def _neg0(x):
680 '''(INTERNAL) Return C{NEG0 if x < 0 else _0_0},
681 unlike C{_copysign_0_0} which returns C{_N_0_0}.
682 '''
683 return _MODS.constants.NEG0 if x < 0 else _0_0
686def _req_d_by(where, **name):
687 '''(INTERNAL) Get the fully qualified name.
688 '''
689 m = _MODS.named
690 n = m._name__(**name)
691 m = m.modulename(where, prefixed=True)
692 if n:
693 m = _DOT_(m, n)
694 return _SPACE_(_required_, _by_, m)
697def _reverange(n, stop=-1, step=-1):
698 '''(INTERNAL) Reversed range yielding C{n-1, n-1-step, ..., stop+1}.
699 '''
700 return range(n - 1, stop, step)
703def signBit(x):
704 '''Return C{signbit(B{x})}, like C++.
706 @return: C{True} if C{B{x} < 0} or C{NEG0} (C{bool}).
707 '''
708 return x < 0 or _MODS.constants.isneg0(x)
711def _signOf(x, ref): # in .fsums
712 '''(INTERNAL) Return the sign of B{C{x}} versus B{C{ref}}.
713 '''
714 return (-1) if x < ref else (+1 if x > ref else 0)
717def signOf(x):
718 '''Return sign of C{x} as C{int}.
720 @return: -1, 0 or +1 (C{int}).
721 '''
722 try:
723 s = x.signOf() # Fsum instance?
724 except AttributeError:
725 s = _signOf(x, 0)
726 return s
729def splice(iterable, n=2, **fill):
730 '''Split an iterable into C{n} slices.
732 @arg iterable: Items to be spliced (C{list}, C{tuple}, ...).
733 @kwarg n: Number of slices to generate (C{int}).
734 @kwarg fill: Optional fill value for missing items.
736 @return: A generator for each of B{C{n}} slices,
737 M{iterable[i::n] for i=0..n}.
739 @raise TypeError: Invalid B{C{n}}.
741 @note: Each generated slice is a C{tuple} or a C{list},
742 the latter only if the B{C{iterable}} is a C{list}.
744 @example:
746 >>> from pygeodesy import splice
748 >>> a, b = splice(range(10))
749 >>> a, b
750 ((0, 2, 4, 6, 8), (1, 3, 5, 7, 9))
752 >>> a, b, c = splice(range(10), n=3)
753 >>> a, b, c
754 ((0, 3, 6, 9), (1, 4, 7), (2, 5, 8))
756 >>> a, b, c = splice(range(10), n=3, fill=-1)
757 >>> a, b, c
758 ((0, 3, 6, 9), (1, 4, 7, -1), (2, 5, 8, -1))
760 >>> tuple(splice(list(range(9)), n=5))
761 ([0, 5], [1, 6], [2, 7], [3, 8], [4])
763 >>> splice(range(9), n=1)
764 <generator object splice at 0x0...>
765 '''
766 if not isint(n):
767 raise _TypeError(n=n)
769 t = _xiterablen(iterable)
770 if not isinstance(t, _list_tuple_types):
771 t = tuple(t)
773 if n > 1:
774 if fill:
775 fill = _xkwds_get1(fill, fill=MISSING)
776 if fill is not MISSING:
777 m = len(t) % n
778 if m > 0: # same type fill
779 t = t + type(t)((fill,) * (n - m))
780 for i in range(n):
781 # XXX t[i::n] chokes PyChecker
782 yield t[slice(i, None, n)]
783 else:
784 yield t # 1 slice, all
787def _splituple(strs, *sep_splits): # in .mgrs, ...
788 '''(INTERNAL) Split a C{comma}- or C{whitespace}-separated
789 string into a C{tuple} of stripped C{str}ings.
790 '''
791 if sep_splits:
792 t = (t.strip() for t in strs.split(*sep_splits))
793 else:
794 t = strs.strip()
795 if t:
796 t = t.replace(_COMMA_, _SPACE_).split()
797 return tuple(t) if t else ()
800def unsigned0(x):
801 '''Unsign if C{0.0}.
803 @return: C{B{x}} if B{C{x}} else C{0.0}.
804 '''
805 return x if x else _0_0
808def _xcopy(obj, deep=False):
809 '''(INTERNAL) Copy an object, shallow or deep.
811 @arg obj: The object to copy (any C{type}).
812 @kwarg deep: If C{True}, make a deep, otherwise
813 a shallow copy (C{bool}).
815 @return: The copy of B{C{obj}}.
816 '''
817 return _deepcopy(obj) if deep else _copy(obj)
820def _xcoverage(where, *required): # in .__main__ # PYCHOK no cover
821 '''(INTERNAL) Import C{coverage} and check required version.
822 '''
823 try:
824 _xpackages(_xcoverage)
825 import coverage
826 except ImportError as x:
827 raise _xImportError(x, where)
828 return _xversion(coverage, where, *required)
831def _xdup(obj, deep=False, **items):
832 '''(INTERNAL) Duplicate an object, replacing some attributes.
834 @arg obj: The object to copy (any C{type}).
835 @kwarg deep: If C{True}, copy deep, otherwise shallow (C{bool}).
836 @kwarg items: Attributes to be changed (C{any}).
838 @return: A duplicate of B{C{obj}} with modified
839 attributes, if any B{C{items}}.
841 @raise AttributeError: Some B{C{items}} invalid.
842 '''
843 d = _xcopy(obj, deep=deep)
844 for n, v in items.items():
845 if getattr(d, n, v) != v:
846 setattr(d, n, v)
847 elif not hasattr(d, n):
848 t = _MODS.named.classname(obj)
849 t = _SPACE_(_DOT_(t, n), _invalid_)
850 raise _AttributeError(txt=t, obj=obj, **items)
851# if items:
852# _MODS.props._update_all(d)
853 return d
856def _xgeographiclib(where, *required):
857 '''(INTERNAL) Import C{geographiclib} and check required version.
858 '''
859 try:
860 _xpackages(_xgeographiclib)
861 import geographiclib
862 except ImportError as x:
863 raise _xImportError(x, where, Error=LazyImportError)
864 return _xversion(geographiclib, where, *required)
867def _xImportError(exc, where, Error=_ImportError, **name):
868 '''(INTERNAL) Embellish an C{Lazy/ImportError}.
869 '''
870 t = _req_d_by(where, **name)
871 return Error(_Xstr(exc), txt=t, cause=exc)
874def _xinstanceof(*Types, **names_values):
875 '''(INTERNAL) Check C{Types} of all C{name=value} pairs.
877 @arg Types: One or more classes or types (C{class}), all
878 positional.
879 @kwarg names_values: One or more C{B{name}=value} pairs
880 with the C{value} to be checked.
882 @raise TypeError: One B{C{names_values}} pair is not an
883 instance of any of the B{C{Types}}.
884 '''
885 if not (Types and names_values):
886 raise _xAssertionError(_xinstanceof, *Types, **names_values)
888 for n, v in names_values.items():
889 if not isinstance(v, Types):
890 raise _TypesError(n, v, *Types)
893def _xiterable(obj):
894 '''(INTERNAL) Return C{obj} if iterable, otherwise raise C{TypeError}.
895 '''
896 return obj if isiterable(obj) else _xiterror(obj, _xiterable) # PYCHOK None
899def _xiterablen(obj):
900 '''(INTERNAL) Return C{obj} if iterable with C{__len__}, otherwise raise C{TypeError}.
901 '''
902 return obj if isiterablen(obj) else _xiterror(obj, _xiterablen) # PYCHOK None
905def _xiterror(obj, _xwhich):
906 '''(INTERNAL) Helper for C{_xinterable} and C{_xiterablen}.
907 '''
908 t = _not_(_xwhich.__name__[2:]) # _DUNDER_nameof
909 raise _TypeError(repr(obj), txt=t)
912def _xnumpy(where, *required):
913 '''(INTERNAL) Import C{numpy} and check required version.
914 '''
915 try:
916 _xpackages(_xnumpy)
917 import numpy
918 except ImportError as x:
919 raise _xImportError(x, where)
920 return _xversion(numpy, where, *required)
923def _xor(x, *xs):
924 '''(INTERNAL) Exclusive-or C{x} and C{xs}.
925 '''
926 for x_ in xs:
927 x ^= x_
928 return x
931def _xpackages(_xpkgf):
932 '''(INTERNAL) Check dependency to be excluded.
933 '''
934 if _XPACKAGES: # PYCHOK no cover
935 n = _xpkgf.__name__[2:] # _DUNDER_nameof, less '_x'
936 if n.lower() in _XPACKAGES:
937 E = _PYGEODESY(_xpackages)
938 x = _SPACE_(n, _in_, E)
939 e = _enquote(_getenv(E, NN))
940 raise ImportError(_EQUAL_(x, e))
943def _xscalar(**names_values):
944 '''(INTERNAL) Check all C{name=value} pairs to be C{scalar}.
945 '''
946 for n, v in names_values.items():
947 if not isscalar(v):
948 raise _TypeError(n, v, txt=_not_scalar_)
951def _xscipy(where, *required):
952 '''(INTERNAL) Import C{scipy} and check required version.
953 '''
954 try:
955 _xpackages(_xscipy)
956 import scipy
957 except ImportError as x:
958 raise _xImportError(x, where)
959 return _xversion(scipy, where, *required)
962def _xsubclassof(*Classes, **names_values):
963 '''(INTERNAL) Check (super) class of all C{name=value} pairs.
965 @arg Classes: One or more classes or types (C{class}), all
966 positional.
967 @kwarg names_values: One or more C{B{name}=value} pairs
968 with the C{value} to be checked.
970 @raise TypeError: One B{C{names_values}} pair is not a
971 (sub-)class of any of the B{C{Classes}}.
972 '''
973 if not (Classes and names_values):
974 raise _xAssertionError(_xsubclassof, *Classes, **names_values)
976 for n, v in names_values.items():
977 if not issubclassof(v, *Classes):
978 raise _TypesError(n, v, *Classes)
981def _xversion(package, where, *required, **name):
982 '''(INTERNAL) Check the C{package} version vs B{C{required}}.
983 '''
984 if required:
985 t = _version_info(package)
986 if t[:len(required)] < required:
987 t = _SPACE_(package.__name__, # _DUNDER_nameof
988 _version_, _DOT_(*t),
989 _below_, _DOT_(*required),
990 _req_d_by(where, **name))
991 raise ImportError(t)
992 return package
995def _xzip(*args, **strict): # PYCHOK no cover
996 '''(INTERNAL) Standard C{zip(..., strict=True)}.
997 '''
998 s = _xkwds_get1(strict, strict=True)
999 if s:
1000 if _zip is zip: # < (3, 10)
1001 t = _MODS.streprs.unstr(_xzip, *args, strict=s)
1002 raise _NotImplementedError(t, txt=None)
1003 return _zip(*args)
1004 return zip(*args)
1007if _MODS.sys_version_info2 < (3, 10): # see .errors
1008 _zip = zip # PYCHOK exported
1009else: # Python 3.10+
1011 def _zip(*args):
1012 return zip(*args, strict=True)
1014_XPACKAGES = _splituple(_getenv(_PYGEODESY(_xpackages), NN).lower()) # test/bases._X_OK
1016# **) MIT License
1017#
1018# Copyright (C) 2016-2025 -- mrJean1 at Gmail -- All Rights Reserved.
1019#
1020# Permission is hereby granted, free of charge, to any person obtaining a
1021# copy of this software and associated documentation files (the "Software"),
1022# to deal in the Software without restriction, including without limitation
1023# the rights to use, copy, modify, merge, publish, distribute, sublicense,
1024# and/or sell copies of the Software, and to permit persons to whom the
1025# Software is furnished to do so, subject to the following conditions:
1026#
1027# The above copyright notice and this permission notice shall be included
1028# in all copies or substantial portions of the Software.
1029#
1030# THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS
1031# OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
1032# FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL
1033# THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR
1034# OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE,
1035# ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR
1036# OTHER DEALINGS IN THE SOFTWARE.