Coverage for pygeodesy/basics.py: 91%

268 statements  

« prev     ^ index     » next       coverage.py v7.6.1, created at 2025-04-09 11:05 -0400

1 

2# -*- coding: utf-8 -*- 

3 

4u'''Some, basic definitions, functions and dependencies. 

5 

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 

16 

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 

34 

35from copy import copy as _copy, deepcopy as _deepcopy 

36from math import copysign as _copysign 

37# import inspect as _inspect # _MODS 

38 

39__all__ = _ALL_LAZY.basics 

40__version__ = '25.01.17' 

41 

42_below_ = 'below' 

43_list_tuple_types = (list, tuple) 

44_required_ = 'required' 

45 

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 

54 

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 

68 

69try: 

70 _Bytes = unicode, bytearray # PYCHOK in .internals 

71 _Strs = basestring, str # XXX str == bytes 

72 str2ub = ub2str = _passarg # avoids UnicodeDecodeError 

73 

74 def _Xstr(exc): # PYCHOK no cover 

75 '''I{Invoke only with caught ImportError} B{C{exc}}. 

76 

77 C{... "can't import name _distributor_init" ...} 

78 

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 

91 

92except NameError: # Python 3+ 

93 from pygeodesy.interns import _utf_8_ 

94 

95 _Bytes = bytes, bytearray # in .internals 

96 _Strs = str, # tuple 

97 _Xstr = str 

98 

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 

105 

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 

112 

113 

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 

137 

138 

139def _args_kwds_names(func, splast=False): 

140 '''(INTERNAL) Get a C{func}'s args and kwds names, including 

141 C{self} for methods. 

142 

143 @kwarg splast: If C{True}, split the last keyword argument 

144 at UNDERscores (C{bool}). 

145 

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) 

162 

163 

164def clips(sb, limit=50, white=NN, length=False): 

165 '''Clip a string to the given length limit. 

166 

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}). 

171 

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 

184 

185 

186def copysign0(x, y): 

187 '''Like C{math.copysign(x, y)} except C{zero}, I{unsigned}. 

188 

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) 

193 

194 

195def copytype(x, y): 

196 '''Return the value of B{x} as C{type} of C{y}. 

197 

198 @return: C{type(B{y})(B{x})}. 

199 ''' 

200 return type(y)(x if x else _0_0) 

201 

202 

203def _enumereverse(iterable): 

204 '''(INTERNAL) Reversed C{enumberate}. 

205 ''' 

206 for j in _reverange(len(iterable)): 

207 yield j, iterable[j] 

208 

209 

210try: 

211 from math import gcd as _gcd 

212except ImportError: # 3.4- 

213 

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 

224 

225 

226def halfs2(str2): 

227 '''Split a string in 2 halfs. 

228 

229 @arg str2: String to split (C{str}). 

230 

231 @return: 2-Tuple C{(_1st, _2nd)} half (C{str}). 

232 

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:] 

239 

240 

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 

248 

249 

250def int1s(x): # PYCHOK no cover 

251 '''Count the number of 1-bits in an C{int}, I{unsigned}. 

252 

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_) 

260 

261 

262def isbool(obj): 

263 '''Is B{C{obj}}ect a C{bool}ean? 

264 

265 @arg obj: The object (any C{type}). 

266 

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) 

271 

272assert not (isbool(1) or isbool(0) or isbool(None)) # PYCHOK 2 

273 

274 

275def isCartesian(obj, ellipsoidal=None): 

276 '''Is B{C{obj}}ect some C{Cartesian}? 

277 

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}. 

282 

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) 

292 

293 

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) 

298 

299 

300def iscomplex(obj, both=False): 

301 '''Is B{C{obj}}ect a C{complex} or complex literal C{str}? 

302 

303 @arg obj: The object (any C{type}). 

304 @kwarg both: If C{True}, check complex C{str} (C{bool}). 

305 

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 

313 

314 

315def isDEPRECATED(obj): 

316 '''Is B{C{obj}}ect a C{DEPRECATED} class, method or function? 

317 

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 

326 

327 

328def isfloat(obj, both=False): 

329 '''Is B{C{obj}}ect a C{float} or float literal C{str}? 

330 

331 @arg obj: The object (any C{type}). 

332 @kwarg both: If C{True}, check float C{str} (C{bool}). 

333 

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 

341 

342 

343try: 

344 isidentifier = str.isidentifier # Python 3, must be str 

345except AttributeError: # Python 2- 

346 

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()) 

353 

354 

355def isinstanceof(obj, *Classes): 

356 '''Is B{C{obj}}ect an instance of one of the C{Classes}? 

357 

358 @arg obj: The object (any C{type}). 

359 @arg Classes: One or more classes (C{Class}). 

360 

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 

365 

366 

367def isint(obj, both=False): 

368 '''Is B{C{obj}}ect an C{int} or integer C{float} value? 

