Coverage for pygeodesy/fsums.py: 96%
734 statements
« prev ^ index » next coverage.py v7.2.2, created at 2024-04-04 14:33 -0400
« prev ^ index » next coverage.py v7.2.2, created at 2024-04-04 14:33 -0400
2# -*- coding: utf-8 -*-
4u'''Class L{Fsum} for precision floating point summation and I{running}
5summation based on, respectively similar to Python's C{math.fsum}.
7Generally, an L{Fsum} instance is considered a C{float} plus a small or zero
8C{residual} value, see property L{Fsum.residual}. However, there are several
9C{integer} L{Fsum} cases, for example the result of C{ceil}, C{floor},
10C{Fsum.__floordiv__} and methods L{Fsum.fint} and L{Fsum.fint2}.
12Also, L{Fsum} methods L{Fsum.pow}, L{Fsum.__ipow__}, L{Fsum.__pow__} and
13L{Fsum.__rpow__} return a (very long) C{int} if invoked with optional argument
14C{mod} set to C{None}. The C{residual} of an C{integer} L{Fsum} may be between
15C{-1.0} and C{+1.0}, including C{INT0} if considered to be I{exact}.
17Set env variable C{PYGEODESY_FSUM_PARTIALS} to string C{"fsum"}) for summation
18of L{Fsum} partials by Python function C{math.fsum}.
20Set env variable C{PYGEODESY_FSUM_RESIDUAL} to a C{float} string greater
21than C{"0.0"} as the threshold to throw a L{ResidualError} in division or
22exponention of an L{Fsum} instance with a I{relative} C{residual} exceeding
23the threshold, see methods L{Fsum.RESIDUAL}, L{Fsum.pow}, L{Fsum.__ipow__}
24and L{Fsum.__itruediv__}.
25'''
26# make sure int/int division yields float quotient, see .basics
27from __future__ import division as _; del _ # PYCHOK semicolon
29from pygeodesy.basics import iscomplex, isint, isscalar, itemsorted, \
30 signOf, _signOf
31from pygeodesy.constants import INT0, _isfinite, isinf, isnan, NEG0, _pos_self, \
32 _0_0, _1_0, _N_1_0, Float, Int
33from pygeodesy.errors import _OverflowError, _TypeError, _ValueError, _xError, \
34 _xError2, _xkwds_get, _ZeroDivisionError
35from pygeodesy.interns import NN, _arg_, _COMMASPACE_, _DASH_, _DOT_, _EQUAL_, \
36 _exceeds_, _from_, _iadd_op_, _LANGLE_, _negative_, \
37 _NOTEQUAL_, _not_finite_, _not_scalar_, _PERCENT_, \
38 _PLUS_, _R_, _RANGLE_, _SLASH_, _SPACE_, _STAR_, _UNDER_
39from pygeodesy.lazily import _ALL_LAZY, _getenv, _sys_version_info2
40from pygeodesy.named import _Named, _NamedTuple, _NotImplemented, Fmt, unstr
41from pygeodesy.props import _allPropertiesOf_n, deprecated_property_RO, \
42 Property_RO, property_RO
43# from pygeodesy.streprs import Fmt, unstr # from .named
44# from pygeodesy.units import Float, Int # from .constants
46from math import ceil as _ceil, fabs, floor as _floor # PYCHOK used! .ltp
48__all__ = _ALL_LAZY.fsums
49__version__ = '24.04.04'
51_add_op_ = _PLUS_ # in .auxilats.auxAngle
52_eq_op_ = _EQUAL_ * 2 # _DEQUAL_
53_COMMASPACE_R_ = _COMMASPACE_ + _R_
54_div_ = 'div'
55_exceeds_R_ = _SPACE_ + _exceeds_(_R_)
56_floordiv_op_ = _SLASH_ * 2 # _DSLASH_
57_fset_op_ = _EQUAL_
58_ge_op_ = _RANGLE_ + _EQUAL_
59_gt_op_ = _RANGLE_
60_integer_ = 'integer'
61_le_op_ = _LANGLE_ + _EQUAL_
62_lt_op_ = _LANGLE_
63_mod_ = 'mod'
64_mod_op_ = _PERCENT_
65_mul_op_ = _STAR_
66_ne_op_ = _NOTEQUAL_
67_non_zero_ = 'non-zero'
68_pow_op_ = _STAR_ * 2 # _DSTAR_, in .fmath
69_sub_op_ = _DASH_ # in .auxilats.auxAngle, .fsums
70_truediv_op_ = _SLASH_
71_divmod_op_ = _floordiv_op_ + _mod_op_
72_isub_op_ = _sub_op_ + _fset_op_ # in .auxilats.auxAngle, .fsums
75def _2float(index=None, **name_value): # in .fmath, .fstats
76 '''(INTERNAL) Raise C{TypeError} or C{ValueError} if not scalar or infinite.
77 '''
78 n, v = name_value.popitem() # _xkwds_item2(name_value)
79 try:
80 v = float(v)
81 if _isfinite(v):
82 return v
83 raise ValueError(_not_finite_)
84 except Exception as X:
85 raise _xError(X, Fmt.INDEX(n, index), v)
88def _2floats(xs, origin=0, neg=False):
89 '''(INTERNAL) Yield each B{C{xs}} as a C{float}.
90 '''
91 if neg:
92 def _X(X):
93 return X._ps_neg
95 def _x(x):
96 return -float(x)
97 else:
98 def _X(X): # PYCHOK re-def
99 return X._ps
101 _x = float
103 return _2yield(xs, origin, _X, _x)
106def _1primed(xs): # in .fmath
107 '''(INTERNAL) 1-Prime the summation of C{xs}
108 arguments I{known} to be C{finite float}.
109 '''
110 yield _1_0
111 for x in xs:
112 if x:
113 yield x
114 yield _N_1_0
117def _2ps(s, r):
118 '''(INTERNAL) Return a C{s} and C{r} pair, I{ps-ordered}.
119 '''
120 if fabs(s) < fabs(r):
121 s, r = r, s
122 return ((r, s) if s else (r,)) if r else (s,)
125def _psum(ps): # PYCHOK used!
126 '''(INTERNAL) Partials sum, updating C{ps}, I{overridden below}.
127 '''
128 # assert isinstance(ps, list)
129 i = len(ps) - 1
130 s = _0_0 if i < 0 else ps[i]
131 _2s = _2sum
132 while i > 0:
133 i -= 1
134 s, r = _2s(s, ps[i])
135 if r: # sum(ps) became inexact
136 if s:
137 ps[i:] = r, s
138 if i > 0:
139 p = ps[i-1] # round half-even
140 if (p > 0 and r > 0) or \
141 (p < 0 and r < 0): # signs match
142 r *= 2
143 t = s + r
144 if r == (t - s):
145 s = t
146 break # return s
147 s = r # PYCHOK no cover
148 ps[i:] = s,
149 return s
152def _2scalar(other, _raiser=None):
153 '''(INTERNAL) Return B{C{other}} as C{int}, C{float} or C{as-is}.
154 '''
155 if isinstance(other, Fsum):
156 s, r = other._fint2
157 if r:
158 s, r = other._fprs2
159 if r: # PYCHOK no cover
160 if _raiser and _raiser(r, s):
161 raise ValueError(_stresidual(_non_zero_, r))
162 s = other # L{Fsum} as-is
163 else:
164 s = other # C{type} as-is
165 if isint(s, both=True):
166 s = int(s)
167 return s
170def _strcomplex(s, *args):
171 '''(INTERNAL) C{Complex} 2- or 3-arg C{pow} error as C{str}.
172 '''
173 c = _strcomplex.__name__[4:]
174 n = _DASH_(len(args), _arg_)
175 t = unstr(pow, *args)
176 return _SPACE_(c, s, _from_, n, t)
179def _stresidual(prefix, residual, **name_values):
180 '''(INTERNAL) Residual error as C{str}.
181 '''
182 p = _stresidual.__name__[3:]
183 t = Fmt.PARENSPACED(p, Fmt(residual))
184 for n, v in itemsorted(name_values):
185 n = n.replace(_UNDER_, _SPACE_)
186 p = Fmt.PARENSPACED(n, Fmt(v))
187 t = _COMMASPACE_(t, p)
188 return _SPACE_(prefix, t)
191def _2sum(a, b): # by .testFmath
192 '''(INTERNAL) Return C{a + b} as 2-tuple (sum, residual).
193 '''
194 s = a + b
195 if not _isfinite(s):
196 u = unstr(_2sum.__name__, a, b)
197 t = Fmt.PARENSPACED(_not_finite_, s)
198 raise _OverflowError(u, txt=t)
199 if fabs(a) < fabs(b):
200 a, b = b, a
201 return s, (b - (s - a))
204def _2yield(xs, i, _X_ps, _x):
205 '''(INTERNAL) Yield each B{C{xs}} as a C{float}.
206 '''
207 x = None
208 try:
209 _fin = _isfinite
210 _Fs = Fsum
211 for x in xs:
212 if isinstance(x, _Fs):
213 for p in _X_ps(x):
214 yield p
215 else:
216 f = _x(x)
217 if f:
218 if not _fin(f):
219 raise ValueError(_not_finite_)
220 yield f
221 i += 1
222 except Exception as X:
223 raise _xError(X, Fmt.INDEX(xs=i), x)
226class Fsum(_Named): # sync __methods__ with .vector3dBase.Vector3dBase
227 '''Precision floating point summation and I{running} summation.
229 Unlike Python's C{math.fsum}, this class accumulates values and provides intermediate,
230 I{running}, precision floating point summations. Accumulation may continue after any
231 intermediate, I{running} summuation.
233 @note: Accumulated values may be L{Fsum} or C{scalar} instances, any C{type} having
234 method C{__float__} to convert the C{scalar} to a single C{float}.
236 @note: Handling of exceptions and C{inf}, C{INF}, C{nan} and C{NAN} differs from
237 Python's C{math.fsum}.
239 @see: U{Hettinger<https://GitHub.com/ActiveState/code/blob/master/recipes/Python/
240 393090_Binary_floating_point_summatiaccurate_full/recipe-393090.py>}, U{Kahan
241 <https://WikiPedia.org/wiki/Kahan_summation_algorithm>}, U{Klein
242 <https://Link.Springer.com/article/10.1007/s00607-005-0139-x>}, Python 2.6+
243 file I{Modules/mathmodule.c} and the issue log U{Full precision summation
244 <https://Bugs.Python.org/issue2819>}.
245 '''
246 _math_fsum = None
247 _n = 0
248# _ps = [] # partial sums
249# _px = 0 # max(Fsum._px, len(Fsum._ps))
250 _ratio = None
251 _RESIDUAL = max(float(_getenv('PYGEODESY_FSUM_RESIDUAL', _0_0)), _0_0)
253 def __init__(self, *xs, **name_RESIDUAL):
254 '''New L{Fsum} for I{running} precision floating point summation.
256 @arg xs: No, one or more initial values, all positional (each C{scalar}
257 or an L{Fsum} instance).
258 @kwarg name_RESIDUAL: Optional C{B{name}=NN} for this L{Fsum} and
259 C{B{RESIDUAL}=None} for the L{ResidualError} threshold.
261 @see: Methods L{Fsum.fadd} and L{Fsum.RESIDUAL}.
262 '''
263 if name_RESIDUAL:
264 n = _xkwds_get(name_RESIDUAL, name=NN)
265 if n: # set name before ...
266 self.name = n
267 r = _xkwds_get(name_RESIDUAL, RESIDUAL=None)
268 if r is not None:
269 self.RESIDUAL(r) # ... ResidualError
270# self._n = 0
271 self._ps = [] # [_0_0], see L{Fsum._fprs}
272 if len(xs) > 1:
273 self._facc(_2floats(xs, origin=1), up=False) # PYCHOK yield
274 elif xs: # len(xs) == 1
275 self._n = 1
276 self._ps[:] = _2float(x=xs[0]),
278 def __abs__(self):
279 '''Return this instance' absolute value as an L{Fsum}.
280 '''
281 s = _fsum(self._ps_1()) # == self._cmp_0(0, ...)
282 return (-self) if s < 0 else self._copy_2(self.__abs__)
284 def __add__(self, other):
285 '''Return the C{Fsum(B{self}, B{other})}.
287 @arg other: An L{Fsum} or C{scalar}.
289 @return: The sum (L{Fsum}).
291 @see: Method L{Fsum.__iadd__}.
292 '''
293 f = self._copy_2(self.__add__)
294 return f._fadd(other, _add_op_)
296 def __bool__(self): # PYCHOK not special in Python 2-
297 '''Return C{True} if this instance is I{exactly} non-zero.
298 '''
299 s, r = self._fprs2
300 return bool(s or r) and s != -r # == self != 0
302 def __ceil__(self): # PYCHOK not special in Python 2-
303 '''Return this instance' C{math.ceil} as C{int} or C{float}.
305 @return: An C{int} in Python 3+, but C{float} in Python 2-.
307 @see: Methods L{Fsum.__floor__} and property L{Fsum.ceil}.
308 '''
309 return self.ceil
311 def __cmp__(self, other): # Python 2-
312 '''Compare this with an other instance or C{scalar}.
314 @return: -1, 0 or +1 (C{int}).
316 @raise TypeError: Incompatible B{C{other}} C{type}.
317 '''
318 s = self._cmp_0(other, self.cmp.__name__)
319 return _signOf(s, 0)
321 cmp = __cmp__
323 def __divmod__(self, other):
324 '''Return C{divmod(B{self}, B{other})} as a L{DivMod2Tuple}
325 with quotient C{div} an C{int} in Python 3+ or C{float}
326 in Python 2- and remainder C{mod} an L{Fsum}.
328 @arg other: An L{Fsum} or C{scalar} modulus.
330 @see: Method L{Fsum.__itruediv__}.
331 '''
332 f = self._copy_2(self.__divmod__)
333 return f._fdivmod2(other, _divmod_op_)
335 def __eq__(self, other):
336 '''Compare this with an other instance or C{scalar}.
337 '''
338 return self._cmp_0(other, _eq_op_) == 0
340 def __float__(self):
341 '''Return this instance' current precision running sum as C{float}.
343 @see: Methods L{Fsum.fsum} and L{Fsum.int_float}.
344 '''
345 return float(self._fprs)
347 def __floor__(self): # PYCHOK not special in Python 2-
348 '''Return this instance' C{math.floor} as C{int} or C{float}.
350 @return: An C{int} in Python 3+, but C{float} in Python 2-.
352 @see: Methods L{Fsum.__ceil__} and property L{Fsum.floor}.
353 '''
354 return self.floor
356 def __floordiv__(self, other):
357 '''Return C{B{self} // B{other}} as an L{Fsum}.
359 @arg other: An L{Fsum} or C{scalar} divisor.
361 @return: The C{floor} quotient (L{Fsum}).
363 @see: Methods L{Fsum.__ifloordiv__}.
364 '''
365 f = self._copy_2(self.__floordiv__)
366 return f._floordiv(other, _floordiv_op_)
368 def __format__(self, *other): # PYCHOK no cover
369 '''Not implemented.'''
370 return _NotImplemented(self, *other)
372 def __ge__(self, other):
373 '''Compare this with an other instance or C{scalar}.
374 '''
375 return self._cmp_0(other, _ge_op_) >= 0
377 def __gt__(self, other):
378 '''Compare this with an other instance or C{scalar}.
379 '''
380 return self._cmp_0(other, _gt_op_) > 0
382 def __hash__(self): # PYCHOK no cover
383 '''Return this instance' C{hash}.
384 '''
385 return hash(self._ps) # XXX id(self)?
387 def __iadd__(self, other):
388 '''Apply C{B{self} += B{other}} to this instance.
390 @arg other: An L{Fsum} or C{scalar} instance.
392 @return: This instance, updated (L{Fsum}).
394 @raise TypeError: Invalid B{C{other}}, not
395 C{scalar} nor L{Fsum}.
397 @see: Methods L{Fsum.fadd} and L{Fsum.fadd_}.
398 '''
399 return self._fadd(other, _iadd_op_)
401 def __ifloordiv__(self, other):
402 '''Apply C{B{self} //= B{other}} to this instance.
404 @arg other: An L{Fsum} or C{scalar} divisor.
406 @return: This instance, updated (L{Fsum}).
408 @raise ResidualError: Non-zero residual in B{C{other}}.
410 @raise TypeError: Invalid B{C{other}} type.
412 @raise ValueError: Invalid or non-finite B{C{other}}.
414 @raise ZeroDivisionError: Zero B{C{other}}.
416 @see: Methods L{Fsum.__itruediv__}.
417 '''
418 return self._floordiv(other, _floordiv_op_ + _fset_op_)
420 def __imatmul__(self, other): # PYCHOK no cover
421 '''Not implemented.'''
422 return _NotImplemented(self, other)
424 def __imod__(self, other):
425 '''Apply C{B{self} %= B{other}} to this instance.
427 @arg other: An L{Fsum} or C{scalar} modulus.
429 @return: This instance, updated (L{Fsum}).
431 @see: Method L{Fsum.__divmod__}.
432 '''
433 return self._fdivmod2(other, _mod_op_ + _fset_op_).mod
435 def __imul__(self, other):
436 '''Apply C{B{self} *= B{other}} to this instance.
438 @arg other: An L{Fsum} or C{scalar} factor.
440 @return: This instance, updated (L{Fsum}).
442 @raise OverflowError: Partial C{2sum} overflow.
444 @raise TypeError: Invalid B{C{other}} type.
446 @raise ValueError: Invalid or non-finite B{C{other}}.
447 '''
448 return self._fmul(other, _mul_op_ + _fset_op_)
450 def __int__(self):
451 '''Return this instance as an C{int}.
453 @see: Methods L{Fsum.int_float}, L{Fsum.__ceil__}
454 and L{Fsum.__floor__} and properties
455 L{Fsum.ceil} and L{Fsum.floor}.
456 '''
457 i, _ = self._fint2
458 return i
460 def __invert__(self): # PYCHOK no cover
461 '''Not implemented.'''
462 # Luciano Ramalho, "Fluent Python", O'Reilly, 2nd Ed, 2022 p. 567
463 return _NotImplemented(self)
465 def __ipow__(self, other, *mod): # PYCHOK 2 vs 3 args
466 '''Apply C{B{self} **= B{other}} to this instance.
468 @arg other: The exponent (L{Fsum} or C{scalar}).
469 @arg mod: Optional modulus (C{int} or C{None}) for the
470 3-argument C{pow(B{self}, B{other}, B{mod})}
471 version.
473 @return: This instance, updated (L{Fsum}).
475 @note: If B{C{mod}} is given, the result will be an C{integer}
476 L{Fsum} in Python 3+ if this instance C{is_integer} or
477 set to C{as_integer} if B{C{mod}} given as C{None}.
479 @raise OverflowError: Partial C{2sum} overflow.
481 @raise ResidualError: Non-zero residual in B{C{other}} and
482 env var C{PYGEODESY_FSUM_RESIDUAL}
483 set or this instance has a non-zero
484 residual and either B{C{mod}} is
485 given and non-C{None} or B{C{other}}
486 is a negative or fractional C{scalar}.
488 @raise TypeError: Invalid B{C{other}} type or 3-argument
489 C{pow} invocation failed.
491 @raise ValueError: If B{C{other}} is a negative C{scalar}
492 and this instance is C{0} or B{C{other}}
493 is a fractional C{scalar} and this
494 instance is negative or has a non-zero
495 residual or B{C{mod}} is given and C{0}.
497 @see: CPython function U{float_pow<https://GitHub.com/
498 python/cpython/blob/main/Objects/floatobject.c>}.
499 '''
500 return self._fpow(other, _pow_op_ + _fset_op_, *mod)
502 def __isub__(self, other):
503 '''Apply C{B{self} -= B{other}} to this instance.
505 @arg other: An L{Fsum} or C{scalar}.
507 @return: This instance, updated (L{Fsum}).
509 @raise TypeError: Invalid B{C{other}} type.
511 @see: Method L{Fsum.fadd}.
512 '''
513 return self._fsub(other, _isub_op_)
515 def __iter__(self):
516 '''Return an C{iter}ator over a C{partials} duplicate.
517 '''
518 return iter(self.partials)
520 def __itruediv__(self, other):
521 '''Apply C{B{self} /= B{other}} to this instance.
523 @arg other: An L{Fsum} or C{scalar} divisor.
525 @return: This instance, updated (L{Fsum}).
527 @raise OverflowError: Partial C{2sum} overflow.
529 @raise ResidualError: Non-zero residual in B{C{other}} and
530 env var C{PYGEODESY_FSUM_RESIDUAL} set.
532 @raise TypeError: Invalid B{C{other}} type.
534 @raise ValueError: Invalid or non-finite B{C{other}}.
536 @raise ZeroDivisionError: Zero B{C{other}}.
538 @see: Method L{Fsum.__ifloordiv__}.
539 '''
540 return self._ftruediv(other, _truediv_op_ + _fset_op_)
542 def __le__(self, other):
543 '''Compare this with an other instance or C{scalar}.
544 '''
545 return self._cmp_0(other, _le_op_) <= 0
547 def __len__(self):
548 '''Return the number of values accumulated (C{int}).
549 '''
550 return self._n
552 def __lt__(self, other):
553 '''Compare this with an other instance or C{scalar}.
554 '''
555 return self._cmp_0(other, _lt_op_) < 0
557 def __matmul__(self, other): # PYCHOK no cover
558 '''Not implemented.'''
559 return _NotImplemented(self, other)
561 def __mod__(self, other):
562 '''Return C{B{self} % B{other}} as an L{Fsum}.
564 @see: Method L{Fsum.__imod__}.
565 '''
566 f = self._copy_2(self.__mod__)
567 return f._fdivmod2(other, _mod_op_).mod
569 def __mul__(self, other):
570 '''Return C{B{self} * B{other}} as an L{Fsum}.
572 @see: Method L{Fsum.__imul__}.
573 '''
574 f = self._copy_2(self.__mul__)
575 return f._fmul(other, _mul_op_)
577 def __ne__(self, other):
578 '''Compare this with an other instance or C{scalar}.
579 '''
580 return self._cmp_0(other, _ne_op_) != 0
582 def __neg__(self):
583 '''Return I{a copy of} this instance, I{negated}.
584 '''
585 f = self._copy_2(self.__neg__)
586 return f._fset(self._neg)
588 def __pos__(self):
589 '''Return this instance I{as-is}, like C{float.__pos__()}.
590 '''
591 return self if _pos_self else self._copy_2(self.__pos__)
593 def __pow__(self, other, *mod): # PYCHOK 2 vs 3 args
594 '''Return C{B{self}**B{other}} as an L{Fsum}.
596 @see: Method L{Fsum.__ipow__}.
597 '''
598 f = self._copy_2(self.__pow__)
599 return f._fpow(other, _pow_op_, *mod)
601 def __radd__(self, other):
602 '''Return C{B{other} + B{self}} as an L{Fsum}.
604 @see: Method L{Fsum.__iadd__}.
605 '''
606 f = self._copy_2r(other, self.__radd__)
607 return f._fadd(self, _add_op_)
609 def __rdivmod__(self, other):
610 '''Return C{divmod(B{other}, B{self})} as 2-tuple C{(quotient,
611 remainder)}.
613 @see: Method L{Fsum.__divmod__}.
614 '''
615 f = self._copy_2r(other, self.__rdivmod__)
616 return f._fdivmod2(self, _divmod_op_)
618# def __repr__(self):
619# '''Return the default C{repr(this)}.
620# '''
621# return self.toRepr(lenc=True)
623 def __rfloordiv__(self, other):
624 '''Return C{B{other} // B{self}} as an L{Fsum}.
626 @see: Method L{Fsum.__ifloordiv__}.
627 '''
628 f = self._copy_2r(other, self.__rfloordiv__)
629 return f._floordiv(self, _floordiv_op_)
631 def __rmatmul__(self, other): # PYCHOK no cover
632 '''Not implemented.'''
633 return _NotImplemented(self, other)
635 def __rmod__(self, other):
636 '''Return C{B{other} % B{self}} as an L{Fsum}.
638 @see: Method L{Fsum.__imod__}.
639 '''
640 f = self._copy_2r(other, self.__rmod__)
641 return f._fdivmod2(self, _mod_op_).mod
643 def __rmul__(self, other):
644 '''Return C{B{other} * B{self}} as an L{Fsum}.
646 @see: Method L{Fsum.__imul__}.
647 '''
648 f = self._copy_2r(other, self.__rmul__)
649 return f._fmul(self, _mul_op_)
651 def __round__(self, *ndigits): # PYCHOK no cover
652 '''Return C{round(B{self}, *B{ndigits}} as an L{Fsum}.
654 @arg ndigits: Optional number of digits (C{int}).
655 '''
656 # <https://docs.Python.org/3.12/reference/datamodel.html?#object.__round__>
657 return _Fsum_ps(round(float(self), *ndigits), # can be C{int}
658 name=self.__round__.__name__)
660 def __rpow__(self, other, *mod):
661 '''Return C{B{other}**B{self}} as an L{Fsum}.
663 @see: Method L{Fsum.__ipow__}.
664 '''
665 f = self._copy_2r(other, self.__rpow__)
666 return f._fpow(self, _pow_op_, *mod)
668 def __rsub__(self, other):
669 '''Return C{B{other} - B{self}} as L{Fsum}.
671 @see: Method L{Fsum.__isub__}.
672 '''
673 f = self._copy_2r(other, self.__rsub__)
674 return f._fsub(self, _sub_op_)
676 def __rtruediv__(self, other):
677 '''Return C{B{other} / B{self}} as an L{Fsum}.
679 @see: Method L{Fsum.__itruediv__}.
680 '''
681 f = self._copy_2r(other, self.__rtruediv__)
682 return f._ftruediv(self, _truediv_op_)
684 def __str__(self):
685 '''Return the default C{str(self)}.
686 '''
687 return self.toStr(lenc=True)
689 def __sub__(self, other):
690 '''Return C{B{self} - B{other}} as an L{Fsum}.
692 @arg other: An L{Fsum} or C{scalar}.
694 @return: The difference (L{Fsum}).
696 @see: Method L{Fsum.__isub__}.
697 '''
698 f = self._copy_2(self.__sub__)
699 return f._fsub(other, _sub_op_)
701 def __truediv__(self, other):
702 '''Return C{B{self} / B{other}} as an L{Fsum}.
704 @arg other: An L{Fsum} or C{scalar} divisor.
706 @return: The quotient (L{Fsum}).
708 @see: Method L{Fsum.__itruediv__}.
709 '''
710 f = self._copy_2(self.__truediv__)
711 return f._ftruediv(other, _truediv_op_)
713 __trunc__ = __int__
715 if _sys_version_info2 < (3, 0): # PYCHOK no cover
716 # <https://docs.Python.org/2/library/operator.html#mapping-operators-to-functions>
717 __div__ = __truediv__
718 __idiv__ = __itruediv__
719 __long__ = __int__
720 __nonzero__ = __bool__
721 __rdiv__ = __rtruediv__
723 def as_integer_ratio(self):
724 '''Return this instance as the ratio of 2 integers.
726 @return: 2-Tuple C{(numerator, denominator)} both
727 C{int} and with positive C{denominator}.
729 @see: Standard C{float.as_integer_ratio} in Python 3+.
730 '''
731 n, r = self._fint2
732 if r:
733 i, d = r.as_integer_ratio()
734 n *= d
735 n += i
736 else: # PYCHOK no cover
737 d = 1
738 return n, d
740 @property_RO
741 def ceil(self):
742 '''Get this instance' C{ceil} value (C{int} in Python 3+,
743 but C{float} in Python 2-).
745 @note: The C{ceil} takes the C{residual} into account.
747 @see: Method L{Fsum.int_float} and properties L{Fsum.floor},
748 L{Fsum.imag} and L{Fsum.real}.
749 '''
750 s, r = self._fprs2
751 c = _ceil(s) + int(r) - 1
752 while r > (c - s): # (s + r) > c
753 c += 1
754 return c
756 def _cmp_0(self, other, op):
757 '''(INTERNAL) Return C{scalar(self - B{other})} for 0-comparison.
758 '''
759 if isinstance(other, Fsum):
760 s = _fsum(self._ps_1(*other._ps))
761 elif isscalar(other):
762 if other:
763 s = _fsum(self._ps_1(other))
764 else:
765 s, r = self._fprs2
766 s = _signOf(s, -r)
767 else:
768 raise self._TypeError(op, other) # txt=_invalid_
769 return s
771 def copy(self, deep=False, name=NN):
772 '''Copy this instance, C{shallow} or B{C{deep}}.
774 @return: The copy (L{Fsum}).
775 '''
776 f = _Named.copy(self, deep=deep, name=name)
777 f._n = self._n if deep else 1
778 f._ps = list(self._ps) # separate list
779 return f
781 def _copy_2(self, which, name=NN):
782 '''(INTERNAL) Copy for I{dyadic} operators.
783 '''
784 n = name or which.__name__
785 # NOT .classof due to .Fdot(a, *b) args, etc.
786 f = _Named.copy(self, deep=False, name=n)
787 # assert f._n == self._n
788 f._ps = list(self._ps) # separate list
789 return f
791 def _copy_2r(self, other, which):
792 '''(INTERNAL) Copy for I{reverse-dyadic} operators.
793 '''
794 return other._copy_2(which) if isinstance(other, Fsum) else \
795 Fsum(other, name=which.__name__)
797# def _copy_RESIDUAL(self, other):
798# '''(INTERNAL) Copy C{other._RESIDUAL}.
799# '''
800# R = other._RESIDUAL
801# if R is not Fsum._RESIDUAL:
802# self._RESIDUAL = R
804 def divmod(self, other):
805 '''Return C{divmod(B{self}, B{other})} as 2-tuple C{(quotient,
806 remainder)}.
808 @arg other: An L{Fsum} or C{scalar} divisor.
810 @return: A L{DivMod2Tuple}C{(div, mod)}, with quotient C{div}
811 an C{int} in Python 3+ or C{float} in Python 2- and
812 remainder C{mod} an L{Fsum} instance.
814 @see: Method L{Fsum.__itruediv__}.
815 '''
816 f = self._copy_2(self.divmod)
817 return f._fdivmod2(other, _divmod_op_)
819 def _Error(self, op, other, Error, **txt_cause):
820 '''(INTERNAL) Format an B{C{Error}} for C{{self} B{op} B{other}}.
821 '''
822 return Error(_SPACE_(self.toRepr(), op, repr(other)), **txt_cause)
824 def _ErrorX(self, X, op, other, *mod):
825 '''(INTERNAL) Format the caught exception C{X}.
826 '''
827 E, t = _xError2(X)
828 if mod:
829 t = _COMMASPACE_(Fmt.PARENSPACED(mod=mod[0]), t)
830 return self._Error(op, other, E, txt=t, cause=X)
832 def _ErrorXs(self, X, xs, **kwds): # in .fmath
833 '''(INTERNAL) Format the caught exception C{X}.
834 '''
835 E, t = _xError2(X)
836 n = unstr(self.named3, *xs[:3], _ELLIPSIS=len(xs) > 3, **kwds)
837 return E(n, txt=t, cause=X)
839 def _facc(self, xs, up=True): # from .elliptic._Defer.Fsum
840 '''(INTERNAL) Accumulate more known C{scalar}s.
841 '''
842 n, ps, _2s = 0, self._ps, _2sum
843 for x in xs: # _iter()
844 # assert isscalar(x) and isfinite(x)
845 if x:
846 i = 0
847 for p in ps:
848 x, p = _2s(x, p)
849 if p:
850 ps[i] = p
851 i += 1
852 ps[i:] = (x,) if x else ()
853 n += 1
854 # assert self._ps is ps
855 if n:
856 self._n += n
857 # Fsum._px = max(Fsum._px, len(ps))
858 if up:
859 self._update()
860 return self
862 def _facc_(self, *xs, **up):
863 '''(INTERNAL) Accumulate all positional C{scalar}s.
864 '''
865 return self._facc(xs, **up) if xs else self
867 def _facc_power(self, power, xs, which): # in .fmath
868 '''(INTERNAL) Add each C{xs} as C{float(x**power)}.
869 '''
870 p = power
871 if isinstance(p, Fsum):
872 if p.is_exact:
873 return self._facc_power(p._fprs, xs, which)
874 _Pow = Fsum._pow_any
875 elif isint(p, both=True) and p >= 0:
876 _Pow, p = Fsum._pow_int, int(p)
877 else:
878 _Pow, p = Fsum._pow_scalar, _2float(power=p)
880 if p:
881 from math import pow as _pow
882 op = which.__name__
884 def _X(X):
885 f = _Pow(X, p, power, op)
886 try: # isinstance(f, Fsum)
887 return f._ps
888 except AttributeError: # scalar
889 return f,
891 def _x(x):
892 return _pow(float(x), p)
894 self._facc(_2yield(xs, 1, _X, _x)) # PYCHOK yield
895 else:
896 self._facc_(float(len(xs))) # x**0 == 1
897 return self
899# def _facc_up(self, up=True):
900# '''(INTERNAL) Update the C{partials}, by removing
901# and re-accumulating the final C{partial}.
902# '''
903# while len(self._ps) > 1:
904# p = self._ps.pop()
905# if p:
906# n = self._n
907# self._facc_(p, up=False)
908# self._n = n
909# break
910# return self._update() if up else self # ._fpsqz()
912 def fadd(self, xs=()):
913 '''Add an iterable of C{scalar} or L{Fsum} instances
914 to this instance.
916 @arg xs: Iterable, list, tuple, etc. (C{scalar} or
917 L{Fsum} instances).
919 @return: This instance (L{Fsum}).
921 @raise OverflowError: Partial C{2sum} overflow.
923 @raise TypeError: An invalid B{C{xs}} type, not C{scalar}
924 nor L{Fsum}.
926 @raise ValueError: Invalid or non-finite B{C{xs}} value.
927 '''
928 if isinstance(xs, Fsum):
929 self._facc(xs._ps)
930 elif isscalar(xs): # for backward compatibility
931 self._facc_(_2float(x=xs)) # PYCHOK no cover
932 elif xs:
933 self._facc(_2floats(xs)) # PYCHOK yield
934 return self
936 def fadd_(self, *xs):
937 '''Add all positional C{scalar} or L{Fsum} instances
938 to this instance.
940 @arg xs: Values to add (C{scalar} or L{Fsum} instances),
941 all positional.
943 @return: This instance (L{Fsum}).
945 @raise OverflowError: Partial C{2sum} overflow.
947 @raise TypeError: An invalid B{C{xs}} type, not C{scalar}
948 nor L{Fsum}.
950 @raise ValueError: Invalid or non-finite B{C{xs}} value.
951 '''
952 return self._facc(_2floats(xs, origin=1)) # PYCHOK yield
954 def _fadd(self, other, op, **up): # in .fmath.Fhorner
955 '''(INTERNAL) Apply C{B{self} += B{other}}.
956 '''
957 if isinstance(other, Fsum):
958 if other is self:
959 self._facc_(*other._ps, **up) # == ._facc(tuple(other._ps))
960 elif other._ps:
961 self._facc(other._ps, **up)
962 elif not isscalar(other):
963 raise self._TypeError(op, other) # txt=_invalid_
964 elif other:
965 self._facc_(other, **up)
966 return self
968 fcopy = copy # for backward compatibility
969 fdiv = __itruediv__ # for backward compatibility
970 fdivmod = __divmod__ # for backward compatibility
972 def _fdivmod2(self, other, op):
973 '''(INTERNAL) Apply C{B{self} %= B{other}} and return a L{DivMod2Tuple}.
974 '''
975 # result mostly follows CPython function U{float_divmod
976 # <https://GitHub.com/python/cpython/blob/main/Objects/floatobject.c>},
977 # but at least divmod(-3, 2) equals Cpython's result (-2, 1).
978 q = self._copy_2(self._fdivmod2)._ftruediv(other, op).floor
979 if q: # == float // other == floor(float / other)
980 self -= other * q
982 s = signOf(other) # make signOf(self) == signOf(other)
983 if s and self.signOf() == -s: # PYCHOK no cover
984 self += other
985 q -= 1
986# t = self.signOf()
987# if t and t != s:
988# raise self._Error(op, other, _AssertionError, txt=signOf.__name__)
989 return DivMod2Tuple(q, self) # q is C{int} in Python 3+, but C{float} in Python 2-
991 def _finite(self, other, op=None):
992 '''(INTERNAL) Return B{C{other}} if C{finite}.
993 '''
994 if _isfinite(other):
995 return other
996 raise ValueError(_not_finite_) if op is None else \
997 self._ValueError(op, other, txt=_not_finite_)
999 def fint(self, raiser=True, **name):
1000 '''Return this instance' current running sum as C{integer}.
1002 @kwarg raiser: If C{True} throw a L{ResidualError} if the
1003 I{integer} residual is non-zero.
1004 @kwarg name: Optional name (C{str}), overriding C{"fint"}.
1006 @return: The C{integer} (L{Fsum}).
1008 @raise ResidualError: Non-zero I{integer} residual.
1010 @see: Methods L{Fsum.int_float} and L{Fsum.is_integer}.
1011 '''
1012 i, r = self._fint2
1013 if r and raiser:
1014 t = _stresidual(_integer_, r)
1015 raise ResidualError(_integer_, i, txt=t)
1016 f = self._copy_2(self.fint, **name)
1017 return f._fset(i)
1019 def fint2(self, **name):
1020 '''Return this instance' current running sum as C{int} and
1021 the I{integer} residual.
1023 @kwarg name: Optional name (C{str}).
1025 @return: An L{Fsum2Tuple}C{(fsum, residual)} with C{fsum}
1026 an C{int} and I{integer} C{residual} a C{float} or
1027 C{INT0} if the C{fsum} is considered to be I{exact}.
1028 '''
1029 return Fsum2Tuple(*self._fint2, **name)
1031 @Property_RO
1032 def _fint2(self): # see ._fset
1033 '''(INTERNAL) Get 2-tuple (C{int}, I{integer} residual).
1034 '''
1035 s, r = self._fprs2
1036 i = int(s)
1037 r = _fsum(self._ps_1(i)) if r else float(s - i)
1038 return i, (r or INT0)
1040 @deprecated_property_RO
1041 def float_int(self): # PYCHOK no cover
1042 '''DEPRECATED, use method C{Fsum.int_float}.'''
1043 return self.int_float() # raiser=False
1045 @property_RO
1046 def floor(self):
1047 '''Get this instance' C{floor} (C{int} in Python 3+, but
1048 C{float} in Python 2-).
1050 @note: The C{floor} takes the C{residual} into account.
1052 @see: Method L{Fsum.int_float} and properties L{Fsum.ceil},
1053 L{Fsum.imag} and L{Fsum.real}.
1054 '''
1055 s, r = self._fprs2
1056 f = _floor(s) + _floor(r) + 1
1057 while (f - s) > r: # f > (s + r)
1058 f -= 1
1059 return f
1061# floordiv = __floordiv__ # for naming consistency
1063 def _floordiv(self, other, op): # rather _ffloordiv?
1064 '''Apply C{B{self} //= B{other}}.
1065 '''
1066 q = self._ftruediv(other, op) # == self
1067 return self._fset(q.floor) # floor(q)
1069 fmul = __imul__ # for backward compatibility
1071 def _fmul(self, other, op):
1072 '''(INTERNAL) Apply C{B{self} *= B{other}}.
1073 '''
1074 if isinstance(other, Fsum):
1075 if len(self._ps) != 1:
1076 f = self._mul_Fsum(other, op)
1077 elif len(other._ps) != 1: # and len(self._ps) == 1
1078 f = other._mul_scalar(self._ps[0], op)
1079 else: # len(other._ps) == len(self._ps) == 1
1080 f = self._finite(self._ps[0] * other._ps[0])
1081 elif isscalar(other):
1082 f = self._mul_scalar(other, op)
1083 else:
1084 raise self._TypeError(op, other) # txt=_invalid_
1085 return self._fset(f) # n=len(self) + 1
1087 def fover(self, over):
1088 '''Apply C{B{self} /= B{over}} and summate.
1090 @arg over: An L{Fsum} or C{scalar} denominator.
1092 @return: Precision running sum (C{float}).
1094 @see: Methods L{Fsum.fsum} and L{Fsum.__itruediv__}.
1095 '''
1096 return float(self.fdiv(over)._fprs)
1098 fpow = __ipow__ # for backward compatibility
1100 def _fpow(self, other, op, *mod):
1101 '''Apply C{B{self} **= B{other}}, optional B{C{mod}} or C{None}.
1102 '''
1103 if mod:
1104 if mod[0] is not None: # == 3-arg C{pow}
1105 f = self._pow_3(other, mod[0], op)
1106 elif self.is_integer():
1107 # return an exact C{int} for C{int}**C{int}
1108 x = _2scalar(other) # C{int}, C{float} or other
1109 i = self._fint2[0] # assert _fint2[1] == 0
1110 f = self._pow_2(i, x, other, op) if isscalar(x) else \
1111 _Fsum_ps(i)._pow_any(x, other, op)
1112 else: # mod[0] is None, power(self, other)
1113 f = self._pow_any(other, other, op)
1114 else: # pow(self, other) == pow(self, other, None)
1115 f = self._pow_any(other, other, op)
1116 return self._fset(f, asis=isint(f)) # n=max(len(self), 1)
1118 @Property_RO
1119 def _fprs(self):
1120 '''(INTERNAL) Get and cache this instance' precision
1121 running sum (C{float} or C{int}), ignoring C{residual}.
1123 @note: The precision running C{fsum} after a C{//=} or
1124 C{//} C{floor} division is C{int} in Python 3+.
1125 '''
1126 return self._fprs2.fsum
1128 @Property_RO
1129 def _fprs2(self):
1130 '''(INTERNAL) Get and cache this instance' precision
1131 running sum and residual (L{Fsum2Tuple}).
1132 '''
1133 ps = self._ps
1134 n = len(ps) - 2
1135 if n > 0: # len(ps) > 2
1136 s = _psum(ps)
1137 r = _fsum(self._ps_1(s)) or INT0
1138 elif n == 0: # len(ps) == 2
1139 ps[:] = _2ps(*_2sum(*ps))
1140 r, s = (INT0, ps[0]) if len(ps) != 2 else ps
1141 elif ps: # len(ps) == 1
1142 s, r = ps[0], INT0
1143 else: # len(ps) == 0
1144 s, r = _0_0, INT0
1145 ps[:] = s,
1146 # assert self._ps is ps
1147 return Fsum2Tuple(s, r)
1149# def _fpsqz(self):
1150# '''(INTERNAL) Compress, squeeze the C{partials}.
1151# '''
1152# if len(self._ps) > 2:
1153# _ = self._fprs
1154# return self
1156 def fset_(self, *xs):
1157 '''Replace this instance' value with C{xs}.
1159 @arg xs: Optional, new values (C{scalar} or L{Fsum}
1160 instances), all positional.
1162 @return: This instance (C{Fsum}).
1164 @see: Method L{Fsum.fadd} for further details.
1165 '''
1166 self._n = 0
1167 self._ps[:] = 0,
1168 return self.fadd(xs) if xs else self._update()
1170 def _fset(self, other, asis=True, n=0):
1171 '''(INTERNAL) Overwrite this instance with an other or a C{scalar}.
1172 '''
1173 if other is self:
1174 pass # from ._fmul, ._ftruediv and ._pow_scalar
1175 elif isinstance(other, Fsum):
1176 self._n = n or other._n
1177 self._ps[:] = other._ps
1178# self._copy_RESIDUAL(other)
1179 # use or zap the C{Property_RO} values
1180 Fsum._fint2._update_from(self, other)
1181 Fsum._fprs ._update_from(self, other)
1182 Fsum._fprs2._update_from(self, other)
1183 elif isscalar(other):
1184 s = other if asis else float(other)
1185 i = int(s) # see ._fint2
1186 t = i, ((s - i) or INT0)
1187 self._n = n or 1
1188 self._ps[:] = s,
1189 # Property_ROs _fint2, _fprs and _fprs2 can't be a Property:
1190 # Property's _fset zaps the value just set by the @setter
1191 self.__dict__.update(_fint2=t, _fprs=s, _fprs2=Fsum2Tuple(s, INT0))
1192 else: # PYCHOK no cover
1193 raise self._TypeError(_fset_op_, other) # txt=_invalid_
1194 return self
1196 def _fset_ps(self, other, n=0): # in .fmath
1197 '''(INTERNAL) Set a known C{Fsum} or C{scalar}.
1198 '''
1199 if isinstance(other, Fsum):
1200 self._n = n or other._n
1201 self._ps[:] = other._ps
1202 else: # assert isscalar(other)
1203 self._n = n or 1
1204 self._ps[:] = other,
1206 def fsub(self, xs=()):
1207 '''Subtract an iterable of C{scalar} or L{Fsum} instances from
1208 this instance.
1210 @arg xs: Iterable, list, tuple. etc. (C{scalar} or L{Fsum}
1211 instances).
1213 @return: This instance, updated (L{Fsum}).
1215 @see: Method L{Fsum.fadd}.
1216 '''
1217 return self._facc(_2floats(xs, neg=True)) if xs else self # PYCHOK yield
1219 def fsub_(self, *xs):
1220 '''Subtract all positional C{scalar} or L{Fsum} instances from
1221 this instance.
1223 @arg xs: Values to subtract (C{scalar} or L{Fsum} instances),
1224 all positional.
1226 @return: This instance, updated (L{Fsum}).
1228 @see: Method L{Fsum.fadd}.
1229 '''
1230 return self._facc(_2floats(xs, origin=1, neg=True)) if xs else self # PYCHOK yield
1232 def _fsub(self, other, op):
1233 '''(INTERNAL) Apply C{B{self} -= B{other}}.
1234 '''
1235 if isinstance(other, Fsum):
1236 if other is self: # or other._fprs2 == self._fprs2:
1237 self._fset(_0_0) # n=len(self) * 2, self -= self
1238 elif other._ps:
1239 self._facc(other._ps_neg)
1240 elif not isscalar(other):
1241 raise self._TypeError(op, other) # txt=_invalid_
1242 elif self._finite(other, op):
1243 self._facc_(-other)
1244 return self
1246 def fsum(self, xs=()):
1247 '''Add more C{scalar} or L{Fsum} instances and summate.
1249 @kwarg xs: Iterable, list, tuple, etc. (C{scalar} or
1250 L{Fsum} instances).
1252 @return: Precision running sum (C{float} or C{int}).
1254 @see: Method L{Fsum.fadd}.
1256 @note: Accumulation can continue after summation.
1257 '''
1258 f = self._facc(_2floats(xs)) if xs else self # PYCHOK yield
1259 return f._fprs
1261 def fsum_(self, *xs):
1262 '''Add all positional C{scalar} or L{Fsum} instances and summate.
1264 @arg xs: Values to add (C{scalar} or L{Fsum} instances),
1265 all positional.
1267 @return: Precision running sum (C{float} or C{int}).
1269 @see: Methods L{Fsum.fsum} and L{Fsum.fsumf_}.
1270 '''
1271 f = self._facc(_2floats(xs, origin=1)) if xs else self # PYCHOK yield
1272 return f._fprs
1274 def fsum2(self, xs=(), name=NN):
1275 '''Add more C{scalar} or L{Fsum} instances and return the
1276 current precision running sum and the C{residual}.
1278 @kwarg xs: Iterable, list, tuple, etc. (C{scalar} or L{Fsum}
1279 instances).
1280 @kwarg name: Optional name (C{str}).
1282 @return: L{Fsum2Tuple}C{(fsum, residual)} with C{fsum} the
1283 current precision running sum and C{residual}, the
1284 (precision) sum of the remaining C{partials}. The
1285 C{residual is INT0} if the C{fsum} is considered
1286 to be I{exact}.
1288 @see: Methods L{Fsum.fint2}, L{Fsum.fsum} and L{Fsum.fsum2_}
1289 '''
1290 f = self._facc(_2floats(xs)) if xs else self # PYCHOK yield
1291 t = f._fprs2
1292 if name:
1293 t = t.dup(name=name)
1294 return t
1296 def fsum2_(self, *xs):
1297 '''Add any positional C{scalar} or L{Fsum} instances and return
1298 the precision running sum and the C{differential}.
1300 @arg xs: Values to add (C{scalar} or L{Fsum} instances),
1301 all positional.
1303 @return: 2-Tuple C{(fsum, delta)} with the current precision
1304 running C{fsum} and C{delta}, the difference with
1305 the previous running C{fsum} (C{float}s).
1307 @see: Methods L{Fsum.fsum_} and L{Fsum.fsum}.
1308 '''
1309 p, r = self._fprs2
1310 if xs:
1311 s, t = self._facc(_2floats(xs, origin=1))._fprs2 # PYCHOK yield
1312 return s, _fsum((s, -p, r, -t)) # ((s - p) + (r - t))
1313 else: # PYCHOK no cover
1314 return p, _0_0
1316 def fsumf_(self, *xs):
1317 '''Like method L{Fsum.fsum_} but only for known C{float B{xs}}.
1318 '''
1319 f = self._facc(xs) if xs else self # PYCHOK yield
1320 return f._fprs
1322# ftruediv = __itruediv__ # for naming consistency
1324 def _ftruediv(self, other, op):
1325 '''(INTERNAL) Apply C{B{self} /= B{other}}.
1326 '''
1327 n = _1_0
1328 if isinstance(other, Fsum):
1329 if other is self or other == self:
1330 return self._fset(_1_0) # n=len(self)
1331 d, r = other._fprs2
1332 if r:
1333 if d:
1334 if self._raiser(r, d):
1335 raise self._ResidualError(op, other, r)
1336 d, n = other.as_integer_ratio()
1337 else: # PYCHOK no cover
1338 d = r
1339 elif isscalar(other):
1340 d = other
1341 else: # PYCHOK no cover
1342 raise self._TypeError(op, other) # txt=_invalid_
1343 try:
1344 s = 0 if isinf(d) else (
1345 d if isnan(d) else self._finite(n / d))
1346 except Exception as X:
1347 raise self._ErrorX(X, op, other)
1348 f = self._mul_scalar(s, _mul_op_) # handles 0, NAN, etc.
1349 return self._fset(f, asis=False)
1351 @property_RO
1352 def imag(self):
1353 '''Get the C{imaginary} part of this instance (C{0.0}, always).
1355 @see: Properties L{Fsum.ceil}, L{Fsum.floor} and L{Fsum.real}.
1356 '''
1357 return _0_0
1359 def int_float(self, raiser=False):
1360 '''Return this instance' current running sum as C{int} or C{float}.
1362 @kwarg raiser: If C{True} throw a L{ResidualError} if the
1363 residual is non-zero.
1365 @return: This C{integer} sum if this instance C{is_integer},
1366 otherwise return the C{float} sum if the residual
1367 is zero or if C{B{raiser}=False}.
1369 @raise ResidualError: Non-zero residual and C{B{raiser}=True}.
1371 @see: Methods L{Fsum.fint} and L{Fsum.fint2}.
1372 '''
1373 s, r = self._fint2
1374 if r:
1375 s, r = self._fprs2
1376 if r and raiser: # PYCHOK no cover
1377 t = _stresidual(_non_zero_, r)
1378 raise ResidualError(int_float=s, txt=t)
1379 s = float(s) # redundant
1380 return s
1382 def is_exact(self):
1383 '''Is this instance' current running C{fsum} considered to
1384 be exact? (C{bool}).
1385 '''
1386 return self.residual is INT0
1388 def is_integer(self):
1389 '''Is this instance' current running sum C{integer}? (C{bool}).
1391 @see: Methods L{Fsum.fint} and L{Fsum.fint2}.
1392 '''
1393 _, r = self._fint2
1394 return False if r else True
1396 def is_math_fsum(self):
1397 '''Return whether functions L{fsum}, L{fsum_}, L{fsum1} and
1398 L{fsum1_} plus partials summation are based on Python's
1399 C{math.fsum} or not.
1401 @return: C{2} if all functions and partials summation
1402 are based on C{math.fsum}, C{True} if only
1403 the functions are based on C{math.fsum} (and
1404 partials summation is not) or C{False} if
1405 none are.
1406 '''
1407 f = Fsum._math_fsum
1408 return 2 if _psum is f else bool(f)
1410 def _mul_Fsum(self, other, op=_mul_op_): # in .fmath.Fhorner
1411 '''(INTERNAL) Return C{B{self} * Fsum B{other}} as L{Fsum} or C{0}.
1412 '''
1413 # assert isinstance(other, Fsum)
1414 if self._ps and other._ps:
1415 f = _Fsum_xs(self._ps_mul(op, *other._ps))
1416 else:
1417 f = _0_0
1418 return f
1420 def _mul_scalar(self, factor, op): # in .fmath.Fhorner
1421 '''(INTERNAL) Return C{B{self} * scalar B{factor}} as L{Fsum}, C{0} or C{self}.
1422 '''
1423 # assert isscalar(factor)
1424 if self._ps and self._finite(factor, op):
1425 f = self if factor == _1_0 else (
1426 self._neg if factor == _N_1_0 else
1427 _Fsum_xs(self._ps_mul(op, factor))) # PYCHOK indent
1428 else:
1429 f = _0_0
1430 return f
1432 @property_RO
1433 def _neg(self):
1434 '''(INTERNAL) Return C{-self}.
1435 '''
1436 return _Fsum_ps(*self._ps_neg) if self._ps else NEG0
1438 @property_RO
1439 def partials(self):
1440 '''Get this instance' current partial sums (C{tuple} of C{float}s and/or C{int}s).
1441 '''
1442 return tuple(self._ps)
1444 def pow(self, x, *mod):
1445 '''Return C{B{self}**B{x}} as L{Fsum}.
1447 @arg x: The exponent (L{Fsum} or C{scalar}).
1448 @arg mod: Optional modulus (C{int} or C{None}) for the 3-argument
1449 C{pow(B{self}, B{other}, B{mod})} version.
1451 @return: The C{pow(self, B{x})} or C{pow(self, B{x}, *B{mod})}
1452 result (L{Fsum}).
1454 @note: If B{C{mod}} is given as C{None}, the result will be an
1455 C{integer} L{Fsum} provided this instance C{is_integer}
1456 or set to C{integer} with L{Fsum.fint}.
1458 @see: Methods L{Fsum.__ipow__}, L{Fsum.fint} and L{Fsum.is_integer}.
1459 '''
1460 f = self._copy_2(self.pow)
1461 return f._fpow(x, _pow_op_, *mod) # f = pow(f, x, *mod)
1463 def _pow_0_1(self, x, other):
1464 '''(INTERNAL) Return B{C{self}**1} or C{B{self}**0 == 1.0}.
1465 '''
1466 return self if x else (1 if isint(other) and self.is_integer() else _1_0)
1468 def _pow_2(self, b, x, other, op):
1469 '''(INTERNAL) 2-arg C{pow(B{b}, scalar B{x})} embellishing errors.
1470 '''
1471 # assert isscalar(b) and isscalar(x)
1472 try: # type(s) == type(x) if x in (_1_0, 1)
1473 s = pow(b, x) # -1**2.3 == -(1**2.3)
1474 if not iscomplex(s):
1475 return self._finite(s) # 0**INF == 0.0, 1**INF==1.0
1476 # neg**frac == complex in Python 3+, but ValueError in 2-
1477 raise ValueError(_strcomplex(s, b, x)) # PYCHOK no cover
1478 except Exception as X:
1479 raise self._ErrorX(X, op, other)
1481 def _pow_3(self, other, mod, op):
1482 '''(INTERNAL) 3-arg C{pow(B{self}, B{other}, int B{mod} or C{None})}.
1483 '''
1484 b, r = self._fprs2 if mod is None else self._fint2
1485 if r and self._raiser(r, b):
1486 t = _non_zero_ if mod is None else _integer_
1487 t = _stresidual(t, r, mod=mod)
1488 raise self._Error(op, other, ResidualError, txt=t)
1490 try: # b, other, mod all C{int}, unless C{mod} is C{None}
1491 x = _2scalar(other, _raiser=self._raiser)
1492 s = pow(b, x, mod)
1493 if not iscomplex(s):
1494 return self._finite(s)
1495 # neg**frac == complex in Python 3+, but ValueError in 2-
1496 raise ValueError(_strcomplex(s, b, x, mod)) # PYCHOK no cover
1497 except Exception as X:
1498 raise self._ErrorX(X, op, other, mod)
1500 def _pow_any(self, other, unused, op):
1501 '''Return C{B{self} ** B{other}}.
1502 '''
1503 if isinstance(other, Fsum):
1504 x, r = other._fprs2
1505 f = self._pow_scalar(x, other, op)
1506 if r:
1507 if self._raiser(r, x):
1508 raise self._ResidualError(op, other, r)
1509 s = self._pow_scalar(r, other, op)
1510# s = _2scalar(s) # _raiser = None
1511 f *= s
1512 elif isscalar(other):
1513 x = self._finite(other, op)
1514 f = self._pow_scalar(x, other, op)
1515 else:
1516 raise self._TypeError(op, other) # txt=_invalid_
1517 return f
1519 def _pow_int(self, x, other, op):
1520 '''(INTERNAL) Return C{B{self} **= B{x}} for C{int B{x} >= 0}.
1521 '''
1522 # assert isint(x) and x >= 0
1523 ps = self._ps
1524 if len(ps) > 1:
1525 f = self
1526 if x > 4:
1527 m = 1 # single-bit mask
1528 if (x & m):
1529 x -= m # x ^= m
1530 else:
1531 f = _Fsum_ps(_1_0)
1532 p = self
1533 while x:
1534 p = p._mul_Fsum(p, op) # p **= 2
1535 m += m # m <<= 1
1536 if (x & m):
1537 x -= m # x ^= m
1538 f = f._mul_Fsum(p, op) # f *= p
1539 elif x > 1: # self**2, 3 or 4
1540 f = f._mul_Fsum(f, op)
1541 if x > 2: # self**3 or 4
1542 p = self if x < 4 else f
1543 f = f._mul_Fsum(p, op)
1544 else: # self**1 or self**0 == 1 or _1_0
1545 f = f._pow_0_1(x, other)
1546 elif ps: # self._ps[0]**x
1547 f = self._pow_2(ps[0], x, other, op)
1548 else: # PYCHOK no cover
1549 # 0**pos_int == 0, but 0**0 == 1
1550 f = 0 if x else 1 # like ._fprs
1551 return f
1553 def _pow_scalar(self, x, other, op):
1554 '''(INTERNAL) Return C{self**B{x}} for C{scalar B{x}}.
1555 '''
1556 s, r = self._fprs2
1557 if isint(x, both=True):
1558 x = int(x) # Fsum**int
1559 y = abs(x)
1560 if y > 1:
1561 if r:
1562 f = self._pow_int(y, other, op)
1563 if x > 0: # > 1
1564 return f
1565 # assert x < 0 # < -1
1566 s, r = f._fprs2 if isinstance(f, Fsum) else (f, 0)
1567 if r:
1568 return _Fsum_ps(_1_0)._ftruediv(f, op)
1569 # use **= -1 for the CPython float_pow
1570 # error if s is zero, and not s = 1 / s
1571 x = -1
1572 elif x < 0: # self**-1 == 1 / self
1573 if r:
1574 return _Fsum_ps(_1_0)._ftruediv(self, op)
1575 else: # self**1 or self**0
1576 return self._pow_0_1(x, other) # self, 1 or 1.0
1577 elif not isscalar(x): # assert ...
1578 raise self._TypeError(op, other, txt=_not_scalar_)
1579 elif r and self._raiser(r, s): # non-zero residual**fractional
1580 # raise self._ResidualError(op, other, r, fractional_power=x)
1581 t = _stresidual(_non_zero_, r, fractional_power=x)
1582 raise self._Error(op, other, ResidualError, txt=t)
1583 # assert isscalar(s) and isscalar(x)
1584 return self._pow_2(s, x, other, op)
1586 def _ps_1(self, *less):
1587 '''(INTERNAL) Yield partials, 1-primed and subtract any C{less}.
1588 '''
1589 n = len(self._ps) + len(less) - 4
1590 if n < 0:
1591 yield _1_0
1592 for p in self._ps:
1593 yield p
1594 for p in less:
1595 yield -p
1596 if n < 0:
1597 yield _N_1_0
1599 def _ps_mul(self, op, *factors): # see .fmath.Fhorner
1600 '''(INTERNAL) Yield all C{partials} times each B{C{factor}},
1601 in total, up to C{len(partials) * len(factors)} items.
1602 '''
1603 ps = self._ps # tuple(self._ps)
1604 if len(ps) < len(factors):
1605 ps, factors = factors, ps
1606 _f = _isfinite
1607 for f in factors:
1608 for p in ps:
1609 p *= f
1610 yield p if _f(p) else self._finite(p, op)
1612 @property_RO
1613 def _ps_neg(self):
1614 '''(INTERNAL) Yield the partials, I{negated}.
1615 '''
1616 for p in self._ps:
1617 yield -p
1619 @property_RO
1620 def real(self):
1621 '''Get the C{real} part of this instance (C{float}).
1623 @see: Methods L{Fsum.__float__} and L{Fsum.fsum}
1624 and properties L{Fsum.ceil}, L{Fsum.floor},
1625 L{Fsum.imag} and L{Fsum.residual}.
1626 '''
1627 return float(self._fprs)
1629 @property_RO
1630 def residual(self):
1631 '''Get this instance' residual (C{float} or C{int}), the
1632 C{sum(partials)} less the precision running sum C{fsum}.
1634 @note: If the C{residual is INT0}, the precision running
1635 C{fsum} is considered to be I{exact}.
1637 @see: Methods L{Fsum.fsum}, L{Fsum.fsum2} and L{Fsum.is_exact}.
1638 '''
1639 return self._fprs2.residual
1641 def _raiser(self, r, s):
1642 '''(INTERNAL) Does ratio C{r / s} exceed threshold?
1643 '''
1644 self._ratio = t = fabs((r / s) if s else r)
1645 return t > self._RESIDUAL
1647 def RESIDUAL(self, *threshold):
1648 '''Get and set this instance' I{ratio} for raising L{ResidualError}s,
1649 overriding the default from env variable C{PYGEODESY_FSUM_RESIDUAL}.
1651 @arg threshold: If C{scalar}, the I{ratio} to exceed for raising
1652 L{ResidualError}s in division and exponention, if
1653 C{None} restore the default set with env variable
1654 C{PYGEODESY_FSUM_RESIDUAL} or if omitted, keep the
1655 current setting.
1657 @return: The previous C{RESIDUAL} setting (C{float}), default C{0}.
1659 @raise ValueError: Negative B{C{threshold}}.
1661 @note: A L{ResidualError} is thrown if the non-zero I{ratio}
1662 C{residual / fsum} exceeds the B{C{threshold}}.
1663 '''
1664 r = self._RESIDUAL
1665 if threshold:
1666 t = threshold[0]
1667 t = Fsum._RESIDUAL if t is None else (
1668 float(t) if isscalar(t) else ( # for backward ...
1669 _0_0 if bool(t) else _1_0)) # ... compatibility
1670 if t < 0:
1671 u = _DOT_(self, unstr(self.RESIDUAL, *threshold))
1672 raise _ValueError(u, RESIDUAL=t, txt=_negative_)
1673 self._RESIDUAL = t
1674 return r
1676 def _ResidualError(self, op, other, residual):
1677 '''(INTERNAL) Non-zero B{C{residual}} etc.
1678 '''
1679 t = _stresidual(_non_zero_, residual, ratio=self._ratio,
1680 RESIDUAL=self._RESIDUAL)
1681 t = t.replace(_COMMASPACE_R_, _exceeds_R_)
1682 return self._Error(op, other, ResidualError, txt=t)
1684 def signOf(self, res=True):
1685 '''Determine the sign of this instance.
1687 @kwarg res: If C{True} consider, otherwise
1688 ignore the residual (C{bool}).
1690 @return: The sign (C{int}, -1, 0 or +1).
1691 '''
1692 s, r = self._fprs2 if res else (self._fprs, 0)
1693 return _signOf(s, -r)
1695 def toRepr(self, **prec_sep_fmt_lenc): # PYCHOK signature
1696 '''Return this C{Fsum} instance as representation.
1698 @kwarg prec_sep_fmt_lenc: Optional keyword arguments for
1699 method L{Fsum2Tuple.toRepr} plus C{B{lenc}=True}
1700 (C{bool}) to in-/exclude the current C{[len]}
1701 of this L{Fsum} enclosed in I{[brackets]}.
1703 @return: This instance (C{repr}).
1704 '''
1705 return self._toT(self._fprs2.toRepr, **prec_sep_fmt_lenc)
1707 def toStr(self, **prec_sep_fmt_lenc): # PYCHOK signature
1708 '''Return this C{Fsum} instance as string.
1710 @kwarg prec_sep_fmt_lenc: Optional keyword arguments for
1711 method L{Fsum2Tuple.toStr} plus C{B{lenc}=True}
1712 (C{bool}) to in-/exclude the current C{[len]}
1713 of this L{Fsum} enclosed in I{[brackets]}.
1715 @return: This instance (C{str}).
1716 '''
1717 return self._toT(self._fprs2.toStr, **prec_sep_fmt_lenc)
1719 def _toT(self, toT, fmt=Fmt.g, lenc=True, **kwds):
1720 '''(INTERNAL) Helper for C{toRepr} and C{toStr}.
1721 '''
1722 n = self.named3
1723 if lenc:
1724 n = Fmt.SQUARE(n, len(self))
1725 return _SPACE_(n, toT(fmt=fmt, **kwds))
1727 def _TypeError(self, op, other, **txt): # PYCHOK no cover
1728 '''(INTERNAL) Return a C{TypeError}.
1729 '''
1730 return self._Error(op, other, _TypeError, **txt)
1732 def _update(self, updated=True): # see ._fset
1733 '''(INTERNAL) Zap all cached C{Property_RO} values.
1734 '''
1735 if updated:
1736 _pop = self.__dict__.pop
1737 for p in _ROs:
1738 _ = _pop(p, None)
1739# Fsum._fint2._update(self)
1740# Fsum._fprs ._update(self)
1741# Fsum._fprs2._update(self)
1742 return self # for .fset_
1744 def _ValueError(self, op, other, **txt): # PYCHOK no cover
1745 '''(INTERNAL) Return a C{ValueError}.
1746 '''
1747 return self._Error(op, other, _ValueError, **txt)
1749 def _ZeroDivisionError(self, op, other, **txt): # PYCHOK no cover
1750 '''(INTERNAL) Return a C{ZeroDivisionError}.
1751 '''
1752 return self._Error(op, other, _ZeroDivisionError, **txt)
1754_ROs = _allPropertiesOf_n(3, Fsum, Property_RO) # PYCHOK assert, see Fsum._fset, -._update
1757def _Float_Int(arg, **name_Error):
1758 '''(INTERNAL) Unit of L{Fsum2Tuple} items.
1759 '''
1760 U = Int if isint(arg) else Float
1761 return U(arg, **name_Error)
1764class DivMod2Tuple(_NamedTuple):
1765 '''2-Tuple C{(div, mod)} with the quotient C{div} and remainder
1766 C{mod} results of a C{divmod} operation.
1768 @note: Quotient C{div} an C{int} in Python 3+ or a C{float} in
1769 Python 2-. Remainder C{mod} an L{Fsum} instance.
1770 '''
1771 _Names_ = (_div_, _mod_)
1772 _Units_ = (_Float_Int, Fsum)
1775class Fsum2Tuple(_NamedTuple):
1776 '''2-Tuple C{(fsum, residual)} with the precision running C{fsum}
1777 and the C{residual}, the sum of the remaining partials. Each
1778 item is either C{float} or C{int}.
1780 @note: If the C{residual is INT0}, the C{fsum} is considered
1781 to be I{exact}, see method L{Fsum2Tuple.is_exact}.
1782 '''
1783 _Names_ = ( Fsum.fsum.__name__, Fsum.residual.name)
1784 _Units_ = (_Float_Int, _Float_Int)
1786 @Property_RO
1787 def Fsum(self):
1788 '''Get this L{Fsum2Tuple} as an L{Fsum}.
1789 '''
1790 s, r = map(float, self)
1791 return _Fsum_ps(*_2ps(s, r), name=self.name)
1793 def is_exact(self):
1794 '''Is this L{Fsum2Tuple} considered to be exact? (C{bool}).
1795 '''
1796 return self.Fsum.is_exact()
1798 def is_integer(self):
1799 '''Is this L{Fsum2Tuple} C{integer}? (C{bool}).
1800 '''
1801 return self.Fsum.is_integer()
1804class ResidualError(_ValueError):
1805 '''Error raised for an operation involving a L{pygeodesy.sums.Fsum}
1806 instance with a non-zero C{residual}, I{integer} or otherwise.
1808 @see: Module L{pygeodesy.fsums} and method L{Fsum.RESIDUAL}.
1809 '''
1810 pass
1813def _Fsum_ps(*ps, **name):
1814 '''(INTERNAL) Return an C{Fsum} from I{ordered} partials C{ps}.
1815 '''
1816 f = Fsum(**name) if name else Fsum()
1817 if ps:
1818 f._n = len(ps)
1819 f._ps[:] = ps
1820 return f
1823def _Fsum_xs(xs, up=False, **name):
1824 '''(INTERNAL) Return an C{Fsum} from known floats C{xs}.
1825 '''
1826 f = Fsum(**name) if name else Fsum()
1827 return f._facc(xs, up=up)
1830try:
1831 from math import fsum as _fsum # precision IEEE-754 sum, Python 2.6+
1833 # make sure _fsum works as expected (XXX check
1834 # float.__getformat__('float')[:4] == 'IEEE'?)
1835 if _fsum((1, 1e101, 1, -1e101)) != 2: # PYCHOK no cover
1836 del _fsum # nope, remove _fsum ...
1837 raise ImportError # ... use _fsum below
1839 Fsum._math_fsum = _sum = _fsum # PYCHOK exported
1841 if _getenv('PYGEODESY_FSUM_PARTIALS', NN) == _fsum.__name__:
1842 _psum = _fsum # PYCHOK re-def
1844except ImportError:
1845 _sum = sum # Fsum(NAN) exception fall-back
1847 def _fsum(xs):
1848 '''(INTERNAL) Precision summation, Python 2.5-.
1849 '''
1850 return Fsum(name=_fsum.__name__).fsum(xs) if xs else _0_0
1853def fsum(xs, floats=False):
1854 '''Precision floating point summation based on or like Python's C{math.fsum}.
1856 @arg xs: Iterable, list, tuple, etc. of values (C{scalar} or L{Fsum}
1857 instances).
1858 @kwarg floats: Optionally, use C{B{floats}=True} iff I{all} B{C{xs}}
1859 are known to be C{float}.
1861 @return: Precision C{fsum} (C{float}).
1863 @raise OverflowError: Partial C{2sum} overflow.
1865 @raise TypeError: Non-scalar B{C{xs}} value.
1867 @raise ValueError: Invalid or non-finite B{C{xs}} value.
1869 @note: Exceptions and I{non-finite} handling may differ if not
1870 based on Python's C{math.fsum}.
1872 @see: Class L{Fsum} and methods L{Fsum.fsum} and L{Fsum.fadd}.
1873 '''
1874 return _fsum(xs if floats else _2floats(xs)) if xs else _0_0 # PYCHOK yield
1877def fsum_(*xs, **floats):
1878 '''Precision floating point summation of all positional arguments.
1880 @arg xs: Values to be added (C{scalar} or L{Fsum} instances), all
1881 positional.
1882 @kwarg floats: Optionally, use C{B{floats}=True} iff I{all} B{C{xs}}
1883 are known to be C{float}.
1885 @return: Precision C{fsum} (C{float}).
1887 @see: Function C{fsum}.
1888 '''
1889 return _fsum(xs if _xkwds_get(floats, floats=False) else
1890 _2floats(xs, origin=1)) if xs else _0_0 # PYCHOK yield
1893def fsumf_(*xs):
1894 '''Precision floating point summation L{fsum_}C{(*xs, floats=True)}.
1895 '''
1896 return _fsum(xs) if xs else _0_0
1899def fsum1(xs, floats=False):
1900 '''Precision floating point summation of a few arguments, 1-primed.
1902 @arg xs: Iterable, list, tuple, etc. of values (C{scalar} or L{Fsum}
1903 instances).
1904 @kwarg floats: Optionally, use C{B{floats}=True} iff I{all} B{C{xs}}
1905 are known to be C{float}.
1907 @return: Precision C{fsum} (C{float}).
1909 @see: Function C{fsum}.
1910 '''
1911 return _fsum(_1primed(xs if floats else _2floats(xs))) if xs else _0_0 # PYCHOK yield
1914def fsum1_(*xs, **floats):
1915 '''Precision floating point summation of a few arguments, 1-primed.
1917 @arg xs: Values to be added (C{scalar} or L{Fsum} instances), all
1918 positional.
1919 @kwarg floats: Optionally, use C{B{floats}=True} iff I{all} B{C{xs}}
1920 are known to be C{float}.
1922 @return: Precision C{fsum} (C{float}).
1924 @see: Function C{fsum}
1925 '''
1926 return _fsum(_1primed(xs if _xkwds_get(floats, floats=False) else
1927 _2floats(xs, origin=1))) if xs else _0_0 # PYCHOK yield
1930def fsum1f_(*xs):
1931 '''Precision floating point summation L{fsum1_}C{(*xs, floats=True)}.
1932 '''
1933 return _fsum(_1primed(xs)) if xs else _0_0
1936if __name__ == '__main__':
1938 # usage: [env PYGEODESY_FSUM_PARTIALS=fsum] python3 -m pygeodesy.fsums
1940 def _test(n):
1941 # copied from Hettinger, see L{Fsum} reference
1942 from pygeodesy import printf
1943 from random import gauss, random, shuffle
1945 printf(_fsum.__name__, end=_COMMASPACE_)
1946 printf(_psum.__name__, end=_COMMASPACE_)
1948 F = Fsum()
1949 if F.is_math_fsum:
1950 c = (7, 1e100, -7, -1e100, -9e-20, 8e-20) * 10
1951 for _ in range(n):
1952 t = list(c)
1953 s = 0
1954 for _ in range(n * 8):
1955 v = gauss(0, random())**7 - s
1956 t.append(v)
1957 s += v
1958 shuffle(t)
1959 assert float(F.fset_(*t)) == _fsum(t)
1960 printf(_DOT_, end=NN)
1961 printf(NN)
1963 _test(128)
1965# **) MIT License
1966#
1967# Copyright (C) 2016-2024 -- mrJean1 at Gmail -- All Rights Reserved.
1968#
1969# Permission is hereby granted, free of charge, to any person obtaining a
1970# copy of this software and associated documentation files (the "Software"),
1971# to deal in the Software without restriction, including without limitation
1972# the rights to use, copy, modify, merge, publish, distribute, sublicense,
1973# and/or sell copies of the Software, and to permit persons to whom the
1974# Software is furnished to do so, subject to the following conditions:
1975#
1976# The above copyright notice and this permission notice shall be included
1977# in all copies or substantial portions of the Software.
1978#
1979# THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS
1980# OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
1981# FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL
1982# THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR
1983# OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE,
1984# ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR
1985# OTHER DEALINGS IN THE SOFTWARE.