1

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

3

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

5

6 Use env variable C{PYGEODESY_XPACKAGES} to avoid import of dependencies

7 C{geographiclib}, C{numpy} and/or C{scipy}. Set C{PYGEODESY_XPACKAGES}

8 to a comma-separated list of package names to be excluded from import.

9'''

10# make sure int/int division yields float quotient

11 from __future__ import division

12 division = 1 / 2 # .albers, .azimuthal, .constants, etc., .utily

13 if not division:

14 raise ImportError('%s 1/2 == %s' % ('division', division))

15 del division

16

17# from pygeodesy.cartesianBase import CartesianBase # _MODS

18# from pygeodesy.constants import isneg0, NEG0 # _MODS

19 from pygeodesy.errors import _AttributeError, _ImportError, _NotImplementedError, \

20 _TypeError, _TypesError, _ValueError, _xAssertionError, \

21 _xkwds_get1

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

23 from 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

27 from 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

34 from copy import copy as _copy, deepcopy as _deepcopy

35 from math import copysign as _copysign

36 import inspect as _inspect

37

38__all__ = _ALL_LAZY.basics

39__version__ = '24.05.29'

40

41_below_ = 'below'

42_list_tuple_types = (list, tuple)

43_PYGEODESY_XPACKAGES_ = 'PYGEODESY_XPACKAGES'

44_required_ = 'required'

45

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

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

48 except 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

55 try:

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

65 except ImportError:

66 _Sequence = tuple # immutable for .points._Basequence

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

68

69 try:

70 _Bytes = unicode, bytearray # PYCHOK expected

71 _Strs = basestring, str # XXX , 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

92 except NameError: # Python 3+

93 from pygeodesy.interns import _utf_8_

94

95 _Bytes = bytes, bytearray

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

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

122 a = k = 0

123 for _, p in _inspect.signature(func).parameters.items():

124 if p.kind is p.POSITIONAL_OR_KEYWORD:

125 if p.default is p.empty:

126 a += 1

127 else:

128 k += 1

129 except AttributeError: # .signature new Python 3+

130 s = _inspect.getargspec(func)

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

132 a = len(s.args) - k

133 if exelf and a > 0 and _inspect.ismethod(func):

134 a -= 1

135 return a, k

136

137

138 def _args_kwds_names(func, splast=False):

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

140 C{self} for methods.

141

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

143 at UNDERscores (C{bool}).

144

145 @note: Python 2 may I{not} include the C{*args} nor the

146 C{**kwds} names.

147 '''

148 try:

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

150 except AttributeError: # .signature new Python 3+

151 args_kwds = _inspect.getargspec(func).args

152 if splast and args_kwds:

153 args_kwds = list(args_kwds)

154 t = args_kwds[-1:]

155 if t:

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

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

158 args_kwds += s

159 return tuple(args_kwds)

160

161

162 def clips(sb, limit=50, white=NN):

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

164

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

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

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

168

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

170 '''

171 T = type(sb)

172 if len(sb) > limit > 8:

173 h = limit // 2

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

175 if white: # replace whitespace

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

177 return sb

178

179

180 def copysign0(x, y):

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

182

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

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

185 '''

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

187

188

189 def copytype(x, y):

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

191

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

193 '''

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

195

196

197 def halfs2(str2):

198 '''Split a string in 2 halfs.

199

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

201

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

203

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

205 '''

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

207 if r or not h:

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

209 return str2[:h], str2[h:]

210

211

212 def int1s(x):

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

214

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

216 '''

217 try:

218 return x.bit_count() # Python 3.10+

219 except AttributeError:

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

221 return bin(x).count(_1_)

222

223

224 def isbool(obj):

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

226

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

228

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

230 '''

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

232# or obj is True)

233

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

235

236

237 def isCartesian(obj, ellipsoidal=None):

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

239

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

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

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

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

244

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

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

247 '''

248 if ellipsoidal is not None:

249 try:

250 return obj.ellipsoidalCartesian if ellipsoidal else obj.sphericalCartesian

251 except AttributeError:

252 return None

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

254

255

256 if _FOR_DOCS: # XXX avoid epydoc Python 2.7 error

257

258 def isclass(obj):

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

260 '''

261 return _inspect.isclass(obj)

262 else:

263 isclass = _inspect.isclass

264

265

266 def iscomplex(obj, both=False):

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

268

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

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

271

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

273 '''

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

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

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

277 except (TypeError, ValueError):

278 return False

279

