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_get1, _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.08.15'

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 L{Fsum2Tuple}

43 instance).

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

45 all positional.

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

47 threshold (C{scalar}) for raising L{ResidualError}s, see class

48 L{Fsum<Fsum.__init__>}.

49

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

51

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

53

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

55

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

57

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

59 '''

60 Fsum.__init__(self, **name_RESIDUAL)

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

62

63

64 class Fhorner(Fsum):

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

66 '''

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

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

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

70

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

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

73 instance), all positional.

74 @kwarg name_RESIDUAL: Optional C{B{name}=NN} (C{str}) and the C{B{RESIDUAL}=0.0}

75 threshold (C{scalar}) for raising L{ResidualError}s, see class

76 L{Fsum<Fsum.__init__>}.

77

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

79

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

81

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

83

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

85 '''

86 Fsum.__init__(self, **name_RESIDUAL)

87 if cs:

88 self._fhorner(x, cs, Fhorner.__name__)

89 else:

90 self._fset_ps(_0_0)

91

92

93 class Fhypot(Fsum):

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

95 '''

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

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

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

99

100 @arg xs: Components (each C{scalar} or an L{Fsum} or L{Fsum2Tuple} instance),

101 all positional.

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

103 (C{scalar}), C{B{name}=NN} (C{str}), the C{B{RESIDUAL}=0.0}

104 threshold (C{scalar}) and C{B{raiser}=True} (C{bool}) for

105 raising L{ResidualError}s, see class L{Fsum<Fsum.__init__>} and

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

107 '''

108 r = None # _xkwds_pop2 error

109 try:

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

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

112 raiser = _Fsum__init__(self, **kwds)

113 if xs:

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

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

116 except Exception as X:

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

118

119

120 class Fpolynomial(Fsum):

121 '''Precision polynomial evaluation.

122 '''

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

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

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

126

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

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

129 instance), all positional.

130 @kwarg name_RESIDUAL: Optional C{B{name}=NN} (C{str}) and the C{B{RESIDUAL}=0.0}

131 threshold (C{scalar}) for raising L{ResidualError}s, see class

132 L{Fsum<Fsum.__init__>}.

133

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

135

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

137

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

139

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

141 '''

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

143 n = len(cs) - 1

144 if n > 0:

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

146 elif n < 0:

147 self._fset_ps(_0_0)

148

149

150 class Fpowers(Fsum):

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

152 '''

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

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

155

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

157 @arg xs: One or more bases (each C{scalar} or an L{Fsum} or L{Fsum2Tuple} instance),

158 all positional.

159 @kwarg name_RESIDUAL_raiser: Optional C{B{name}=NN} (C{str}), the C{B{RESIDUAL}=0.0}

160 threshold (C{scalar}) and C{B{raiser}=True} (C{bool}) for raising

161 L{ResidualError}s, see class L{Fsum<Fsum.__init__>} and method

162 L{fpow<Fsum.fpow>}.

163 '''

164 try:

165 raiser = _Fsum__init__(self, **name_RESIDUAL_raiser)

166 if xs:

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

168 except Exception as X:

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

170

171

172 class Froot(Fsum):

173 '''The root of a precision summation.

174 '''

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

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

177

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

179 @arg xs: Items to summate (each a C{scalar} or an L{Fsum} or L{Fsum2Tuple} instance),

180 all positional.

181 @kwarg name_RESIDUAL_raiser: Optional C{B{name}=NN} (C{str}), the C{B{RESIDUAL}=0.0}

182 threshold (C{scalar}) and C{B{raiser}=True} (C{bool}) for raising

183 L{ResidualError}s, see class L{Fsum<Fsum.__init__>} and method

184 L{fpow<Fsum.fpow>}.

185 '''

186 try:

187 raiser = _Fsum__init__(self, **name_RESIDUAL_raiser)

188 if xs:

189 self.fadd(xs)

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

191 except Exception as X:

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

193

194

195 class Fcbrt(Froot):

196 '''Cubic root of a precision summation.

