# Coverage for pygeodesy/basics.py : 96%

## 192 statements 185 run 7 missing 77 excluded

Hot-keys on this page

r m x p toggle line displays

j k next/prev highlighted chunk

0 (zero) top of page

1 (one) first highlighted chunk

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594 595 596 597 598 599 600 601 602 603 604 605 606 607 608 609 610 611 612 613 614 615 616 617 618 619 620 621 622 623 624 625 626 627 628 629 630 631 632 633 634 635 636 637 638 639 640 641 642 643 644 645 646 647 648 649 650 651 652 653 654 655 656 657 658 659 660 661 662 663 664 665 666 667 668 669 670 671 672 673 674 675 676 677 678 679 680 681 682 683 684 685 686 687 688 689 690 691 692 | # -*- coding: utf-8 -*- u'''Some, basic definitions, functions and dependencies. Use env variable C{PYGEODESY_XPACKAGES} to avoid import of dependencies C{geographiclib}, C{numpy} and/or C{scipy}. Set C{PYGEODESY_XPACKAGES} to a comma-separated list of package names to be excluded from import. ''' # make sure int/int division yields float quotient from __future__ import division division = 1 / 2 # .albers, .azimuthal, .constants, etc., .utily if not division: raise ImportError('%s 1/2 == %s' % ('division', division)) del division from pygeodesy.errors import _AssertionError, _AttributeError, _ImportError, \ _TypeError, _TypesError, _ValueError, _xkwds_get from pygeodesy.interns import MISSING, NN, _by_, _DOT_, _ELLIPSIS4_, _enquote, \ _EQUAL_, _in_, _invalid_, _N_A_, _name_, _SPACE_, \ _splituple, _UNDER_, _version_ from pygeodesy.lazily import _ALL_LAZY, _ALL_MODS as _MODS, _FOR_DOCS, \ _getenv, _sys_version_info2 from copy import copy as _copy, deepcopy as _deepcopy from math import copysign as _copysign import inspect as _inspect __all__ = _ALL_LAZY.basics __version__ = '23.01.09' _0_0 = 0.0 # see .constants _below_ = 'below' _cannot_ = 'cannot' _odd_ = 'odd' _required_ = 'required' _PYGEODESY_XPACKAGES_ = 'PYGEODESY_XPACKAGES' _XPACKAGES = _splituple(_getenv(_PYGEODESY_XPACKAGES_, NN)) try: # Luciano Ramalho, "Fluent Python", page 395, O'Reilly, 2016 from numbers import Integral as _Ints, Real as _Scalars except ImportError: try: _Ints = int, long # int objects (C{tuple}) except NameError: # Python 3+ _Ints = int, # int objects (C{tuple}) _Scalars = _Ints + (float,) try: try: # use C{from collections.abc import ...} in Python 3.9+ from collections.abc import Sequence as _Sequence # in .points except ImportError: # no .abc in Python 3.8- and 2.7- from collections import Sequence as _Sequence # in .points if isinstance([], _Sequence) and isinstance((), _Sequence): # and isinstance(range(1), _Sequence): _Seqs = _Sequence else: raise ImportError # _AssertionError except ImportError: _Sequence = tuple # immutable for .points._Basequence _Seqs = list, _Sequence # , range for function len2 below try: _Bytes = unicode, bytearray # PYCHOK expected _Strs = basestring, str # XXX , bytes def _NOP(x): '''NOP, pass thru.''' return x str2ub = ub2str = _NOP # avoids UnicodeDecodeError def _Xstr(exc): # PYCHOK no cover '''I{Invoke only with caught ImportError} B{C{exc}}. C{... "cannot import name _distributor_init" ...} only for C{numpy}, C{scipy} import errors occurring on arm64 Apple Silicon running macOS' Python 2.7.16? ''' t = str(exc) if '_distributor_init' in t: from sys import exc_info from traceback import extract_tb tb = exc_info()[2] # 3-tuple (type, value, traceback) t4 = extract_tb(tb, 1)[0] # 4-tuple (file, line, name, 'import ...') t = _SPACE_(_cannot_, t4[3] or _N_A_) del tb, t4 return t except NameError: # Python 3+ from pygeodesy.interns import _utf_8_ _Bytes = bytes, bytearray _Strs = str, # tuple _Xstr = str def str2ub(sb): '''Convert C{str} to C{unicode bytes}. ''' if isinstance(sb, _Strs): sb = sb.encode(_utf_8_) return sb def ub2str(ub): '''Convert C{unicode bytes} to C{str}. ''' if isinstance(ub, _Bytes): ub = str(ub.decode(_utf_8_)) return ub def clips(sb, limit=50, white=NN): '''Clip a string to the given length limit. @arg sb: String (C{str} or C{bytes}). @kwarg limit: Length limit (C{int}). @kwarg white: Optionally, replace all whitespace (C{str}). @return: The clipped or unclipped B{C{sb}}. ''' T = type(sb) if len(sb) > limit > 8: h = limit // 2 sb = T(_ELLIPSIS4_).join((sb[:h], sb[-h:])) if white: # replace whitespace sb = T(white).join(sb.split()) return sb def copysign0(x, y): '''Like C{math.copysign(x, y)} except C{zero}, I{unsigned}. @return: C{math.copysign(B{x}, B{y})} if B{C{x}} else C{type(B{x})(0)}. ''' return _copysign(x, (y if y else 0)) if x else copytype(0, x) def copytype(x, y): '''Return the value of B{x} as C{type} of C{y}. @return: C{type(B{y})(B{x})}. ''' return type(y)(x if x else _0_0) def halfs2(str2): '''Split a string in 2 halfs. @arg str2: String to split (C{str}). @return: 2-Tuple (_1st, _2nd) half (C{str}). @raise ValueError: Zero or odd C{len}(B{C{str2}}). ''' h, r = divmod(len(str2), 2) if r or not h: raise _ValueError(str2=str2, txt=_odd_) return str2[:h], str2[h:] def isbool(obj): '''Check whether an object is C{bool}ean. @arg obj: The object (any C{type}). @return: C{True} if B{C{obj}} is C{bool}ean, C{False} otherwise. ''' return isinstance(obj, bool) # and (obj is False # or obj is True) if isbool(1) or isbool(0): # PYCHOK assert raise _AssertionError(isbool=1) if _FOR_DOCS: # XXX avoid epidoc Python 2.7 error def isclass(obj): '''Return C{True} if B{C{obj}} is a C{class} or C{type}. @see: Python's C{inspect.isclass}. ''' return _inspect.isclass(obj) else: isclass = _inspect.isclass def iscomplex(obj): '''Check whether an object is C{complex}. @arg obj: The object (any C{type}). @return: C{True} if B{C{obj}} is C{complex}, C{False} otherwise. ''' # hasattr('conjugate'), hasattr('real') and hasattr('imag') return isinstance(obj, complex) # numbers.Complex? def isfloat(obj): '''Check whether an object is a C{float} or float C{str}. @arg obj: The object (any C{type}). @return: C{True} if B{C{obj}} is a C{float}, C{False} otherwise. ''' try: return isinstance( obj, float) or (isstr(obj) and isinstance(float(obj), float)) except (TypeError, ValueError): return False try: isidentifier = str.isidentifier # Python 3, must be str except AttributeError: # Python 2- def isidentifier(obj): '''Return C{True} if B{C{obj}} is a valid Python identifier. ''' return bool(obj and obj.replace(_UNDER_, NN).isalnum() and not obj[:1].isdigit()) def isinstanceof(obj, *classes): '''Check an instance of one or several C{classes}. @arg obj: The instance (C{any}). @arg classes: One or more classes (C{class}). @return: C{True} if B{C{obj}} is in instance of one of the B{C{classes}}. ''' return isinstance(obj, classes) def isint(obj, both=False): '''Check for C{int} type or an integer C{float} value. @arg obj: The object (any C{type}). @kwarg both: If C{true}, check C{float} and L{Fsum} type and value (C{bool}). @return: C{True} if B{C{obj}} is C{int} or I{integer} C{float} or L{Fsum}, C{False} otherwise. @note: Both C{isint(True)} and C{isint(False)} return C{False} (and no longer C{True}). ''' if isinstance(obj, _Ints) and not isbool(obj): return True elif both: # and isinstance(obj, (float, Fsum)) ... try: # ... NOT , Scalars) to include Fsum! return obj.is_integer() except AttributeError: pass # XXX float(int(obj)) == obj? return False try: from keyword import iskeyword # Python 2.7+ except ImportError: def iskeyword(unused): '''Not Implemented. Return C{False}, always. ''' return False def isodd(x): '''Is B{C{x}} odd? @arg x: Value (C{scalar}). @return: C{True} if B{C{x}} is odd, C{False} otherwise. ''' return bool(int(x) & 1) def isscalar(obj): '''Check for scalar types. @arg obj: The object (any C{type}). @return: C{True} if B{C{obj}} is C{scalar}, C{False} otherwise. ''' return isinstance(obj, _Scalars) and not isbool(obj) def issequence(obj, *excls): '''Check for sequence types. @arg obj: The object (any C{type}). @arg excls: Classes to exclude (C{type}), all positional. @note: Excluding C{tuple} implies excluding C{namedtuple}. @return: C{True} if B{C{obj}} is a sequence, C{False} otherwise. ''' return isinstance(obj, _Seqs) and not (excls and isinstance(obj, excls)) def isstr(obj): '''Check for string types. @arg obj: The object (any C{type}). @return: C{True} if B{C{obj}} is C{str}, C{False} otherwise. ''' return isinstance(obj, _Strs) def issubclassof(Sub, *Supers): '''Check whether a class is a sub-class of some other class(es). @arg Sub: The sub-class (C{class}). @arg Supers: One or more C(super) classes (C{class}). @return: C{True} if B{C{Sub}} is a sub-class of any B{C{Supers}}, C{False} if not (C{bool}) or C{None} if B{C{Sub}} is not a class or if no B{C{Supers}} are given or none of those are a class. ''' if isclass(Sub): t = tuple(S for S in Supers if isclass(S)) if t: return bool(issubclass(Sub, t)) return None def istuplist(obj, minum=0): '''Check for tuple or list types and minumal length. @arg obj: The object (any C{type}). @kwarg minum: Minimal C{len} required C({int}). @return: C{True} if B{C{obj}} is C{tuple} or C{list} with C{len} at least B{C{minum}}, C{False} otherwise. ''' return type(obj) in (tuple, list) and len(obj) >= (minum or 0) def len2(items): '''Make built-in function L{len} work for generators, iterators, etc. since those can only be started exactly once. @arg items: Generator, iterator, list, range, tuple, etc. @return: 2-Tuple C{(n, items)} of the number of items (C{int}) and the items (C{list} or C{tuple}). ''' if not isinstance(items, _Seqs): # NOT hasattr(items, '__len__'): items = list(items) return len(items), items def map1(fun1, *xs): # XXX map_ '''Apply each argument to a single-argument function and return a C{tuple} of results. @arg fun1: 1-Arg function to apply (C{callable}). @arg xs: Arguments to apply (C{any positional}). @return: Function results (C{tuple}). ''' return tuple(map(fun1, xs)) # note xs, not *xs def map2(func, *xs): '''Apply arguments to a function and return a C{tuple} of results. Unlike Python 2's built-in L{map}, Python 3+ L{map} returns a L{map} object, an iterator-like object which generates the results only once. Converting the L{map} object to a tuple maintains the Python 2 behavior. @arg func: Function to apply (C{callable}). @arg xs: Arguments to apply (C{list, tuple, ...}). @return: Function results (C{tuple}). ''' return tuple(map(func, *xs)) # note *xs, not xs def neg(x): '''Negate C{x} unless C{zero} or C{NEG0}. @return: C{-B{x}} if B{C{x}} else C{0.0}. ''' return -x if x else _0_0 def neg_(*xs): '''Negate all of C{xs} with L{neg}. @return: A C{tuple(neg(x) for x in B{xs})}. ''' return tuple(map(neg, xs)) # like map1 def signBit(x): '''Return C{signbit(B{x})}, like C++. @return: C{True} if C{B{x} < 0} or C{NEG0} (C{bool}). ''' return x < 0 or _MODS.constants.isneg0(x) def _signOf(x, off): '''(INTERNAL) Return the sign of B{C{x}} versus B{C{off}}. ''' return +1 if x > off else (-1 if x < off else 0) def signOf(x): '''Return sign of C{x} as C{int}. @return: -1, 0 or +1 (C{int}). ''' try: s = x.signOf() # Fsum instance? except AttributeError: s = _signOf(x, 0) return s def splice(iterable, n=2, **fill): '''Split an iterable into C{n} slices. @arg iterable: Items to be spliced (C{list}, C{tuple}, ...). @kwarg n: Number of slices to generate (C{int}). @kwarg fill: Optional fill value for missing items. @return: A generator for each of B{C{n}} slices, M{iterable[i::n] for i=0..n}. @raise TypeError: Invalid B{C{n}}. @note: Each generated slice is a C{tuple} or a C{list}, the latter only if the B{C{iterable}} is a C{list}. @example: >>> from pygeodesy import splice >>> a, b = splice(range(10)) >>> a, b ((0, 2, 4, 6, 8), (1, 3, 5, 7, 9)) >>> a, b, c = splice(range(10), n=3) >>> a, b, c ((0, 3, 6, 9), (1, 4, 7), (2, 5, 8)) >>> a, b, c = splice(range(10), n=3, fill=-1) >>> a, b, c ((0, 3, 6, 9), (1, 4, 7, -1), (2, 5, 8, -1)) >>> tuple(splice(list(range(9)), n=5)) ([0, 5], [1, 6], [2, 7], [3, 8], [4]) >>> splice(range(9), n=1) <generator object splice at 0x0...> ''' if not isint(n): raise _TypeError(n=n) t = iterable if not isinstance(t, (list, tuple)): t = tuple(t) # force tuple, also for PyPy3 if n > 1: if fill: fill = _xkwds_get(fill, fill=MISSING) if fill is not MISSING: m = len(t) % n if m > 0: # fill with same type t += type(t)((fill,)) * (n - m) for i in range(n): # XXX t[i::n] chokes PyChecker yield t[slice(i, None, n)] else: yield t def unsigned0(x): '''Return C{0.0} unsigned. @return: C{B{x}} if B{C{x}} else C{0.0}. ''' return x if x else _0_0 def _xargs_names(callabl): '''(INTERNAL) Get the C{callabl}'s args names. ''' try: args_kwds = _inspect.signature(callabl).parameters.keys() except AttributeError: # .signature new Python 3+ args_kwds = _inspect.getargspec(callabl).args return tuple(args_kwds) def _xcopy(inst, deep=False): '''(INTERNAL) Copy an object, shallow or deep. @arg inst: The object to copy (any C{type}). @kwarg deep: If C{True} make a deep, otherwise a shallow copy (C{bool}). @return: The copy of B{C{inst}}. ''' return _deepcopy(inst) if deep else _copy(inst) def _xdup(inst, **items): '''(INTERNAL) Duplicate an object, replacing some attributes. @arg inst: The object to copy (any C{type}). @kwarg items: Attributes to be changed (C{any}). @return: Shallow duplicate of B{C{inst}} with modified attributes, if any B{C{items}}. @raise AttributeError: Some B{C{items}} invalid. ''' d = _xcopy(inst, deep=False) for n, v in items.items(): if not hasattr(d, n): t = _MODS.named.classname(inst) t = _SPACE_(_DOT_(t, n), _invalid_) raise _AttributeError(txt=t, this=inst, **items) setattr(d, n, v) return d def _xgeographiclib(where, *required): '''(INTERNAL) Import C{geographiclib} and check required version ''' try: _xpackage(_xgeographiclib) import geographiclib except ImportError as x: raise _xImportError(x, where) return _xversion(geographiclib, where, *required) def _xImportError(x, where, **name): '''(INTERNAL) Embellish an C{ImportError}. ''' t = _SPACE_(_required_, _by_, _xwhere(where, **name)) return _ImportError(_Xstr(x), txt=t, cause=x) def _xinstanceof(*Types, **name_value_pairs): '''(INTERNAL) Check C{Types} of all C{name=value} pairs. @arg Types: One or more classes or types (C{class}), all positional. @kwarg name_value_pairs: One or more C{B{name}=value} pairs with the C{value} to be checked. @raise TypeError: One of the B{C{name_value_pairs}} is not an instance of any of the B{C{Types}}. ''' for n, v in name_value_pairs.items(): if not isinstance(v, Types): raise _TypesError(n, v, *Types) def _xnumpy(where, *required): '''(INTERNAL) Import C{numpy} and check required version ''' try: _xpackage(_xnumpy) import numpy except ImportError as x: raise _xImportError(x, where) return _xversion(numpy, where, *required) def _xpackage(_xpkg): '''(INTERNAL) Check dependency to be excluded. ''' n = _xpkg.__name__[2:] if n in _XPACKAGES: x = _SPACE_(n, _in_, _PYGEODESY_XPACKAGES_) e = _enquote(_getenv(_PYGEODESY_XPACKAGES_, NN)) raise ImportError(_EQUAL_(x, e)) def _xor(x, *xs): '''(INTERNAL) Exclusive-or C{x} and C{xs}. ''' for x_ in xs: x ^= x_ return x def _xscipy(where, *required): '''(INTERNAL) Import C{scipy} and check required version ''' try: _xpackage(_xscipy) import scipy except ImportError as x: raise _xImportError(x, where) return _xversion(scipy, where, *required) def _xsubclassof(*Classes, **name_value_pairs): '''(INTERNAL) Check (super) class of all C{name=value} pairs. @arg Classes: One or more classes or types (C{class}), all positional. @kwarg name_value_pairs: One or more C{B{name}=value} pairs with the C{value} to be checked. @raise TypeError: One of the B{C{name_value_pairs}} is not a (sub-)class of any of the B{C{Classes}}. ''' for n, v in name_value_pairs.items(): if not issubclassof(v, *Classes): raise _TypesError(n, v, *Classes) def _xversion(package, where, *required, **name): # in .karney '''(INTERNAL) Check the C{package} version vs B{C{required}}. ''' n = len(required) if n: t = _xversion_info(package) if t[:n] < required: t = _SPACE_(package.__name__, _version_, _DOT_(*t), _below_, _DOT_(*required), _required_, _by_, _xwhere(where, **name)) raise ImportError(t) return package def _xversion_info(package): # in .karney '''(INTERNAL) Get the C{package.__version_info__} as a 2- or 3-tuple C{(major, minor, revision)} if C{int}s. ''' try: t = package.__version_info__ except AttributeError: t = package.__version__.strip() t = t.replace(_DOT_, _SPACE_).split()[:3] return map2(int, t) def _xwhere(where, **name): '''(INTERNAL) Get the fully qualified name. ''' m = _MODS.named.modulename(where, prefixed=True) n = name.get(_name_, NN) if n: m = _DOT_(m, n) return m if _sys_version_info2 < (3, 10): # see .errors _zip = zip # PYCHOK exported else: # Python 3.10+ def _zip(*args): return zip(*args, strict=True) # **) MIT License # # Copyright (C) 2016-2023 -- mrJean1 at Gmail -- All Rights Reserved. # # Permission is hereby granted, free of charge, to any person obtaining a # copy of this software and associated documentation files (the "Software"), # to deal in the Software without restriction, including without limitation # the rights to use, copy, modify, merge, publish, distribute, sublicense, # and/or sell copies of the Software, and to permit persons to whom the # Software is furnished to do so, subject to the following conditions: # # The above copyright notice and this permission notice shall be included # in all copies or substantial portions of the Software. # # THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS # OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, # FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL # THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR # OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, # ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR # OTHER DEALINGS IN THE SOFTWARE.