280

281 def isDEPRECATED(obj):

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

283

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

285 C{None} if undetermined.

286 '''

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

288 doc = obj.__doc__.lstrip()

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

290 except AttributeError:

291 return None

292

293

294 def isfloat(obj, both=False):

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

296

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

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

299

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

301 '''

302 try:

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

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

305 except (TypeError, ValueError):

306 return False

307

308

309 try:

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

311 except AttributeError: # Python 2-

312

313 def isidentifier(obj):

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

315 '''

316 return bool(obj and isstr(obj)

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

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

319

320

321 def isinstanceof(obj, *Classes):

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

323

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

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

326

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

328 C{None} otherwise.

329 '''

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

331

332

333 def isint(obj, both=False):

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

335

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

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

338 type and value (C{bool}).

339

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

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

342

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

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

345 '''

346 if isinstance(obj, _Ints):

347 return not isbool(obj)

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

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

350 return obj.is_integer()

351 except AttributeError:

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

353 return False

354

355

356 def isiterable(obj):

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

358

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

360

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

362 '''

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

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

365

366

367 def isiterablen(obj):

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

369

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

371

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

373 '''

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

375

376

377 try:

378 from keyword import iskeyword # Python 2.7+

379 except ImportError:

380

381 def iskeyword(unused):

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

383 '''

384 return False

385

386

387 def isLatLon(obj, ellipsoidal=None):

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

389

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

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

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

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

394

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

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

397 '''

398 if ellipsoidal is not None:

399 try:

400 return obj.ellipsoidalLatLon if ellipsoidal else obj.sphericalLatLon

401 except AttributeError:

402 return None

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

404

405

406 def islistuple(obj, minum=0):

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

408

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

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

411

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

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

414 '''

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

416

417

418 def isNvector(obj, ellipsoidal=None):

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

420

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

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

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

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

425

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

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

428 '''

429 if ellipsoidal is not None:

430 try:

431 return obj.ellipsoidalNvector if ellipsoidal else obj.sphericalNvector

432 except AttributeError:

433 return None

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

435

436

437 def isodd(x):

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

439

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

441

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

443 '''

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

445

446

447 def isscalar(obj, both=False):

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

449

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

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

452

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

454 zero residual, C{False} otherwise.

455 '''

456 if isinstance(obj, _Scalars):

457 return not isbool(obj)

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

459 try:

460 return bool(obj.residual == 0)

461 except (AttributeError, TypeError):

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

463 return False

464

465

466 def issequence(obj, *excls):

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

468

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

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

471

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

473

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

475 '''

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

477

478

479 def isstr(obj):

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

481

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

483

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

485 C{False} otherwise.

486 '''

487 return isinstance(obj, _Strs)

488

489

490 def issubclassof(Sub, *Supers):

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

492

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

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

495

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

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

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

499 '''

500 if isclass(Sub):

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

502 if t:

503 return bool(issubclass(Sub, t))

504 return None

505

506

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

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

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

510

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

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

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

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

515 sorting in C{descending} order.

516 '''

517 def _ins(item): # functools.cmp_to_key

518 k, v = item

519 return k.lower()

520

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

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

523

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

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

526

527

528 def len2(items):

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

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

531

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

533

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

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

536 '''

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

538 items = list(items)

539 return len(items), items

540

541

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

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

544 and return a C{tuple} of results.

545

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

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

548

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

550 '''

551 return tuple(map(fun1, xs))

552

553

554 def map2(fun, *xs):

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

556

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

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

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

560 maintains the Python 2 behavior.

561

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

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

564

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

566 '''

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

568

569

570 def neg(x, neg0=None):

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

572

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

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

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

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

577

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

579 '''

580 return (-x) if x else (

581 _0_0 if neg0 is None else (

582 x if not neg0 else (

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

584 NEG0))) # PYCHOK indent

585

586

587 def neg_(*xs):

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

589

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

591 '''

592 return map(neg, xs)

593

594

595 def _neg0(x):

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

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

598 '''

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

600

601

602 def _req_d_by(where, **name):

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

604 '''

605 m = _MODS.named

606 n = m._name__(**name)

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

608 if n:

609 m = _DOT_(m, n)

610 return _SPACE_(_required_, _by_, m)

611

612

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

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

615 '''

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

617

618

619 def signBit(x):

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

621

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

623 '''

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

625

626

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

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

629 '''

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

631

632

633 def signOf(x):

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

635

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

637 '''

638 try:

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

