Coverage for pygeodesy/basics.py: 88%

267 statements  

« prev     ^ index     » next       coverage.py v7.6.0, created at 2024-08-02 18:24 -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 

22from pygeodesy.internals import _0_0, _enquote, _passarg, _version_info 

23from pygeodesy.interns import MISSING, NN, _1_, _by_, _COMMA_, _DOT_, _DEPRECATED_, \ 

24 _ELLIPSIS4_, _EQUAL_, _in_, _invalid_, _N_A_, _not_, \ 

25 _not_scalar_, _odd_, _SPACE_, _UNDER_, _version_ 

26# from pygeodesy.latlonBase import LatLonBase # _MODS 

27from pygeodesy.lazily import _ALL_LAZY, _ALL_MODS as _MODS, _FOR_DOCS, _getenv, \ 

28 LazyImportError, _sys_version_info2 

29# from pygeodesy.named import classname, modulename, _name__ # _MODS 

30# from pygeodesy.nvectorBase import NvectorBase # _MODS 

31# from pygeodesy.props import _update_all # _MODS 

32# from pygeodesy.streprs import Fmt # _MODS 

33# from pygeodesy.unitsBase import _NamedUnit, Str # _MODS 

34 

35from copy import copy as _copy, deepcopy as _deepcopy 

36from math import copysign as _copysign 

37import inspect as _inspect 

38 

39__all__ = _ALL_LAZY.basics 

40__version__ = '24.07.06' 

41 

42_below_ = 'below' 

43_list_tuple_types = (list, tuple) 

44_PYGEODESY_XPACKAGES_ = 'PYGEODESY_XPACKAGES' 

45_required_ = 'required' 

46 

47try: # Luciano Ramalho, "Fluent Python", O'Reilly, 2016 p. 395, 2022 p. 577+ 

48 from numbers import Integral as _Ints, Real as _Scalars # .units 

49except ImportError: 

50 try: 

51 _Ints = int, long # int objects (C{tuple}) 

52 except NameError: # Python 3+ 

53 _Ints = int, # int objects (C{tuple}) 

54 _Scalars = (float,) + _Ints 

55 

56try: 

57 try: # use C{from collections.abc import ...} in Python 3.9+ 

58 from collections.abc import Sequence as _Sequence # in .points 

59 except ImportError: # no .abc in Python 3.8- and 2.7- 

60 from collections import Sequence as _Sequence # in .points 

61 if isinstance([], _Sequence) and isinstance((), _Sequence): 

62 # and isinstance(range(1), _Sequence): 

63 _Seqs = _Sequence 

64 else: 

65 raise ImportError() # _AssertionError 

66except ImportError: 

67 _Sequence = tuple # immutable for .points._Basequence 

68 _Seqs = list, _Sequence # range for function len2 below 

69 

70try: 

71 _Bytes = unicode, bytearray # PYCHOK expected 

72 _Strs = basestring, str # XXX , bytes 

73 str2ub = ub2str = _passarg # avoids UnicodeDecodeError 

74 

75 def _Xstr(exc): # PYCHOK no cover 

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

77 

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

79 

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_("can't", t4[3] or _N_A_) 

90 del tb, t4 

91 return t 

92 

93except NameError: # Python 3+ 

94 from pygeodesy.interns import _utf_8_ 

95 

96 _Bytes = bytes, bytearray 

97 _Strs = str, # tuple 

98 _Xstr = str 

99 

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 

106 

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 

113 

114 

115def _args_kwds_count2(func, exelf=True): 

116 '''(INTERNAL) Get a C{func}'s args and kwds count as 2-tuple 

117 C{(nargs, nkwds)}, including arg C{self} for methods. 

118 

119 @kwarg exelf: If C{True}, exclude C{self} in the C{args} 

120 of a method (C{bool}). 

121 ''' 

122 try: 

123 a = k = 0 

124 for _, p in _inspect.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: # .signature new Python 3+ 

131 s = _inspect.getargspec(func) 

132 k = len(s.defaults or ()) 

133 a = len(s.args) - k 

134 if exelf and a > 0 and _inspect.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 try: 

150 args_kwds = _inspect.signature(func).parameters.keys() 

151 except AttributeError: # .signature new Python 3+ 

152 args_kwds = _inspect.getargspec(func).args 

153 if splast and args_kwds: 

154 args_kwds = list(args_kwds) 

155 t = args_kwds[-1:] 

156 if t: 

157 s = t[0].strip(_UNDER_).split(_UNDER_) 

158 if len(s) > 1 or s != t: 

159 args_kwds += s 

