1

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

3

4 u'''Utilities using precision floating point summation.

5'''

6# make sure int/int division yields float quotient, see .basics

7 from __future__ import division as _; del _ # PYCHOK semicolon

8

9 from pygeodesy.basics import _copysign, copysign0, isbool, isint, isscalar, \

10 len2, map1, _xiterable

11 from pygeodesy.constants import EPS0, EPS02, EPS1, NAN, PI, PI_2, PI_4, \

12 _0_0, _0_125, _1_6th, _0_25, _1_3rd, _0_5, _1_0, \

13 _N_1_0, _1_5, _copysign_0_0, _isfinite, remainder

14 from pygeodesy.errors import _IsnotError, LenError, _TypeError, _ValueError, \

15 _xError, _xkwds_get, _xkwds_pop2

16 from pygeodesy.fsums import _2float, Fsum, fsum, fsum1_, _isFsumTuple, _1primed, \

17 Fmt, unstr

18 from pygeodesy.interns import MISSING, _negative_, _not_scalar_

19 from pygeodesy.lazily import _ALL_LAZY, _sys_version_info2

20# from pygeodesy.streprs import Fmt, unstr # from .fsums

21 from pygeodesy.units import Int_, _isHeight, _isRadius, Float_ # PYCHOK for .heights

22

23 from math import fabs, sqrt # pow

24 import operator as _operator # in .datums, .trf, .utm

25

26__all__ = _ALL_LAZY.fmath

27__version__ = '24.05.10'

28

29# sqrt(2) <https://WikiPedia.org/wiki/Square_root_of_2>

30_0_4142 = 0.41421356237309504880 # ... sqrt(2) - 1

31_2_3rd = _1_3rd * 2

32_h_lt_b_ = 'abs(h) < abs(b)'

33

34

35 class Fdot(Fsum):

36 '''Precision dot product.

37 '''

38 def __init__(self, a, *b, **name_RESIDUAL):

39 '''New L{Fdot} precision dot product M{sum(a[i] * b[i] for

40 i=0..len(a)-1)}.

41

42 @arg a: Iterable of values (each C{scalar} or an L{Fsum} or

43 L{Fsum2Tuple} instance).

44 @arg b: Other values (each C{scalar} or an L{Fsum} or L{Fsum2Tuple}

45 instance), all positional.

46 @kwarg name_RESIDUAL: Optional C{B{name}=NN} and C{B{RESIDUAL}=0.0}

47 threshold, see L{Fsum<Fsum.__init__>}.

48

49 @raise LenError: Unequal C{len(B{a})} and C{len(B{b})}.

50

51 @raise OverflowError: Partial C{2sum} overflow.

52

53 @raise TypeError: Invalid B{C{x}}.

54

55 @raise ValueError: Non-finite B{C{x}}.

56

57 @see: Function L{fdot} and method L{Fsum.fadd}.

58 '''

59 Fsum.__init__(self, **name_RESIDUAL)

60 self.fadd(_map_mul(a, b, Fdot))

61

62

63 class Fhorner(Fsum):

64 '''Precision polynomial evaluation using the Horner form.

65 '''

66 def __init__(self, x, *cs, **name_RESIDUAL):

67 '''New L{Fhorner} evaluation of polynomial M{sum(cs[i] * x**i for

68 i=0..len(cs)-1)}.

69

70 @arg x: Polynomial argument (C{scalar} or an L{Fsum} or L{Fsum2Tuple}).

71 @arg cs: Polynomial coeffients (each C{scalar} or an L{Fsum} or

72 L{Fsum2Tuple} instance), all positional.

73 @kwarg name_RESIDUAL: Optional C{B{name}=NN} and C{B{RESIDUAL}=0.0}

74 threshold, see L{Fsum<Fsum.__init__>}.

75

76 @raise OverflowError: Partial C{2sum} overflow.

77

78 @raise TypeError: Invalid B{C{x}}.

79

80 @raise ValueError: Non-finite B{C{x}}.

81

82 @see: Function L{fhorner} and methods L{Fsum.fadd} and L{Fsum.fmul}.

83 '''

84 Fsum.__init__(self, **name_RESIDUAL)

85 if cs:

86 if _isFsumTuple(x):

87 _mul = self._mul_Fsum

88 else:

89 _mul = self._mul_scalar

90 x = _2float(x=x)

91 op = Fhorner.__name__

92 if len(cs) > 1 and x:

93 for c in reversed(cs):

94 self._fset_ps(_mul(x, op))

95 self._fadd(c, op, up=False)

96 self._update()

97 else: # x == 0

98 self._fadd(cs[0], op)

99 else:

100 self._fset_ps(_0_0)

101

102

103 class Fhypot(Fsum):

104 '''Precision summation and hypotenuse, default C{root=2}.

105 '''

106 def __init__(self, *xs, **root_name_RESIDUAL_raiser):

107 '''New L{Fhypot} hypotenuse of (the I{root} of) several components

108 (raised to the power I{root}).

109

110 @arg xs: Components (each C{scalar} or an L{Fsum} or L{Fsum2Tuple}

111 instance), all positional.

112 @kwarg root_name_RESIDUAL_raiser: Optional, exponent and C{B{root}=2}

113 order, C{B{name}=NN}, C{B{RESIDUAL}=0.0} threshold and

114 C{B{raiser}=True}, see class L{Fsum<Fsum.__init__>} and

115 method L{root<Fsum.root>}.

116 '''