640 except AttributeError:

641 s = _signOf(x, 0)

642 return s

643

644

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

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

647

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

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

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

651

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

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

654

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

656

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

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

659

660 @example:

661

662 >>> from pygeodesy import splice

663

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

665 >>> a, b

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

667

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

669 >>> a, b, c

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

671

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

673 >>> a, b, c

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

675

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

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

678

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

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

681 '''

682 if not isint(n):

683 raise _TypeError(n=n)

684

685 t = _xiterablen(iterable)

686 if not isinstance(t, _list_tuple_types):

687 t = tuple(t)

688

689 if n > 1:

690 if fill:

691 fill = _xkwds_get1(fill, fill=MISSING)

692 if fill is not MISSING:

693 m = len(t) % n

694 if m > 0: # same type fill

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

696 for i in range(n):

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

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

699 else:

700 yield t # 1 slice, all

701

702

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

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

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

706 '''

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

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

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

710

711

712 def unsigned0(x):

713 '''Unsign if C{0.0}.

714

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

716 '''

717 return x if x else _0_0

718

719

720 def _xcopy(obj, deep=False):

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

722

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

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

725 a shallow copy (C{bool}).

726

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

728 '''

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

730

731

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

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

734

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

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

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

738

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

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

741

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

743 '''

744 d = _xcopy(obj, deep=deep)

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

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

747 setattr(d, n, v)

748 elif not hasattr(d, n):

749 t = _MODS.named.classname(obj)

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

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

752# if items:

753# _MODS.props._update_all(d)

754 return d

755

756

757 def _xgeographiclib(where, *required):

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

759 '''

760 try:

761 _xpackage(_xgeographiclib)

762 import geographiclib

763 except ImportError as x:

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

765 return _xversion(geographiclib, where, *required)

766

767

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

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

770 '''

771 t = _req_d_by(where, **name)

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

773

774

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

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

777

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

779 positional.

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

781 with the C{value} to be checked.

782

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

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

785 '''

786 if not (Types and names_values):

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

788

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

790 if not isinstance(v, Types):

791 raise _TypesError(n, v, *Types)

792

793

794 def _xiterable(obj):

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

796 '''

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

798

799

800 def _xiterablen(obj):

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

802 '''

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

804

805

806 def _xiterror(obj, _xwhich):

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

808 '''

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

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

811

812

813 def _xnumpy(where, *required):

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

815 '''

816 try:

817 _xpackage(_xnumpy)

818 import numpy

819 except ImportError as x:

820 raise _xImportError(x, where)

821 return _xversion(numpy, where, *required)

822

823

824 def _xor(x, *xs):

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

826 '''

827 for x_ in xs:

828 x ^= x_

829 return x

830

831

832 def _xpackage(_xpkg):

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

834 '''

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

836 if n in _XPACKAGES:

837 x = _SPACE_(n, _in_, _PYGEODESY_XPACKAGES_)

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

839 raise ImportError(_EQUAL_(x, e))

840

841

842 def _xscalar(**names_values):

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

844 '''

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

846 if not isscalar(v):

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

848

849

850 def _xscipy(where, *required):

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

852 '''

853 try:

854 _xpackage(_xscipy)

855 import scipy

856 except ImportError as x:

857 raise _xImportError(x, where)

858 return _xversion(scipy, where, *required)

859

860

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

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

863

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

865 positional.

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

867 with the C{value} to be checked.

868

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

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

871 '''

872 if not (Classes and names_values):

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

874

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

876 if not issubclassof(v, *Classes):

877 raise _TypesError(n, v, *Classes)

878

879

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

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

882 '''

883 if required:

884 t = _version_info(package)

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

886 t = _SPACE_(package.__name__, # _dunder_nameof

887 _version_, _DOT_(*t),

888 _below_, _DOT_(*required),

889 _req_d_by(where, **name))

890 raise ImportError(t)

891 return package

892

893

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

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

896 '''

897 s = _xkwds_get1(strict, strict=True)

898 if s:

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

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

901 raise _NotImplementedError(t, txt=None)

902 return _zip(*args)

903 return zip(*args)

904

905

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

907 _zip = zip # PYCHOK exported

908 else: # Python 3.10+

909

910 def _zip(*args):

911 return zip(*args, strict=True)

912

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

914

915# **) MIT License

916#

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

918#

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

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

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

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

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

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

925#

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

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

928#

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

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

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

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

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

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

935# OTHER DEALINGS IN THE SOFTWARE.