160 return tuple(args_kwds) 

161 

162 

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

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

165 

166 @arg sb: String (C{str} or C{bytes}). 

167 @kwarg limit: Length limit (C{int}). 

168 @kwarg white: Optionally, replace all whitespace (C{str}). 

169 @kwarg len: IF C{True} append the original I{[length]} (C{bool}). 

170 

171 @return: The clipped or unclipped B{C{sb}}. 

172 ''' 

173 T, n = type(sb), len(sb) 

174 if n > limit > 8: 

175 h = limit // 2 

176 sb = T(_ELLIPSIS4_).join((sb[:h], sb[-h:])) 

177 if length: 

178 n = _MODS.streprs.Fmt.SQUARE(n) 

179 sb = T(NN).join((sb, n)) 

180 if white: # replace whitespace 

181 sb = T(white).join(sb.split()) 

182 return sb 

183 

184 

185def copysign0(x, y): 

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

187 

188 @return: C{math.copysign(B{x}, B{y})} if B{C{x}} else 

189 C{type(B{x})(0)}. 

190 ''' 

191 return _copysign(x, (y if y else 0)) if x else copytype(0, x) 

192 

193 

194def copytype(x, y): 

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

196 

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

198 ''' 

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

200 

201 

202def _enumereverse(iterable): 

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

204 ''' 

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

206 yield j, iterable[j] 

207 

208 

209def halfs2(str2): 

210 '''Split a string in 2 halfs. 

211 

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

213 

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

215 

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

217 ''' 

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

219 if r or not h: 

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

221 return str2[:h], str2[h:] 

222 

223 

224def int1s(x): 

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

226 

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

228 ''' 

229 try: 

230 return x.bit_count() # Python 3.10+ 

231 except AttributeError: 

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

233 return bin(x).count(_1_) 

234 

235 

236def isbool(obj): 

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

238 

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

240 

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

242 ''' 

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

244# or obj is True) 

245 

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

247 

248 

249def isCartesian(obj, ellipsoidal=None): 

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

251 

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

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

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

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

256 

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

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

259 ''' 

260 if ellipsoidal is not None: 

261 try: 

262 return obj.ellipsoidalCartesian if ellipsoidal else obj.sphericalCartesian 

263 except AttributeError: 

264 return None 

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

266 

267 

268if _FOR_DOCS: # XXX avoid epydoc Python 2.7 error 

269 

270 def isclass(obj): 

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

272 ''' 

273 return _inspect.isclass(obj) 

274else: 

275 isclass = _inspect.isclass 

276 

277 

278def iscomplex(obj, both=False): 

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

280 

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

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

283 

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

285 ''' 

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

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

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

289 except (TypeError, ValueError): 

290 return False 

291 

292 

293def isDEPRECATED(obj): 

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

295 

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

297 C{None} if undetermined. 

298 ''' 

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

300 doc = obj.__doc__.lstrip() 

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

302 except AttributeError: 

303 return None 

304 

305 

306def isfloat(obj, both=False): 

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

308 

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

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

311 

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

313 ''' 

314 try: 

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

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

317 except (TypeError, ValueError): 

318 return False 

319 

320 

321try: 

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

323except AttributeError: # Python 2- 

324 

325 def isidentifier(obj): 

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

327 ''' 

