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.errors import _AssertionError, _AttributeError, _ImportError, \

18 _TypeError, _TypesError, _ValueError, _xkwds_get

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

20 _ELLIPSIS4_, _enquote, _EQUAL_, _in_, _invalid_, _N_A_, \

21 _SPACE_, _UNDER_, _version_ # _utf_8_

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

23 _getenv, _sys, _sys_version_info2

24

25 from copy import copy as _copy, deepcopy as _deepcopy

26 from math import copysign as _copysign

27 import inspect as _inspect

28

29__all__ = _ALL_LAZY.basics

30__version__ = '23.11.21'

31

32_0_0 = 0.0 # in .constants

33_below_ = 'below'

34_can_t_ = "can't"

35_list_tuple_types = (list, tuple)

36_list_tuple_set_types = (list, tuple, set)

37_odd_ = 'odd'

38_required_ = 'required'

39_PYGEODESY_XPACKAGES_ = 'PYGEODESY_XPACKAGES'

40

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

42 from numbers import Integral as _Ints, Real as _Scalars

43 except ImportError:

44 try:

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

46 except NameError: # Python 3+

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

48 _Scalars = _Ints + (float,)

49

50 try:

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

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

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

54 from collections import Sequence as _Sequence # in .points

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

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

57 _Seqs = _Sequence

58 else:

59 raise ImportError # _AssertionError

60 except ImportError:

61 _Sequence = tuple # immutable for .points._Basequence

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

63

64 try:

65 _Bytes = unicode, bytearray # PYCHOK expected

66 _Strs = basestring, str # XXX , bytes

67

68 def _pass(x): # == .utily._passarg

69 '''Pass thru, no-op'''

70 return x

71

72 str2ub = ub2str = _pass # 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 clips(sb, limit=50, white=NN):

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

116

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

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

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

120

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

122 '''

123 T = type(sb)

124 if len(sb) > limit > 8:

125 h = limit // 2

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

127 if white: # replace whitespace

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

129 return sb

130

131

132 def copysign0(x, y):

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

134

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

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

137 '''

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

139

140

141 def copytype(x, y):

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

143

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

145 '''

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

147

148

149 def halfs2(str2):

150 '''Split a string in 2 halfs.

151

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

153

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

155

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

157 '''

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

159 if r or not h:

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

161 return str2[:h], str2[h:]

162

163

164 def int1s(x):

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

166

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

168 '''

169 try:

170 return x.bit_count() # Python 3.10+

171 except AttributeError:

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

173 return bin(x).count(_1_)

174

175

176 def isbool(obj):

177 '''Check whether an object is C{bool}ean.

178

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

180

181 @return: C{True} if B{C{obj}} is C{bool}ean,

182 C{False} otherwise.

183 '''

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

185# or obj is True)

186

187 if isbool(1) or isbool(0): # PYCHOK assert

188 raise _AssertionError(isbool=1)

189

190 if _FOR_DOCS: # XXX avoid epidoc Python 2.7 error

191

192 def isclass(obj):

193 '''Return C{True} if B{C{obj}} is a C{class} or C{type}.

194

195 @see: Python's C{inspect.isclass}.

196 '''

197 return _inspect.isclass(obj)

198 else:

199 isclass = _inspect.isclass

200

201

202 def isCartesian(obj, ellipsoidal=None):

203 '''Is B{C{obj}} some C{Cartesian}?

204

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

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

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

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

209

210 @return: C{type(B{obj}} if B{C{obj}} is a C{Cartesian} instance of

211 the required type, C{False} if a C{Cartesian} of an other

212 type or C{None} otherwise.

213 '''

214 if ellipsoidal is not None:

215 try:

216 return obj.ellipsoidalCartesian if ellipsoidal else obj.sphericalCartesian

217 except AttributeError:

218 return None

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

220

221

222 def iscomplex(obj):

223 '''Check whether an object is a C{complex} or complex C{str}.

224

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

226

227 @return: C{True} if B{C{obj}} is C{complex}, otherwise

228 C{False}.

229 '''

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

231 return isinstance(obj, complex) or (isstr(obj)

232 and isinstance(complex(obj), complex)) # numbers.Complex?

233 except (TypeError, ValueError):

234 return False

235

236

237 def isDEPRECATED(obj):

238 '''Return C{True} if C{B{obj}} is a C{DEPRECATED} class, method

239 or function, C{False} if not or C{None} if undetermined.

240 '''

241 try: # XXX inspect.getdoc(obj)

