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_, _ELLIPSIS4_, \

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

21 _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.10.15'

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 isfloat(obj):

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

239

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

241

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

243 C{False}.

244 '''

245 try:

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

247 and isinstance(float(obj), float))

248 except (TypeError, ValueError):

249 return False

250

251

252 try:

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

254 except AttributeError: # Python 2-

255

256 def isidentifier(obj):

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

258 '''

259 return bool(obj and isstr(obj)

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

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

262

263

264 def isinstanceof(obj, *classes):

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

266

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

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

269

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

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

272 '''

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

274

275

276 def isint(obj, both=False):

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

278

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

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

281 type and value (C{bool}).

282

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

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

285

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

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

288 '''

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

290 return True

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

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

293 return obj.is_integer()

294 except AttributeError:

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

296 return False

297

298

299 try:

300 from keyword import iskeyword # Python 2.7+

301 except ImportError:

302

303 def iskeyword(unused):

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

305 '''

306 return False

307

308

309 def isLatLon(obj, ellipsoidal=None):

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

311

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

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

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

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

316

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

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

319 type or {None} otherwise.

320 '''

321 if ellipsoidal is not None:

322 try:

323 return obj.ellipsoidalLatLon if ellipsoidal else obj.sphericalLatLon

324 except AttributeError:

325 return None

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

327

328

329 def islistuple(obj, minum=0):

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

331

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

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

334

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

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

337 '''

338 return type(obj) in _list_tuple_types and len(obj) >= (minum or 0)

339

340

341 def isNvector(obj, ellipsoidal=None):

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

343

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

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

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

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

348

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

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

351 type or {None} otherwise.

352 '''

353 if ellipsoidal is not None:

354 try:

355 return obj.ellipsoidalNvector if ellipsoidal else obj.sphericalNvector

356 except AttributeError:

357 return None

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

359

360

361 def isodd(x):

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

363

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

365

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

367 C{False} otherwise.

368 '''

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

370

371

372 def isscalar(obj):

373 '''Check for scalar types.

374

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

376

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

378 '''

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

380

381

382 def issequence(obj, *excls):

383 '''Check for sequence types.

384

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

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

387

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

389

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

391 '''

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

393

394

395 def isstr(obj):

396 '''Check for string types.

397

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

399

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

401 '''

402 return isinstance(obj, _Strs)

403

404

405 def issubclassof(Sub, *Supers):

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

407

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

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

410

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

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

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

414 are a class.

415 '''

416 if isclass(Sub):

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

418 if t:

419 return bool(issubclass(Sub, t))

420 return None

421

422

423 def len2(items):

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

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

426

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

428

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

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

431 '''

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

433 items = list(items)

434 return len(items), items

435

436

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

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

439 return a C{tuple} of results.

440

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

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

443

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

445 '''

446 return tuple(map(fun1, xs))

447

448

449 def map2(func, *xs):

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

451

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

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

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

455 maintains the Python 2 behavior.

456

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

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

459

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

461 '''

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

463

464

465 def neg(x, neg0=None):

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

467

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

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

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

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

472

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

474 '''

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

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

477

478

479 def neg_(*xs):

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

481

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

483 '''

484 return map(neg, xs)

485

486

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

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

489 '''

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

491

492

493 def signBit(x):

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

495

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

497 '''

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

499

500

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

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

503 '''

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

505

506

507 def signOf(x):

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

509

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

511 '''

512 try:

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

514 except AttributeError:

515 s = _signOf(x, 0)

516 return s

517

518

519 def _sizeof(inst):

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

521

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

523 ignoring class attributes and

524 counting duplicates only once or

525 C{None}.

526

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

528 '''

529 try:

530 _zB = _sys.getsizeof

531 _zD = _zB(None) # get some default

532 except TypeError: # PyPy3.10

533 return None

534

535 def _zR(s, iterable):

536 z, _s = 0, s.add

537 for o in iterable:

538 i = id(o)

539 if i not in s:

540 _s(i)

541 z += _zB(o, _zD)

542 if isinstance(o, dict):

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

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

545 elif isinstance(o, _list_tuple_set_types):

546 z += _zR(s, o)

547 else:

548 try: # size instance' attr values only

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

550 except AttributeError: # None, int, etc.

551 pass

552 return z

553

554 return _zR(set(), (inst,))

555

556

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

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

559

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

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

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

563

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

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

566

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

568

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

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

571

572 @example:

573

574 >>> from pygeodesy import splice

575

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

577 >>> a, b

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

579

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

581 >>> a, b, c

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

583

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

585 >>> a, b, c

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

587

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

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

590

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

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

593 '''

594 if not isint(n):

595 raise _TypeError(n=n)

596

597 t = iterable

598 if not isinstance(t, _list_tuple_types):

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

600

601 if n > 1:

602 if fill:

603 fill = _xkwds_get(fill, fill=MISSING)

604 if fill is not MISSING:

605 m = len(t) % n

606 if m > 0: # same type fill

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

608 for i in range(n):

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

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

611 else:

612 yield t

613

614

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

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

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

618 '''

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

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

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

622

623

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

625

626

627 def unsigned0(x):

628 '''Unsign if C{0.0}.

629

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

631 '''

632 return x if x else _0_0

633

634

635 def _xargs_names(callabl):

636 '''(INTERNAL) Get the C{callabl}'s args names.

637 '''

638 try:

639 args_kwds = _inspect.signature(callabl).parameters.keys()

640 except AttributeError: # .signature new Python 3+

641 args_kwds = _inspect.getargspec(callabl).args

642 return tuple(args_kwds)

643

644

645 def _xcopy(inst, deep=False):

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

647

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

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

650 a shallow copy (C{bool}).

651

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

653 '''

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

655

656

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

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

659

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

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

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

663

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

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

666

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

668 '''

669 d = _xcopy(inst, deep=deep)

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

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

672 setattr(d, n, v)

673 elif not hasattr(d, n):

674 t = _MODS.named.classname(inst)

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

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

677 return d

678

679

680 def _xgeographiclib(where, *required):

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

682 '''

683 try:

684 _xpackage(_xgeographiclib)

685 import geographiclib

686 except ImportError as x:

687 raise _xImportError(x, where)

688 return _xversion(geographiclib, where, *required)

689

690

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

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

693 '''

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

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

696

697

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

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

700

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

702 all positional.

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

704 with the C{value} to be checked.

705

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

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

708 '''

709 if Types and name_value_pairs:

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

711 if not isinstance(v, Types):

712 raise _TypesError(n, v, *Types)

713 else:

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

715

716

717 def _xnumpy(where, *required):

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

719 '''

720 try:

721 _xpackage(_xnumpy)

722 import numpy

723 except ImportError as x:

724 raise _xImportError(x, where)

725 return _xversion(numpy, where, *required)

726

727

728 def _xpackage(_xpkg):

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

730 '''

731 n = _xpkg.__name__[2:]

732 if n in _XPACKAGES:

733 x = _SPACE_(n, _in_, _PYGEODESY_XPACKAGES_)

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

735 raise ImportError(_EQUAL_(x, e))

736

737

738 def _xor(x, *xs):

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

740 '''

741 for x_ in xs:

742 x ^= x_

743 return x

744

745

746 def _xscipy(where, *required):

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

748 '''

749 try:

750 _xpackage(_xscipy)

751 import scipy

752 except ImportError as x:

753 raise _xImportError(x, where)

754 return _xversion(scipy, where, *required)

755

756

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

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

759

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

761 all positional.

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

763 with the C{value} to be checked.

764

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

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

767 '''

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

769 if not issubclassof(v, *Classes):

770 raise _TypesError(n, v, *Classes)

771

772

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

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

775 '''

776 n = len(required)

777 if n:

778 t = _xversion_info(package)

779 if t[:n] < required:

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

781 _below_, _DOT_(*required),

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

783 raise ImportError(t)

784 return package

785

786

787 def _xversion_info(package): # in .karney

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

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

790 '''

791 try:

792 t = package.__version_info__

793 except AttributeError:

794 t = package.__version__.strip()

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

796 return map2(int, t)

797

798

799 def _xwhere(where, **name):

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

801 '''

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

803 if name:

804 n = _xkwds_get(name, name=NN)

805 if n:

806 m = _DOT_(m, n)

807 return m

808

809

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

811 _zip = zip # PYCHOK exported

812 else: # Python 3.10+

813

814 def _zip(*args):

815 return zip(*args, strict=True)

816

817# **) MIT License

818#

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

820#

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

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

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

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

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

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

827#

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

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

830#

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

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

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

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

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

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

837# OTHER DEALINGS IN THE SOFTWARE.