369 

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}). 

373 

374 @return: C{True} if C{int} or I{integer} C{float} 

375 or L{Fsum}, C{False} otherwise. 

376 

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 

388 

389 

390def isiterable(obj, strict=False): 

391 '''Is B{C{obj}}ect C{iterable}? 

392 

393 @arg obj: The object (any C{type}). 

394 @kwarg strict: If C{True}, check class attributes (C{bool}). 

395 

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 

400 

401 

402def isiterablen(obj, strict=False): 

403 '''Is B{C{obj}}ect C{iterable} and has C{len}gth? 

404 

405 @arg obj: The object (any C{type}). 

406 @kwarg strict: If C{True}, check class attributes (C{bool}). 

407 

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__')) 

412 

413 

414def isiterabletype(obj, method='__iter__'): 

415 '''Is B{C{obj}}ect an instance of an C{iterable} class or type? 

416 

417 @arg obj: The object (any C{type}). 

418 @kwarg method: The name of the required method (C{str}). 

419 

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 

432 

433 

434try: 

435 from keyword import iskeyword # Python 2.7+ 

436except ImportError: 

437 

438 def iskeyword(unused): 

439 '''Not Implemented, C{False} always. 

440 ''' 

441 return False 

442 

443 

444def isLatLon(obj, ellipsoidal=None): 

445 '''Is B{C{obj}}ect some C{LatLon}? 

446 

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}. 

451 

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) 

461 

462 

463def islistuple(obj, minum=0): 

464 '''Is B{C{obj}}ect a C{list} or C{tuple} with non-zero length? 

465 

466 @arg obj: The object (any C{type}). 

467 @kwarg minum: Minimal C{len} required C({int}). 

468 

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 

473 

474 

475def isNvector(obj, ellipsoidal=None): 

476 '''Is B{C{obj}}ect some C{Nvector}? 

477 

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}. 

482 

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) 

492 

493 

494def isodd(x): 

495 '''Is B{C{x}} odd? 

496 

497 @arg x: Value (C{scalar}). 

498 

499 @return: C{True} if odd, C{False} otherwise. 

500 ''' 

501 return bool(int(x) & 1) # == bool(int(x) % 2) 

502 

503 

504def isscalar(obj, both=False): 

505 '''Is B{C{obj}}ect an C{int} or integer C{float} value? 

506 

507 @arg obj: The object (any C{type}). 

508 @kwarg both: If C{True}, check L{Fsum} and L{Fsum2Tuple} 

509 residuals. 

510 

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 

519 

520 

521def issequence(obj, *excls): 

522 '''Is B{C{obj}}ect some sequence type? 

523 

524 @arg obj: The object (any C{type}). 

525 @arg excls: Classes to exclude (C{type}), all positional. 

526 

527 @note: Excluding C{tuple} implies excluding C{namedtuple}. 

528 

529 @return: C{True} if a sequence, C{False} otherwise. 

530 ''' 

531 return isinstance(obj, _Seqs) and not (excls and isinstance(obj, excls)) 

532 

533 

534def isstr(obj): 

535 '''Is B{C{obj}}ect some string type? 

536 

537 @arg obj: The object (any C{type}). 

538 

539 @return: C{True} if a C{str}, C{bytes}, ..., 

540 C{False} otherwise. 

541 ''' 

542 return isinstance(obj, _Strs) 

543 

544 

545def issubclassof(Sub, *Supers): 

546 '''Is B{C{Sub}} a class and sub-class of some other class(es)? 

547 

548 @arg Sub: The sub-class (C{Class}). 

549 @arg Supers: One or more C(super) classes (C{Class}). 

550 

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 

560 

561 

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. 

565 

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() 

575 

576 def _reverse_key(asorted=True, reverse=False): 

577 return dict(reverse=reverse, key=_ins if asorted else None) 

578 

579 items = adict.items(*items_args) if items_args else adict.items() 

580 return sorted(items, **_reverse_key(**asorted_reverse)) 

581 

582 

583def len2(items): 

584 '''Make built-in function L{len} work for generators, iterators, 

585 etc. since those can only be started exactly once. 

586 

587 @arg items: Generator, iterator, list, range, tuple, etc. 

588 

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 

595 

596 

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. 

600 

601 @arg fun1: 1-Arg function (C{callable}). 

602 @arg xs: Arguments (C{any positional}). 

603 

604 @return: Function results (C{tuple}). 

605 ''' 

606 return tuple(map(fun1, xs)) 

607 

608 

609def map2(fun, *xs, **strict): 

610 '''Like Python's B{C{map}} but returning a C{tuple} of results. 

611 

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. 

616 

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}). 

621 

622 @return: Function results (C{tuple}). 

623 ''' 

624 return tuple(map(fun, *xs, **strict) if strict else map(fun, *xs)) 