117 r = None # _xkwds_pop2 error

118 try:

119 r, kwds = _xkwds_pop2(root_name_RESIDUAL_raiser, root=2)

120 r, kwds = _xkwds_pop2(kwds, power=r) # for backward compatibility

121 raiser = _Fsum__init__(self, **kwds)

122 if xs:

123 self._facc_power(r, xs, Fhypot, **raiser)

124 self._fset(self.root(r, **raiser))

125 except Exception as X:

126 raise self._ErrorXs(X, xs, root=r)

127

128

129 class Fpolynomial(Fsum):

130 '''Precision polynomial evaluation.

131 '''

132 def __init__(self, x, *cs, **name_RESIDUAL):

133 '''New L{Fpolynomial} evaluation of the polynomial

134 M{sum(cs[i] * x**i for i=0..len(cs)-1)}.

135

136 @arg x: Polynomial argument (C{scalar} or an L{Fsum} or L{Fsum2Tuple}).

137 @arg cs: Polynomial coeffients (each C{scalar} or an L{Fsum} or

138 L{Fsum2Tuple} instance), all positional.

139 @kwarg name_RESIDUAL: Optional C{B{name}=NN} and C{B{RESIDUAL}=0.0}

140 threshold, see L{Fsum<Fsum.__init__>}.

141

142 @raise OverflowError: Partial C{2sum} overflow.

143

144 @raise TypeError: Invalid B{C{x}}.

145

146 @raise ValueError: Non-finite B{C{x}}.

147

148 @see: Class L{Fhorner}, function L{fpolynomial} and method L{Fsum.fadd}.

149 '''

150 Fsum.__init__(self, *cs[:1], **name_RESIDUAL)

151 n = len(cs) - 1

152 if n > 0:

153 self.fadd(_1map_mul(cs[1:], _powers(x, n)))

154 elif n < 0:

155 self._fset_ps(_0_0)

156

157

158 class Fpowers(Fsum):

159 '''Precision summation of powers, optimized for C{power=2, 3 and 4}.

160 '''

161 def __init__(self, power, *xs, **name_RESIDUAL_raiser):

162 '''New L{Fpowers} sum of (the I{power} of) several bases.

163

164 @arg power: The exponent (C{scalar} or an L{Fsum} or L{Fsum2Tuple}).

165 @arg xs: One or more bases (each C{scalar} or an L{Fsum} or L{Fsum2Tuple}

166 instance), all positional.

167 @kwarg name_RESIDUAL_raiser: Optional C{B{name}=NN}, C{B{RESIDUAL}=0.0}

168 threshold and C{B{raiser}=True}, see L{Fsum<Fsum.__init__>}

169 and L{fpow<Fsum.fpow>}.

170 '''

171 try:

172 raiser = _Fsum__init__(self, **name_RESIDUAL_raiser)

173 if xs:

174 self._facc_power(power, xs, Fpowers, **raiser) # x**0 == 1

175 except Exception as X:

176 raise self._ErrorXs(X, xs, power=power)

177

178

179 class Froot(Fsum):

180 '''The root of a precision summation.

181 '''

182 def __init__(self, root, *xs, **name_RESIDUAL_raiser):

183 '''New L{Froot} root of a precision sum.

184

185 @arg root: The order (C{scalar} or an L{Fsum} or L{Fsum2Tuple}), non-zero.

186 @arg xs: Items to summate (each a C{scalar} or an L{Fsum} or L{Fsum2Tuple}

187 instance), all positional.

188 @kwarg name_RESIDUAL_raiser: Optional C{B{name}=NN}, C{B{RESIDUAL}=0.0}

189 threshold and C{B{raiser}=True}, see L{Fsum<Fsum.__init__>}

190 and L{fpow<Fsum.fpow>}.

191 '''

192 try:

193 raiser = _Fsum__init__(self, **name_RESIDUAL_raiser)

194 if xs:

195 self.fadd(xs)

196 self._fset(self.root(root, **raiser))

197 except Exception as X:

198 raise self._ErrorXs(X, xs, root=root)

199

200

201 class Fcbrt(Froot):

202 '''Cubic root of a precision summation.

203 '''

204 def __init__(self, *xs, **name_RESIDUAL_raiser):

205 '''New L{Fcbrt} cubic root of a precision sum.

206

207 @see: Class L{Froot} for further details.

208 '''

209 Froot.__init__(self, 3, *xs, **name_RESIDUAL_raiser)

210

211

212 class Fsqrt(Froot):

213 '''Square root of a precision summation.

214 '''

215 def __init__(self, *xs, **name_RESIDUAL_raiser):

216 '''New L{Fsqrt} square root of a precision sum.

217

218 @see: Class L{Froot} for further details.

219 '''

220 Froot.__init__(self, 2, *xs, **name_RESIDUAL_raiser)

221

222

223 def _Fsum__init__(inst, raiser=MISSING, **name_RESIDUAL):

224 '''(INTERNAL) Init an C{F...} instance above.

225 '''