328 return bool(obj and isstr(obj) 

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

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

331 

332 

333def isinstanceof(obj, *Classes): 

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

335 

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

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

338 

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

340 C{None} otherwise. 

341 ''' 

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

343 

344 

345def isint(obj, both=False): 

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

347 

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

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

350 type and value (C{bool}). 

351 

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

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

354 

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

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

357 ''' 

358 if isinstance(obj, _Ints): 

359 return not isbool(obj) 

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

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

362 return obj.is_integer() 

363 except AttributeError: 

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

365 return False 

366 

367 

368def isiterable(obj): 

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

370 

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

372 

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

374 ''' 

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

376 return hasattr(obj, '__iter__') # map, range, set 

377 

378 

379def isiterablen(obj): 

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

381 

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

383 

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

385 ''' 

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

387 

388 

389try: 

390 from keyword import iskeyword # Python 2.7+ 

391except ImportError: 

392 

393 def iskeyword(unused): 

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

395 ''' 

396 return False 

397 

398 

399def isLatLon(obj, ellipsoidal=None): 

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

401 

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

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

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

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

406 

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

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

409 ''' 

410 if ellipsoidal is not None: 

411 try: 

412 return obj.ellipsoidalLatLon if ellipsoidal else obj.sphericalLatLon 

413 except AttributeError: 

414 return None 

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

416 

417 

418def islistuple(obj, minum=0): 

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

420 

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

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

423 

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

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

426 ''' 

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

428 

429 

430def isNvector(obj, ellipsoidal=None): 

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

432 

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

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

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

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

437 

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

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

440 ''' 

441 if ellipsoidal is not None: 

442 try: 

443 return obj.ellipsoidalNvector if ellipsoidal else obj.sphericalNvector 

444 except AttributeError: 

445 return None 

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

447 

448 

449def isodd(x): 

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

451 

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

453 

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

455 ''' 

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

457 

458 

459def isscalar(obj, both=False): 

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

461 

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

463 @kwarg both: If C{True}, check L{Fsum<Fsum.residual>}. 

464 

465 @return: C{True} if C{int}, C{float} or L{Fsum} with 

466 zero residual, C{False} otherwise. 

467 ''' 

468 if isinstance(obj, _Scalars): 

469 return not isbool(obj) 

470 elif both: # and isinstance(obj, Fsum) 

471 try: 

472 return bool(obj.residual == 0) 

473 except (AttributeError, TypeError): 

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

475 return False 

476 

477 

478def issequence(obj, *excls): 

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

480 

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

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

483 

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

485 

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

487 ''' 

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

489 

490 

491def isstr(obj): 

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

493 

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

495 

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

497 C{False} otherwise. 

498 ''' 

499 return isinstance(obj, _Strs) 

500 

501 

502def issubclassof(Sub, *Supers): 

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

504 

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

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

507 

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

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

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

511 ''' 

512 if isclass(Sub): 

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

514 if t: 

515 return bool(issubclass(Sub, t)) 

516 return None 

517 

518 

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

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

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

522 

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

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

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

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

527 sorting in C{descending} order. 

528 ''' 

529 def _ins(item): # functools.cmp_to_key 

530 k, v = item 

531 return k.lower() 

532 

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

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

535 

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

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

538 

539 

540def len2(items): 

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

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

543 

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

545 

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

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

548 ''' 

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

550 items = list(items) 

551 return len(items), items 

552 

553 

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

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

556 and return a C{tuple} of results. 

557 

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

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

560 

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

562 ''' 

563 return tuple(map(fun1, xs)) 

564 

565 

566def map2(fun, *xs): 

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

568 

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

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

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

572 maintains the Python 2 behavior. 

573 

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

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

576 

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

578 ''' 

579 return tuple(map(fun, *xs)) 

580 

581 

582def neg(x, neg0=None): 

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

584 

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

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

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

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

589 

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

591 ''' 

592 return (-x) if x else ( 

593 _0_0 if neg0 is None else ( 

594 x if not neg0 else ( 

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

596 NEG0))) # PYCHOK indent 

597 

598 

599def neg_(*xs): 

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

601 

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

603 ''' 

604 return map(neg, xs) 

605 

606 

607def _neg0(x): 

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

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

610 ''' 

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

612 

613 

614def _req_d_by(where, **name): 

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

616 ''' 

617 m = _MODS.named 

618 n = m._name__(**name) 

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

620 if n: 

621 m = _DOT_(m, n) 

622 return _SPACE_(_required_, _by_, m) 

623 

624 

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

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

627 ''' 

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

629 

630 

631def signBit(x): 

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

633 

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

635 ''' 

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

637 

638 

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

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

641 ''' 

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

643 

644 

645def signOf(x): 

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

647 

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

649 ''' 

650 try: 

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

652 except AttributeError: 

653 s = _signOf(x, 0) 

654 return s 

655 

656 

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

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

659 

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

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

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

663 

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

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

666 

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

668 

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

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

671 

672 @example: 

673 

674 >>> from pygeodesy import splice 

675 

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

677 >>> a, b 

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

679 

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

681 >>> a, b, c 

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

683 

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

685 >>> a, b, c 

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

687 

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

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

690 

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

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

693 ''' 

694 if not isint(n): 

695 raise _TypeError(n=n) 

696 

697 t = _xiterablen(iterable) 

698 if not isinstance(t, _list_tuple_types): 

699 t = tuple(t) 

700 

701 if n > 1: 

702 if fill: 

703 fill = _xkwds_get1(fill, fill=MISSING) 

704 if fill is not MISSING: 

705 m = len(t) % n 

706 if m > 0: # same type fill 

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

708 for i in range(n): 

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

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

711 else: 

712 yield t # 1 slice, all 

713 

714 

715def _splituple(strs, *sep_splits): # in .mgrs, .osgr, .webmercator 

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

717 string into a C{tuple} of stripped strings. 

718 ''' 

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

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

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

722 

723 

724def unsigned0(x): 

725 '''Unsign if C{0.0}. 

726 

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

728 ''' 

729 return x if x else _0_0 

730 

731 

732def _xcopy(obj, deep=False): 

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

734 

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

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

737 a shallow copy (C{bool}). 

738 

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

740 ''' 

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

742 

743 

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

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

746 

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

748 @kwarg deep: If C{True} copy deep, otherwise shallow. 

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

750 

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

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

753 

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

755 ''' 

756 d = _xcopy(obj, deep=deep) 

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

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

759 setattr(d, n, v) 

760 elif not hasattr(d, n): 

761 t = _MODS.named.classname(obj) 

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

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

764# if items: 

765# _MODS.props._update_all(d) 

766 return d 

767 

768 

769def _xgeographiclib(where, *required): 

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

771 ''' 

772 try: 

773 _xpackage(_xgeographiclib) 

774 import geographiclib 

775 except ImportError as x: 

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

777 return _xversion(geographiclib, where, *required) 

778 

779 

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

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

782 ''' 

783 t = _req_d_by(where, **name) 

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

785 

786 

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

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

789 

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

791 positional. 

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

793 with the C{value} to be checked. 

794 

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

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

797 ''' 

798 if not (Types and names_values): 

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

800 

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

802 if not isinstance(v, Types): 

803 raise _TypesError(n, v, *Types) 

804 

805 

806def _xiterable(obj): 

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

808 ''' 

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

810 

811 

812def _xiterablen(obj): 

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

814 ''' 

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

816 

817 

818def _xiterror(obj, _xwhich): 

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

820 ''' 

821 t = _not_(_xwhich.__name__[2:]) # _dunder_nameof 

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

823 

824 

825def _xnumpy(where, *required): 

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

827 ''' 

828 try: 

829 _xpackage(_xnumpy) 

830 import numpy 

831 except ImportError as x: 

832 raise _xImportError(x, where) 

833 return _xversion(numpy, where, *required) 

834 

835 

836def _xor(x, *xs): 

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

838 ''' 

839 for x_ in xs: 

840 x ^= x_ 

841 return x 

842 

843 

844def _xpackage(_xpkg): 

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

846 ''' 

847 n = _xpkg.__name__[2:] # _dunder_nameof 

848 if n in _XPACKAGES: 

849 x = _SPACE_(n, _in_, _PYGEODESY_XPACKAGES_) 

850 e = _enquote(_getenv(_PYGEODESY_XPACKAGES_, NN)) 

851 raise ImportError(_EQUAL_(x, e)) 

852 

853 

854def _xscalar(**names_values): 

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

856 ''' 

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

858 if not isscalar(v): 

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

860 

861 

862def _xscipy(where, *required): 

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

864 ''' 

865 try: 

866 _xpackage(_xscipy) 

867 import scipy 

868 except ImportError as x: 

869 raise _xImportError(x, where) 

870 return _xversion(scipy, where, *required) 

871 

872 

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

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

875 

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

877 positional. 

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

879 with the C{value} to be checked. 

880 

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

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

883 ''' 

884 if not (Classes and names_values): 

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

886 

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

888 if not issubclassof(v, *Classes): 

889 raise _TypesError(n, v, *Classes) 

890 

891 

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

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

894 ''' 

895 if required: 

896 t = _version_info(package) 

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

898 t = _SPACE_(package.__name__, # _dunder_nameof 

899 _version_, _DOT_(*t), 

900 _below_, _DOT_(*required), 

901 _req_d_by(where, **name)) 

902 raise ImportError(t) 

903 return package 

904 

905 

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

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

908 ''' 

909 s = _xkwds_get1(strict, strict=True) 

910 if s: 

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

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

913 raise _NotImplementedError(t, txt=None) 

914 return _zip(*args) 

915 return zip(*args) 

916 

917 

918if _sys_version_info2 < (3, 10): # see .errors 

919 _zip = zip # PYCHOK exported 

920else: # Python 3.10+ 

921 

922 def _zip(*args): 

923 return zip(*args, strict=True) 

924 

925_XPACKAGES = _splituple(_getenv(_PYGEODESY_XPACKAGES_, NN).lower()) 

926 

927# **) MIT License 

928# 

929# Copyright (C) 2016-2024 -- mrJean1 at Gmail -- All Rights Reserved. 

930# 

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

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

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

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

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

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

937# 

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

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

940# 

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

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

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

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

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

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

947# OTHER DEALINGS IN THE SOFTWARE.