197 '''

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

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

200

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

202 '''

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

204

205

206 class Fsqrt(Froot):

207 '''Square root of a precision summation.

208 '''

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

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

211

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

213 '''

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

215

216

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

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

219 '''

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

221 inst._fset_ps(_0_0)

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

223

224

225 def bqrt(x):

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

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

228

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

230

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

232

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

234

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

236

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

238 '''

239 return _root(x, _0_25, bqrt)

240

241

242 try:

243 from math import cbrt as _cbrt # Python 3.11+

244

245 except ImportError: # Python 3.10-

246

247 def _cbrt(x):

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

249 '''

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

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

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

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

254

255

256 def cbrt(x):

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

258

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

260

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

262

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

264 '''

265 if _isFsumTuple(x):

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

267 if x.signOf() < 0:

268 r = -r

269 else:

270 r = _cbrt(x)

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

272

273

274 def cbrt2(x): # PYCHOK attr

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

276

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

278

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

280

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

282 '''

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

284

285

286 def euclid(x, y):

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

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

289

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

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

292

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

294

295 @see: Function L{euclid_}.

296 '''

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

298 if y > x:

299 x, y = y, x

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

301

302

303 def euclid_(*xs):

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

305 cascaded L{euclid}.

306

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

308 instance), all positional.

309

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

311

312 @see: Function L{euclid}.

313 '''

314 e = _0_0

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

316 # e = euclid(x, e)

317 if e < x:

318 e, x = x, e

319 if x:

320 e += x * _0_4142

321 return e

322

323

324 def facos1(x):

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

326

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

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

329 '''

330 a = fabs(x)

331 if a < EPS0:

332 r = PI_2

333 elif a < EPS1:

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

335 H *= Fsqrt(_1_0, -a)

336 r = float(H)

337 if x < 0:

338 r = PI - r

339 else:

340 r = PI if x < 0 else _0_0

341 return r

342

343

344 def fasin1(x): # PYCHOK no cover

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

346

347 @see: L{facos1}.

348 '''

349 return PI_2 - facos1(x)

350

351

352 def fatan(x):

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

354 '''

355 a = fabs(x)

356 if a < _1_0:

357 r = fatan1(a) if a else _0_0

358 elif a > _1_0:

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

360 else:

361 r = PI_4

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

363 r = -r

364 return r

365

366

367 def fatan1(x):

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

369

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

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

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

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

374 IEEE Signal Processing Magazine, 111, May 2006.

375 '''

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

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

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

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

380 return float(H)

381

382

383 def fatan2(y, x):

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

385

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

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

388 and L{fatan1}.

389 '''

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

391 if b > a:

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

393 elif a > b:

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

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

396 r = PI_4

397 else: # a == b == 0

398 return _0_0

399 if x < 0:

400 r = PI - r

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

402 r = -r

403 return r

404

405

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

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

408

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

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

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

412

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

414 '''

415# @raise ValueError: Fraction out of range.

416# '''

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

418# raise _ValueError(fraction=f)

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

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

421

422

423 def fdot(a, *b):

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

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

426

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

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

429

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

431

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

433

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

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

436 '''

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

438

439

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

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

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

443

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

445 L{Fsum2Tuple} instance).

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

447 L{Fsum2Tuple} instance).

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

449 L{Fsum2Tuple} instance).

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

451 or L{Fsum2Tuple}).

452

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

454

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

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

457

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

459 '''

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

461 if s:

462 yield s

463 if p:

464 yield _1_0

465 _F = Fsum

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

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

468 if p:

469 yield _N_1_0

470

471 n = len(xs)

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

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

474

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

476

477

478 def fhorner(x, *cs):

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

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

481

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

483

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

485 '''

486 H = Fhorner(x, *cs)

487 return float(H)

488

489

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

491 '''Interpolate using U{Inverse Distance Weighting

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

493

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

495 L{Fsum2Tuple} instance).

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