226 Fsum.__init__(inst, **name_RESIDUAL) # PYCHOK self

227 inst._fset_ps(_0_0)

228 return {} if raiser is MISSING else dict(raiser=raiser)

229

230

231 def bqrt(x):

232 '''Return the 4-th, I{bi-quadratic} or I{quartic} root, M{x**(1 / 4)},

233 preserving C{type(B{x})}.

234

235 @arg x: Value (C{scalar} or an L{Fsum} or L{Fsum2Tuple}).

236

237 @return: I{Quartic} root (C{float} or an L{Fsum}).

238

239 @raise TypeeError: Invalid B{C{x}}.

240

241 @raise ValueError: Negative B{C{x}}.

242

243 @see: Functions L{zcrt} and L{zqrt}.

244 '''

245 return _root(x, _0_25, bqrt)

246

247

248 try:

249 from math import cbrt as _cbrt # Python 3.11+

250

251 except ImportError: # Python 3.10-

252

253 def _cbrt(x):

254 '''(INTERNAL) Compute the I{signed}, cube root M{x**(1/3)}.

255 '''

256 # <https://archive.lib.MSU.edu/crcmath/math/math/r/r021.htm>

257 # simpler and more accurate than Ken Turkowski's CubeRoot, see

258 # <https://People.FreeBSD.org/~lstewart/references/apple_tr_kt32_cuberoot.pdf>

259 return _copysign(pow(fabs(x), _1_3rd), x) # to avoid complex

260

261

262 def cbrt(x):

263 '''Compute the cube root M{x**(1/3)}, preserving C{type(B{x})}.

264

265 @arg x: Value (C{scalar} or an L{Fsum} or L{Fsum2Tuple}).

266

267 @return: Cubic root (C{float} or L{Fsum}).

268

269 @see: Functions L{cbrt2} and L{sqrt3}.

270 '''

271 if _isFsumTuple(x):

272 r = abs(x).fpow(_1_3rd)

273 if x.signOf() < 0:

274 r = -r

275 else:

276 r = _cbrt(x)

277 return r # cbrt(-0.0) == -0.0

278

279

280 def cbrt2(x): # PYCHOK attr

281 '''Compute the cube root I{squared} M{x**(2/3)}, preserving C{type(B{x})}.

282

283 @arg x: Value (C{scalar} or an L{Fsum} or L{Fsum2Tuple}).

284

285 @return: Cube root I{squared} (C{float} or L{Fsum}).

286

287 @see: Functions L{cbrt} and L{sqrt3}.

288 '''

289 return abs(x).fpow(_2_3rd) if _isFsumTuple(x) else _cbrt(x**2)

290

291

292 def euclid(x, y):

293 '''I{Appoximate} the norm M{sqrt(x**2 + y**2)} by

294 M{max(abs(x), abs(y)) + min(abs(x), abs(y)) * 0.4142...}.

295

296 @arg x: X component (C{scalar} or L{Fsum} instance).

297 @arg y: Y component (C{scalar} or L{Fsum} instance).

298

299 @return: Appoximate norm (C{float} or L{Fsum}).

300

301 @see: Function L{euclid_}.

302 '''

303 x, y = abs(x), abs(y) # NOT fabs!

304 if y > x:

305 x, y = y, x

306 return x + y * _0_4142 # XXX * _0_5 before 20.10.02

307

308

309 def euclid_(*xs):

310 '''I{Appoximate} the norm M{sqrt(sum(x**2 for x in xs))} by

311 cascaded L{euclid}.

312

313 @arg xs: X arguments (each C{scalar} or an L{Fsum}

314 instance), all positional.

315

316 @return: Appoximate norm (C{float} or L{Fsum}).

317

318 @see: Function L{euclid}.

319 '''

320 e = _0_0

321 for x in sorted(map(abs, xs)): # NOT fabs, reverse=True!

322 # e = euclid(x, e)

323 if e < x:

324 e, x = x, e

325 if x:

326 e += x * _0_4142

327 return e

328

329

330 def facos1(x):

331 '''Fast approximation of L{pygeodesy.acos1}C{(B{x})}.

332

333 @see: U{ShaderFastLibs.h<https://GitHub.com/michaldrobot/

334 ShaderFastLibs/blob/master/ShaderFastMathLib.h>}.

335 '''

336 a = fabs(x)

337 if a < EPS0:

338 r = PI_2

339 elif a < EPS1:

340 H = Fhorner(-a, 1.5707288, 0.2121144, 0.0742610, 0.0187293)

341 r = float(H * sqrt(_1_0 - a))

342 if x < 0:

343 r = PI - r

344 else:

345 r = PI if x < 0 else _0_0

346 return r

347

348

349 def fasin1(x): # PYCHOK no cover

350 '''Fast approximation of L{pygeodesy.asin1}C{(B{x})}.

351

352 @see: L{facos1}.

353 '''

354 return PI_2 - facos1(x)

355

356

357 def fatan(x):

358 '''Fast approximation of C{atan(B{x})}.

359 '''

360 a = fabs(x)

361 if a < _1_0:

362 r = fatan1(a) if a else _0_0

363 elif a > _1_0:

364 r = PI_2 - fatan1(_1_0 / a) # == fatan2(a, _1_0)

