Coverage for pygeodesy/basics.py: 91%

262 statements  

« prev     ^ index     » next       coverage.py v7.6.1, created at 2025-01-06 12:20 -0500

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__ = '24.12.31' 

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 

210def halfs2(str2): 

211 '''Split a string in 2 halfs. 

212 

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

214 

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

216 

217 @raise ValueError: Zero or odd C{len(B{str2})}. 

218 ''' 

219 h, r = divmod(len(str2), 2) 

220 if r or not h: 

221 raise _ValueError(str2=str2, txt=_odd_) 

222 return str2[:h], str2[h:] 

223 

224 

225def int1s(x): # PYCHOK no cover 

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

227 

228 @note: C{int1s(-B{x}) == int1s(abs(B{x}))}. 

229 ''' 

230 try: 

231 return x.bit_count() # Python 3.10+ 

232 except AttributeError: 

233 # bin(-x) = '-' + bin(abs(x)) 

234 return bin(x).count(_1_) 

235 

236 

237def isbool(obj): 

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

239 

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

241 

242 @return: C{True} if C{bool}ean, C{False} otherwise. 

243 ''' 

244 return isinstance(obj, bool) # and (obj is False 

245# or obj is True) 

246 

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

248 

249 

250def isCartesian(obj, ellipsoidal=None): 

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

252 

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

254 @kwarg ellipsoidal: If C{None}, return the type of any C{Cartesian}, 

255 if C{True}, only an ellipsoidal C{Cartesian type} 

256 or if C{False}, only a spherical C{Cartesian type}. 

257 

