processsupport 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,97 @@
1
+ """Causal missingness and drift profiling with training-frozen thresholds."""
2
+
3
+ import numpy as np
4
+ from ._validation import array, ids, require
5
+ from .results import NumericalResult
6
+
7
+
8
+ def profile(
9
+ values,
10
+ time_s,
11
+ *,
12
+ train_indices=None,
13
+ reference=None,
14
+ window=10,
15
+ drift_z=3.0,
16
+ missing_policy="preserve",
17
+ max_fill_gap=0,
18
+ row_ids=None,
19
+ source_ids=(),
20
+ ):
21
+ raw, t = array(values, "values", 1, finite=False), array(time_s, "time_s", 1)
22
+ require(
23
+ len(raw) == len(t) and np.all(np.diff(t) > 0),
24
+ "timebase",
25
+ "Times must increase strictly and match values",
26
+ )
27
+ require(
28
+ 3 <= window <= 1000 and int(window) == window and drift_z >= 0 and max_fill_gap >= 0,
29
+ "parameters",
30
+ "Invalid causal window or gap bounds",
31
+ )
32
+ require(missing_policy in {"preserve", "forward-fill-bounded"}, "policy", "Unsupported missing policy")
33
+ names = ids(row_ids, len(raw))
34
+ if reference is None:
35
+ require(
36
+ train_indices is not None, "training-reference", "Supply training indices or a frozen reference"
37
+ )
38
+ ix = np.asarray(train_indices, dtype=int)
39
+ require(
40
+ len(ix) > 1 and (ix >= 0).all() and (ix < len(raw)).all(),
41
+ "training-reference",
42
+ "Invalid training rows",
43
+ )
44
+ ref = raw[ix]
45
+ ref = ref[np.isfinite(ref)]
46
+ require(len(ref) > 1, "training-reference", "At least two observed reference values are required")
47
+ reference = {
48
+ "median": float(np.median(ref)),
49
+ "scale": float(np.std(ref)),
50
+ "training_row_ids": [names[i] for i in ix],
51
+ }
52
+ require(
53
+ np.isfinite(reference["median"]) and np.isfinite(reference["scale"]) and reference["scale"] >= 0,
54
+ "training-reference",
55
+ "Invalid frozen reference",
56
+ )
57
+ result = raw.copy()
58
+ flags = []
59
+ gap = 0
60
+ for i, x in enumerate(raw):
61
+ row = []
62
+ if not np.isfinite(x):
63
+ gap += 1
64
+ row.append("missing")
65
+ if (
66
+ missing_policy == "forward-fill-bounded"
67
+ and i > 0
68
+ and gap <= max_fill_gap
69
+ and np.isfinite(result[i - 1])
70
+ ):
71
+ result[i] = result[i - 1]
72
+ row.append("causal-fill")
73
+ else:
74
+ gap = 0
75
+ recent = raw[max(0, i - window + 1) : i + 1]
76
+ finite = recent[np.isfinite(recent)]
77
+ if len(finite) == window and np.ptp(finite) == 0:
78
+ row.append("constant-window")
79
+ if len(finite) >= 3:
80
+ delta = abs(float(np.median(finite)) - reference["median"])
81
+ if reference["scale"] == 0:
82
+ if delta > 0:
83
+ row.append("changed-constant-reference")
84
+ elif delta / reference["scale"] > drift_z:
85
+ row.append("drift-or-regime-change")
86
+ flags.append({"row_id": names[i], "flags": row})
87
+ return NumericalResult(
88
+ result,
89
+ dict(
90
+ raw=raw,
91
+ flags=flags,
92
+ reference=reference,
93
+ missing_policy=missing_policy,
94
+ max_fill_gap=max_fill_gap,
95
+ ),
96
+ source_ids,
97
+ )
@@ -0,0 +1,102 @@
1
+ """Covariance-weighted affine reconciliation with optional physical inequalities."""
2
+
3
+ import numpy as np
4
+ from scipy.linalg import solve, cholesky, solve_triangular
5
+ from scipy.optimize import minimize
6
+ from ._validation import array, covariance as validate_covariance, require
7
+ from .results import NumericalResult, ScientificRefusal
8
+
9
+
10
+ def reconcile(
11
+ measured,
12
+ covariance,
13
+ A,
14
+ b,
15
+ *,
16
+ nonnegative=False,
17
+ tolerance=1e-8,
18
+ units=None,
19
+ constraint_units=None,
20
+ source_ids=(),
21
+ ):
22
+ y, matrix, target = array(measured, "measured", 1), array(A, "A", 2), array(b, "b", 1)
23
+ cov = validate_covariance(covariance, len(y), "covariance", positive=True)
24
+ require(matrix.shape == (len(target), len(y)), "shape", "Constraint dimensions do not match")
25
+ require(np.linalg.matrix_rank(matrix) == len(target), "rank", "Constraint rows must be independent")
26
+ require(0 < tolerance <= 1e-3, "tolerance", "Invalid solution tolerance")
27
+ if units is not None:
28
+ require(
29
+ len(units) == len(y) and all(u and u != "unknown" for u in units),
30
+ "unit-basis",
31
+ "Declare every physical quantity unit",
32
+ )
33
+ if len(set(units)) > 1:
34
+ require(
35
+ constraint_units is not None and len(constraint_units) == len(target),
36
+ "unit-basis",
37
+ "Mixed quantity constraints need explicit scaled constraint units",
38
+ )
39
+ closure = matrix @ y - target
40
+ middle = matrix @ cov @ matrix.T
41
+ try:
42
+ x = y - cov @ matrix.T @ solve(middle, closure, assume_a="pos")
43
+ except np.linalg.LinAlgError as exc:
44
+ raise ScientificRefusal("singular", "Affine reconciliation system is singular") from exc
45
+ chol = cholesky(cov, lower=True)
46
+ if nonnegative and np.any(x < 0):
47
+
48
+ def objective(z):
49
+ return float((z - y) @ solve(cov, z - y, assume_a="pos"))
50
+
51
+ def gradient(z):
52
+ return 2 * solve(cov, z - y, assume_a="pos")
53
+
54
+ opt = minimize(
55
+ objective,
56
+ np.maximum(x, 0),
57
+ jac=gradient,
58
+ method="SLSQP",
59
+ bounds=[(0, None)] * len(y),
60
+ constraints=[dict(type="eq", fun=lambda z: matrix @ z - target, jac=lambda z: matrix)],
61
+ options=dict(ftol=1e-12, maxiter=1000),
62
+ )
63
+ if not opt.success:
64
+ raise ScientificRefusal(
65
+ "infeasible-or-nonconverged",
66
+ "Nonnegative reconciliation did not converge",
67
+ details={"solver": opt.message},
68
+ )
69
+ x = opt.x
70
+ residual = matrix @ x - target
71
+ scale = max(1.0, float(np.linalg.norm(target)), float(np.linalg.norm(matrix) * np.linalg.norm(x)))
72
+ require(
73
+ np.max(np.abs(residual)) <= tolerance * scale,
74
+ "infeasible",
75
+ "Affine solution violates declared tolerance",
76
+ )
77
+ require(
78
+ not nonnegative or np.all(x >= -tolerance),
79
+ "negative-state",
80
+ "Requested nonnegative solution is negative",
81
+ )
82
+ standardized = solve_triangular(chol, x - y, lower=True)
83
+ whitened_closure = solve_triangular(cholesky(middle, lower=True), closure, lower=True)
84
+ return NumericalResult(
85
+ x,
86
+ dict(
87
+ unit_audit="abstract-unspecified"
88
+ if units is None
89
+ else "declared-units; material-basis-not-inferred",
90
+ declared_units=units,
91
+ declared_constraint_units=constraint_units,
92
+ raw_closure=closure,
93
+ closure_residual=residual,
94
+ standardized_residuals=standardized,
95
+ weighted_residual=float(standardized @ standardized),
96
+ raw_standardized_closure=whitened_closure,
97
+ gross_error=bool(np.any(np.abs(whitened_closure) > 3)),
98
+ solver="SLSQP" if nonnegative else "affine-Cholesky",
99
+ tolerance=tolerance,
100
+ ),
101
+ source_ids,
102
+ )
@@ -0,0 +1,75 @@
1
+ """Explicit scientific results, errors and JSON-safe serialization."""
2
+
3
+ from dataclasses import dataclass, field
4
+ from collections.abc import Mapping
5
+ import numpy as np
6
+
7
+
8
+ def json_safe(value):
9
+ """Represent declared missing/nonfinite diagnostics as null, never JSON NaN."""
10
+ if isinstance(value, np.ndarray):
11
+ return json_safe(value.tolist())
12
+ if isinstance(value, np.generic):
13
+ return json_safe(value.item())
14
+ if isinstance(value, float) and not np.isfinite(value):
15
+ return None
16
+ if isinstance(value, Mapping):
17
+ return {str(k): json_safe(v) for k, v in value.items()}
18
+ if isinstance(value, (tuple, list)):
19
+ return [json_safe(v) for v in value]
20
+ return value
21
+
22
+
23
+ class ScientificRefusal(ValueError):
24
+ """An input or interpretation cannot support the requested calculation."""
25
+
26
+ def __init__(self, code, message, field=None, details=None, reference=None):
27
+ super().__init__(message)
28
+ self.code, self.field = str(code), field
29
+ self.details = details or {}
30
+ self.reference = reference
31
+
32
+ def to_dict(self):
33
+ return json_safe(
34
+ dict(
35
+ status="refused",
36
+ code=self.code,
37
+ message=str(self),
38
+ field=self.field,
39
+ details=self.details,
40
+ reference=self.reference,
41
+ )
42
+ )
43
+
44
+
45
+ class DependencyUnavailable(ScientificRefusal):
46
+ """A named real engine is absent; no replacement is admitted."""
47
+
48
+
49
+ @dataclass
50
+ class NumericalResult:
51
+ value: object
52
+ diagnostics: dict = field(default_factory=dict)
53
+ source_ids: tuple = ()
54
+ status: str = "available"
55
+ unit: str | None = None
56
+ basis: str | None = None
57
+
58
+ def __post_init__(self):
59
+ self.source_ids = tuple(self.source_ids or ())
60
+
61
+ @property
62
+ def predictions(self):
63
+ return self.value
64
+
65
+ def to_dict(self):
66
+ return json_safe(
67
+ dict(
68
+ value=self.value,
69
+ diagnostics=self.diagnostics,
70
+ source_ids=self.source_ids,
71
+ status=self.status,
72
+ unit=self.unit,
73
+ basis=self.basis,
74
+ )
75
+ )
@@ -0,0 +1,98 @@
1
+ """Reduced batch interface fits with explicit closed-column inventory."""
2
+
3
+ import numpy as np
4
+ from scipy.optimize import least_squares
5
+ from ._validation import array, require
6
+ from .results import NumericalResult, ScientificRefusal
7
+
8
+
9
+ def fit(
10
+ times,
11
+ heights,
12
+ *,
13
+ initial_height_m,
14
+ solids_fraction,
15
+ family="constant-velocity",
16
+ regime="hindered",
17
+ area_m2=1.0,
18
+ max_nfev=2000,
19
+ source_ids=(),
20
+ ):
21
+ require(
22
+ regime in {"hindered", "dilute"},
23
+ "compressive-regime",
24
+ "The reduced interface law does not model compression",
25
+ "regime",
26
+ )
27
+ require(
28
+ family in {"constant-velocity", "exponential-interface"}, "family", "Unsupported interface family"
29
+ )
30
+ t, h = array(times, "times", 1), array(heights, "heights", 1)
31
+ require(
32
+ t.shape == h.shape and len(t) >= 3 and np.all(t >= 0) and np.all(np.diff(t) > 0),
33
+ "sampling",
34
+ "At least three increasing nonnegative times are required",
35
+ )
36
+ require(
37
+ np.isfinite([initial_height_m, area_m2, solids_fraction]).all()
38
+ and initial_height_m > 0
39
+ and area_m2 > 0
40
+ and 0 < solids_fraction <= 0.7
41
+ and np.isfinite(initial_height_m * area_m2),
42
+ "physical-domain",
43
+ "Positive column and declared solids fraction are required",
44
+ )
45
+ floor = initial_height_m * solids_fraction
46
+ require(
47
+ np.all((h >= floor) & (h <= initial_height_m)),
48
+ "inventory",
49
+ "Interface violates the declared closed-column solids/water inventory",
50
+ )
51
+ require(t.max() > 0 and 1 <= max_nfev <= 2000, "budget", "Invalid time range or fit budget")
52
+ upper = (
53
+ (initial_height_m - floor) / t.max()
54
+ if family == "constant-velocity"
55
+ else -np.log(solids_fraction) / t.max()
56
+ )
57
+
58
+ def curve(rate):
59
+ return (
60
+ initial_height_m - rate * t
61
+ if family == "constant-velocity"
62
+ else initial_height_m * np.exp(-rate * t)
63
+ )
64
+
65
+ opt = least_squares(
66
+ lambda v: curve(v[0]) - h,
67
+ [upper / 2],
68
+ bounds=(0, upper),
69
+ max_nfev=max_nfev,
70
+ ftol=1e-12,
71
+ xtol=1e-12,
72
+ gtol=1e-12,
73
+ )
74
+ if not opt.success:
75
+ raise ScientificRefusal("nonconvergence", "Settling fit did not converge")
76
+ fitted = curve(opt.x[0])
77
+ solids = initial_height_m * area_m2 * solids_fraction
78
+ suspended_water = fitted * area_m2 - solids
79
+ clarified = (initial_height_m - fitted) * area_m2
80
+ return NumericalResult(
81
+ fitted,
82
+ dict(
83
+ parameters={"rate": float(opt.x[0])},
84
+ rate_unit="m/s" if family == "constant-velocity" else "1/s",
85
+ family=family,
86
+ regime=regime,
87
+ solids_volume_m3=np.full(len(t), solids),
88
+ suspension_water_m3=suspended_water,
89
+ clarified_water_m3=clarified,
90
+ initial_water_m3=initial_height_m * area_m2 - solids,
91
+ initial_solids_volume_fraction=solids_fraction,
92
+ solids_fraction_basis="volume",
93
+ assumptions=["closed-column", "constant-solids-volume", "no-compression"],
94
+ residuals=fitted - h,
95
+ ),
96
+ source_ids,
97
+ unit="m",
98
+ )
@@ -0,0 +1,225 @@
1
+ """Metric IDW and actual PyKrige adapters with preserved geometry evidence."""
2
+
3
+ import numpy as np
4
+ from scipy.spatial.distance import cdist
5
+ from scipy.linalg import solve
6
+ from ._validation import array, ids, require
7
+ from .results import NumericalResult, ScientificRefusal, DependencyUnavailable
8
+
9
+
10
+ def _prepare(coordinates, values, queries, frame, row_ids, weights=None, policy="matching-only"):
11
+ x, y, q = array(coordinates, "coordinates", 2), array(values, "values", 1), array(queries, "queries", 2)
12
+ require(
13
+ len(x) == len(y) and x.shape[1] == q.shape[1] and x.shape[1] in {2, 3},
14
+ "geometry",
15
+ "Shared two- or three-dimensional coordinates are required",
16
+ )
17
+ require(
18
+ isinstance(frame, dict)
19
+ and frame.get("kind") in {"local-metric", "geodetic-projected"}
20
+ and frame.get("axis_units") == "m"
21
+ and bool(frame.get("id"))
22
+ and bool(frame.get("source_ids")),
23
+ "metric-frame",
24
+ "Document a common metre frame and its source",
25
+ )
26
+ require(
27
+ frame.get("trajectory_assumption") in {"surveyed", "vertical-assumed", "not-applicable"},
28
+ "geometry",
29
+ "Declare trajectory evidence",
30
+ )
31
+ if x.shape[1] == 3:
32
+ require(
33
+ frame["trajectory_assumption"] != "not-applicable",
34
+ "geometry",
35
+ "Three-dimensional support requires surveyed or explicitly assumed trajectory",
36
+ )
37
+ names = ids(row_ids, len(x))
38
+ w = np.ones(len(x)) if weights is None else array(weights, "support_weights", 1)
39
+ require(
40
+ len(w) == len(x) and (w > 0).all(), "support", "Replicate weights must be positive and match rows"
41
+ )
42
+ require(policy in {"matching-only", "weighted-mean"}, "replicates", "Unknown replicate policy")
43
+ unique, inverse = np.unique(x, axis=0, return_inverse=True)
44
+ targets, groups = [], []
45
+ for i in range(len(unique)):
46
+ group = np.flatnonzero(inverse == i)
47
+ matching = np.all(y[group] == y[group[0]])
48
+ require(
49
+ matching or (policy == "weighted-mean" and weights is not None),
50
+ "coincident-conflict",
51
+ "Coincident values disagree without a declared noise/weighted-replicate policy",
52
+ row_ids=[names[j] for j in group],
53
+ )
54
+ targets.append(float(np.average(y[group], weights=w[group])))
55
+ groups.append([names[j] for j in group])
56
+ return unique, np.asarray(targets), q, groups
57
+
58
+
59
+ def idw(
60
+ coordinates,
61
+ values,
62
+ queries,
63
+ *,
64
+ frame,
65
+ power=2.0,
66
+ neighbors=16,
67
+ support_weights=None,
68
+ row_ids=None,
69
+ source_ids=(),
70
+ replicate_policy="matching-only",
71
+ ):
72
+ x, y, q, groups = _prepare(
73
+ coordinates, values, queries, frame, row_ids, support_weights, replicate_policy
74
+ )
75
+ require(
76
+ np.isfinite(power) and power > 0 and isinstance(neighbors, (int, np.integer)) and neighbors > 0,
77
+ "parameters",
78
+ "Positive IDW power and neighbor count are required",
79
+ )
80
+ distance = cdist(q, x)
81
+ estimates = []
82
+ neighbor_rows = []
83
+ sums = []
84
+ for d in distance:
85
+ exact = np.flatnonzero(d == 0)
86
+ selected = exact[:1] if len(exact) else np.argsort(d, kind="stable")[: min(neighbors, len(x))]
87
+ if len(exact):
88
+ w = np.ones(1)
89
+ else:
90
+ log_weight = -power * np.log(d[selected])
91
+ w = np.exp(log_weight - log_weight.max())
92
+ w /= w.sum()
93
+ estimates.append(float(w @ y[selected]))
94
+ sums.append(float(w.sum()))
95
+ neighbor_rows.append([groups[i] for i in selected])
96
+ return NumericalResult(
97
+ np.asarray(estimates),
98
+ dict(
99
+ frame=frame,
100
+ dimension=x.shape[1],
101
+ replicate_groups=groups,
102
+ replicate_policy=replicate_policy,
103
+ neighbors=neighbor_rows,
104
+ weight_sums=sums,
105
+ power=power,
106
+ geometry_evidence=_geometry(frame, x.shape[1]),
107
+ ),
108
+ source_ids,
109
+ )
110
+
111
+
112
+ def _geometry(frame, dimension):
113
+ if dimension == 2:
114
+ return "declared-2D-metric-support"
115
+ return (
116
+ "authored-vertical-midpoint"
117
+ if frame["trajectory_assumption"] == "vertical-assumed"
118
+ else "surveyed-support"
119
+ )
120
+
121
+
122
+ def kriging(
123
+ coordinates,
124
+ values,
125
+ queries,
126
+ *,
127
+ frame,
128
+ dimension=2,
129
+ variogram_model="spherical",
130
+ variogram_parameters=None,
131
+ nlags=6,
132
+ row_ids=None,
133
+ source_ids=(),
134
+ ):
135
+ x, y, q, groups = _prepare(coordinates, values, queries, frame, row_ids)
136
+ require(
137
+ dimension in {2, 3} and x.shape[1] == dimension,
138
+ "geometry",
139
+ "Kriging dimension must match all coordinate axes",
140
+ )
141
+ require(
142
+ len(x) >= dimension + 1 and np.linalg.matrix_rank(x - x.mean(axis=0)) == dimension,
143
+ "geometry-rank",
144
+ "Declared spatial dimensions lack independent coordinate support",
145
+ )
146
+ require(
147
+ variogram_model in {"spherical", "exponential", "gaussian"} and nlags == 6,
148
+ "variogram",
149
+ "Use a declared model and six training-only lag bins",
150
+ )
151
+ try:
152
+ from pykrige.ok import OrdinaryKriging
153
+ from pykrige.ok3d import OrdinaryKriging3D
154
+ except ImportError as exc:
155
+ raise DependencyUnavailable(
156
+ "missing-dependency", "Install processsupport[spatial] for actual PyKrige"
157
+ ) from exc
158
+ kwargs = dict(
159
+ variogram_model=variogram_model,
160
+ variogram_parameters=variogram_parameters,
161
+ nlags=nlags,
162
+ verbose=False,
163
+ enable_plotting=False,
164
+ exact_values=True,
165
+ pseudo_inv=False,
166
+ )
167
+ try:
168
+ engine = (
169
+ OrdinaryKriging(x[:, 0], x[:, 1], y, **kwargs)
170
+ if dimension == 2
171
+ else OrdinaryKriging3D(x[:, 0], x[:, 1], x[:, 2], y, **kwargs)
172
+ )
173
+ outputs, variance = engine.execute(
174
+ "points", *[q[:, j] for j in range(dimension)], backend="vectorized"
175
+ )
176
+ # Independent affine constraint diagnostic using the engine's fitted variogram.
177
+ gamma = engine.variogram_function(engine.variogram_model_parameters, cdist(x, x))
178
+ np.fill_diagonal(gamma, 0)
179
+ matrix = np.block([[gamma, np.ones((len(x), 1))], [np.ones((1, len(x))), np.zeros((1, 1))]])
180
+ require(
181
+ np.linalg.matrix_rank(matrix) == len(x) + 1,
182
+ "singular-covariance",
183
+ "Kriging constraint matrix is rank deficient",
184
+ )
185
+ right = engine.variogram_function(engine.variogram_model_parameters, cdist(x, q))
186
+ right[cdist(x, q) == 0] = 0
187
+ weights = solve(matrix, np.vstack([right, np.ones((1, len(q)))]), assume_a="sym")[:-1]
188
+ except ScientificRefusal:
189
+ raise
190
+ except (ValueError, np.linalg.LinAlgError, RuntimeError) as exc:
191
+ raise ScientificRefusal(
192
+ "kriging-engine", "Actual PyKrige fit or solve failed", details={"engine_error": str(exc)}
193
+ ) from exc
194
+ output = np.asarray(outputs, dtype=float)
195
+ raw_variance = np.asarray(variance, dtype=float)
196
+ tolerance = 1e-10 * max(float(np.var(y)), np.finfo(float).tiny)
197
+ require(
198
+ np.isfinite(output).all() and np.isfinite(raw_variance).all() and np.min(raw_variance) >= -tolerance,
199
+ "kriging-variance",
200
+ "Kriging returned nonfinite values or materially negative variance",
201
+ )
202
+ require(
203
+ np.allclose(weights.sum(axis=0), 1, atol=1e-8, rtol=1e-8),
204
+ "kriging-weights",
205
+ "Kriging weights violate ordinary mean constraint",
206
+ )
207
+ return NumericalResult(
208
+ output,
209
+ dict(
210
+ variance=np.maximum(raw_variance, 0),
211
+ raw_variance=raw_variance,
212
+ variance_roundoff_adjusted=bool(np.any(raw_variance < 0)),
213
+ variance_tolerance=tolerance,
214
+ engine="pykrige.ok.OrdinaryKriging" if dimension == 2 else "pykrige.ok3d.OrdinaryKriging3D",
215
+ frame=frame,
216
+ dimension=dimension,
217
+ geometry_evidence=_geometry(frame, dimension),
218
+ variogram_model=variogram_model,
219
+ variogram_parameters=engine.variogram_model_parameters,
220
+ weight_sums=weights.sum(axis=0),
221
+ replicate_groups=groups,
222
+ constraint_condition=float(np.linalg.cond(matrix)),
223
+ ),
224
+ source_ids,
225
+ )
@@ -0,0 +1,91 @@
1
+ """Positive declared-support compositing; no inferred wet/dry conversion."""
2
+
3
+ import numpy as np
4
+ from ._validation import array, ids, require
5
+ from .results import NumericalResult
6
+
7
+
8
+ def composite(
9
+ values,
10
+ weights,
11
+ *,
12
+ unit,
13
+ basis,
14
+ weight_basis,
15
+ missing_policy="reject",
16
+ row_ids=None,
17
+ source_ids=(),
18
+ value_bases=None,
19
+ censoring=None,
20
+ ):
21
+ v, w = array(values, "values", 1, finite=False), array(weights, "weights", 1)
22
+ require(
23
+ v.shape == w.shape and (w > 0).all(),
24
+ "support",
25
+ "Equal-length positive support weights are required",
26
+ "weights",
27
+ )
28
+ require(
29
+ bool(unit) and basis in {"dry-solids", "wet-mass", "slurry-volume", "metal-mass"},
30
+ "unit-basis",
31
+ "Declare a supported unit and physical basis",
32
+ "basis",
33
+ )
34
+ require(
35
+ weight_basis in {"mass", "length", "duration"},
36
+ "support",
37
+ "Declare mass, length or duration support",
38
+ "weight_basis",
39
+ )
40
+ require(missing_policy in {"reject", "observed-only"}, "policy", "Unknown missing-data policy")
41
+ names = ids(row_ids, len(v))
42
+ if value_bases is not None:
43
+ require(
44
+ len(value_bases) == len(v) and all(b == basis for b in value_bases),
45
+ "unit-basis",
46
+ "Physical bases cannot be mixed",
47
+ "value_bases",
48
+ )
49
+ if censoring is not None:
50
+ require(
51
+ len(censoring) == len(v) and all(c == "none" for c in censoring),
52
+ "censoring",
53
+ "A censored assay is not a point value",
54
+ "censoring",
55
+ )
56
+ observed = np.isfinite(v)
57
+ require(
58
+ observed.all() or missing_policy == "observed-only",
59
+ "missing",
60
+ "Missing values require the explicit observed-only policy",
61
+ "values",
62
+ )
63
+ require(observed.any(), "missing", "No observed value remains", "values")
64
+ with np.errstate(over="ignore", invalid="ignore"):
65
+ effective = w[observed].sum()
66
+ total = w.sum()
67
+ require(
68
+ np.isfinite(effective) and np.isfinite(total),
69
+ "support-overflow",
70
+ "Declared total support exceeds finite numerical representation",
71
+ )
72
+ contributions = np.zeros(len(v))
73
+ contributions[observed] = (w[observed] / effective) * v[observed]
74
+ value = contributions.sum()
75
+ require(np.isfinite(value), "support-overflow", "Weighted result is not finitely representable")
76
+ return NumericalResult(
77
+ float(value),
78
+ dict(
79
+ contributions=contributions.tolist(),
80
+ normalized_weights=np.where(observed, w / effective, 0).tolist(),
81
+ effective_weight=float(effective),
82
+ retained_fraction=float(effective / total),
83
+ row_ids=names,
84
+ excluded_row_ids=[names[i] for i in np.flatnonzero(~observed)],
85
+ weight_basis=weight_basis,
86
+ missing_policy=missing_policy,
87
+ ),
88
+ source_ids,
89
+ unit=unit,
90
+ basis=basis,
91
+ )