365 else:

366 r = PI_4

367 if x < 0: # copysign0(r, x)

368 r = -r

369 return r

370

371

372 def fatan1(x):

373 '''Fast approximation of C{atan(B{x})} for C{0 <= B{x} <= 1}, I{unchecked}.

374

375 @see: U{ShaderFastLibs.h<https://GitHub.com/michaldrobot/ShaderFastLibs/

376 blob/master/ShaderFastMathLib.h>} and U{Efficient approximations

377 for the arctangent function<http://www-Labs.IRO.UMontreal.CA/

378 ~mignotte/IFT2425/Documents/EfficientApproximationArctgFunction.pdf>},

379 IEEE Signal Processing Magazine, 111, May 2006.

380 '''

381 # Eq (9): PI_4 * x - x * (abs(x) - 1) * (0.2447 + 0.0663 * abs(x)), for -1 < x < 1

382 # PI_4 * x - (x**2 - x) * (0.2447 + 0.0663 * x), for 0 < x - 1

383 # x * (1.0300981633974482 + x * (-0.1784 - x * 0.0663))

384 H = Fhorner(x, _0_0, 1.0300981634, -0.1784, -0.0663)

385 return float(H)

386

387

388 def fatan2(y, x):

389 '''Fast approximation of C{atan2(B{y}, B{x})}.

390

391 @see: U{fastApproximateAtan(x, y)<https://GitHub.com/CesiumGS/cesium/blob/

392 master/Source/Shaders/Builtin/Functions/fastApproximateAtan.glsl>}

393 and L{fatan1}.

394 '''

395 a, b = fabs(x), fabs(y)

396 if b > a:

397 r = (PI_2 - fatan1(a / b)) if a else PI_2

398 elif a > b:

399 r = fatan1(b / a) if b else _0_0

400 elif a: # a == b != 0

401 r = PI_4

402 else: # a == b == 0

403 return _0_0

404 if x < 0:

405 r = PI - r

406 if y < 0: # copysign0(r, y)

407 r = -r

408 return r

409

410

411 def favg(a, b, f=_0_5):

412 '''Return the precision average of two values.

413

414 @arg a: One (C{scalar} or an L{Fsum} or L{Fsum2Tuple}).

415 @arg b: Other (C{scalar} or an L{Fsum} or L{Fsum2Tuple}).

416 @kwarg f: Optional fraction (C{float}).

417

418 @return: M{a + f * (b - a)} (C{float}).

419 '''

420# @raise ValueError: Fraction out of range.

421# '''

422# if not 0 <= f <= 1: # XXX restrict fraction?

423# raise _ValueError(fraction=f)

424 # a + f * (b - a) == a * (1 - f) + b * f

425 return fsum1_(a, a * (-f), b * f)

426

427

428 def fdot(a, *b):

429 '''Return the precision dot product M{sum(a[i] * b[i] for

430 i=0..len(a))}.

431

432 @arg a: Iterable of values (each C{scalar}).

433 @arg b: Other values (each C{scalar}), all positional.

434

435 @return: Dot product (C{float}).

436

437 @raise LenError: Unequal C{len(B{a})} and C{len(B{b})}.

438

439 @see: Class L{Fdot} and U{Algorithm 5.10 B{DotK}

440 <https://www.TUHH.De/ti3/paper/rump/OgRuOi05.pdf>}.

441 '''

442 return fsum(_map_mul(a, b, fdot))

443

444

445 def fdot3(xs, ys, zs, start=0):

446 '''Return the precision dot product M{start +

447 sum(a[i] * b[i] * c[i] for i=0..len(a)-1)}.

448

449 @arg xs: Iterable (each C{scalar} or an L{Fsum} or

450 L{Fsum2Tuple} instance).

451 @arg ys: Iterable (each C{scalar} or an L{Fsum} or

452 L{Fsum2Tuple} instance).

453 @arg zs: Iterable (each C{scalar} or an L{Fsum} or

454 L{Fsum2Tuple} instance).

455 @kwarg start: Optional bias (C{scalar} or an L{Fsum}

456 or L{Fsum2Tuple}).

457

458 @return: Dot product (C{float}).

459

460 @raise LenError: Unequal C{len(B{xs})}, C{len(B{ys})}

461 and/or C{len(B{zs})}.

462

463 @raise OverflowError: Partial C{2sum} overflow.

464 '''

465 def _mul3(xs, ys, zs, s, p):

466 if s:

467 yield s

468 if p:

469 yield _1_0

470 _F = Fsum

471 for x, y, z in zip(xs, ys, zs):

472 yield (_F(x) * y) * z

473 if p:

474 yield _N_1_0

475

476 n = len(xs)

477 if not n == len(ys) == len(zs):

478 raise LenError(fdot3, xs=n, ys=len(ys), zs=len(zs))

479

480 return fsum(_mul3(xs, ys, zs, start, n < 4))

481

482

483 def fhorner(x, *cs):

484 '''Evaluate the polynomial M{sum(cs[i] * x**i for

485 i=0..len(cs)-1)} using the Horner form.

486

487 @return: Horner sum (C{float}).

488

489 @see: Class L{Fhorner} for further details.

490 '''

491 H = Fhorner(x, *cs)