258 @return: C{type(B{obj}} if a C{Cartesian} of the required type, C{False} 

259 if a C{Cartesian} of an other type or {None} otherwise. 

260 ''' 

261 if ellipsoidal is not None: 

262 try: 

263 return obj.ellipsoidalCartesian if ellipsoidal else obj.sphericalCartesian 

264 except AttributeError: 

265 return None 

266 return isinstanceof(obj, _MODS.cartesianBase.CartesianBase) 

267 

268 

269def isclass(obj): # XXX avoid epydoc Python 2.7 error 

270 '''Is B{C{obj}}ect a C{Class} or C{type}? 

271 ''' 

272 return _MODS.inspect.isclass(obj) 

273 

274 

275def iscomplex(obj, both=False): 

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

277 

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

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

280 

281 @return: C{True} if C{complex}, C{False} otherwise. 

282 ''' 

283 try: # hasattr('conjugate', 'real' and 'imag') 

284 return isinstance(obj, complex) or bool(both and isstr(obj) and 

285 isinstance(complex(obj), complex)) # numbers.Complex? 

286 except (TypeError, ValueError): 

287 return False 

288 

289 

290def isDEPRECATED(obj): 

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

292 

293 @return: C{True} if C{DEPRECATED}, {False} if not or 

294 C{None} if undetermined. 

295 ''' 

296 try: # XXX inspect.getdoc(obj) or obj.__doc__ 

297 doc = obj.__doc__.lstrip() 

298 return bool(doc and doc.startswith(_DEPRECATED_)) 

299 except AttributeError: 

300 return None 

301 

302 

303def isfloat(obj, both=False): 

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

305 

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

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

308 

309 @return: C{True} if C{float}, C{False} otherwise. 

310 ''' 

311 try: 

312 return isinstance(obj, float) or bool(both and 

313 isstr(obj) and isinstance(float(obj), float)) 

314 except (TypeError, ValueError): 

315 return False 

316 

317 

318try: 

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

320except AttributeError: # Python 2- 

321 

322 def isidentifier(obj): 

323 '''Is B{C{obj}}ect a Python identifier? 

324 ''' 

325 return bool(obj and isstr(obj) 

326 and obj.replace(_UNDER_, NN).isalnum() 

327 and not obj[:1].isdigit()) 

328 

329 

330def isinstanceof(obj, *Classes): 

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

332 

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

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

335 

336 @return: C{type(B{obj}} if one of the B{C{Classes}}, 

337 C{None} otherwise. 

338 ''' 

339 return type(obj) if isinstance(obj, Classes) else None 

340 

341 

342def isint(obj, both=False): 

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

344 

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

346 @kwarg both: If C{True}, check C{float} and L{Fsum} 

347 type and value (C{bool}). 

348 

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

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

351 

352 @note: Both C{isint(True)} and C{isint(False)} return 

353 C{False} (and no longer C{True}). 

354 ''' 

355 if isinstance(obj, _Ints): 

356 return not isbool(obj) 

357 elif both: # and isinstance(obj, (float, Fsum)) 

358 try: # NOT , _Scalars) to include Fsum! 

359 return obj.is_integer() 

360 except AttributeError: 

361 pass # XXX float(int(obj)) == obj? 

362 return False 

363 

364 

365def isiterable(obj, strict=False): 

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

367 

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

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

370 

371 @return: C{True} if C{iterable}, C{False} otherwise. 

372 ''' 

373 # <https://PyPI.org/project/isiterable/> 

374 return isiterabletype(obj) if strict else hasattr(obj, '__iter__') # map, range, set 

375 

376 

377def isiterablen(obj, strict=False): 

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

379 

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

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

382 

383 @return: C{True} if C{iterable} with C{len}gth, C{False} otherwise. 

384 ''' 

385 _has = isiterabletype if strict else hasattr 

386 return _has(obj, '__len__') and _has(obj, '__getitem__') 

387 

388 

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

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

391 

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

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

394 

395 @return: The C{base-class} if C{iterable}, C{None} otherwise. 

396 ''' 

397 try: # <https://StackOverflow.com/questions/73568964> 

398 for b in type(obj).__mro__[:-1]: # ignore C{object} 

399 try: 

400 if callable(b.__dict__[method]): 

401 return b 

402 except (AttributeError, KeyError): 

403 pass 

404 except (AttributeError, TypeError): 

405 pass 

406 return None 

407 

408 

409try: 

410 from keyword import iskeyword # Python 2.7+ 

411except ImportError: 

412 

413 def iskeyword(unused): 

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

415 ''' 

416 return False 

417 

418 

419def isLatLon(obj, ellipsoidal=None): 

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

421 

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

423 @kwarg ellipsoidal: If C{None}, return the type of any C{LatLon}, 

424 if C{True}, only an ellipsoidal C{LatLon type} 

425 or if C{False}, only a spherical C{LatLon type}. 

426 

427 @return: C{type(B{obj}} if a C{LatLon} of the required type, C{False} 

428 if a C{LatLon} of an other type or {None} otherwise. 

429 ''' 

430 if ellipsoidal is not None: 

431 try: 

432 return obj.ellipsoidalLatLon if ellipsoidal else obj.sphericalLatLon 

433 except AttributeError: 

434 return None 

435 return isinstanceof(obj, _MODS.latlonBase.LatLonBase) 

436 

437 

438def islistuple(obj, minum=0): 

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

440 

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

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

443 

444 @return: C{True} if a C{list} or C{tuple} with C{len} at 

445 least B{C{minum}}, C{False} otherwise. 

446 ''' 

447 return isinstance(obj, _list_tuple_types) and len(obj) >= minum 

448 

449 

450def isNvector(obj, ellipsoidal=None): 

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

452 

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

454 @kwarg ellipsoidal: If C{None}, return the type of any C{Nvector}, 

455 if C{True}, only an ellipsoidal C{Nvector type} 

456 or if C{False}, only a spherical C{Nvector type}. 

457 

458 @return: C{type(B{obj}} if an C{Nvector} of the required type, C{False} 

459 if an C{Nvector} of an other type or {None} otherwise. 

460 ''' 

461 if ellipsoidal is not None: 

462 try: 

463 return obj.ellipsoidalNvector if ellipsoidal else obj.sphericalNvector 

464 except AttributeError: 

465 return None 

466 return isinstanceof(obj, _MODS.nvectorBase.NvectorBase) 

467 

468 

469def isodd(x): 

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

471 

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

473 

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

475 ''' 

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

477 

478 

479def isscalar(obj, both=False): 

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

481 

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

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

484 residuals. 

485 

486 @return: C{True} if C{int}, C{float} or C{Fsum/-2Tuple} 

487 with zero residual, C{False} otherwise. 

488 ''' 

489 if isinstance(obj, _Scalars): 

490 return not isbool(obj) # exclude bool 

491 elif both and _MODS.fsums._isFsum_2Tuple(obj): 

492 return bool(obj.residual == 0) 

493 return False 

494 

495 

496def issequence(obj, *excls): 

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

498 

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

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

501 

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

503 

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

505 ''' 

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

507 

508 

509def isstr(obj): 

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

511 

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

513 

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

515 C{False} otherwise. 

516 ''' 

517 return isinstance(obj, _Strs) 

518 

519 

520def issubclassof(Sub, *Supers): 

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

522 

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

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

525 

526 @return: C{True} if a sub-class of any B{C{Supers}}, C{False} 

527 if not (C{bool}) or C{None} if not a class or if no 

528 B{C{Supers}} are given or none of those are a class. 

529 ''' 

530 if isclass(Sub): 

531 t = tuple(S for S in Supers if isclass(S)) 

532 if t: 

533 return bool(issubclass(Sub, t)) # built-in 

534 return None 

535 

536 

537def itemsorted(adict, *items_args, **asorted_reverse): 

538 '''Return the items of C{B{adict}} sorted I{alphabetically, 

539 case-insensitively} and in I{ascending} order. 

540 

541 @arg items_args: Optional positional argument(s) for method 

542 C{B{adict}.items(B*{items_args})}. 

543 @kwarg asorted_reverse: Use C{B{asorted}=False} for I{alphabetical, 

544 case-sensitive} sorting and C{B{reverse}=True} for 

545 sorting in C{descending} order. 

546 ''' 

547 def _ins(item): # functools.cmp_to_key 

548 k, v = item 

549 return k.lower() 

550 

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

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

553 

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

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

556 

557 

558def len2(items): 

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

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

561 

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

563 

564 @return: 2-Tuple C{(n, items)} of the number of items (C{int}) 

565 and the items (C{list} or C{tuple}). 

566 ''' 

567 if not isinstance(items, _Seqs): # NOT hasattr(items, '__len__'): 

568 items = list(items) 

569 return len(items), items 

570 

571 

572def map1(fun1, *xs): # XXX map_ 

573 '''Call a single-argument function to each B{C{xs}} 

574 and return a C{tuple} of results. 

575 

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

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

578 

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

580 ''' 

581 return tuple(map(fun1, xs)) 

582 

583 

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

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

586 

587 Unlike Python 2's built-in L{map}, Python 3+ L{map} returns a 

588 L{map} object, an iterator-like object which generates the 

589 results only once. Converting the L{map} object to a tuple 

590 maintains the Python 2 behavior. 

591 

592 @arg fun: Function (C{callable}). 

593 @arg xs: Arguments (C{all positional}). 

594 @kwarg strict: See U{Python 3.14+ map<https://docs.Python.org/ 

595 3.14/library/functions.html#map>} (C{bool}). 

596 

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

598 ''' 

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

600 

601 

602def max2(*xs): 

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

604 ''' 

605 return _max2min2(xs, max, max2) 

606 

607 

608def _max2min2(xs, _m, _m2): 

609 '''(INTERNAL) Helper for C{max2} and C{min2}. 

610 ''' 

611 if len(xs) == 1: 

612 x = xs[0] 

613 if isiterable(x) or isiterablen(x): 

614 x, i = _m2(*x) 

615 else: 

616 i = 0 

617 else: 

618 x = _m(xs) # max or min 

619 i = xs.index(x) 

620 return x, i 

621 

622 

623def min2(*xs): 

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

625 ''' 

626 return _max2min2(xs, min, min2) 

627 

628 

629def neg(x, neg0=None): 

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

631 

632 @kwarg neg0: Defines the return value for zero C{B{x}}: if C{None} 

633 return C{0.0}, if C{True} return C{NEG0 if B{x}=0.0} 

634 and C{0.0 if B{x}=NEG0} or if C{False} return C{B{x}} 

635 I{as-is} (C{bool} or C{None}). 

636 

637 @return: C{-B{x} if B{x} else 0.0, NEG0 or B{x}}. 

638 ''' 

639 return (-x) if x else ( 

640 _0_0 if neg0 is None else ( 

641 x if not neg0 else ( 

642 _0_0 if signBit(x) else _MODS.constants. 

643 NEG0))) # PYCHOK indent 

644 

645 

646def neg_(*xs): 

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

648 

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

650 ''' 

651 return map(neg, xs) 

652 

653 

654def _neg0(x): 

655 '''(INTERNAL) Return C{NEG0 if x < 0 else _0_0}, 

656 unlike C{_copysign_0_0} which returns C{_N_0_0}. 

657 ''' 

658 return _MODS.constants.NEG0 if x < 0 else _0_0 

659 

660 

661def _req_d_by(where, **name): 

662 '''(INTERNAL) Get the fully qualified name. 

663 ''' 

664 m = _MODS.named 

665 n = m._name__(**name) 

666 m = m.modulename(where, prefixed=True) 

667 if n: 

668 m = _DOT_(m, n) 

669 return _SPACE_(_required_, _by_, m) 

670 

671 

672def _reverange(n, stop=-1, step=-1): 

673 '''(INTERNAL) Reversed range yielding C{n-1, n-1-step, ..., stop+1}. 

674 ''' 

675 return range(n - 1, stop, step) 

676 

677 

678def signBit(x): 

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

680 

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

682 ''' 

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

684 

685 

686def _signOf(x, ref): # in .fsums 

687 '''(INTERNAL) Return the sign of B{C{x}} versus B{C{ref}}. 

688 ''' 

689 return (-1) if x < ref else (+1 if x > ref else 0) 

690 

691 

692def signOf(x): 

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

694 

695 @return: -1, 0 or +1 (C{int}). 

696 ''' 

697 try: 

698 s = x.signOf() # Fsum instance? 

699 except AttributeError: 

700 s = _signOf(x, 0) 

701 return s 

702 

703 

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

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

706 

707 @arg iterable: Items to be spliced (C{list}, C{tuple}, ...). 

708 @kwarg n: Number of slices to generate (C{int}). 

709 @kwarg fill: Optional fill value for missing items. 

710 

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

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

713 

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

715 

716 @note: Each generated slice is a C{tuple} or a C{list}, 

717 the latter only if the B{C{iterable}} is a C{list}. 

718 

719 @example: 

720 

721 >>> from pygeodesy import splice 

722 

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

724 >>> a, b 

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

726 

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

728 >>> a, b, c 

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

730 

731 >>> a, b, c = splice(range(10), n=3, fill=-1) 

732 >>> a, b, c 

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

734 

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

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

737 

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

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

740 ''' 

741 if not isint(n): 

742 raise _TypeError(n=n) 

743 

744 t = _xiterablen(iterable) 

745 if not isinstance(t, _list_tuple_types): 

746 t = tuple(t) 

747 

748 if n > 1: 

749 if fill: 

750 fill = _xkwds_get1(fill, fill=MISSING) 

751 if fill is not MISSING: 

752 m = len(t) % n 

753 if m > 0: # same type fill 

754 t = t + type(t)((fill,) * (n - m)) 

755 for i in range(n): 

756 # XXX t[i::n] chokes PyChecker 

757 yield t[slice(i, None, n)] 

758 else: 

759 yield t # 1 slice, all 

760 

761 

762def _splituple(strs, *sep_splits): # in .mgrs, ... 

763 '''(INTERNAL) Split a C{comma}- or C{whitespace}-separated 

764 string into a C{tuple} of stripped C{str}ings. 

765 ''' 

766 t = (strs.split(*sep_splits) if sep_splits else 

767 strs.replace(_COMMA_, _SPACE_).split()) if strs else () 

768 return tuple(s.strip() for s in t if s) 

769 

770 

771def unsigned0(x): 

772 '''Unsign if C{0.0}. 

773 

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

775 ''' 

776 return x if x else _0_0 

777 

778 

779def _xcopy(obj, deep=False): 

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

781 

782 @arg obj: The object to copy (any C{type}). 

783 @kwarg deep: If C{True}, make a deep, otherwise 

784 a shallow copy (C{bool}). 

785 

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

787 ''' 

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

789 

790 

791def _xcoverage(where, *required): # in .__main__ # PYCHOK no cover 

792 '''(INTERNAL) Import C{coverage} and check required version. 

793 ''' 

794 try: 

795 _xpackages(_xcoverage) 

796 import coverage 

797 except ImportError as x: 

798 raise _xImportError(x, where) 

799 return _xversion(coverage, where, *required) 

800 

801 

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

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

804 

805 @arg obj: The object to copy (any C{type}). 

806 @kwarg deep: If C{True}, copy deep, otherwise shallow (C{bool}). 

807 @kwarg items: Attributes to be changed (C{any}). 

808 

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

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

811 

812 @raise AttributeError: Some B{C{items}} invalid. 

813 ''' 

814 d = _xcopy(obj, deep=deep) 

815 for n, v in items.items(): 

816 if getattr(d, n, v) != v: 

817 setattr(d, n, v) 

818 elif not hasattr(d, n): 

819 t = _MODS.named.classname(obj) 

820 t = _SPACE_(_DOT_(t, n), _invalid_) 

821 raise _AttributeError(txt=t, obj=obj, **items) 

822# if items: 

823# _MODS.props._update_all(d) 

824 return d 

825 

826 

827def _xgeographiclib(where, *required): 

828 '''(INTERNAL) Import C{geographiclib} and check required version. 

829 ''' 

830 try: 

831 _xpackages(_xgeographiclib) 

832 import geographiclib 

833 except ImportError as x: 

834 raise _xImportError(x, where, Error=LazyImportError) 

835 return _xversion(geographiclib, where, *required) 

836 

837 

838def _xImportError(exc, where, Error=_ImportError, **name): 

839 '''(INTERNAL) Embellish an C{Lazy/ImportError}. 

840 ''' 

841 t = _req_d_by(where, **name) 

842 return Error(_Xstr(exc), txt=t, cause=exc) 

843 

844 

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

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

847 

848 @arg Types: One or more classes or types (C{class}), all 

849 positional. 

850 @kwarg names_values: One or more C{B{name}=value} pairs 

851 with the C{value} to be checked. 

852 

853 @raise TypeError: One B{C{names_values}} pair is not an 

854 instance of any of the B{C{Types}}. 

855 ''' 

856 if not (Types and names_values): 

857 raise _xAssertionError(_xinstanceof, *Types, **names_values) 

858 

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

860 if not isinstance(v, Types): 

861 raise _TypesError(n, v, *Types) 

862 

863 

864def _xiterable(obj): 

865 '''(INTERNAL) Return C{obj} if iterable, otherwise raise C{TypeError}. 

866 ''' 

867 return obj if isiterable(obj) else _xiterror(obj, _xiterable) # PYCHOK None 

868 

869 

870def _xiterablen(obj): 

871 '''(INTERNAL) Return C{obj} if iterable with C{__len__}, otherwise raise C{TypeError}. 

872 ''' 

873 return obj if isiterablen(obj) else _xiterror(obj, _xiterablen) # PYCHOK None 

874 

875 

876def _xiterror(obj, _xwhich): 

877 '''(INTERNAL) Helper for C{_xinterable} and C{_xiterablen}. 

878 ''' 

879 t = _not_(_xwhich.__name__[2:]) # _DUNDER_nameof 

880 raise _TypeError(repr(obj), txt=t) 

881 

882 

883def _xnumpy(where, *required): 

884 '''(INTERNAL) Import C{numpy} and check required version. 

885 ''' 

886 try: 

887 _xpackages(_xnumpy) 

888 import numpy 

889 except ImportError as x: 

890 raise _xImportError(x, where) 

891 return _xversion(numpy, where, *required) 

892 

893 

894def _xor(x, *xs): 

895 '''(INTERNAL) Exclusive-or C{x} and C{xs}. 

896 ''' 

897 for x_ in xs: 

898 x ^= x_ 

899 return x 

900 

901 

902def _xpackages(_xpkgf): 

903 '''(INTERNAL) Check dependency to be excluded. 

904 ''' 

905 if _XPACKAGES: # PYCHOK no cover 

906 n = _xpkgf.__name__[2:] # _DUNDER_nameof, less '_x' 

907 if n.lower() in _XPACKAGES: 

908 E = _PYGEODESY(_xpackages) 

909 x = _SPACE_(n, _in_, E) 

910 e = _enquote(_getenv(E, NN)) 

911 raise ImportError(_EQUAL_(x, e)) 

912 

913 

914def _xscalar(**names_values): 

915 '''(INTERNAL) Check all C{name=value} pairs to be C{scalar}. 

916 ''' 

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

918 if not isscalar(v): 

919 raise _TypeError(n, v, txt=_not_scalar_) 

920 

921 

922def _xscipy(where, *required): 

923 '''(INTERNAL) Import C{scipy} and check required version. 

924 ''' 

925 try: 

926 _xpackages(_xscipy) 

927 import scipy 

928 except ImportError as x: 

929 raise _xImportError(x, where) 

930 return _xversion(scipy, where, *required) 

931 

932 

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

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

935 

936 @arg Classes: One or more classes or types (C{class}), all 

937 positional. 

938 @kwarg names_values: One or more C{B{name}=value} pairs 

939 with the C{value} to be checked. 

940 

941 @raise TypeError: One B{C{names_values}} pair is not a 

942 (sub-)class of any of the B{C{Classes}}. 

943 ''' 

944 if not (Classes and names_values): 

945 raise _xAssertionError(_xsubclassof, *Classes, **names_values) 

946 

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

948 if not issubclassof(v, *Classes): 

949 raise _TypesError(n, v, *Classes) 

950 

951 

952def _xversion(package, where, *required, **name): 

953 '''(INTERNAL) Check the C{package} version vs B{C{required}}. 

954 ''' 

955 if required: 

956 t = _version_info(package) 

957 if t[:len(required)] < required: 

958 t = _SPACE_(package.__name__, # _DUNDER_nameof 

959 _version_, _DOT_(*t), 

960 _below_, _DOT_(*required), 

961 _req_d_by(where, **name)) 

962 raise ImportError(t) 

963 return package 

964 

965 

966def _xzip(*args, **strict): # PYCHOK no cover 

967 '''(INTERNAL) Standard C{zip(..., strict=True)}. 

968 ''' 

969 s = _xkwds_get1(strict, strict=True) 

970 if s: 

971 if _zip is zip: # < (3, 10) 

972 t = _MODS.streprs.unstr(_xzip, *args, strict=s) 

973 raise _NotImplementedError(t, txt=None) 

974 return _zip(*args) 

975 return zip(*args) 

976 

977 

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

979 _zip = zip # PYCHOK exported 

980else: # Python 3.10+ 

981 

982 def _zip(*args): 

983 return zip(*args, strict=True) 

984 

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

986 

987# **) MIT License 

988# 

989# Copyright (C) 2016-2025 -- mrJean1 at Gmail -- All Rights Reserved. 

990# 

991# Permission is hereby granted, free of charge, to any person obtaining a 

992# copy of this software and associated documentation files (the "Software"), 

993# to deal in the Software without restriction, including without limitation 

994# the rights to use, copy, modify, merge, publish, distribute, sublicense, 

995# and/or sell copies of the Software, and to permit persons to whom the 

996# Software is furnished to do so, subject to the following conditions: 

997# 

998# The above copyright notice and this permission notice shall be included 

999# in all copies or substantial portions of the Software. 

1000# 

1001# THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS 

1002# OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, 

1003# FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL 

1004# THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR 

1005# OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, 

1006# ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR 

1007# OTHER DEALINGS IN THE SOFTWARE.