errorcalculus 0.1.0__py3-none-any.whl

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -0,0 +1,1067 @@
1
+ """Arrays of quantities with dense storage, and the NumPy protocols (private module).
2
+
3
+ A :class:`QuantityArray` stores its sharp densely, ``(*shape, k)`` on a local support of k sources, its bias
4
+ ``(*shape,)`` (second order), and the same structural information as scalar quantities (groups whose bias was assumed
5
+ to be zero; bias breakdown). The propagation rules are those of the scalar engine, element by element,
6
+ with NumPy broadcasting; results agree with the scalar (sparse) engine to rounding (guarantee G16).
7
+ """
8
+
9
+ from __future__ import annotations
10
+
11
+ import numbers
12
+ import operator
13
+
14
+ import numpy as np
15
+
16
+ from . import _rules
17
+ from ._core import (
18
+ Model,
19
+ Quantity,
20
+ _apply_binary,
21
+ _apply_unary,
22
+ _is_number,
23
+ _new,
24
+ contributions,
25
+ )
26
+ from .errors import (
27
+ DomainError,
28
+ FirstOrderError,
29
+ InputError,
30
+ ModelMismatchError,
31
+ NonDifferentiableError,
32
+ NonFiniteError,
33
+ UnsupportedOperationError,
34
+ )
35
+
36
+ _EMPTY_IDX = np.zeros(0, dtype=np.intp)
37
+
38
+
39
+ def _ro(a):
40
+ a = np.asarray(a)
41
+ if a.flags.writeable:
42
+ a.setflags(write=False)
43
+ return a
44
+
45
+
46
+ def _expand(M: np.ndarray, sup_from: np.ndarray, sup_to: np.ndarray, dtype=float) -> np.ndarray:
47
+ """Re-express the trailing axis of M (indexed by sup_from) on the larger support sup_to."""
48
+ if sup_from.shape == sup_to.shape and np.array_equal(sup_from, sup_to):
49
+ return M
50
+ out = np.zeros(M.shape[:-1] + (len(sup_to),), dtype=dtype)
51
+ if len(sup_from):
52
+ out[..., np.searchsorted(sup_to, sup_from)] = M
53
+ return out
54
+
55
+
56
+ def _partner(m: Model, T: np.ndarray, sup: np.ndarray) -> np.ndarray:
57
+ """T, or, in the private paired mode of the model (sources u, v; see ``_core._form_dot``), T with its trailing
58
+ axis re-indexed so that position j holds the coefficient of the partner of sup[j] (0 if the partner is not in
59
+ sup). Then Σ_j S[..., j]·_partner(T)[..., j] is the form <S, T>_P = S_u T_v + S_v T_u that feeds A. Every dense
60
+ contraction of sharps that feeds A goes through this function (engine, matmul, linalg)."""
61
+ if m._pair is None:
62
+ return T
63
+ u, v = m._pair
64
+ pos = {int(s): j for j, s in enumerate(np.asarray(sup).tolist())}
65
+ out = np.zeros(T.shape)
66
+ for s, j in pos.items():
67
+ p = v if s == u else (u if s == v else None)
68
+ if p is not None and p in pos:
69
+ out[..., j] = T[..., pos[p]]
70
+ return out
71
+
72
+
73
+ def _union(a: np.ndarray, b: np.ndarray) -> np.ndarray:
74
+ if a.shape == b.shape and np.array_equal(a, b):
75
+ return a
76
+ return np.union1d(a, b).astype(np.intp)
77
+
78
+
79
+ def _m0(d, X, nonzero=None):
80
+ """d·X, with 0 where the operand is exactly zero (``nonzero`` False; by default X == 0) or the derivative is
81
+ exactly zero, so that inf·0 never gives nan. The mask mirrors the scalar engine, which skips exactly the same
82
+ terms (zero derivatives, pruned coefficients, zero bias, empty sharp)."""
83
+ with np.errstate(all="ignore"):
84
+ r = d * X
85
+ if not np.all(np.isfinite(r)):
86
+ r = np.where((X != 0 if nonzero is None else nonzero) & (d != 0), r, 0.0)
87
+ return r
88
+
89
+
90
+ def _check_finite(v, S, A, B, K):
91
+ if not np.all(np.isfinite(v)):
92
+ raise NonFiniteError("a value is not finite (overflow)")
93
+ if not np.all(np.isfinite(S)):
94
+ raise NonFiniteError("a coefficient of the sharp is not finite (overflow)")
95
+ if A is not None and not np.all(np.isfinite(A)):
96
+ raise NonFiniteError("a bias is not finite (overflow)")
97
+ if B is not None and (not np.all(np.isfinite(B)) or not np.all(np.isfinite(K))):
98
+ raise NonFiniteError("a term of the bias breakdown is not finite (overflow)")
99
+
100
+
101
+ class QuantityArray:
102
+ """An array of quantities with errors (same semantics as :class:`Quantity`, element by element).
103
+
104
+ Attributes ``values``, ``gamma``, ``std`` and ``bias`` are read-only ``ndarray`` (``bias`` raises
105
+ :class:`FirstOrderError` at order 1). Arithmetic, the elementary functions, ``@``, ``sum``, ``mean`` and the
106
+ NumPy functions ``np.sum, np.mean, np.dot, np.matmul, np.stack, np.concatenate, np.reshape, np.transpose,
107
+ np.linalg.solve, np.linalg.inv, np.linalg.det`` are supported; any other NumPy function raises
108
+ :class:`UnsupportedOperationError` (never a silent conversion to float).
109
+ """
110
+
111
+ __slots__ = ("_m", "_v", "_S", "_sup", "_A", "_Z", "_zg", "_B", "_bg", "_K", "_objs")
112
+ __hash__ = None
113
+ __array_priority__ = 1000
114
+
115
+ def __init__(self, *args, **kwargs):
116
+ raise TypeError("QuantityArray objects are created by Model.input_array, Model.correlated(as_array=True), "
117
+ "errorcalculus.array or by operations")
118
+
119
+ def __setattr__(self, name, value):
120
+ raise AttributeError("QuantityArray objects are immutable")
121
+
122
+ def __getstate__(self):
123
+ return tuple(getattr(self, k) for k in QuantityArray.__slots__)
124
+
125
+ def __setstate__(self, state):
126
+ for k, v in zip(QuantityArray.__slots__, state):
127
+ if isinstance(v, np.ndarray) and v.dtype != object:
128
+ v = _ro(v)
129
+ object.__setattr__(self, k, v)
130
+
131
+ # --- construction -------------------------------------------------------------------------------------------
132
+ @staticmethod
133
+ def _make(m: Model, v, S, sup, A, Z, zg, B, bg, K, objs=None, check=True) -> QuantityArray:
134
+ v = np.asarray(v, dtype=float)
135
+ if check:
136
+ _check_finite(v, S, A, B, K)
137
+ qa = object.__new__(QuantityArray)
138
+ st = object.__setattr__
139
+ st(qa, "_m", m)
140
+ st(qa, "_v", _ro(v))
141
+ st(qa, "_S", _ro(S))
142
+ st(qa, "_sup", _ro(np.asarray(sup, dtype=np.intp)))
143
+ st(qa, "_A", None if A is None else _ro(np.asarray(A, dtype=float)))
144
+ st(qa, "_Z", _ro(Z))
145
+ st(qa, "_zg", _ro(np.asarray(zg, dtype=np.intp)))
146
+ st(qa, "_B", None if B is None else _ro(B))
147
+ st(qa, "_bg", _ro(np.asarray(bg, dtype=np.intp)))
148
+ st(qa, "_K", None if K is None else _ro(K))
149
+ st(qa, "_objs", objs)
150
+ return qa
151
+
152
+ @staticmethod
153
+ def _from_quantities(objs: np.ndarray, model: Model | None = None) -> QuantityArray:
154
+ """Dense array from an object array of quantities (and numbers, taken as exact)."""
155
+ flat = list(objs.ravel())
156
+ for q in flat:
157
+ if isinstance(q, Quantity):
158
+ if model is None:
159
+ model = q._m
160
+ elif q._m is not model:
161
+ raise ModelMismatchError("these quantities belong to two different models")
162
+ elif not _is_number(q):
163
+ raise InputError("an array of quantities may contain only quantities and numbers")
164
+ if model is None:
165
+ raise InputError("no quantity in the sequence: use a NumPy array")
166
+ qs = [q for q in flat if isinstance(q, Quantity)]
167
+ sup = np.array(sorted(set().union(*[q._s.keys() for q in qs],
168
+ *[(q._kappa or {}).keys() for q in qs])), dtype=np.intp)
169
+ zg = np.array(sorted(set().union(*[q._z for q in qs])), dtype=np.intp)
170
+ col = {k: j for j, k in enumerate(sup.tolist())}
171
+ zcol = {g: j for j, g in enumerate(zg.tolist())}
172
+ N = len(flat)
173
+ v = np.empty(N)
174
+ S = np.zeros((N, len(sup)))
175
+ Z = np.zeros((N, len(zg)), dtype=bool)
176
+ order2 = model._order == 2
177
+ A = np.zeros(N) if order2 else None
178
+ bb = model._bb
179
+ if bb:
180
+ bg = np.array(sorted(set().union(*[q._beta.keys() for q in qs])), dtype=np.intp)
181
+ bcol = {g: j for j, g in enumerate(bg.tolist())}
182
+ B = np.zeros((N, len(bg)))
183
+ K = np.zeros((N, len(sup)))
184
+ else:
185
+ bg, B, K = _EMPTY_IDX, None, None
186
+ for i, q in enumerate(flat):
187
+ if not isinstance(q, Quantity):
188
+ v[i] = float(q)
189
+ continue
190
+ v[i] = q._v
191
+ for k, c in q._s.items():
192
+ S[i, col[k]] = c
193
+ for g in q._z:
194
+ Z[i, zcol[g]] = True
195
+ if order2:
196
+ A[i] = q._a
197
+ if bb:
198
+ for g, c in q._beta.items():
199
+ B[i, bcol[g]] = c
200
+ for k, c in q._kappa.items():
201
+ K[i, col[k]] = c
202
+ shape = objs.shape
203
+ keep = objs if all(isinstance(q, Quantity) for q in flat) else None
204
+ if keep is not None:
205
+ keep = keep.copy()
206
+ keep.setflags(write=False)
207
+ return QuantityArray._make(
208
+ model, v.reshape(shape), S.reshape(shape + (len(sup),)), sup,
209
+ None if A is None else A.reshape(shape), Z.reshape(shape + (len(zg),)), zg,
210
+ None if B is None else B.reshape(shape + (len(bg),)), bg,
211
+ None if K is None else K.reshape(shape + (len(sup),)), objs=keep)
212
+
213
+ # --- readings -----------------------------------------------------------------------------------------------
214
+ @property
215
+ def model(self) -> Model:
216
+ return self._m
217
+
218
+ @property
219
+ def shape(self) -> tuple:
220
+ return self._v.shape
221
+
222
+ @property
223
+ def ndim(self) -> int:
224
+ return self._v.ndim
225
+
226
+ @property
227
+ def size(self) -> int:
228
+ return self._v.size
229
+
230
+ @property
231
+ def values(self) -> np.ndarray:
232
+ return self._v
233
+
234
+ @property
235
+ def gamma(self) -> np.ndarray:
236
+ with np.errstate(over="ignore"):
237
+ g = np.sum(self._S * self._S, axis=-1)
238
+ if not np.all(np.isfinite(g)):
239
+ raise NonFiniteError("Γ is not finite (overflow)")
240
+ return _ro(g)
241
+
242
+ @property
243
+ def std(self) -> np.ndarray:
244
+ # scaled norm: representable even where Γ over- or underflows
245
+ M = np.max(np.abs(self._S), axis=-1, initial=0.0)
246
+ safe = np.where(M > 0, M, 1.0)
247
+ with np.errstate(over="ignore"):
248
+ r = M * np.sqrt(np.sum((self._S / safe[..., None]) ** 2, axis=-1))
249
+ return _ro(r)
250
+
251
+ @property
252
+ def bias(self) -> np.ndarray:
253
+ if self._A is None:
254
+ raise FirstOrderError("a first-order model does not propagate biases: declare the model with order=2 "
255
+ "to obtain A")
256
+ return self._A
257
+
258
+ def cov(self) -> np.ndarray:
259
+ """Matrix of Γ of the flattened array (N × N), symmetrised explicitly."""
260
+ S = self._S.reshape(self.size, -1)
261
+ with np.errstate(all="ignore"):
262
+ M = S @ S.T
263
+ M = 0.5 * (M + M.T)
264
+ if not np.all(np.isfinite(M)):
265
+ raise NonFiniteError("the covariance matrix is not finite (overflow)")
266
+ return M
267
+
268
+ def summary(self, *, scale: float = 1.0) -> list:
269
+ return [q.summary(scale=scale) for q in self._tolist_flat()]
270
+
271
+ def __repr__(self) -> str:
272
+ if self._A is None:
273
+ return f"QuantityArray(values={self._v.tolist()!r}, std={self.std.tolist()!r})"
274
+ return (f"QuantityArray(values={self._v.tolist()!r}, std={self.std.tolist()!r}, "
275
+ f"bias={self._A.tolist()!r})")
276
+
277
+ # --- elements -----------------------------------------------------------------------------------------------
278
+ def _element(self, i: int) -> Quantity:
279
+ """The flat element i, as a scalar quantity (the registered object when the array is made of them)."""
280
+ if self._objs is not None:
281
+ return self._objs.ravel()[i]
282
+ n = self.size
283
+ S = self._S.reshape(n, -1)[i]
284
+ sup = self._sup
285
+ s = {int(sup[j]): float(S[j]) for j in np.flatnonzero(S)}
286
+ a = None if self._A is None else float(self._A.ravel()[i])
287
+ Z = self._Z.reshape(n, -1)[i]
288
+ z = frozenset(int(g) for g in self._zg[Z])
289
+ beta = kappa = None
290
+ if self._B is not None:
291
+ B = self._B.reshape(n, -1)[i]
292
+ K = self._K.reshape(n, -1)[i]
293
+ beta = {int(self._bg[j]): float(B[j]) for j in np.flatnonzero(B)}
294
+ kappa = {int(sup[j]): float(K[j]) for j in np.flatnonzero(K)}
295
+ return _new(self._m, float(self._v.ravel()[i]), s, a, z, beta, kappa)
296
+
297
+ def _gather(self, pos: np.ndarray):
298
+ """Array (or quantity, for a 0-d pos) of the flat elements at positions pos."""
299
+ pos = np.asarray(pos)
300
+ if pos.ndim == 0:
301
+ return self._element(int(pos))
302
+ n = self.size
303
+ take = lambda C: None if C is None else C.reshape((n,) + C.shape[self.ndim:])[pos] # noqa: E731
304
+ objs = None
305
+ if self._objs is not None:
306
+ objs = self._objs.ravel()[pos]
307
+ objs.setflags(write=False)
308
+ return QuantityArray._make(self._m, self._v.ravel()[pos], take(self._S), self._sup, take(self._A),
309
+ take(self._Z), self._zg, take(self._B), self._bg, take(self._K), objs=objs,
310
+ check=False)
311
+
312
+ def _positions(self) -> np.ndarray:
313
+ return np.arange(self.size).reshape(self.shape)
314
+
315
+ def __getitem__(self, idx):
316
+ if isinstance(idx, QuantityArray) or isinstance(idx, Quantity):
317
+ raise UnsupportedOperationError("a quantity cannot be used as an index")
318
+ return self._gather(self._positions()[idx])
319
+
320
+ def __len__(self) -> int:
321
+ if self.ndim == 0:
322
+ raise UnsupportedOperationError("len() of a 0-d QuantityArray")
323
+ return self.shape[0]
324
+
325
+ def __iter__(self):
326
+ if self.ndim == 0:
327
+ raise UnsupportedOperationError("iteration over a 0-d QuantityArray")
328
+ for i in range(self.shape[0]):
329
+ yield self[i]
330
+
331
+ def tolist(self):
332
+ """Nested lists of :class:`Quantity` (the registered objects for an array of inputs)."""
333
+ if self.ndim == 0:
334
+ return self._element(0)
335
+ if self.ndim == 1:
336
+ return [self._element(i) for i in range(self.size)]
337
+ return [self[i].tolist() for i in range(self.shape[0])]
338
+
339
+ def _tolist_flat(self) -> list:
340
+ return [self._element(i) for i in range(self.size)]
341
+
342
+ @property
343
+ def T(self):
344
+ return self._gather(self._positions().T)
345
+
346
+ def transpose(self, *axes):
347
+ if len(axes) == 1 and (axes[0] is None or isinstance(axes[0], (tuple, list))):
348
+ axes = axes[0]
349
+ return self._gather(self._positions().transpose(axes or None))
350
+
351
+ def reshape(self, *shape):
352
+ if len(shape) == 1 and isinstance(shape[0], (tuple, list)):
353
+ shape = tuple(shape[0])
354
+ return self._gather(self._positions().reshape(shape))
355
+
356
+ def ravel(self):
357
+ return self._gather(np.arange(self.size))
358
+
359
+ # --- reductions ---------------------------------------------------------------------------------------------
360
+ def _axes(self, axis) -> tuple:
361
+ nd = self.ndim
362
+ if axis is None:
363
+ return tuple(range(nd))
364
+ if isinstance(axis, numbers.Integral):
365
+ axis = (axis,)
366
+ out = []
367
+ for a in axis:
368
+ a = int(a)
369
+ if not -nd <= a < nd:
370
+ raise InputError(f"axis {a} is out of bounds for an array of dimension {nd}")
371
+ out.append(a % nd)
372
+ return tuple(sorted(set(out)))
373
+
374
+ def sum(self, axis=None):
375
+ """Sum (linear, exact rule) over the given axes (all by default)."""
376
+ ax = self._axes(axis)
377
+ red = lambda C: None if C is None else C.sum(axis=ax) # noqa: E731
378
+ v = self._v.sum(axis=ax)
379
+ res = QuantityArray._make(self._m, v, red(self._S), self._sup, red(self._A), self._Z.any(axis=ax), self._zg,
380
+ red(self._B), self._bg, red(self._K))
381
+ return res._element(0) if res.ndim == 0 else res
382
+
383
+ def mean(self, axis=None):
384
+ """Mean (linear, exact rule) over the given axes (all by default)."""
385
+ ax = self._axes(axis)
386
+ count = int(np.prod([self.shape[a] for a in ax])) if ax else 1
387
+ if count == 0:
388
+ raise DomainError("mean of an empty array")
389
+ red = lambda C: None if C is None else C.sum(axis=ax) / count # noqa: E731
390
+ v = self._v.sum(axis=ax) / count
391
+ res = QuantityArray._make(self._m, v, red(self._S), self._sup, red(self._A), self._Z.any(axis=ax), self._zg,
392
+ red(self._B), self._bg, red(self._K))
393
+ return res._element(0) if res.ndim == 0 else res
394
+
395
+ # --- operators ----------------------------------------------------------------------------------------------
396
+ def __add__(self, o):
397
+ return apply_ufunc(np.add, (self, o))
398
+
399
+ def __radd__(self, o):
400
+ return apply_ufunc(np.add, (o, self))
401
+
402
+ def __sub__(self, o):
403
+ return apply_ufunc(np.subtract, (self, o))
404
+
405
+ def __rsub__(self, o):
406
+ return apply_ufunc(np.subtract, (o, self))
407
+
408
+ def __mul__(self, o):
409
+ return apply_ufunc(np.multiply, (self, o))
410
+
411
+ def __rmul__(self, o):
412
+ return apply_ufunc(np.multiply, (o, self))
413
+
414
+ def __truediv__(self, o):
415
+ return apply_ufunc(np.true_divide, (self, o))
416
+
417
+ def __rtruediv__(self, o):
418
+ return apply_ufunc(np.true_divide, (o, self))
419
+
420
+ def __pow__(self, o, mod=None):
421
+ if mod is not None:
422
+ raise UnsupportedOperationError("pow with a modulus is not supported on quantities")
423
+ return apply_ufunc(np.power, (self, o))
424
+
425
+ def __rpow__(self, o):
426
+ return apply_ufunc(np.power, (o, self))
427
+
428
+ def __matmul__(self, o):
429
+ return matmul(self, o)
430
+
431
+ def __rmatmul__(self, o):
432
+ return matmul(o, self)
433
+
434
+ def __neg__(self):
435
+ return apply_ufunc(np.negative, (self,))
436
+
437
+ def __pos__(self):
438
+ return self
439
+
440
+ def __abs__(self):
441
+ return apply_ufunc(np.absolute, (self,))
442
+
443
+ def __eq__(self, o):
444
+ return apply_ufunc(np.equal, (self, o))
445
+
446
+ def __ne__(self, o):
447
+ return apply_ufunc(np.not_equal, (self, o))
448
+
449
+ def __lt__(self, o):
450
+ return apply_ufunc(np.less, (self, o))
451
+
452
+ def __le__(self, o):
453
+ return apply_ufunc(np.less_equal, (self, o))
454
+
455
+ def __gt__(self, o):
456
+ return apply_ufunc(np.greater, (self, o))
457
+
458
+ def __ge__(self, o):
459
+ return apply_ufunc(np.greater_equal, (self, o))
460
+
461
+ def __bool__(self):
462
+ if self.size != 1:
463
+ raise UnsupportedOperationError("the truth value of an array with more than one element is ambiguous")
464
+ return bool(self._element(0))
465
+
466
+ def _refuse(self, *args, **kwargs):
467
+ raise UnsupportedOperationError("this conversion is not supported on quantities with errors (use .values "
468
+ "for the nominal values)")
469
+
470
+ __float__ = __int__ = __index__ = __complex__ = _refuse
471
+ __floor__ = __ceil__ = __round__ = __trunc__ = _refuse
472
+ __mod__ = __rmod__ = __floordiv__ = __rfloordiv__ = __divmod__ = __rdivmod__ = _refuse
473
+
474
+ def __array__(self, dtype=None, copy=None):
475
+ raise UnsupportedOperationError("a QuantityArray does not convert to a NumPy array (use .values for the "
476
+ "nominal values)")
477
+
478
+ def __array_ufunc__(self, ufunc, method, *inputs, **kwargs):
479
+ return array_ufunc(ufunc, method, inputs, kwargs)
480
+
481
+ def __array_function__(self, func, types, args, kwargs):
482
+ impl = _HANDLED.get(func)
483
+ if impl is None:
484
+ raise UnsupportedOperationError(f"the NumPy function {getattr(func, '__name__', func)} is not supported "
485
+ "on quantities with errors")
486
+ return impl(*args, **kwargs)
487
+
488
+
489
+ # ======================================================================================================================
490
+ # Conversion of operands
491
+ # ======================================================================================================================
492
+ def _model_of(operands) -> Model:
493
+ m = None
494
+ for o in operands:
495
+ if isinstance(o, (Quantity, QuantityArray)):
496
+ if m is None:
497
+ m = o._m
498
+ elif o._m is not m:
499
+ raise ModelMismatchError("these quantities belong to two different models")
500
+ return m
501
+
502
+
503
+ def _as_qa(o, m: Model) -> QuantityArray:
504
+ """Any operand as a QuantityArray of model m (numbers and ndarray: exact, no source)."""
505
+ if isinstance(o, QuantityArray):
506
+ return o
507
+ if isinstance(o, Quantity):
508
+ return QuantityArray._from_quantities(_obj0(o), m)
509
+ if isinstance(o, np.ndarray) and o.dtype == object:
510
+ return QuantityArray._from_quantities(o, m)
511
+ if isinstance(o, (list, tuple)) and _contains_quantity(o):
512
+ return array(o)
513
+ if o is None or isinstance(o, (str, bytes)):
514
+ raise UnsupportedOperationError(f"unsupported operand of type {type(o).__name__}")
515
+ raw = np.asarray(o)
516
+ if raw.dtype.kind not in "biuf": # complex, strings, objects: not supported, never truncated
517
+ raise UnsupportedOperationError(f"unsupported operand of dtype {raw.dtype} (real numbers only)")
518
+ v = raw.astype(float)
519
+ sh = v.shape
520
+ bb = m._bb
521
+ return QuantityArray._make(m, v, np.zeros(sh + (0,)), _EMPTY_IDX, np.zeros(sh) if m._order == 2 else None,
522
+ np.zeros(sh + (0,), dtype=bool), _EMPTY_IDX,
523
+ np.zeros(sh + (0,)) if bb else None, _EMPTY_IDX, np.zeros(sh + (0,)) if bb else None,
524
+ check=False)
525
+
526
+
527
+ def _contains_quantity(o) -> bool:
528
+ if isinstance(o, (Quantity, QuantityArray)):
529
+ return True
530
+ if isinstance(o, (list, tuple)):
531
+ return any(_contains_quantity(e) for e in o)
532
+ return False
533
+
534
+
535
+ def _obj0(q: Quantity) -> np.ndarray:
536
+ a = np.empty((), dtype=object)
537
+ a[()] = q
538
+ return a
539
+
540
+
541
+ def _has_sources(x: QuantityArray) -> bool:
542
+ return x._S.shape[-1] > 0
543
+
544
+
545
+ def _exact_mask(x: QuantityArray) -> np.ndarray:
546
+ """Exact zero error (empty sharp and zero bias): the rule of ==."""
547
+ ex = ~np.any(x._S != 0.0, axis=-1)
548
+ if x._A is not None:
549
+ ex &= x._A == 0.0
550
+ return ex
551
+
552
+
553
+ def _errorless_mask(x: QuantityArray) -> np.ndarray:
554
+ """Empty sharp: the criterion of the domain rules, identical at both orders."""
555
+ return ~np.any(x._S != 0.0, axis=-1)
556
+
557
+
558
+ def _check_bias_at(name: str, where, *xs: QuantityArray) -> None:
559
+ """NonFiniteError if an operand carries a bias where the function is not C² (scalar `_singular_exact`)."""
560
+ for x in xs:
561
+ if x._A is not None and np.any(np.broadcast_to(where, np.broadcast_shapes(np.shape(where), x._A.shape))
562
+ & (x._A != 0.0)):
563
+ raise NonFiniteError(f"{name}: the bias of an element cannot be propagated at a point where the "
564
+ "derivative is infinite or undefined")
565
+
566
+
567
+ # ======================================================================================================================
568
+ # Dense engine
569
+ # ======================================================================================================================
570
+ def _engine(x: QuantityArray, y: QuantityArray | None, f, fx, fy, fxx, fxy, fyy, linear=False) -> QuantityArray:
571
+ """f(x, y) element by element (y None: one argument), with the propagation rules of the sharp and the bias (and of its breakdown)."""
572
+ m = x._m
573
+ f = np.asarray(f, dtype=float)
574
+ shape = f.shape
575
+ fx = np.asarray(fx, dtype=float)
576
+ two = y is not None and (_has_sources(y) or (y._A is not None and np.any(y._A != 0.0))
577
+ or (y._B is not None and y._B.shape[-1] > 0) or y._Z.shape[-1] > 0)
578
+ if y is not None and y._m is not m:
579
+ raise ModelMismatchError("these quantities belong to two different models")
580
+ if two:
581
+ fy = np.asarray(fy, dtype=float)
582
+ sup = _union(x._sup, y._sup)
583
+ k = len(sup)
584
+ Sx = np.broadcast_to(_expand(x._S, x._sup, sup), shape + (k,))
585
+ Sy = np.broadcast_to(_expand(y._S, y._sup, sup), shape + (k,))
586
+ S = _m0(fx[..., None], Sx) + _m0(fy[..., None], Sy)
587
+ else:
588
+ sup = x._sup
589
+ k = len(sup)
590
+ Sx = np.broadcast_to(x._S, shape + (k,))
591
+ Sy = None
592
+ S = _m0(fx[..., None], Sx)
593
+ if m._order == 1:
594
+ Zs = np.zeros(shape + (0,), dtype=bool)
595
+ return QuantityArray._make(m, f, S, sup, None, Zs, _EMPTY_IDX, None, _EMPTY_IDX, None)
596
+ Ax = np.broadcast_to(x._A, shape)
597
+ A = _m0(fx, Ax)
598
+ if two:
599
+ A = A + _m0(fy, np.broadcast_to(y._A, shape))
600
+ if not linear:
601
+ fxx = np.asarray(fxx, dtype=float)
602
+ nzx = np.any(Sx != 0.0, axis=-1)
603
+ Px = _partner(m, Sx, sup)
604
+ with np.errstate(all="ignore"):
605
+ curv = _m0(fxx, np.sum(Sx * Px, axis=-1), nzx)
606
+ if two:
607
+ fxy = np.asarray(fxy, dtype=float)
608
+ fyy = np.asarray(fyy, dtype=float)
609
+ nzy = np.any(Sy != 0.0, axis=-1)
610
+ Py = _partner(m, Sy, sup)
611
+ curv = curv + 2.0 * _m0(fxy, np.sum(Sx * Py, axis=-1), nzx & nzy) + _m0(fyy, np.sum(Sy * Py, axis=-1),
612
+ nzy)
613
+ A = A + 0.5 * curv
614
+ # structural dependency on groups with an assumed zero bias
615
+ if two:
616
+ zg = _union(x._zg, y._zg)
617
+ Z = (np.broadcast_to(_expand(x._Z, x._zg, zg, bool), shape + (len(zg),))
618
+ | np.broadcast_to(_expand(y._Z, y._zg, zg, bool), shape + (len(zg),)))
619
+ else:
620
+ zg = x._zg
621
+ Z = np.broadcast_to(x._Z, shape + (len(zg),))
622
+ B = K = None
623
+ bg = _EMPTY_IDX
624
+ if m._bb:
625
+ Kx = np.broadcast_to(_expand(x._K, x._sup, sup), shape + (k,))
626
+ if two:
627
+ bg = _union(x._bg, y._bg)
628
+ Bx = np.broadcast_to(_expand(x._B, x._bg, bg), shape + (len(bg),))
629
+ By = np.broadcast_to(_expand(y._B, y._bg, bg), shape + (len(bg),))
630
+ B = _m0(fx[..., None], Bx) + _m0(fy[..., None], By)
631
+ Ky = np.broadcast_to(_expand(y._K, y._sup, sup), shape + (k,))
632
+ K = _m0(fx[..., None], Kx) + _m0(fy[..., None], Ky)
633
+ else:
634
+ bg = x._bg
635
+ B = _m0(fx[..., None], np.broadcast_to(x._B, shape + (len(bg),)))
636
+ K = _m0(fx[..., None], Kx)
637
+ if not linear:
638
+ curvK = _m0(fxx[..., None], Sx * Sx, Sx != 0.0)
639
+ if two:
640
+ curvK = (curvK + 2.0 * _m0(fxy[..., None], Sx * Sy, (Sx != 0.0) & (Sy != 0.0))
641
+ + _m0(fyy[..., None], Sy * Sy, Sy != 0.0))
642
+ K = K + 0.5 * curvK
643
+ return QuantityArray._make(m, f, S, sup, A, np.ascontiguousarray(Z), zg, B, bg, K)
644
+
645
+
646
+ def _unary_array(name: str, x: QuantityArray) -> QuantityArray:
647
+ derivs, domain, nondiff = _rules.UNARY[name]
648
+ v = x._v
649
+ if domain is not None and np.any(domain(v)):
650
+ raise DomainError(f"{name}: an argument is outside the domain of the function")
651
+ with np.errstate(all="ignore"):
652
+ f, f1, f2 = derivs(v)
653
+ f = np.broadcast_to(np.asarray(f, dtype=float), v.shape)
654
+ f1 = np.broadcast_to(np.asarray(f1, dtype=float), v.shape)
655
+ f2 = np.broadcast_to(np.asarray(f2, dtype=float), v.shape)
656
+ if nondiff is not None:
657
+ nd = np.asarray(nondiff(v))
658
+ if np.any(nd):
659
+ if np.any(nd & ~_errorless_mask(x)):
660
+ raise NonDifferentiableError(f"{name} is not twice differentiable (or has an infinite derivative) "
661
+ "at an element that carries an error")
662
+ _check_bias_at(name, nd, x)
663
+ with np.errstate(all="ignore"):
664
+ f = np.where(nd, _rules.VALUE[name](v), f)
665
+ f1 = np.where(nd, 0.0, f1)
666
+ f2 = np.where(nd, 0.0, f2)
667
+ return _engine(x, None, f, f1, 0.0, f2, 0.0, 0.0)
668
+
669
+
670
+ def _binary_fn_array(name: str, x: QuantityArray, y: QuantityArray) -> QuantityArray:
671
+ """atan2 / hypot element by element (x: first argument)."""
672
+ xv, yv = np.broadcast_arrays(x._v, y._v)
673
+ ex = np.broadcast_to(_errorless_mask(x), xv.shape)
674
+ ey = np.broadcast_to(_errorless_mask(y), xv.shape)
675
+ origin = (xv == 0.0) & (yv == 0.0)
676
+ if name == "atan2":
677
+ singular = (origin & ~(ex & ey)) | ((xv == 0.0) & (yv < 0.0) & ~ex)
678
+ else:
679
+ singular = origin & ~(ex & ey)
680
+ if np.any(singular):
681
+ raise NonDifferentiableError(f"{name} is not differentiable at an element where the arguments carry an error")
682
+ _check_bias_at(name, origin, x, y)
683
+ if name == "atan2":
684
+ _check_bias_at(name, (xv == 0.0) & (yv < 0.0), x)
685
+ with np.errstate(all="ignore"):
686
+ f, fx, fy, fxx, fxy, fyy = _rules.BINARY[name](xv, yv)
687
+ if np.any(origin):
688
+ f = np.where(origin, _rules.VALUE[name](xv, yv), f)
689
+ fx, fy, fxx, fxy, fyy = (np.where(origin, 0.0, d) for d in (fx, fy, fxx, fxy, fyy))
690
+ return _engine(x, y, f, fx, fy, fxx, fxy, fyy)
691
+
692
+
693
+ def _is_exact_operand(o) -> bool:
694
+ return not isinstance(o, (Quantity, QuantityArray))
695
+
696
+
697
+ def _pow_array(xo, yo, m: Model) -> QuantityArray:
698
+ x = _as_qa(xo, m)
699
+ if _is_exact_operand(yo):
700
+ p = np.asarray(yo, dtype=float)
701
+ if not np.all(np.isfinite(p)):
702
+ raise DomainError("the exponent must be finite")
703
+ xv, pv = np.broadcast_arrays(x._v, p)
704
+ domain, nondiff, zero_ok = _rules.pow_number_masks(xv, pv)
705
+ if np.any(domain):
706
+ raise DomainError("an element is outside the domain of the power function")
707
+ ex = np.broadcast_to(_errorless_mask(x), xv.shape)
708
+ if np.any(nondiff & ~ex):
709
+ raise NonDifferentiableError("x ** p is not differentiable at x = 0 (boundary of the domain [0, ∞)) "
710
+ "and an element carries an error there")
711
+ if np.any(nondiff & ~zero_ok):
712
+ raise DomainError("0 ** p is not defined for p < 0")
713
+ _check_bias_at("pow", nondiff, x)
714
+ with np.errstate(all="ignore"):
715
+ f, f1, f2 = _rules.pow_number(xv, pv)
716
+ f1 = np.where(nondiff, 0.0, f1)
717
+ f2 = np.where(nondiff, 0.0, f2)
718
+ f = np.where(nondiff, 0.0, f)
719
+ # p == 0 gives an exact 1 and p == 1 the operand itself: f1, f2 are exact there (pow_number).
720
+ return _engine(x, None, f, f1, 0.0, f2, 0.0, 0.0)
721
+ y = _as_qa(yo, m)
722
+ if not np.all(x._v > 0.0):
723
+ raise DomainError("x ** y with an exponent carrying errors requires x > 0")
724
+ xv, yv = np.broadcast_arrays(x._v, y._v)
725
+ with np.errstate(all="ignore"):
726
+ d = _rules.pow_qq(xv, yv)
727
+ return _engine(x, y, *d)
728
+
729
+
730
+ # ======================================================================================================================
731
+ # Ufunc dispatch
732
+ # ======================================================================================================================
733
+ _UNARY_UFUNCS = {
734
+ np.exp: "exp", np.expm1: "expm1", np.log: "log", np.log1p: "log1p", np.log2: "log2", np.log10: "log10",
735
+ np.sqrt: "sqrt", np.sin: "sin", np.cos: "cos", np.tan: "tan", np.arcsin: "asin", np.arccos: "acos",
736
+ np.arctan: "atan", np.sinh: "sinh", np.cosh: "cosh", np.tanh: "tanh", np.arcsinh: "asinh",
737
+ np.arccosh: "acosh", np.arctanh: "atanh", np.absolute: "abs",
738
+ }
739
+ if _rules.ERF_UFUNCS:
740
+ _UNARY_UFUNCS[_rules.ERF_UFUNCS[0]] = "erf"
741
+ _UNARY_UFUNCS[_rules.ERF_UFUNCS[1]] = "erfc"
742
+ _BINARY_FN_UFUNCS = {np.arctan2: "atan2", np.hypot: "hypot"}
743
+ _ARITH = {np.add: operator.add, np.subtract: operator.sub, np.multiply: operator.mul,
744
+ np.true_divide: operator.truediv, np.power: operator.pow}
745
+ _CMP = {np.less: operator.lt, np.less_equal: operator.le, np.greater: operator.gt,
746
+ np.greater_equal: operator.ge}
747
+
748
+
749
+ def array_ufunc(ufunc, method, inputs, kwargs):
750
+ if method != "__call__":
751
+ raise UnsupportedOperationError(f"{ufunc.__name__}.{method} is not supported on quantities with errors")
752
+ if kwargs:
753
+ raise UnsupportedOperationError(f"keyword arguments of {ufunc.__name__} ({', '.join(kwargs)}) are not "
754
+ "supported on quantities with errors")
755
+ return apply_ufunc(ufunc, inputs)
756
+
757
+
758
+ def _scalar_operand(o):
759
+ if isinstance(o, Quantity):
760
+ return o
761
+ if _is_number(o):
762
+ return float(o)
763
+ return None
764
+
765
+
766
+ def apply_ufunc(ufunc, operands):
767
+ """Apply a supported ufunc to operands among quantities, quantity arrays, ndarray and numbers."""
768
+ if ufunc is np.matmul:
769
+ return matmul(*operands)
770
+ scal = [_scalar_operand(o) for o in operands]
771
+ if all(s is not None for s in scal):
772
+ return _apply_scalar(ufunc, scal)
773
+ if ufunc in (np.equal, np.not_equal):
774
+ return _equal(ufunc, *operands)
775
+ m = _model_of(operands)
776
+ if m is None: # pragma: no cover - dispatch happens only with one of our types
777
+ return ufunc(*operands)
778
+ if ufunc in _UNARY_UFUNCS:
779
+ return _unary_array(_UNARY_UFUNCS[ufunc], _as_qa(operands[0], m))
780
+ if ufunc in _BINARY_FN_UFUNCS:
781
+ return _binary_fn_array(_BINARY_FN_UFUNCS[ufunc], _as_qa(operands[0], m), _as_qa(operands[1], m))
782
+ if ufunc is np.negative:
783
+ x = _as_qa(operands[0], m)
784
+ return _engine(x, None, -x._v, -1.0, 0.0, 0.0, 0.0, 0.0, linear=True)
785
+ if ufunc is np.positive:
786
+ return _as_qa(operands[0], m)
787
+ if ufunc is np.square:
788
+ return _pow_array(operands[0], 2.0, m)
789
+ if ufunc in (np.add, np.subtract):
790
+ x, y = (_as_qa(o, m) for o in operands)
791
+ sign = 1.0 if ufunc is np.add else -1.0
792
+ with np.errstate(all="ignore"):
793
+ f = x._v + y._v if sign > 0 else x._v - y._v
794
+ return _engine(x, y, f, 1.0, sign, 0.0, 0.0, 0.0, linear=True)
795
+ if ufunc is np.multiply:
796
+ x, y = (_as_qa(o, m) for o in operands)
797
+ xv, yv = np.broadcast_arrays(x._v, y._v)
798
+ with np.errstate(all="ignore"):
799
+ f, fx, fy, fxx, fxy, fyy = _rules.mul(xv, yv)
800
+ linear = not (_has_sources(x) and _has_sources(y))
801
+ return _engine(x, y, f, fx, fy, fxx, fxy, fyy, linear=linear)
802
+ if ufunc is np.true_divide:
803
+ x, y = (_as_qa(o, m) for o in operands)
804
+ if np.any(y._v == 0.0):
805
+ raise DomainError("division by an element of nominal value 0")
806
+ xv, yv = np.broadcast_arrays(x._v, y._v)
807
+ with np.errstate(all="ignore"):
808
+ d = _rules.div(xv, yv)
809
+ return _engine(x, y, *d, linear=not _has_sources(y) and not _has_sources(x))
810
+ if ufunc is np.power:
811
+ return _pow_array(operands[0], operands[1], m)
812
+ if ufunc in _CMP:
813
+ a, b = operands
814
+ av = a.values if isinstance(a, QuantityArray) else (a._v if isinstance(a, Quantity) else np.asarray(a))
815
+ bv = b.values if isinstance(b, QuantityArray) else (b._v if isinstance(b, Quantity) else np.asarray(b))
816
+ return _CMP[ufunc](av, bv)
817
+ raise UnsupportedOperationError(f"the NumPy function {ufunc.__name__} is not supported on quantities with "
818
+ "errors")
819
+
820
+
821
+ def _equal(ufunc, a, b):
822
+ """== element by element with the exact-zero rule; False between two models."""
823
+ ours = (Quantity, QuantityArray)
824
+ ma = a._m if isinstance(a, ours) else None
825
+ mb = b._m if isinstance(b, ours) else None
826
+ m = ma or mb
827
+ try:
828
+ if ma is not None and mb is not None and ma is not mb:
829
+ raise _Unequal
830
+ qa_, qb_ = _as_qa(a, m), _as_qa(b, m) # None, complex, strings: never equal
831
+ try:
832
+ d = _as_qa(apply_ufunc(np.subtract, (a, b)), m)
833
+ eq = (d._v == 0.0) & _exact_mask(d)
834
+ except NonFiniteError: # the difference overflows: certainly not an exact zero (equal values subtract to 0)
835
+ eq = np.zeros(np.broadcast_shapes(qa_._v.shape, qb_._v.shape), dtype=bool)
836
+ except (_Unequal, UnsupportedOperationError):
837
+ shape = np.broadcast_shapes(np.shape(_shape_probe(a)), np.shape(_shape_probe(b)))
838
+ eq = np.zeros(shape, dtype=bool)
839
+ return eq if ufunc is np.equal else ~eq
840
+
841
+
842
+ class _Unequal(Exception):
843
+ """Internal signal: operands of different models, or an unsupported operand (== is then False)."""
844
+
845
+
846
+ def _apply_scalar(ufunc, scal):
847
+ """All operands are scalar (Quantity or Python float): the scalar engine."""
848
+ if ufunc in _UNARY_UFUNCS:
849
+ x = scal[0]
850
+ if isinstance(x, Quantity):
851
+ return _apply_unary(_UNARY_UFUNCS[ufunc], x)
852
+ return ufunc(x)
853
+ if ufunc in _BINARY_FN_UFUNCS:
854
+ return _apply_binary(_BINARY_FN_UFUNCS[ufunc], scal[0], scal[1])
855
+ if ufunc in _ARITH:
856
+ return _ARITH[ufunc](*scal)
857
+ if ufunc is np.negative:
858
+ return -scal[0]
859
+ if ufunc is np.positive:
860
+ return scal[0]
861
+ if ufunc is np.square:
862
+ return scal[0] ** 2
863
+ if ufunc in _CMP:
864
+ return _CMP[ufunc](*scal)
865
+ if ufunc is np.equal:
866
+ return scal[0] == scal[1] if isinstance(scal[0], Quantity) else scal[1] == scal[0]
867
+ if ufunc is np.not_equal:
868
+ return scal[0] != scal[1] if isinstance(scal[0], Quantity) else scal[1] != scal[0]
869
+ raise UnsupportedOperationError(f"the NumPy function {ufunc.__name__} is not supported on quantities with "
870
+ "errors")
871
+
872
+
873
+ # ======================================================================================================================
874
+ # Matrix product, readings, NumPy functions
875
+ # ======================================================================================================================
876
+ def matmul(a, b):
877
+ """a @ b for dimensions ≤ 2: (ab)♯_ij = Σ_k (a♯_ik b_kj + a_ik b♯_kj); A[(ab)_ij] = Σ_k (A[a_ik] b_kj +
878
+ a_ik A[b_kj] + Γ[a_ik, b_kj])."""
879
+ m = _model_of((a, b))
880
+ if m is None: # pragma: no cover
881
+ return np.matmul(a, b)
882
+ if _is_number(a) or _is_number(b) or isinstance(a, Quantity) or isinstance(b, Quantity):
883
+ raise UnsupportedOperationError("matmul: scalar operands are not allowed (use *)")
884
+ x, y = _as_qa(a, m), _as_qa(b, m)
885
+ if not (1 <= x.ndim <= 2 and 1 <= y.ndim <= 2):
886
+ raise UnsupportedOperationError("matmul is supported for dimensions 1 and 2 only")
887
+ xa = x if x.ndim == 2 else x.reshape(1, x.shape[0])
888
+ yb = y if y.ndim == 2 else y.reshape(y.shape[0], 1)
889
+ if xa.shape[1] != yb.shape[0]:
890
+ raise InputError(f"matmul: shapes {x.shape} and {y.shape} are not aligned")
891
+ sup = _union(xa._sup, yb._sup)
892
+ Sa = _expand(xa._S, xa._sup, sup)
893
+ Sb = _expand(yb._S, yb._sup, sup)
894
+ av, bv = xa._v, yb._v
895
+ v = av @ bv
896
+ S = np.einsum("imk,mp->ipk", Sa, bv) + np.einsum("im,mpk->ipk", av, Sb)
897
+ A = B = K = None
898
+ bg = _EMPTY_IDX
899
+ if m._order == 1:
900
+ zg = _EMPTY_IDX
901
+ Z = np.zeros(v.shape + (0,), dtype=bool)
902
+ else:
903
+ A = xa._A @ bv + av @ yb._A + np.einsum("imk,mpk->ip", Sa, _partner(m, Sb, sup))
904
+ zg = _union(xa._zg, yb._zg)
905
+ za = _expand(xa._Z, xa._zg, zg, bool).any(axis=1)
906
+ zb = _expand(yb._Z, yb._zg, zg, bool).any(axis=0)
907
+ Z = za[:, None, :] | zb[None, :, :]
908
+ if m._bb:
909
+ bg = _union(xa._bg, yb._bg)
910
+ Ba = _expand(xa._B, xa._bg, bg)
911
+ Bb = _expand(yb._B, yb._bg, bg)
912
+ B = np.einsum("img,mp->ipg", Ba, bv) + np.einsum("im,mpg->ipg", av, Bb)
913
+ Ka = _expand(xa._K, xa._sup, sup)
914
+ Kb = _expand(yb._K, yb._sup, sup)
915
+ K = (np.einsum("imk,mp->ipk", Ka, bv) + np.einsum("im,mpk->ipk", av, Kb)
916
+ + np.einsum("imk,mpk->ipk", Sa, Sb))
917
+ res = QuantityArray._make(m, v, S, sup, A, Z, zg, B, bg, K)
918
+ if x.ndim == 1 and y.ndim == 1:
919
+ return res[0, 0]
920
+ if x.ndim == 1:
921
+ return res[0]
922
+ if y.ndim == 1:
923
+ return res[:, 0]
924
+ return res
925
+
926
+
927
+ def elementwise_gamma(f, g=None):
928
+ m = _model_of((f, g))
929
+ x = _as_qa(f, m)
930
+ if g is None:
931
+ return x.gamma
932
+ y = _as_qa(g, m)
933
+ sup = _union(x._sup, y._sup)
934
+ with np.errstate(all="ignore"):
935
+ g = np.sum(_expand(x._S, x._sup, sup) * _expand(y._S, y._sup, sup), axis=-1)
936
+ if not np.all(np.isfinite(g)):
937
+ raise NonFiniteError("Γ is not finite (overflow)")
938
+ return g
939
+
940
+
941
+ def elementwise_contributions(qa: QuantityArray, *, by: str, kind: str) -> dict:
942
+ dicts = [contributions(q, by=by, kind=kind) for q in qa._tolist_flat()]
943
+ keys = []
944
+ for d in dicts:
945
+ for key in d:
946
+ if key not in keys:
947
+ keys.append(key)
948
+ out = {}
949
+ for key in keys:
950
+ out[key] = np.array([d.get(key, 0.0) for d in dicts]).reshape(qa.shape)
951
+ return out
952
+
953
+
954
+ def array(seq) -> QuantityArray:
955
+ """A :class:`QuantityArray` from a (nested) sequence of quantities (numbers are taken as exact)."""
956
+ if isinstance(seq, QuantityArray):
957
+ return seq
958
+ objs = np.empty(np.shape(np.array(seq, dtype=object)), dtype=object)
959
+ src = np.array(seq, dtype=object)
960
+ for ix in np.ndindex(src.shape):
961
+ e = src[ix]
962
+ if isinstance(e, QuantityArray):
963
+ raise InputError("errorcalculus.array expects quantities and numbers, not arrays of quantities "
964
+ "(use np.stack or np.concatenate)")
965
+ objs[ix] = e
966
+ return QuantityArray._from_quantities(objs)
967
+
968
+
969
+ def _np_sum(a, axis=None, dtype=None, out=None, keepdims=False, **kwargs):
970
+ if dtype is not None or out is not None or keepdims or kwargs:
971
+ raise UnsupportedOperationError("np.sum on quantities supports only the argument axis")
972
+ return _as_qa(a, _model_of((a,))).sum(axis=axis)
973
+
974
+
975
+ def _np_mean(a, axis=None, dtype=None, out=None, keepdims=False, **kwargs):
976
+ if dtype is not None or out is not None or keepdims or kwargs:
977
+ raise UnsupportedOperationError("np.mean on quantities supports only the argument axis")
978
+ return _as_qa(a, _model_of((a,))).mean(axis=axis)
979
+
980
+
981
+ def _np_dot(a, b, out=None):
982
+ if out is not None:
983
+ raise UnsupportedOperationError("np.dot on quantities does not support out=")
984
+ if np.ndim(_shape_probe(a)) == 0 or np.ndim(_shape_probe(b)) == 0:
985
+ return apply_ufunc(np.multiply, (a, b))
986
+ return matmul(a, b)
987
+
988
+
989
+ def _shape_probe(o):
990
+ if isinstance(o, QuantityArray):
991
+ return o.values
992
+ if isinstance(o, Quantity):
993
+ return o._v
994
+ return np.empty(np.shape(o))
995
+
996
+
997
+ def _combine(arrays, how: str, axis: int):
998
+ arrays = list(arrays)
999
+ m = _model_of(arrays)
1000
+ qs = [_as_qa(a, m) for a in arrays]
1001
+ if not qs:
1002
+ raise InputError(f"np.{how} needs at least one array")
1003
+ nd = qs[0].ndim
1004
+ if how == "stack":
1005
+ ax = axis % (nd + 1)
1006
+ op = np.stack
1007
+ else:
1008
+ if nd == 0:
1009
+ raise InputError("zero-dimensional arrays cannot be concatenated")
1010
+ ax = axis % nd
1011
+ op = np.concatenate
1012
+ sup = qs[0]._sup
1013
+ zg = qs[0]._zg
1014
+ bg = qs[0]._bg
1015
+ for q in qs[1:]:
1016
+ sup, zg, bg = _union(sup, q._sup), _union(zg, q._zg), _union(bg, q._bg)
1017
+ v = op([q._v for q in qs], axis=ax)
1018
+ S = op([_expand(q._S, q._sup, sup) for q in qs], axis=ax)
1019
+ A = None if m._order == 1 else op([q._A for q in qs], axis=ax)
1020
+ Z = op([_expand(q._Z, q._zg, zg, bool) for q in qs], axis=ax)
1021
+ B = K = None
1022
+ if m._bb:
1023
+ B = op([_expand(q._B, q._bg, bg) for q in qs], axis=ax)
1024
+ K = op([_expand(q._K, q._sup, sup) for q in qs], axis=ax)
1025
+ else:
1026
+ bg = _EMPTY_IDX
1027
+ return QuantityArray._make(m, v, S, sup, A, Z, zg, B, bg, K, check=False)
1028
+
1029
+
1030
+ def _np_stack(arrays, axis=0, out=None, **kwargs):
1031
+ if out is not None or kwargs:
1032
+ raise UnsupportedOperationError("np.stack on quantities supports only the argument axis")
1033
+ return _combine(arrays, "stack", axis)
1034
+
1035
+
1036
+ def _np_concatenate(arrays, axis=0, out=None, **kwargs):
1037
+ if out is not None or kwargs or axis is None:
1038
+ raise UnsupportedOperationError("np.concatenate on quantities supports only an integer axis")
1039
+ return _combine(arrays, "concatenate", axis)
1040
+
1041
+
1042
+ def _np_reshape(a, *args, **kwargs):
1043
+ shape = kwargs.pop("shape", kwargs.pop("newshape", None))
1044
+ if shape is None:
1045
+ shape = args[0] if args else None
1046
+ if kwargs.get("order", "C") != "C" or shape is None:
1047
+ raise UnsupportedOperationError("np.reshape on quantities supports only a shape, in C order")
1048
+ return _as_qa(a, _model_of((a,))).reshape(shape)
1049
+
1050
+
1051
+ def _np_transpose(a, axes=None):
1052
+ return _as_qa(a, _model_of((a,))).transpose(axes)
1053
+
1054
+
1055
+ def _linalg(name):
1056
+ def impl(*args, **kwargs):
1057
+ from . import linalg
1058
+
1059
+ return getattr(linalg, name)(*args, **kwargs)
1060
+ return impl
1061
+
1062
+
1063
+ _HANDLED = {
1064
+ np.sum: _np_sum, np.mean: _np_mean, np.dot: _np_dot, np.stack: _np_stack, np.concatenate: _np_concatenate,
1065
+ np.reshape: _np_reshape, np.transpose: _np_transpose,
1066
+ np.linalg.solve: _linalg("solve"), np.linalg.inv: _linalg("inv"), np.linalg.det: _linalg("det"),
1067
+ }