492 return float(H)

493

494

495 def fidw(xs, ds, beta=2):

496 '''Interpolate using U{Inverse Distance Weighting

497 <https://WikiPedia.org/wiki/Inverse_distance_weighting>} (IDW).

498

499 @arg xs: Known values (each C{scalar} or an L{Fsum} or

500 L{Fsum2Tuple} instance).

501 @arg ds: Non-negative distances (each C{scalar} or an L{Fsum}

502 or L{Fsum2Tuple} instance).

503 @kwarg beta: Inverse distance power (C{int}, 0, 1, 2, or 3).

504

505 @return: Interpolated value C{x} (C{float}).

506

507 @raise LenError: Unequal or zero C{len(B{ds})} and C{len(B{xs})}.

508

509 @raise TypeError: An invalid B{C{ds}} or B{C{xs}}.

510

511 @raise ValueError: Invalid B{C{beta}}, negative B{C{ds}} or

512 weighted B{C{ds}} below L{EPS}.

513

514 @note: Using C{B{beta}=0} returns the mean of B{C{xs}}.

515 '''

516 n, xs = len2(xs)

517 if n > 1:

518 b = -Int_(beta=beta, low=0, high=3)

519 if b < 0:

520 try: # weighted

521 _F = Fsum

522 W = _F()

523 X = _F()

524 for i, d in enumerate(_xiterable(ds)):

525 x = xs[i]

526 D = _F(d)

527 if D < EPS0:

528 if D < 0:

529 raise ValueError(_negative_)

530 x = float(x)

531 i = n

532 break

533 if D.fpow(b):

534 W += D

535 X += D.fmul(x)

536 else:

537 x = X.fover(W, raiser=False)

538 i += 1 # len(xs) >= len(ds)

539 except IndexError:

540 i += 1 # len(xs) < i < len(ds)

541 except Exception as X:

542 _I = Fmt.INDEX

543 raise _xError(X, _I(xs=i), x, _I(ds=i), d)

544 else: # b == 0

545 x = fsum(xs) / n # fmean(xs)

546 i = n

547 elif n:

548 x = float(xs[0])

549 i = n

550 else:

551 x = _0_0

552 i, _ = len2(ds)

553 if i != n:

554 raise LenError(fidw, xs=n, ds=i)

555 return x

556

557

558 def fmean(xs):

559 '''Compute the accurate mean M{sum(xs) / len(xs)}.

560

561 @arg xs: Values (C{scalar} or L{Fsum} instances).

562

563 @return: Mean value (C{float}).

564

565 @raise LenError: No B{C{xs}} values.

566

567 @raise OverflowError: Partial C{2sum} overflow.

568 '''

569 n, xs = len2(xs)

570 if n < 1:

571 raise LenError(fmean, xs=xs)

572 return Fsum(*xs).fover(n) if n > 1 else _2float(index=0, xs=xs[0])

573

574

575 def fmean_(*xs):

576 '''Compute the accurate mean M{sum(xs) / len(xs)}.

577

578 @see: Function L{fmean} for further details.

579 '''

580 return fmean(xs)

581

582

583 def fpolynomial(x, *cs, **over):

584 '''Evaluate the polynomial M{sum(cs[i] * x**i for

585 i=0..len(cs)) [/ over]}.

586

587 @kwarg over: Optional final, I{non-zero} divisor (C{scalar}).

588

589 @return: Polynomial value (C{float}).

590

591 @see: Class L{Fpolynomial} for further details.

592 '''

593 P = Fpolynomial(x, *cs)

594 d = _xkwds_get(over, over=0) if over else 0

595 return P.fover(d) if d else float(P)

596

597

598 def fpowers(x, n, alts=0):

599 '''Return a series of powers M{[x**i for i=1..n]}.

600

601 @arg x: Value (C{scalar} or an L{Fsum} or L{Fsum2Tuple}).

602 @arg n: Highest exponent (C{int}).

603 @kwarg alts: Only alternating powers, starting with this

604 exponent (C{int}).

605

606 @return: Tuple of powers of B{C{x}} (each C{type(B{x})}).

607

608 @raise TypeError: Invalid B{C{x}} or B{C{n}} not C{int}.

609

610 @raise ValueError: Non-finite B{C{x}} or invalid B{C{n}}.

611 '''

612 if not isint(n):

613 raise _IsnotError(int.__name__, n=n)

614 elif n < 1:

615 raise _ValueError(n=n)

616

617 p = x if isint(x) or _isFsumTuple(x) else _2float(x=x)

618 ps = tuple(_powers(p, n))

619

620 if alts > 0: # x**2, x**4, ...

621 # ps[alts-1::2] chokes PyChecker

622 ps = ps[slice(alts-1, None, 2)]

623

624 return ps

625

626

627 try:

628 from math import prod as fprod # Python 3.8

629 except ImportError:

630

631 def fprod(xs, start=1):

632 '''Iterable product, like C{math.prod} or C{numpy.prod}.

633

634 @arg xs: Iterable of values to be multiplied (each

635 C{scalar} or an L{Fsum}).

636 @kwarg start: Initial value, also the value returned

637 for an empty B{C{xs}} (C{scalar}).

638

639 @return: The product (C{float} or an L{Fsum}).

640

641 @see: U{NumPy.prod<https://docs.SciPy.org/doc/

642 numpy/reference/generated/numpy.prod.html>}.

643 '''