625 

626 

627def max2(*xs): 

628 '''Return 2-tuple C{(max(xs), xs.index(max(xs)))}. 

629 ''' 

630 return _max2min2(xs, max, max2) 

631 

632 

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 

646 

647 

648def min2(*xs): 

649 '''Return 2-tuple C{(min(xs), xs.index(min(xs)))}. 

650 ''' 

651 return _max2min2(xs, min, min2) 

652 

653 

654def neg(x, neg0=None): 

655 '''Negate C{x} and optionally, negate C{0.0} and C{-0.0}. 

656 

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}). 

661 

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 

669 

670 

671def neg_(*xs): 

672 '''Negate all C{xs} with L{neg}. 

673 

674 @return: A C{map(neg, B{xs})}. 

675 ''' 

676 return map(neg, xs) 

677 

678 

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 

684 

685 

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) 

695 

696 

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) 

701 

702 

703def signBit(x): 

704 '''Return C{signbit(B{x})}, like C++. 

705 

706 @return: C{True} if C{B{x} < 0} or C{NEG0} (C{bool}). 

707 ''' 

708 return x < 0 or _MODS.constants.isneg0(x) 

709 

710 

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) 

715 

716 

717def signOf(x): 

718 '''Return sign of C{x} as C{int}. 

719 

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 

727 

728 

729def splice(iterable, n=2, **fill): 

730 '''Split an iterable into C{n} slices. 

731 

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. 

735 

736 @return: A generator for each of B{C{n}} slices, 

737 M{iterable[i::n] for i=0..n}. 

738 

739 @raise TypeError: Invalid B{C{n}}. 

740 

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}. 

743 

744 @example: 

745 

746 >>> from pygeodesy import splice 

747 

748 >>> a, b = splice(range(10)) 

749 >>> a, b 

750 ((0, 2, 4, 6, 8), (1, 3, 5, 7, 9)) 

751 

752 >>> a, b, c = splice(range(10), n=3) 

753 >>> a, b, c 

754 ((0, 3, 6, 9), (1, 4, 7), (2, 5, 8)) 

755 

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)) 

759 

760 >>> tuple(splice(list(range(9)), n=5)) 

761 ([0, 5], [1, 6], [2, 7], [3, 8], [4]) 

762 

763 >>> splice(range(9), n=1) 

764 <generator object splice at 0x0...> 

765 ''' 

766 if not isint(n): 

767 raise _TypeError(n=n) 

768 

769 t = _xiterablen(iterable) 

770 if not isinstance(t, _list_tuple_types): 

771 t = tuple(t) 

772 

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 

785 

786 

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 () 

798 

799 

800def unsigned0(x): 

801 '''Unsign if C{0.0}. 

802 

803 @return: C{B{x}} if B{C{x}} else C{0.0}. 

804 ''' 

805 return x if x else _0_0 

806 

807 

808def _xcopy(obj, deep=False): 

809 '''(INTERNAL) Copy an object, shallow or deep. 

810 

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}). 

814 

815 @return: The copy of B{C{obj}}. 

816 ''' 

817 return _deepcopy(obj) if deep else _copy(obj) 

818 

819 

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) 

829 

830 

831def _xdup(obj, deep=False, **items): 

832 '''(INTERNAL) Duplicate an object, replacing some attributes. 

833 

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}). 

837 

838 @return: A duplicate of B{C{obj}} with modified 

839 attributes, if any B{C{items}}. 

840 

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 

854 

855 

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) 

865 

866 

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) 

872 

873 

874def _xinstanceof(*Types, **names_values): 

875 '''(INTERNAL) Check C{Types} of all C{name=value} pairs. 

876 

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. 

881 

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) 

887 

888 for n, v in names_values.items(): 

889 if not isinstance(v, Types): 

890 raise _TypesError(n, v, *Types) 

891 

892 

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 

897 

898 

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 

903 

904 

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) 

910 

911 

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) 

921 

922 

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 

929 

930 

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)) 

941 

942 

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_) 

949 

950 

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) 

960 

961 

962def _xsubclassof(*Classes, **names_values): 

963 '''(INTERNAL) Check (super) class of all C{name=value} pairs. 

964 

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. 

969 

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) 

975 

976 for n, v in names_values.items(): 

977 if not issubclassof(v, *Classes): 

978 raise _TypesError(n, v, *Classes) 

979 

980 

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 

993 

994 

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) 

1005 

1006 

1007if _MODS.sys_version_info2 < (3, 10): # see .errors 

1008 _zip = zip # PYCHOK exported 

1009else: # Python 3.10+ 

1010 

1011 def _zip(*args): 

1012 return zip(*args, strict=True) 

1013 

1014_XPACKAGES = _splituple(_getenv(_PYGEODESY(_xpackages), NN).lower()) # test/bases._X_OK 

1015 

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.