497 or L{Fsum2Tuple} instance).

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

499

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

501

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

503

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

505

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

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

508

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

510 '''

511 n, xs = len2(xs)

512 if n > 1:

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

514 if b < 0:

515 try: # weighted

516 _F = Fsum

517 W = _F()

518 X = _F()

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

520 x = xs[i]

521 D = _F(d)

522 if D < EPS0:

523 if D < 0:

524 raise ValueError(_negative_)

525 x = float(x)

526 i = n

527 break

528 if D.fpow(b):

529 W += D

530 X += D.fmul(x)

531 else:

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

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

534 except IndexError:

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

536 except Exception as X:

537 _I = Fmt.INDEX

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

539 else: # b == 0

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

541 i = n

542 elif n:

543 x = float(xs[0])

544 i = n

545 else:

546 x = _0_0

547 i, _ = len2(ds)

548 if i != n:

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

550 return x

551

552

553 def fmean(xs):

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

555

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

557

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

559

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

561

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

563 '''

564 n, xs = len2(xs)

565 if n < 1:

566 raise LenError(fmean, xs=xs)

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

568

569

570 def fmean_(*xs):

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

572

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

574 '''

575 return fmean(xs)

576

577

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

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

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

581

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

583

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

585

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

587 '''

588 P = Fpolynomial(x, *cs)

589 d = _xkwds_get1(over, over=0) if over else 0

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

591

592

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

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

595

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

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

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

599 exponent (C{int}).

600

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

602

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

604

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

606 '''

607 if not isint(n):

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

609 elif n < 1:

610 raise _ValueError(n=n)

611

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

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

614

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

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

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

618

619 return ps

620

621

622 try:

623 from math import prod as fprod # Python 3.8

624 except ImportError:

625

626 def fprod(xs, start=1):

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

628

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

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

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

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

633

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

635

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

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

638 '''

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

640

641

642 def frandoms(n, seeded=None):

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

644

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

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

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

648

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

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

651 '''

652 from random import gauss, random, seed, shuffle

653

654 if seeded is None:

655 pass

656 elif seeded and isbool(seeded):

657 from time import localtime

658 seed(localtime().tm_yday)

659 elif isscalar(seeded):

660 seed(seeded)

661

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

663 for _ in range(n):

664 s = 0

665 t = list(c)

666 _a = t.append

667 for _ in range(n * 8):

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

669 _a(v)

670 s += v

671 shuffle(t)

672 yield t

673

674

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

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

677

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

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

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

681

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

683

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

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

686 '''

687 if not isint(number):

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

689 for i in range(number):

690 yield start + (step * i)

691

692

693 try:

694 from functools import reduce as freduce

695 except ImportError:

696 try:

697 freduce = reduce # PYCHOK expected

698 except NameError: # Python 3+

699

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

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

702 '''

703 if start:

704 r = v = start[0]

705 else:

706 r, v = 0, MISSING

707 for v in xs:

708 r = f(r, v)

709 if v is MISSING:

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

711 return r

712

713

714 def fremainder(x, y):

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

716

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

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

719

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

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

722

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

724

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

726 project/geographiclib/>} and Python 3.7+

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

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

729 '''

730 # with Python 2.7.16 and 3.7.3 on macOS 10.13.6 and

731 # with Python 3.10.2 on macOS 12.2.1 M1 arm64 native

732 # fmod( 0, 360) == 0.0

733 # fmod( 360, 360) == 0.0

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

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

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

737 # however, using the % operator ...

738 # 0 % 360 == 0

739 # 360 % 360 == 0

740 # 360.0 % 360 == 0.0

741 # -0 % 360 == 0

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

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

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

745

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

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

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

749 if _isfinite(x):

750 try:

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

752 except Exception as e:

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

754 else: # handle x INF and NINF as NAN

755 r = NAN

756 return r

757

758

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

760 from math import hypot # OK in Python 3.7-

761

762 def hypot_(*xs):

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