644 return freduce(_operator.mul, xs, start)

645

646

647 def frandoms(n, seeded=None):

648 '''Generate C{n} (long) lists of random C{floats}.

649

650 @arg n: Number of lists to generate (C{int}, non-negative).

651 @kwarg seeded: If C{scalar}, use C{random.seed(B{seeded})} or

652 if C{True}, seed using today's C{year-day}.

653

654 @see: U{Hettinger<https://GitHub.com/ActiveState/code/tree/master/recipes/

655 Python/393090_Binary_floating_point_summatiaccurate_full/recipe-393090.py>}.

656 '''

657 from random import gauss, random, seed, shuffle

658

659 if seeded is None:

660 pass

661 elif seeded and isbool(seeded):

662 from time import localtime

663 seed(localtime().tm_yday)

664 elif isscalar(seeded):

665 seed(seeded)

666

667 c = (7, 1e100, -7, -1e100, -9e-20, 8e-20) * 7

668 for _ in range(n):

669 s = 0

670 t = list(c)

671 _a = t.append

672 for _ in range(n * 8):

673 v = gauss(0, random())**7 - s

674 _a(v)

675 s += v

676 shuffle(t)

677 yield t

678

679

680 def frange(start, number, step=1):

681 '''Generate a range of C{float}s.

682

683 @arg start: First value (C{float}).

684 @arg number: The number of C{float}s to generate (C{int}).

685 @kwarg step: Increment value (C{float}).

686

687 @return: A generator (C{float}s).

688

689 @see: U{NumPy.prod<https://docs.SciPy.org/doc/

690 numpy/reference/generated/numpy.arange.html>}.

691 '''

692 if not isint(number):

693 raise _IsnotError(int.__name__, number=number)

694 for i in range(number):

695 yield start + (step * i)

696

697

698 try:

699 from functools import reduce as freduce

700 except ImportError:

701 try:

702 freduce = reduce # PYCHOK expected

703 except NameError: # Python 3+

704

705 def freduce(f, xs, *start):

706 '''For missing C{functools.reduce}.

707 '''

708 if start:

709 r = v = start[0]

710 else:

711 r, v = 0, MISSING

712 for v in xs:

713 r = f(r, v)

714 if v is MISSING:

715 raise _TypeError(xs=(), start=MISSING)

716 return r

717

718

719 def fremainder(x, y):

720 '''Remainder in range C{[-B{y / 2}, B{y / 2}]}.

721

722 @arg x: Numerator (C{scalar}).

723 @arg y: Modulus, denominator (C{scalar}).

724

725 @return: Remainder (C{scalar}, preserving signed

726 0.0) or C{NAN} for any non-finite B{C{x}}.

727

728 @raise ValueError: Infinite or near-zero B{C{y}}.

729

730 @see: I{Karney}'s U{Math.remainder<https://PyPI.org/

731 project/geographiclib/>} and Python 3.7+

732 U{math.remainder<https://docs.Python.org/3/

733 library/math.html#math.remainder>}.

734 '''

735 # with Python 2.7.16 and 3.7.3 on macOS 10.13.6 and

736 # with Python 3.10.2 on macOS 12.2.1 M1 arm64 native

737 # fmod( 0, 360) == 0.0

738 # fmod( 360, 360) == 0.0

739 # fmod(-0, 360) == 0.0

740 # fmod(-0.0, 360) == -0.0

741 # fmod(-360, 360) == -0.0

742 # however, using the % operator ...

743 # 0 % 360 == 0

744 # 360 % 360 == 0

745 # 360.0 % 360 == 0.0

746 # -0 % 360 == 0

747 # -360 % 360 == 0 == (-360) % 360

748 # -0.0 % 360 == 0.0 == (-0.0) % 360

749 # -360.0 % 360 == 0.0 == (-360.0) % 360

750

751 # On Windows 32-bit with python 2.7, math.fmod(-0.0, 360)

752 # == +0.0. This fixes this bug. See also Math::AngNormalize

753 # in the C++ library, Math.sincosd has a similar fix.

754 if _isfinite(x):

755 try:

756 r = remainder(x, y) if x else x

757 except Exception as e:

758 raise _xError(e, unstr(fremainder, x, y))

759 else: # handle x INF and NINF as NAN

760 r = NAN

761 return r

762

763

764 if _sys_version_info2 < (3, 8): # PYCHOK no cover

765 from math import hypot # OK in Python 3.7-

766

767 def hypot_(*xs):

768 '''Compute the norm M{sqrt(sum(x**2 for x in xs))}.

769

770 Similar to Python 3.8+ n-dimension U{math.hypot

771 <https://docs.Python.org/3.8/library/math.html#math.hypot>},

772 but exceptions, C{nan} and C{infinite} values are

773 handled differently.

774

775 @arg xs: X arguments (C{scalar}s), all positional.

776

777 @return: Norm (C{float}).

778

779 @raise OverflowError: Partial C{2sum} overflow.

780

781 @raise ValueError: Invalid or no B{C{xs}} values.

782

783 @note: The Python 3.8+ Euclidian distance U{math.dist

784 <https://docs.Python.org/3.8/library/math.html#math.dist>}

785 between 2 I{n}-dimensional points I{p1} and I{p2} can be

786 computed as M{hypot_(*((c1 - c2) for c1, c2 in zip(p1, p2)))},

787 provided I{p1} and I{p2} have the same, non-zero length I{n}.

788 '''

