Coverage for pygeodesy/basics.py: 90%
215 statements
« prev ^ index » next coverage.py v7.2.2, created at 2023-06-07 08:37 -0400
« prev ^ index » next coverage.py v7.2.2, created at 2023-06-07 08:37 -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
17from pygeodesy.errors import _AssertionError, _AttributeError, _ImportError, \
18 _TypeError, _TypesError, _ValueError, _xkwds_get
19from pygeodesy.interns import MISSING, NN, _by_, _DOT_, _ELLIPSIS4_, _enquote, \
20 _EQUAL_, _in_, _invalid_, _N_A_, _SPACE_, \
21 _splituple, _UNDER_, _version_ # _utf_8_
22from pygeodesy.lazily import _ALL_LAZY, _ALL_MODS as _MODS, _FOR_DOCS, \
23 _getenv, _sys, _sys_version_info2
25from copy import copy as _copy, deepcopy as _deepcopy
26from math import copysign as _copysign
27import inspect as _inspect
29__all__ = _ALL_LAZY.basics
30__version__ = '23.05.31'
32_0_0 = 0.0 # in .constants
33_below_ = 'below'
34_cannot_ = 'cannot'
35_list_tuple_types = (list, tuple)
36_list_tuple_set_types = (list, tuple, set)
37_odd_ = 'odd'
38_required_ = 'required'
39_PYGEODESY_XPACKAGES_ = 'PYGEODESY_XPACKAGES'
40_XPACKAGES = _splituple(_getenv(_PYGEODESY_XPACKAGES_, NN))
42try: # Luciano Ramalho, "Fluent Python", page 395, O'Reilly, 2016
43 from numbers import Integral as _Ints, Real as _Scalars
44except ImportError:
45 try:
46 _Ints = int, long # int objects (C{tuple})
47 except NameError: # Python 3+
48 _Ints = int, # int objects (C{tuple})
49 _Scalars = _Ints + (float,)
51try:
52 try: # use C{from collections.abc import ...} in Python 3.9+
53 from collections.abc import Sequence as _Sequence # in .points
54 except ImportError: # no .abc in Python 3.8- and 2.7-
55 from collections import Sequence as _Sequence # in .points
56 if isinstance([], _Sequence) and isinstance((), _Sequence):
57 # and isinstance(range(1), _Sequence):
58 _Seqs = _Sequence
59 else:
60 raise ImportError # _AssertionError
61except ImportError:
62 _Sequence = tuple # immutable for .points._Basequence
63 _Seqs = list, _Sequence # , range for function len2 below
65try:
66 _Bytes = unicode, bytearray # PYCHOK expected
67 _Strs = basestring, str # XXX , bytes
69 def _NOP(x):
70 '''NOP, pass thru.'''
71 return x
73 str2ub = ub2str = _NOP # avoids UnicodeDecodeError
75 def _Xstr(exc): # PYCHOK no cover
76 '''I{Invoke only with caught ImportError} B{C{exc}}.
78 C{... "cannot import name _distributor_init" ...}
80 only for C{numpy}, C{scipy} import errors occurring
81 on arm64 Apple Silicon running macOS' Python 2.7.16?
82 '''
83 t = str(exc)
84 if '_distributor_init' in t:
85 from sys import exc_info
86 from traceback import extract_tb
87 tb = exc_info()[2] # 3-tuple (type, value, traceback)
88 t4 = extract_tb(tb, 1)[0] # 4-tuple (file, line, name, 'import ...')
89 t = _SPACE_(_cannot_, t4[3] or _N_A_)
90 del tb, t4
91 return t
93except NameError: # Python 3+
94 from pygeodesy.interns import _utf_8_
96 _Bytes = bytes, bytearray
97 _Strs = str, # tuple
98 _Xstr = str
100 def str2ub(sb):
101 '''Convert C{str} to C{unicode bytes}.
102 '''
103 if isinstance(sb, _Strs):
104 sb = sb.encode(_utf_8_)
105 return sb
107 def ub2str(ub):
108 '''Convert C{unicode bytes} to C{str}.
109 '''
110 if isinstance(ub, _Bytes):
111 ub = str(ub.decode(_utf_8_))
112 return ub
115def clips(sb, limit=50, white=NN):
116 '''Clip a string to the given length limit.
118 @arg sb: String (C{str} or C{bytes}).
119 @kwarg limit: Length limit (C{int}).
120 @kwarg white: Optionally, replace all whitespace (C{str}).
122 @return: The clipped or unclipped B{C{sb}}.
123 '''
124 T = type(sb)
125 if len(sb) > limit > 8:
126 h = limit // 2
127 sb = T(_ELLIPSIS4_).join((sb[:h], sb[-h:]))
128 if white: # replace whitespace
129 sb = T(white).join(sb.split())
130 return sb
133def copysign0(x, y):
134 '''Like C{math.copysign(x, y)} except C{zero}, I{unsigned}.
136 @return: C{math.copysign(B{x}, B{y})} if B{C{x}} else
137 C{type(B{x})(0)}.
138 '''
139 return _copysign(x, (y if y else 0)) if x else copytype(0, x)
142def copytype(x, y):
143 '''Return the value of B{x} as C{type} of C{y}.
145 @return: C{type(B{y})(B{x})}.
146 '''
147 return type(y)(x if x else _0_0)
150def halfs2(str2):
151 '''Split a string in 2 halfs.
153 @arg str2: String to split (C{str}).
155 @return: 2-Tuple C{(_1st, _2nd)} half (C{str}).
157 @raise ValueError: Zero or odd C{len(B{str2})}.
158 '''
159 h, r = divmod(len(str2), 2)
160 if r or not h:
161 raise _ValueError(str2=str2, txt=_odd_)
162 return str2[:h], str2[h:]
165def isbool(obj):
166 '''Check whether an object is C{bool}ean.
168 @arg obj: The object (any C{type}).
170 @return: C{True} if B{C{obj}} is C{bool}ean,
171 C{False} otherwise.
172 '''
173 return isinstance(obj, bool) # and (obj is False
174# or obj is True)
176if isbool(1) or isbool(0): # PYCHOK assert
177 raise _AssertionError(isbool=1)
179if _FOR_DOCS: # XXX avoid epidoc Python 2.7 error
181 def isclass(obj):
182 '''Return C{True} if B{C{obj}} is a C{class} or C{type}.
184 @see: Python's C{inspect.isclass}.
185 '''
186 return _inspect.isclass(obj)
187else:
188 isclass = _inspect.isclass
191def iscomplex(obj):
192 '''Check whether an object is a C{complex} or complex C{str}.
194 @arg obj: The object (any C{type}).
196 @return: C{True} if B{C{obj}} is C{complex}, otherwise
197 C{False}.
198 '''
199 try: # hasattr('conjugate'), hasattr('real') and hasattr('imag')
200 return isinstance(obj, complex) or (isstr(obj)
201 and isinstance(complex(obj), complex)) # numbers.Complex?
202 except (TypeError, ValueError):
203 return False
206def isfloat(obj):
207 '''Check whether an object is a C{float} or float C{str}.
209 @arg obj: The object (any C{type}).
211 @return: C{True} if B{C{obj}} is a C{float}, otherwise
212 C{False}.
213 '''
214 try:
215 return isinstance( obj, float) or (isstr(obj)
216 and isinstance(float(obj), float))
217 except (TypeError, ValueError):
218 return False
221try:
222 isidentifier = str.isidentifier # Python 3, must be str
223except AttributeError: # Python 2-
225 def isidentifier(obj):
226 '''Return C{True} if B{C{obj}} is a Python identifier.
227 '''
228 return bool(obj and isstr(obj)
229 and obj.replace(_UNDER_, NN).isalnum()
230 and not obj[:1].isdigit())
233def isinstanceof(obj, *classes):
234 '''Check an instance of one or several C{classes}.
236 @arg obj: The instance (C{any}).
237 @arg classes: One or more classes (C{class}).
239 @return: C{True} if B{C{obj}} is in instance of
240 one of the B{C{classes}}.
241 '''
242 return isinstance(obj, classes)
245def isint(obj, both=False):
246 '''Check for C{int} type or an integer C{float} value.
248 @arg obj: The object (any C{type}).
249 @kwarg both: If C{true}, check C{float} and L{Fsum}
250 type and value (C{bool}).
252 @return: C{True} if B{C{obj}} is C{int} or I{integer}
253 C{float} or L{Fsum}, C{False} otherwise.
255 @note: Both C{isint(True)} and C{isint(False)} return
256 C{False} (and no longer C{True}).
257 '''
258 if isinstance(obj, _Ints) and not isbool(obj):
259 return True
260 elif both: # and isinstance(obj, (float, Fsum))
261 try: # NOT , _Scalars) to include Fsum!
262 return obj.is_integer()
263 except AttributeError:
264 pass # XXX float(int(obj)) == obj?
265 return False
268try:
269 from keyword import iskeyword # Python 2.7+
270except ImportError:
272 def iskeyword(unused):
273 '''Not Implemented, C{False} always.
274 '''
275 return False
278def islistuple(obj, minum=0):
279 '''Check for list or tuple C{type} with a minumal length.
281 @arg obj: The object (any C{type}).
282 @kwarg minum: Minimal C{len} required C({int}).
284 @return: C{True} if B{C{obj}} is C{list} or C{tuple} with
285 C{len} at least B{C{minum}}, C{False} otherwise.
286 '''
287 return type(obj) in _list_tuple_types and len(obj) >= (minum or 0)
290def isodd(x):
291 '''Is B{C{x}} odd?
293 @arg x: Value (C{scalar}).
295 @return: C{True} if B{C{x}} is odd,
296 C{False} otherwise.
297 '''
298 return bool(int(x) & 1) # == bool(int(x) % 2)
301def isscalar(obj):
302 '''Check for scalar types.
304 @arg obj: The object (any C{type}).
306 @return: C{True} if B{C{obj}} is C{scalar}, C{False} otherwise.
307 '''
308 return isinstance(obj, _Scalars) and not isbool(obj)
311def issequence(obj, *excls):
312 '''Check for sequence types.
314 @arg obj: The object (any C{type}).
315 @arg excls: Classes to exclude (C{type}), all positional.
317 @note: Excluding C{tuple} implies excluding C{namedtuple}.
319 @return: C{True} if B{C{obj}} is a sequence, C{False} otherwise.
320 '''
321 return isinstance(obj, _Seqs) and not (excls and isinstance(obj, excls))
324def isstr(obj):
325 '''Check for string types.
327 @arg obj: The object (any C{type}).
329 @return: C{True} if B{C{obj}} is C{str}, C{False} otherwise.
330 '''
331 return isinstance(obj, _Strs)
334def issubclassof(Sub, *Supers):
335 '''Check whether a class is a sub-class of some other class(es).
337 @arg Sub: The sub-class (C{class}).
338 @arg Supers: One or more C(super) classes (C{class}).
340 @return: C{True} if B{C{Sub}} is a sub-class of any B{C{Supers}},
341 C{False} if not (C{bool}) or C{None} if B{C{Sub}} is not
342 a class or if no B{C{Supers}} are given or none of those
343 are a class.
344 '''
345 if isclass(Sub):
346 t = tuple(S for S in Supers if isclass(S))
347 if t:
348 return bool(issubclass(Sub, t))
349 return None
352def len2(items):
353 '''Make built-in function L{len} work for generators, iterators,
354 etc. since those can only be started exactly once.
356 @arg items: Generator, iterator, list, range, tuple, etc.
358 @return: 2-Tuple C{(n, items)} of the number of items (C{int})
359 and the items (C{list} or C{tuple}).
360 '''
361 if not isinstance(items, _Seqs): # NOT hasattr(items, '__len__'):
362 items = list(items)
363 return len(items), items
366def map1(fun1, *xs): # XXX map_
367 '''Apply each B{C{xs}} to a single-argument function and
368 return a C{tuple} of results.
370 @arg fun1: 1-Arg function to apply (C{callable}).
371 @arg xs: Arguments to apply (C{any positional}).
373 @return: Function results (C{tuple}).
374 '''
375 return tuple(map(fun1, xs))
378def map2(func, *xs):
379 '''Apply arguments to a function and return a C{tuple} of results.
381 Unlike Python 2's built-in L{map}, Python 3+ L{map} returns a
382 L{map} object, an iterator-like object which generates the
383 results only once. Converting the L{map} object to a tuple
384 maintains the Python 2 behavior.
386 @arg func: Function to apply (C{callable}).
387 @arg xs: Arguments to apply (C{list, tuple, ...}).
389 @return: Function results (C{tuple}).
390 '''
391 return tuple(map(func, *xs))
394def neg(x):
395 '''Negate C{x} unless C{zero} or C{NEG0}.
397 @return: C{-B{x}} if B{C{x}} else C{0.0}.
398 '''
399 return (-x) if x else _0_0
402def neg_(*xs):
403 '''Negate all C{xs} with L{neg}.
405 @return: A C{map(neg, B{xs})}.
406 '''
407 return map(neg, xs)
410def signBit(x):
411 '''Return C{signbit(B{x})}, like C++.
413 @return: C{True} if C{B{x} < 0} or C{NEG0} (C{bool}).
414 '''
415 return x < 0 or _MODS.constants.isneg0(x)
418def _signOf(x, ref): # in .fsums
419 '''(INTERNAL) Return the sign of B{C{x}} versus B{C{ref}}.
420 '''
421 return +1 if x > ref else (-1 if x < ref else 0)
424def signOf(x):
425 '''Return sign of C{x} as C{int}.
427 @return: -1, 0 or +1 (C{int}).
428 '''
429 try:
430 s = x.signOf() # Fsum instance?
431 except AttributeError:
432 s = _signOf(x, 0)
433 return s
436def _sizeof(inst):
437 '''(INTERNAL) Recursively size an C{inst}ance.
439 @return: Instance' size in bytes (C{int}),
440 ignoring class attributes and
441 counting duplicates only once.
442 '''
443 _zB = _sys.getsizeof
444 _zD = _zB(None) # some default
446 def _zR(s, iterable):
447 z, _s = 0, s.add
448 for o in iterable:
449 i = id(o)
450 if i not in s:
451 _s(i)
452 z += _zB(o, _zD)
453 if isinstance(o, dict):
454 z += _zR(s, o.keys())
455 z += _zR(s, o.values())
456 elif isinstance(o, _list_tuple_set_types):
457 z += _zR(s, o)
458 else:
459 try: # size instance' attr values only
460 z += _zR(s, o.__dict__.values())
461 except AttributeError: # None, int, etc.
462 pass
463 return z
465 return _zR(set(), (inst,))
468def splice(iterable, n=2, **fill):
469 '''Split an iterable into C{n} slices.
471 @arg iterable: Items to be spliced (C{list}, C{tuple}, ...).
472 @kwarg n: Number of slices to generate (C{int}).
473 @kwarg fill: Optional fill value for missing items.
475 @return: A generator for each of B{C{n}} slices,
476 M{iterable[i::n] for i=0..n}.
478 @raise TypeError: Invalid B{C{n}}.
480 @note: Each generated slice is a C{tuple} or a C{list},
481 the latter only if the B{C{iterable}} is a C{list}.
483 @example:
485 >>> from pygeodesy import splice
487 >>> a, b = splice(range(10))
488 >>> a, b
489 ((0, 2, 4, 6, 8), (1, 3, 5, 7, 9))
491 >>> a, b, c = splice(range(10), n=3)
492 >>> a, b, c
493 ((0, 3, 6, 9), (1, 4, 7), (2, 5, 8))
495 >>> a, b, c = splice(range(10), n=3, fill=-1)
496 >>> a, b, c
497 ((0, 3, 6, 9), (1, 4, 7, -1), (2, 5, 8, -1))
499 >>> tuple(splice(list(range(9)), n=5))
500 ([0, 5], [1, 6], [2, 7], [3, 8], [4])
502 >>> splice(range(9), n=1)
503 <generator object splice at 0x0...>
504 '''
505 if not isint(n):
506 raise _TypeError(n=n)
508 t = iterable
509 if not isinstance(t, _list_tuple_types):
510 t = tuple(t) # force tuple, also for PyPy3
512 if n > 1:
513 if fill:
514 fill = _xkwds_get(fill, fill=MISSING)
515 if fill is not MISSING:
516 m = len(t) % n
517 if m > 0: # same type fill
518 t += type(t)((fill,) * (n - m))
519 for i in range(n):
520 # XXX t[i::n] chokes PyChecker
521 yield t[slice(i, None, n)]
522 else:
523 yield t
526def unsigned0(x):
527 '''Unsign if C{0.0}.
529 @return: C{B{x}} if B{C{x}} else C{0.0}.
530 '''
531 return x if x else _0_0
534def _xargs_names(callabl):
535 '''(INTERNAL) Get the C{callabl}'s args names.
536 '''
537 try:
538 args_kwds = _inspect.signature(callabl).parameters.keys()
539 except AttributeError: # .signature new Python 3+
540 args_kwds = _inspect.getargspec(callabl).args
541 return tuple(args_kwds)
544def _xcopy(inst, deep=False):
545 '''(INTERNAL) Copy an object, shallow or deep.
547 @arg inst: The object to copy (any C{type}).
548 @kwarg deep: If C{True} make a deep, otherwise
549 a shallow copy (C{bool}).
551 @return: The copy of B{C{inst}}.
552 '''
553 return _deepcopy(inst) if deep else _copy(inst)
556def _xdup(inst, **items):
557 '''(INTERNAL) Duplicate an object, replacing some attributes.
559 @arg inst: The object to copy (any C{type}).
560 @kwarg items: Attributes to be changed (C{any}).
562 @return: Shallow duplicate of B{C{inst}} with modified
563 attributes, if any B{C{items}}.
565 @raise AttributeError: Some B{C{items}} invalid.
566 '''
567 d = _xcopy(inst, deep=False)
568 for n, v in items.items():
569 if not hasattr(d, n):
570 t = _MODS.named.classname(inst)
571 t = _SPACE_(_DOT_(t, n), _invalid_)
572 raise _AttributeError(txt=t, this=inst, **items)
573 setattr(d, n, v)
574 return d
577def _xgeographiclib(where, *required):
578 '''(INTERNAL) Import C{geographiclib} and check required version.
579 '''
580 try:
581 _xpackage(_xgeographiclib)
582 import geographiclib
583 except ImportError as x:
584 raise _xImportError(x, where)
585 return _xversion(geographiclib, where, *required)
588def _xImportError(x, where, **name):
589 '''(INTERNAL) Embellish an C{ImportError}.
590 '''
591 t = _SPACE_(_required_, _by_, _xwhere(where, **name))
592 return _ImportError(_Xstr(x), txt=t, cause=x)
595def _xinstanceof(*Types, **name_value_pairs):
596 '''(INTERNAL) Check C{Types} of all C{name=value} pairs.
598 @arg Types: One or more classes or types (C{class}),
599 all positional.
600 @kwarg name_value_pairs: One or more C{B{name}=value} pairs
601 with the C{value} to be checked.
603 @raise TypeError: One of the B{C{name_value_pairs}} is not
604 an instance of any of the B{C{Types}}.
605 '''
606 for n, v in name_value_pairs.items():
607 if not isinstance(v, Types):
608 raise _TypesError(n, v, *Types)
611def _xnumpy(where, *required):
612 '''(INTERNAL) Import C{numpy} and check required version.
613 '''
614 try:
615 _xpackage(_xnumpy)
616 import numpy
617 except ImportError as x:
618 raise _xImportError(x, where)
619 return _xversion(numpy, where, *required)
622def _xpackage(_xpkg):
623 '''(INTERNAL) Check dependency to be excluded.
624 '''
625 n = _xpkg.__name__[2:]
626 if n in _XPACKAGES:
627 x = _SPACE_(n, _in_, _PYGEODESY_XPACKAGES_)
628 e = _enquote(_getenv(_PYGEODESY_XPACKAGES_, NN))
629 raise ImportError(_EQUAL_(x, e))
632def _xor(x, *xs):
633 '''(INTERNAL) Exclusive-or C{x} and C{xs}.
634 '''
635 for x_ in xs:
636 x ^= x_
637 return x
640def _xscipy(where, *required):
641 '''(INTERNAL) Import C{scipy} and check required version.
642 '''
643 try:
644 _xpackage(_xscipy)
645 import scipy
646 except ImportError as x:
647 raise _xImportError(x, where)
648 return _xversion(scipy, where, *required)
651def _xsubclassof(*Classes, **name_value_pairs):
652 '''(INTERNAL) Check (super) class of all C{name=value} pairs.
654 @arg Classes: One or more classes or types (C{class}),
655 all positional.
656 @kwarg name_value_pairs: One or more C{B{name}=value} pairs
657 with the C{value} to be checked.
659 @raise TypeError: One of the B{C{name_value_pairs}} is not
660 a (sub-)class of any of the B{C{Classes}}.
661 '''
662 for n, v in name_value_pairs.items():
663 if not issubclassof(v, *Classes):
664 raise _TypesError(n, v, *Classes)
667def _xversion(package, where, *required, **name):
668 '''(INTERNAL) Check the C{package} version vs B{C{required}}.
669 '''
670 n = len(required)
671 if n:
672 t = _xversion_info(package)
673 if t[:n] < required:
674 t = _SPACE_(package.__name__, _version_, _DOT_(*t),
675 _below_, _DOT_(*required),
676 _required_, _by_, _xwhere(where, **name))
677 raise ImportError(t)
678 return package
681def _xversion_info(package): # in .karney
682 '''(INTERNAL) Get the C{package.__version_info__} as a 2- or
683 3-tuple C{(major, minor, revision)} if C{int}s.
684 '''
685 try:
686 t = package.__version_info__
687 except AttributeError:
688 t = package.__version__.strip()
689 t = t.replace(_DOT_, _SPACE_).split()[:3]
690 return map2(int, t)
693def _xwhere(where, **name):
694 '''(INTERNAL) Get the fully qualified name.
695 '''
696 m = _MODS.named.modulename(where, prefixed=True)
697 if name:
698 n = _xkwds_get(name, name=NN)
699 if n:
700 m = _DOT_(m, n)
701 return m
704if _sys_version_info2 < (3, 10): # see .errors
705 _zip = zip # PYCHOK exported
706else: # Python 3.10+
708 def _zip(*args):
709 return zip(*args, strict=True)
711# **) MIT License
712#
713# Copyright (C) 2016-2023 -- mrJean1 at Gmail -- All Rights Reserved.
714#
715# Permission is hereby granted, free of charge, to any person obtaining a
716# copy of this software and associated documentation files (the "Software"),
717# to deal in the Software without restriction, including without limitation
718# the rights to use, copy, modify, merge, publish, distribute, sublicense,
719# and/or sell copies of the Software, and to permit persons to whom the
720# Software is furnished to do so, subject to the following conditions:
721#
722# The above copyright notice and this permission notice shall be included
723# in all copies or substantial portions of the Software.
724#
725# THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS
726# OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
727# FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL
728# THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR
729# OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE,
730# ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR
731# OTHER DEALINGS IN THE SOFTWARE.