764

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

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

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

768 handled differently.

769

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

771

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

773

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

775

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

777

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

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

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

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

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

783 '''

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

785

786 elif _sys_version_info2 < (3, 10):

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

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

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

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

791

792 def hypot(x, y):

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

794

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

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

797

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

799 '''

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

801

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

803 else:

804 from math import hypot # PYCHOK in Python 3.10+

805 hypot_ = hypot

806

807

808 def hypot1(x):

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

810

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

812

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

814 '''

815 if _isFsumTuple(x):

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

817 else:

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

819 return h

820

821

822 def hypot2(x, y):

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

824

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

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

827

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

829 '''

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

831 if y > x:

832 x, y = y, x

833 if x:

834 h2 = x**2

835 if y:

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

837 h2 = float(h2)

838 else:

839 h2 = _0_0

840 return h2

841

842

843 def hypot2_(*xs):

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

845

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

847 L{Fsum2Tuple} instance), all positional.

848

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

850

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

852 '''

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

854 if h2:

855 _h = _1_0 / h2

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

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

858 return h2

859

860

861 def _map_mul(xs, ys, where):

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

863 '''

864 n = len(ys)

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

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

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

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

869

870

871 def _1map_mul(xs, ys):

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

873 '''

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

875

876

877 def norm2(x, y):

878 '''Normalize a 2-dimensional vector.

879

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

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

882

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

884

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

886 or zero norm.

887 '''

888 try:

889 h = None

890 h = hypot(x, y)

891 if h:

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

893 else:

894 x = _copysign_0_0(x) # pass?

895 y = _copysign_0_0(y)

896 except Exception as e:

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

898 return x, y

899

900

901 def norm_(*xs):

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

903

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

905

906 @return: Yield each component, normalized.

907

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

909 or zero norm.

910 '''

911 try:

912 i = x = h = None

913 h = hypot_(*xs)

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

915 for i, x in enumerate(xs):

916 yield x * _h

917 except Exception as X:

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

919

920

921 def _powers(x, n):

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

923 '''

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

925 for _ in range(n):

926 p *= x

927 yield p

928

929

930 def _root(x, p, where):

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

932 '''

933 try:

934 if x > 0:

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

936 elif x < 0:

937 raise ValueError(_negative_)

938 except Exception as X:

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

940 return _0_0

941

942

943 def sqrt0(x, Error=None):

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

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

946

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

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

949

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

951

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

953

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

955 returns C{0.0}.

956 '''

957 if Error and x < 0:

958 raise Error(unstr(sqrt0, x))

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

960

961

962 def sqrt3(x):

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

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

965

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

967

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

969

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

971

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

973

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

975 '''

976 return _root(x, _1_5, sqrt3)

977

978

979 def sqrt_a(h, b):

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

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

982

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

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

985

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

987

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

989

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

991

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

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

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

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

996 '''

997 try:

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

999 raise TypeError(_not_scalar_)

1000 c = fabs(h)

1001 if c > EPS0:

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

1003 if s < 0:

1004 raise ValueError(_h_lt_b_)

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

1006 else: # PYCHOK no cover

1007 b = fabs(b)

1008 d = c - b

1009 if d < 0:

1010 raise ValueError(_h_lt_b_)

1011 d *= c + b

1012 a = sqrt(d) if d else _0_0

1013 except Exception as x:

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

1015 return copysign0(a, h)

1016

1017

1018 def zcrt(x):

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

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

1021

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

1023

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

1025

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

1027

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

1029

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

1031 '''

1032 return _root(x, _1_6th, zcrt)

1033

1034

1035 def zqrt(x):

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

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

1038

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

1040

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

1042

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

1044

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

1046

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

1048 '''

1049 return _root(x, _0_125, zqrt)

1050

1051# **) MIT License

1052#

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

1054#

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

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

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

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

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

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

1061#

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

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

1064#

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

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

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

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

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

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

1071# OTHER DEALINGS IN THE SOFTWARE.