789 return float(Fhypot(*xs, raiser=False))

790

791 elif _sys_version_info2 < (3, 10):

792 # In Python 3.8 and 3.9 C{math.hypot} is inaccurate, see

793 # U{agdhruv<https://GitHub.com/geopy/geopy/issues/466>},

794 # U{cffk<https://Bugs.Python.org/issue43088>} and module

795 # U{geomath.py<https://PyPI.org/project/geographiclib/1.52>}

796

797 def hypot(x, y):

798 '''Compute the norm M{sqrt(x**2 + y**2)}.

799

800 @arg x: X argument (C{scalar}).

801 @arg y: Y argument (C{scalar}).

802

803 @return: C{sqrt(B{x}**2 + B{y}**2)} (C{float}).

804 '''

805 return float(Fhypot(x, y, raiser=False))

806

807 from math import hypot as hypot_ # PYCHOK in Python 3.8 and 3.9

808 else:

809 from math import hypot # PYCHOK in Python 3.10+

810 hypot_ = hypot

811

812

813 def hypot1(x):

814 '''Compute the norm M{sqrt(1 + x**2)}.

815

816 @arg x: Argument (C{scalar} or L{Fsum} or L{Fsum2Tuple}).

817

818 @return: Norm (C{float}).

819 '''

820 if _isFsumTuple(x):

821 h = float(Fhypot(_1_0, x)) if x else _1_0

822 else:

823 h = hypot(_1_0, x) if x else _1_0

824 return h

825

826

827 def hypot2(x, y):

828 '''Compute the I{squared} norm M{x**2 + y**2}.

829

830 @arg x: X (C{scalar} or L{Fsum} or L{Fsum2Tuple}).

831 @arg y: Y (C{scalar} or L{Fsum} or L{Fsum2Tuple}).

832

833 @return: C{B{x}**2 + B{y}**2} (C{float}).

834 '''

835 x, y = map1(abs, x, y) # NOT fabs!

836 if y > x:

837 x, y = y, x

838 if x:

839 h2 = x**2

840 if y:

841 h2 *= (y / x)**2 + _1_0

842 h2 = float(h2)

843 else:

844 h2 = _0_0

845 return h2

846

847

848 def hypot2_(*xs):

849 '''Compute the I{squared} norm C{fsum(x**2 for x in B{xs})}.

850

851 @arg xs: Components (each C{scalar} or an L{Fsum} or

852 L{Fsum2Tuple} instance), all positional.

853

854 @return: Squared norm (C{float}).

855

856 @see: Class L{Fpowers} for further details.

857 '''

858 h2 = float(max(map(abs, xs))) if xs else _0_0

859 if h2:

860 _h = _1_0 / h2

861 h2 = Fpowers(2, *((x * _h) for x in xs))

862 h2 = h2.fover(_h**2)

863 return h2

864

865

866 def _map_mul(xs, ys, where):

867 '''(INTERNAL) Yield each B{C{x * y}}.

868 '''

869 n = len(ys)

870 if len(xs) != n: # PYCHOK no cover

871 raise LenError(where, xs=len(xs), ys=n)

872 return _1map_mul(xs, ys) if n < 4 else map(

873 _operator.mul, map(Fsum, xs), ys)

874

875

876 def _1map_mul(xs, ys):

877 '''(INTERNAL) Yield each B{C{x * y}}, 1-primed.

878 '''

879 return _1primed(map(_operator.mul, map(Fsum, xs), ys))

880

881

882 def norm2(x, y):

883 '''Normalize a 2-dimensional vector.

884

885 @arg x: X component (C{scalar}).

886 @arg y: Y component (C{scalar}).

887

888 @return: 2-Tuple C{(x, y)}, normalized.

889

890 @raise ValueError: Invalid B{C{x}} or B{C{y}}

891 or zero norm.

892 '''

893 try:

894 h = hypot(x, y)

895 if h:

896 x, y = (x / h), (y / h)

897 else:

898 x = _copysign_0_0(x) # pass?

899 y = _copysign_0_0(y)

900 except Exception as e:

901 raise _xError(e, x=x, y=y, h=h)

902 return x, y

903

904

905 def norm_(*xs):

906 '''Normalize all n-dimensional vector components.

907

908 @arg xs: Components (C{scalar}s), all positional.

909

910 @return: Yield each component, normalized.

911

912 @raise ValueError: Invalid or insufficent B{C{xs}}

913 or zero norm.

914 '''

915 try:

916 i = x = h = None

917 h = hypot_(*xs)

918 _h = (_1_0 / h) if h else _0_0

919 for i, x in enumerate(xs):

920 yield x * _h

921 except Exception as X:

922 raise _xError(X, Fmt.SQUARE(xs=i), x, h=h)

923

924

925 def _powers(x, n):

926 '''(INTERNAL) Yield C{x**i for i=1..n}.

927 '''