242 return bool(obj.__doc__.lstrip().startswith(_DEPRECATED_))

243 except AttributeError:

244 return None

245

246

247 def isfloat(obj):

248 '''Check whether an object is a C{float} or float C{str}.

249

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

251

252 @return: C{True} if B{C{obj}} is a C{float}, otherwise

253 C{False}.

254 '''

255 try:

256 return isinstance( obj, float) or (isstr(obj)

257 and isinstance(float(obj), float))

258 except (TypeError, ValueError):

259 return False

260

261

262 try:

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

264 except AttributeError: # Python 2-

265

266 def isidentifier(obj):

267 '''Return C{True} if B{C{obj}} is a Python identifier.

268 '''

269 return bool(obj and isstr(obj)

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

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

272

273

274 def isinstanceof(obj, *classes):

275 '''Is B{C{ob}} an intance of one of the C{classes}?

276

277 @arg obj: The instance (any C{type}).

278 @arg classes: One or more classes (C{class}).

279

280 @return: C{type(B{obj}} if B{C{obj}} is an instance

281 of the B{C{classes}}, C{None} otherwise.

282 '''

283 return type(obj) if isinstance(obj, classes) else None

284

285

286 def isint(obj, both=False):

287 '''Check for C{int} type or an integer C{float} value.

288

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

290 @kwarg both: If C{true}, check C{float} and L{Fsum}

291 type and value (C{bool}).

292

293 @return: C{True} if B{C{obj}} is C{int} or I{integer}

294 C{float} or L{Fsum}, C{False} otherwise.

295

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

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

298 '''

299 if isinstance(obj, _Ints) and not isbool(obj):

300 return True

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

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

303 return obj.is_integer()

304 except AttributeError:

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

306 return False

307

308

309 try:

310 from keyword import iskeyword # Python 2.7+

311 except ImportError:

312

313 def iskeyword(unused):

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

315 '''

316 return False

317

318

319 def isLatLon(obj, ellipsoidal=None):

320 '''Is B{C{obj}} some C{LatLon}?

321

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

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

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

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

326

327 @return: C{type(B{obj}} if B{C{obj}} is a C{LatLon} instance of

328 the required type, C{False} if a C{LatLon} of an other

329 type or {None} otherwise.

330 '''

331 if ellipsoidal is not None:

332 try:

333 return obj.ellipsoidalLatLon if ellipsoidal else obj.sphericalLatLon

334 except AttributeError:

335 return None

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

337

338

339 def islistuple(obj, minum=0):

340 '''Check for list or tuple C{type} with a minumal length.

341

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

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

344

345 @return: C{True} if B{C{obj}} is C{list} or C{tuple} with

346 C{len} at least B{C{minum}}, C{False} otherwise.

347 '''

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

349

350

351 def isNvector(obj, ellipsoidal=None):

352 '''Is B{C{obj}} some C{Nvector}?

353

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

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

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

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

358

359 @return: C{type(B{obj}} if B{C{obj}} is an C{Nvector} instance of

360 the required type, C{False} if an C{Nvector} of an other

361 type or {None} otherwise.

362 '''

363 if ellipsoidal is not None:

364 try:

365 return obj.ellipsoidalNvector if ellipsoidal else obj.sphericalNvector

366 except AttributeError:

367 return None

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

369

370

371 def isodd(x):

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

373

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

375

376 @return: C{True} if B{C{x}} is odd,

377 C{False} otherwise.

378 '''

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

380

381

382 def isscalar(obj):

383 '''Check for scalar types.

384

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

386

387 @return: C{True} if B{C{obj}} is C{scalar}, C{False} otherwise.

388 '''

389 return isinstance(obj, _Scalars) and not isbool(obj)

390

391

392 def issequence(obj, *excls):

393 '''Check for sequence types.

394

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

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

397

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

399

400 @return: C{True} if B{C{obj}} is a sequence, C{False} otherwise.

401 '''

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

403

404

405 def isstr(obj):

406 '''Check for string types.

407

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

409

410 @return: C{True} if B{C{obj}} is C{str}, C{False} otherwise.

411 '''

412 return isinstance(obj, _Strs)

413

414

415 def issubclassof(Sub, *Supers):

416 '''Check whether a class is a sub-class of some other class(es).

417

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

419 @arg Supers: One or more C(super) classes (C{class}).

420

421 @return: C{True} if B{C{Sub}} is a sub-class of any B{C{Supers}},

422 C{False} if not (C{bool}) or C{None} if B{C{Sub}} is not

423 a class or if no B{C{Supers}} are given or none of those

424 are a class.

425 '''

426 if isclass(Sub):

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

428 if t:

429 return bool(issubclass(Sub, t))

430 return None

431

432

433 def len2(items):

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

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

436

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

438

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

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

441 '''

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

443 items = list(items)

444 return len(items), items

445

446

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

448 '''Apply each B{C{xs}} to a single-argument function and

449 return a C{tuple} of results.

450

451 @arg fun1: 1-Arg function to apply (C{callable}).

452 @arg xs: Arguments to apply (C{any positional}).

453

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

455 '''

456 return tuple(map(fun1, xs))

457

458

459 def map2(func, *xs):

460 '''Apply arguments to a function and return a C{tuple} of results.

461

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

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

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

465 maintains the Python 2 behavior.

466

467 @arg func: Function to apply (C{callable}).

468 @arg xs: Arguments to apply (C{list, tuple, ...}).

469

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

471 '''

472 return tuple(map(func, *xs))

473

474

475 def neg(x, neg0=None):

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

477

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

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

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

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

482

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

484 '''

485 return (-x) if x else (_0_0 if neg0 is None else (x if not neg0 else

486 (_0_0 if signBit(x) else _MODS.constants.NEG0)))

487

488

489 def neg_(*xs):

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

491

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

493 '''

494 return map(neg, xs)

495

496

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

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

499 '''

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

501

502

503 def signBit(x):

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

505

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

507 '''

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

509

510

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

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

513 '''

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

515

516

517 def signOf(x):

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

519

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

521 '''

522 try:

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

524 except AttributeError:

525 s = _signOf(x, 0)

526 return s

527

528

529 def _sizeof(inst):

530 '''(INTERNAL) Recursively size an C{inst}ance.

531

532 @return: Instance' size in bytes (C{int}),

533 ignoring class attributes and

534 counting duplicates only once or

535 C{None}.

536

537 @note: With C{PyPy}, the size is always C{None}.

538 '''

539 try:

540 _zB = _sys.getsizeof

541 _zD = _zB(None) # get some default

542 except TypeError: # PyPy3.10

543 return None

544

545 def _zR(s, iterable):

546 z, _s = 0, s.add

547 for o in iterable:

548 i = id(o)

549 if i not in s:

550 _s(i)

551 z += _zB(o, _zD)

552 if isinstance(o, dict):

553 z += _zR(s, o.keys())

554 z += _zR(s, o.values())

555 elif isinstance(o, _list_tuple_set_types):

556 z += _zR(s, o)

557 else:

558 try: # size instance' attr values only

559 z += _zR(s, o.__dict__.values())

560 except AttributeError: # None, int, etc.

561 pass

562 return z

563

564 return _zR(set(), (inst,))

565

566

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

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

569

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

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

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

573

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

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

576

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

578

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

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

581

582 @example:

583

584 >>> from pygeodesy import splice

585

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

587 >>> a, b

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

589

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

591 >>> a, b, c

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

593

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

595 >>> a, b, c

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

597

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

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

600

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

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

603 '''

604 if not isint(n):

605 raise _TypeError(n=n)

606

607 t = iterable

608 if not isinstance(t, _list_tuple_types):

609 t = tuple(t) # force tuple, also for PyPy3

610

611 if n > 1:

612 if fill:

613 fill = _xkwds_get(fill, fill=MISSING)

614 if fill is not MISSING:

615 m = len(t) % n

616 if m > 0: # same type fill

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

618 for i in range(n):

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

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

621 else:

622 yield t

623

624

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

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

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

628 '''

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

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

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

632

633

634_XPACKAGES = _splituple(_getenv(_PYGEODESY_XPACKAGES_, NN))

635

636

637 def unsigned0(x):

638 '''Unsign if C{0.0}.

639

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

641 '''

642 return x if x else _0_0

643

644

645 def _xargs_kwds_names(func):

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

647 C{self} for methods.

648

649 @note: Python 2 does I{not} include the C{*args} nor the

650 C{**kwds} names.

651 '''

652 try:

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

654 except AttributeError: # .signature new Python 3+

655 args_kwds = _inspect.getargspec(func).args

656 return tuple(args_kwds)

657

658

659 def _xcopy(inst, deep=False):

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

661

662 @arg inst: The object to copy (any C{type}).

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

664 a shallow copy (C{bool}).

665

666 @return: The copy of B{C{inst}}.

667 '''

668 return _deepcopy(inst) if deep else _copy(inst)

669

670

671 def _xdup(inst, deep=False, **items):

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

673

674 @arg inst: The object to copy (any C{type}).

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

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

677

678 @return: A duplicate of B{C{inst}} with modified

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

680

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

682 '''

683 d = _xcopy(inst, deep=deep)

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

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

686 setattr(d, n, v)

687 elif not hasattr(d, n):

688 t = _MODS.named.classname(inst)

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

690 raise _AttributeError(txt=t, this=inst, **items)

691 return d

692

693

694 def _xgeographiclib(where, *required):

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

696 '''

697 try:

698 _xpackage(_xgeographiclib)

699 import geographiclib

700 except ImportError as x:

701 raise _xImportError(x, where)

702 return _xversion(geographiclib, where, *required)

703

704

705 def _xImportError(x, where, **name):

706 '''(INTERNAL) Embellish an C{ImportError}.

707 '''

708 t = _SPACE_(_required_, _by_, _xwhere(where, **name))

709 return _ImportError(_Xstr(x), txt=t, cause=x)

710

711

712 def _xinstanceof(*Types, **name_value_pairs):

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

714

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

716 all positional.

717 @kwarg name_value_pairs: One or more C{B{name}=value} pairs

718 with the C{value} to be checked.

719

720 @raise TypeError: One of the B{C{name_value_pairs}} is not

721 an instance of any of the B{C{Types}}.

722 '''

723 if Types and name_value_pairs:

724 for n, v in name_value_pairs.items():

725 if not isinstance(v, Types):

726 raise _TypesError(n, v, *Types)

727 else:

728 raise _AssertionError(Types=Types, name_value_pairs=name_value_pairs)

729

730

731 def _xnumpy(where, *required):

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

733 '''

734 try:

735 _xpackage(_xnumpy)

736 import numpy

737 except ImportError as x:

738 raise _xImportError(x, where)

739 return _xversion(numpy, where, *required)

740

741

742 def _xpackage(_xpkg):

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

744 '''

745 n = _xpkg.__name__[2:]

746 if n in _XPACKAGES:

747 x = _SPACE_(n, _in_, _PYGEODESY_XPACKAGES_)

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

749 raise ImportError(_EQUAL_(x, e))

750

751

752 def _xor(x, *xs):

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

754 '''

755 for x_ in xs:

756 x ^= x_

757 return x

758

759

760 def _xscipy(where, *required):

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

762 '''

763 try:

764 _xpackage(_xscipy)

765 import scipy

766 except ImportError as x:

767 raise _xImportError(x, where)

768 return _xversion(scipy, where, *required)

769

770

771 def _xsubclassof(*Classes, **name_value_pairs):

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

773

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

775 all positional.

776 @kwarg name_value_pairs: One or more C{B{name}=value} pairs

777 with the C{value} to be checked.

778

779 @raise TypeError: One of the B{C{name_value_pairs}} is not

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

781 '''

782 for n, v in name_value_pairs.items():

783 if not issubclassof(v, *Classes):

784 raise _TypesError(n, v, *Classes)

785

786

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

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

789 '''

790 n = len(required)

791 if n:

792 t = _xversion_info(package)

793 if t[:n] < required:

794 t = _SPACE_(package.__name__, _version_, _DOT_(*t),

795 _below_, _DOT_(*required),

796 _required_, _by_, _xwhere(where, **name))

797 raise ImportError(t)

798 return package

799

800

801 def _xversion_info(package): # in .karney

802 '''(INTERNAL) Get the C{package.__version_info__} as a 2- or

803 3-tuple C{(major, minor, revision)} if C{int}s.

804 '''

805 try:

806 t = package.__version_info__

807 except AttributeError:

808 t = package.__version__.strip()

809 t = t.replace(_DOT_, _SPACE_).split()[:3]

810 return map2(int, t)

811

812

813 def _xwhere(where, **name):

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

815 '''

816 m = _MODS.named.modulename(where, prefixed=True)

817 if name:

818 n = _xkwds_get(name, name=NN)

819 if n:

820 m = _DOT_(m, n)

821 return m

822

823

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

825 _zip = zip # PYCHOK exported

826 else: # Python 3.10+

827

828 def _zip(*args):

829 return zip(*args, strict=True)

830

831# **) MIT License

832#

833# Copyright (C) 2016-2023 -- mrJean1 at Gmail -- All Rights Reserved.

834#

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

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

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

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

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

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

841#

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

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

844#

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

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

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

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

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

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

851# OTHER DEALINGS IN THE SOFTWARE.