928 p = 1 # type(p) == type(x)

929 for _ in range(n):

930 p *= x

931 yield p

932

933

934 def _root(x, p, where):

935 '''(INTERNAL) Raise C{x} to power C{0 < p < 1}.

936 '''

937 try:

938 if x > 0:

939 return Fsum(x).fpow(p).as_iscalar

940 elif x < 0:

941 raise ValueError(_negative_)

942 except Exception as X:

943 raise _xError(X, unstr(where, x))

944 return _0_0

945

946

947 def sqrt0(x, Error=None):

948 '''Return the square root C{sqrt(B{x})} iff C{B{x} > }L{EPS02},

949 preserving C{type(B{x})}.

950

951 @arg x: Value (C{scalar} or an L{Fsum} or L{Fsum2Tuple}).

952 @kwarg Error: Error to raise for negative B{C{x}}.

953

954 @return: Square root (C{float} or L{Fsum}) or C{0.0}.

955

956 @raise TypeeError: Invalid B{C{x}}.

957

958 @note: Any C{B{x} < }L{EPS02} I{including} C{B{x} < 0}

959 returns C{0.0}.

960 '''

961 if Error and x < 0:

962 raise Error(unstr(sqrt0, x))

963 return _root(x, _0_5, sqrt0) if x > EPS02 else (_0_0 if x < EPS02 else EPS0)

964

965

966 def sqrt3(x):

967 '''Return the square root, I{cubed} M{sqrt(x)**3} or M{sqrt(x**3)},

968 preserving C{type(B{x})}.

969

970 @arg x: Value (C{scalar} or an L{Fsum} or L{Fsum2Tuple}).

971

972 @return: Square root I{cubed} (C{float} or L{Fsum}).

973

974 @raise TypeeError: Invalid B{C{x}}.

975

976 @raise ValueError: Negative B{C{x}}.

977

978 @see: Functions L{cbrt} and L{cbrt2}.

979 '''

980 return _root(x, _1_5, sqrt3)

981

982

983 def sqrt_a(h, b):

984 '''Compute C{I{a}} side of a right-angled triangle from

985 C{sqrt(B{h}**2 - B{b}**2)}.

986

987 @arg h: Hypotenuse or outer annulus radius (C{scalar}).

988 @arg b: Triangle side or inner annulus radius (C{scalar}).

989

990 @return: C{copysign(I{a}, B{h})} or C{unsigned 0.0} (C{float}).

991

992 @raise TypeError: Non-scalar B{C{h}} or B{C{b}}.

993

994 @raise ValueError: If C{abs(B{h}) < abs(B{b})}.

995

996 @see: Inner tangent chord B{I{d}} of an U{annulus

997 <https://WikiPedia.org/wiki/Annulus_(mathematics)>}

998 and function U{annulus_area<https://People.SC.FSU.edu/

999 ~jburkardt/py_src/geometry/geometry.py>}.

1000 '''

1001 try:

1002 if not (_isHeight(h) and _isRadius(b)):

1003 raise TypeError(_not_scalar_)

1004 c = fabs(h)

1005 if c > EPS0:

1006 s = _1_0 - (b / c)**2

1007 if s < 0:

1008 raise ValueError(_h_lt_b_)

1009 a = (sqrt(s) * c) if 0 < s < 1 else (c if s else _0_0)

1010 else: # PYCHOK no cover

1011 b = fabs(b)

1012 d = c - b

1013 if d < 0:

1014 raise ValueError(_h_lt_b_)

1015 d *= c + b

1016 a = sqrt(d) if d else _0_0

1017 except Exception as x:

1018 raise _xError(x, h=h, b=b)

1019 return copysign0(a, h)

1020

1021

1022 def zcrt(x):

1023 '''Return the 6-th, I{zenzi-cubic} root, M{x**(1 / 6)},

1024 preserving C{type(B{x})}.

1025

1026 @arg x: Value (C{scalar} or an L{Fsum} or L{Fsum2Tuple}).

1027

1028 @return: I{Zenzi-cubic} root (C{float} or L{Fsum}).

1029

1030 @see: Functions L{bqrt} and L{zqrt}.

1031

1032 @raise TypeeError: Invalid B{C{x}}.

1033

1034 @raise ValueError: Negative B{C{x}}.

1035 '''

1036 return _root(x, _1_6th, zcrt)

1037

1038

1039 def zqrt(x):

1040 '''Return the 8-th, I{zenzi-quartic} or I{squared-quartic} root,

1041 M{x**(1 / 8)}, preserving C{type(B{x})}.

1042

1043 @arg x: Value (C{scalar} or an L{Fsum} or L{Fsum2Tuple}).

1044

1045 @return: I{Zenzi-quartic} root (C{float} or L{Fsum}).

1046

1047 @see: Functions L{bqrt} and L{zcrt}.

1048

1049 @raise TypeeError: Invalid B{C{x}}.

1050

1051 @raise ValueError: Negative B{C{x}}.

1052 '''

1053 return _root(x, _0_125, zqrt)

1054

1055# **) MIT License

1056#

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

1058#

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

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

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

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

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

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

1065#

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

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

1068#

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

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

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

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

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

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

1075# OTHER DEALINGS IN THE SOFTWARE.