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,6 @@
1
+ """Auditable physical-support and process numerical operators."""
2
+
3
+ from .results import DependencyUnavailable, NumericalResult, ScientificRefusal
4
+
5
+ __version__ = "0.1.0"
6
+ __all__ = ["DependencyUnavailable", "NumericalResult", "ScientificRefusal", "__version__"]
@@ -0,0 +1,64 @@
1
+ """Common shape, finite, identity and covariance invariants."""
2
+
3
+ import numpy as np
4
+ from .results import ScientificRefusal
5
+
6
+
7
+ def require(condition, code, message, field=None, **details):
8
+ if not condition:
9
+ raise ScientificRefusal(code, message, field, details)
10
+
11
+
12
+ def array(value, name, ndim=None, finite=True):
13
+ try:
14
+ a = np.asarray(value, dtype=float)
15
+ except (ValueError, TypeError) as exc:
16
+ raise ScientificRefusal("numeric-type", "Expected a numeric array", name) from exc
17
+ require(a.size > 0, "empty", "Empty arrays have no scientific support", name)
18
+ if ndim is not None:
19
+ require(a.ndim == ndim, "shape", f"Expected {ndim} dimensions", name, actual=list(a.shape))
20
+ if finite:
21
+ require(
22
+ np.isfinite(a).all(),
23
+ "nonfinite",
24
+ "Nonfinite values require an explicit missing-data policy",
25
+ name,
26
+ )
27
+ return a
28
+
29
+
30
+ def ids(row_ids, n):
31
+ names = list(row_ids) if row_ids is not None else [str(i) for i in range(n)]
32
+ require(
33
+ len(names) == n and all(isinstance(name, str) and name for name in names) and len(set(names)) == n,
34
+ "identity",
35
+ "Row IDs must be unique and match rows",
36
+ "row_ids",
37
+ )
38
+ return names
39
+
40
+
41
+ def covariance(value, n, name, positive=False):
42
+ a = array(value, name, 2)
43
+ require(a.shape == (n, n), "shape", "Covariance shape does not match state", name)
44
+ scale = max(float(np.max(np.abs(a))), np.finfo(float).tiny)
45
+ require(
46
+ np.allclose(a, a.T, atol=1e-12 * scale, rtol=1e-12),
47
+ "covariance",
48
+ "Covariance must be symmetric",
49
+ name,
50
+ )
51
+ eigen = np.linalg.eigvalsh(a)
52
+ require(
53
+ eigen.min() > 0 if positive else eigen.min() >= -1e-12 * scale,
54
+ "covariance",
55
+ "Covariance must be positive definite" if positive else "Covariance must be positive semidefinite",
56
+ name,
57
+ )
58
+ return (a + a.T) / 2
59
+
60
+
61
+ def positive(value, name):
62
+ a = array(value, name)
63
+ require((a > 0).all(), "physical-domain", "Expected strictly positive physical values", name)
64
+ return a
@@ -0,0 +1,86 @@
1
+ """Release-aware alignment on an explicitly verified timebase."""
2
+
3
+ import numpy as np
4
+ from ._validation import array, ids, require
5
+ from .results import NumericalResult
6
+
7
+
8
+ def asof(
9
+ observation_times,
10
+ release_times,
11
+ values,
12
+ decision_times,
13
+ *,
14
+ max_age_s,
15
+ timebase,
16
+ row_ids=None,
17
+ source_ids=(),
18
+ availability_status=None,
19
+ retrospective=False,
20
+ ):
21
+ require(
22
+ timebase in {"verified-utc-seconds", "verified-relative-seconds"},
23
+ "timebase",
24
+ "Known UTC or relative seconds are required",
25
+ "timebase",
26
+ )
27
+ t, v = array(observation_times, "observation_times", 1), array(values, "values", 1)
28
+ decisions = array(decision_times, "decision_times", 1)
29
+ releases = array(release_times, "release_times", 1, finite=False)
30
+ require(len(t) == len(v) == len(releases), "shape", "Observation vectors must match")
31
+ require(np.isfinite(max_age_s) and max_age_s >= 0, "staleness", "Maximum age must be nonnegative")
32
+ names = ids(row_ids, len(t))
33
+ status = (
34
+ list(availability_status)
35
+ if availability_status is not None
36
+ else ["known" if np.isfinite(x) else "unknown" for x in releases]
37
+ )
38
+ require(
39
+ len(status) == len(t) and set(status) <= {"known", "bounded-upper", "unknown"},
40
+ "availability",
41
+ "Invalid availability status",
42
+ )
43
+ known = np.array([s != "unknown" and np.isfinite(r) for s, r in zip(status, releases)])
44
+ require(
45
+ np.all(releases[known] >= t[known]),
46
+ "availability",
47
+ "Release cannot precede the represented observation end",
48
+ )
49
+ selected, chosen, exclusion = [], [], []
50
+ for decision in decisions:
51
+ eligible = np.flatnonzero(
52
+ known & (t <= decision) & (releases <= decision) & (decision - t <= max_age_s)
53
+ )
54
+ if not len(eligible):
55
+ selected.append(None)
56
+ chosen.append(None)
57
+ else:
58
+ latest = eligible[t[eligible] == t[eligible].max()]
59
+ require(
60
+ np.ptp(v[latest]) == 0,
61
+ "ambiguous-release",
62
+ "Conflicting equally recent observations require a declared replicate policy",
63
+ )
64
+ index = int(latest[np.argmax(releases[latest])])
65
+ selected.append(float(v[index]))
66
+ chosen.append(names[index])
67
+ exclusion.append(
68
+ {
69
+ "unknown": [names[i] for i in np.flatnonzero(~known)],
70
+ "future": [
71
+ names[i] for i in np.flatnonzero(known & ((releases > decision) | (t > decision)))
72
+ ],
73
+ "stale": [names[i] for i in np.flatnonzero(known & (decision - t > max_age_s))],
74
+ }
75
+ )
76
+ return NumericalResult(
77
+ selected,
78
+ dict(
79
+ selected_row_ids=chosen,
80
+ exclusions=exclusion,
81
+ timebase=timebase,
82
+ availability_policy="offline-only" if retrospective else "asof-known-or-upper-bound",
83
+ retrospective=bool(retrospective),
84
+ ),
85
+ source_ids,
86
+ )
@@ -0,0 +1,119 @@
1
+ """Transparent release-aware and training-frozen reference predictors."""
2
+
3
+ import numpy as np
4
+ from .alignment import asof
5
+ from ._validation import array, require
6
+ from .results import NumericalResult
7
+
8
+
9
+ def persistence(
10
+ observation_times,
11
+ release_times,
12
+ values,
13
+ decision_times,
14
+ *,
15
+ max_age_s,
16
+ timebase,
17
+ row_ids=None,
18
+ source_ids=(),
19
+ ):
20
+ result = asof(
21
+ observation_times,
22
+ release_times,
23
+ values,
24
+ decision_times,
25
+ max_age_s=max_age_s,
26
+ timebase=timebase,
27
+ row_ids=row_ids,
28
+ source_ids=source_ids,
29
+ )
30
+ result.diagnostics["method"] = "released-predecessor-persistence"
31
+ return result
32
+
33
+
34
+ def fit_healthy_reference(train_features, *, feature_names=None, feature_units=None, source_ids=()):
35
+ x = array(train_features, "train_features", 2, finite=False)
36
+ require(
37
+ len(x) >= 2 and not np.isinf(x).any(),
38
+ "training-reference",
39
+ "At least two finite-or-missing training rows are required",
40
+ )
41
+ observed = np.sum(np.isfinite(x), axis=0)
42
+ medians = np.array(
43
+ [np.median(x[np.isfinite(x[:, i]), i]) if observed[i] else 0 for i in range(x.shape[1])]
44
+ )
45
+ filled = np.where(np.isfinite(x), x, medians)
46
+ q = np.quantile(filled, [0.25, 0.75], axis=0)
47
+ scales = (q[1] - q[0]) / 1.349
48
+ require(
49
+ np.isfinite(medians).all() and np.isfinite(scales).all(),
50
+ "reference-scale",
51
+ "Healthy-reference transforms must be finitely representable",
52
+ )
53
+ mask = (observed > 1) & (scales > 0) & (np.ptp(filled, axis=0) > 0)
54
+ require(mask.any(), "constant-reference", "No informative healthy-reference feature remains")
55
+ names = list(feature_names) if feature_names is not None else [f"feature-{i}" for i in range(x.shape[1])]
56
+ units = list(feature_units) if feature_units is not None else ["unspecified"] * x.shape[1]
57
+ require(
58
+ len(names) == len(units) == x.shape[1] and len(set(names)) == len(names),
59
+ "feature-order",
60
+ "Feature metadata must match columns",
61
+ )
62
+ return dict(
63
+ schema_version="1.0.0",
64
+ medians=medians.tolist(),
65
+ scales=scales.tolist(),
66
+ mask=mask.tolist(),
67
+ observed_counts=observed.tolist(),
68
+ feature_names=names,
69
+ feature_units=units,
70
+ source_ids=list(source_ids),
71
+ )
72
+
73
+
74
+ def healthy_distance(reference, query_features, *, clip=5.0, source_ids=()):
75
+ x = array(query_features, "query_features", 2, finite=False)
76
+ require(
77
+ isinstance(reference, dict) and {"medians", "scales", "mask"} <= set(reference),
78
+ "reference-state",
79
+ "Healthy reference is missing its frozen numerical transforms",
80
+ )
81
+ require(
82
+ isinstance(reference["mask"], list) and all(isinstance(v, bool) for v in reference["mask"]),
83
+ "reference-state",
84
+ "Restored reference mask must contain actual booleans",
85
+ )
86
+ med, scale = (
87
+ array(reference["medians"], "reference.medians", 1),
88
+ array(reference["scales"], "reference.scales", 1),
89
+ )
90
+ mask = np.asarray(reference["mask"], dtype=bool)
91
+ require(
92
+ x.shape[1] == len(med) == len(scale) == len(mask) and mask.any(),
93
+ "feature-order",
94
+ "Reference and query columns do not match",
95
+ )
96
+ require(
97
+ clip > 0 and np.isfinite(clip) and np.all(scale[mask] > 0) and np.all(scale >= 0),
98
+ "reference-scale",
99
+ "Healthy-reference scales and clip must be positive",
100
+ )
101
+ require(not np.isinf(x).any(), "nonfinite", "Infinite query features are invalid")
102
+ imputed = ~np.isfinite(x)
103
+ filled = np.where(imputed, med, x)
104
+ z = (filled[:, mask] - med[mask]) / scale[mask]
105
+ score = np.mean(np.minimum(np.abs(z), clip) ** 2, axis=1)
106
+ changed = np.any(filled[:, ~mask] != med[~mask], axis=1) if (~mask).any() else np.zeros(len(x), bool)
107
+ return NumericalResult(
108
+ score,
109
+ dict(
110
+ feature_mask=mask,
111
+ changed_dropped_feature=changed,
112
+ imputed_cells=imputed,
113
+ clip=clip,
114
+ reference=reference,
115
+ score="mean-clipped-squared-robust-standardized-distance",
116
+ ),
117
+ source_ids,
118
+ unit="dimensionless",
119
+ )
@@ -0,0 +1,38 @@
1
+ """Explicit Kuznetsov-Cunningham empirical fragmentation convention."""
2
+
3
+ from ._validation import positive, require
4
+ from .results import NumericalResult
5
+
6
+
7
+ def kuznetsov(
8
+ rock_factor, rock_volume_m3, explosive_kg, relative_strength_pct, *, size_unit="cm", source_ids=()
9
+ ):
10
+ require(size_unit in {"cm", "mm"}, "units", "Fragment-size output must be cm or mm")
11
+ a, volume, charge, strength = [
12
+ positive(x, n)
13
+ for x, n in zip(
14
+ [rock_factor, rock_volume_m3, explosive_kg, relative_strength_pct],
15
+ ["rock_factor", "rock_volume_m3", "explosive_kg", "relative_strength_pct"],
16
+ )
17
+ ]
18
+ require(
19
+ all(value.ndim == 0 for value in [a, volume, charge, strength]),
20
+ "shape",
21
+ "Fragmentation reference inputs are scalar quantities",
22
+ )
23
+ value = a * (volume / charge) ** 0.8 * charge ** (1 / 6) * (115 / strength) ** (19 / 30)
24
+ if size_unit == "mm":
25
+ value = value * 10
26
+ return NumericalResult(
27
+ float(value),
28
+ dict(
29
+ powder_factor_kg_m3=float(charge / volume),
30
+ convention="Cunningham-adapted Kuz-Ram median x50 cm=A*(V/Q)^0.8*Q^(1/6)*(115/RWS)^(19/30); RWS ANFO=100, TNT=115",
31
+ original_kuznetsov_quantity="mean fragment size; not relabelled as a median",
32
+ empirical=True,
33
+ calibration="not-established",
34
+ operational_recommendation=False,
35
+ ),
36
+ source_ids,
37
+ unit=size_unit,
38
+ )
@@ -0,0 +1,34 @@
1
+ """Bond reference: micrometre sizes and kWh per dry tonne work index."""
2
+
3
+ import numpy as np
4
+ from ._validation import positive, require
5
+ from .results import NumericalResult
6
+
7
+
8
+ def bond(f80, p80, work_index, *, size_unit="um", work_index_unit="kWh/t", source_ids=()):
9
+ require(
10
+ size_unit in {"um", "mm", "m"} and work_index_unit == "kWh/t",
11
+ "units",
12
+ "Bond requires known length and kWh/t work-index units",
13
+ )
14
+ factor = {"um": 1.0, "mm": 1000.0, "m": 1e6}[size_unit]
15
+ f, p, wi = (
16
+ positive(f80, "f80") * factor,
17
+ positive(p80, "p80") * factor,
18
+ positive(work_index, "work_index"),
19
+ )
20
+ require(np.all(f > p), "physical-domain", "Feed F80 must exceed product P80")
21
+ value = 10 * wi * (1 / np.sqrt(p) - 1 / np.sqrt(f))
22
+ return NumericalResult(
23
+ float(value) if value.ndim == 0 else value,
24
+ dict(
25
+ f80_um=f,
26
+ p80_um=p,
27
+ work_index_kwh_t=wi,
28
+ empirical=True,
29
+ coefficient_convention="10 with micrometres and kWh/t; not plant calibration",
30
+ ),
31
+ source_ids,
32
+ unit="kWh/t",
33
+ basis="dry-solids",
34
+ )
@@ -0,0 +1,175 @@
1
+ """Bounded batch kinetic reference models; no implied full-plant transport."""
2
+
3
+ import numpy as np
4
+ from scipy.optimize import least_squares, brentq
5
+ from ._validation import array, require
6
+ from .results import NumericalResult, ScientificRefusal
7
+
8
+
9
+ def _data(times, values, time_unit):
10
+ t, y = array(times, "times", 1), array(values, "values", 1)
11
+ require(
12
+ t.shape == y.shape and len(np.unique(t[t > 0])) >= 5,
13
+ "sampling",
14
+ "At least five distinct positive times are required",
15
+ )
16
+ require(np.all(t >= 0) and np.all(np.diff(t) > 0), "timebase", "Times must increase and be nonnegative")
17
+ require(time_unit in {"s", "min", "h"}, "units", "Declare a supported time unit")
18
+ require(
19
+ np.all((y >= 0) & (y <= 1)),
20
+ "fraction-domain",
21
+ "Measured conversion/recovery must be a fraction in [0,1]",
22
+ )
23
+ require(np.ptp(y) > 1e-12, "identification", "A constant response cannot identify a kinetic law")
24
+ return t, y
25
+
26
+
27
+ def _flotation_curve(t, rate, asymptote, family):
28
+ u = rate * t
29
+ if family == "first-order":
30
+ return asymptote * (-np.expm1(-u))
31
+ ratio = np.ones_like(u)
32
+ np.divide(-np.expm1(-u), u, out=ratio, where=u != 0)
33
+ return asymptote * (1 - ratio)
34
+
35
+
36
+ def _fit_flotation(t, y, family, max_nfev):
37
+ time_scale = float(t.max())
38
+ candidates = []
39
+ for start in np.logspace(-2, 2, 4):
40
+ opt = least_squares(
41
+ lambda p: _flotation_curve(t, p[0] / time_scale, p[1], family) - y,
42
+ [start, min(0.999999, max(0.01, float(y.max())))],
43
+ bounds=([1e-12, 0], [1e6, 1]),
44
+ max_nfev=max_nfev,
45
+ ftol=1e-12,
46
+ xtol=1e-12,
47
+ gtol=1e-12,
48
+ )
49
+ if opt.success:
50
+ candidates.append(opt)
51
+ if not candidates:
52
+ raise ScientificRefusal("nonconvergence", "No bounded kinetic start converged")
53
+ opt = min(candidates, key=lambda o: float(o.fun @ o.fun))
54
+ return opt, np.array([opt.x[0] / time_scale, opt.x[1]])
55
+
56
+
57
+ def fit_flotation(
58
+ times,
59
+ recovery,
60
+ *,
61
+ family="first-order",
62
+ time_unit="min",
63
+ max_nfev=2000,
64
+ bootstrap_samples=200,
65
+ seed=11,
66
+ source_ids=(),
67
+ ):
68
+ require(family in {"first-order", "rectangular-rate"}, "family", "Unsupported flotation family")
69
+ require(
70
+ 1 <= max_nfev <= 2000 and 0 <= bootstrap_samples <= 200,
71
+ "budget",
72
+ "Kinetic fit/bootstrap budget exceeded",
73
+ )
74
+ t, y = _data(times, recovery, time_unit)
75
+ opt, params = _fit_flotation(t, y, family, max_nfev)
76
+ fitted = _flotation_curve(t, *params, family)
77
+ rank = np.linalg.matrix_rank(opt.jac)
78
+ condition = float(np.linalg.cond(opt.jac))
79
+ residual = y - fitted
80
+ samples = []
81
+ failures = 0
82
+ rng = np.random.default_rng(seed)
83
+ for _ in range(bootstrap_samples):
84
+ generated = fitted + rng.choice(residual - residual.mean(), len(t), replace=True)
85
+ # Bootstrap draws outside fractional measurement support are refused, not clipped.
86
+ if np.any((generated < 0) | (generated > 1)):
87
+ failures += 1
88
+ continue
89
+ try:
90
+ _, parameter = _fit_flotation(t, generated, family, max_nfev)
91
+ samples.append(parameter)
92
+ except ScientificRefusal:
93
+ failures += 1
94
+ interval = np.quantile(samples, [0.025, 0.975], axis=0).tolist() if len(samples) >= 2 else None
95
+ identified = bool(rank == 2 and condition < 1e8)
96
+ return NumericalResult(
97
+ fitted,
98
+ dict(
99
+ parameters={"rate": float(params[0]), "asymptote": float(params[1])},
100
+ rate_unit="1/" + time_unit,
101
+ rate_interpretation="single rate"
102
+ if family == "first-order"
103
+ else "upper limit of a uniform rate distribution; its mean is rate/2",
104
+ family=family,
105
+ rank=int(rank),
106
+ condition=condition,
107
+ identified=identified,
108
+ residuals=fitted - y,
109
+ bounds={"asymptote": [0.0, 1.0], "dimensionless_rate": [1e-12, 1e6]},
110
+ bootstrap={
111
+ "requested": bootstrap_samples,
112
+ "successful": len(samples),
113
+ "refused": failures,
114
+ "parameter_percentiles_95": interval,
115
+ "coverage_claim": False,
116
+ },
117
+ nfev=int(opt.nfev),
118
+ ),
119
+ source_ids,
120
+ status="available" if identified else "partial",
121
+ unit="fraction",
122
+ )
123
+
124
+
125
+ def fit_leach(times, conversion, *, family="reaction-control", time_unit="min", max_nfev=2000, source_ids=()):
126
+ require(
127
+ family in {"reaction-control", "diffusion-control"}, "family", "Unsupported shrinking-core family"
128
+ )
129
+ require(1 <= max_nfev <= 2000, "budget", "Fit budget cannot exceed 2000 evaluations")
130
+ t, x = _data(times, conversion, time_unit)
131
+
132
+ def transform(z):
133
+ if family == "reaction-control":
134
+ return 1 - np.cbrt(1 - z)
135
+ return 1 - 3 * np.cbrt(1 - z) ** 2 + 2 * (1 - z)
136
+
137
+ target = transform(x)
138
+ initial = max(float(t @ target / (t @ t)), np.finfo(float).eps / t.max())
139
+ opt = least_squares(
140
+ lambda k: k[0] * t - target,
141
+ [initial],
142
+ bounds=(0, np.inf),
143
+ max_nfev=max_nfev,
144
+ ftol=1e-12,
145
+ xtol=1e-12,
146
+ gtol=1e-12,
147
+ )
148
+ if not opt.success:
149
+ raise ScientificRefusal("nonconvergence", "Leaching fit did not converge")
150
+ rate = float(opt.x[0])
151
+ fitted = []
152
+ for ti in t:
153
+ z = rate * ti
154
+ fitted.append(
155
+ 0.0 if z <= 0 else 1.0 if z >= 1 else brentq(lambda a: transform(a) - z, 0, 1, xtol=1e-13)
156
+ )
157
+ profile_rates = rate * np.linspace(0.1, 2, 13)
158
+ profile = [float(np.mean((k * t - target) ** 2)) for k in profile_rates]
159
+ return NumericalResult(
160
+ np.asarray(fitted),
161
+ dict(
162
+ parameters={"rate": rate},
163
+ rate_unit="1/" + time_unit,
164
+ family=family,
165
+ rank=int(np.linalg.matrix_rank(opt.jac)),
166
+ condition=float(np.linalg.cond(opt.jac)),
167
+ conversion_range=[float(x.min()), float(x.max())],
168
+ transformed_residuals=rate * t - target,
169
+ rate_profile={"rates": profile_rates, "objective": profile},
170
+ family_discrimination="not-established-by-single-family-fit",
171
+ nfev=int(opt.nfev),
172
+ ),
173
+ source_ids,
174
+ unit="fraction",
175
+ )
@@ -0,0 +1,61 @@
1
+ """Linear Gaussian observer with a Joseph covariance update and no silent clipping."""
2
+
3
+ import numpy as np
4
+ from scipy.linalg import solve
5
+ from ._validation import array, covariance, require
6
+ from .results import NumericalResult, ScientificRefusal
7
+
8
+
9
+ def kalman(
10
+ F, H, Q, R, observations, initial_state, initial_covariance, *, nonnegative=False, dt_s=1.0, source_ids=()
11
+ ):
12
+ f, h, y = array(F, "F", 2), array(H, "H", 2), array(observations, "observations", 2)
13
+ x = array(initial_state, "initial_state", 1).copy()
14
+ n = len(x)
15
+ q = y.shape[1]
16
+ require(f.shape == (n, n) and h.shape == (q, n), "shape", "Observer matrix dimensions do not match")
17
+ require(np.isfinite(dt_s) and dt_s > 0, "timebase", "Declare a positive discrete time step")
18
+ p = covariance(initial_covariance, n, "initial_covariance")
19
+ process, measurement = covariance(Q, n, "Q"), covariance(R, q, "R")
20
+ states, covariances, innovations, ranks = [], [], [], []
21
+ for row in y:
22
+ prior = f @ x
23
+ pp = f @ p @ f.T + process
24
+ innovation = row - h @ prior
25
+ s = h @ pp @ h.T + measurement
26
+ rank = np.linalg.matrix_rank(s)
27
+ ranks.append(int(rank))
28
+ if rank == q:
29
+ gain = solve(s, h @ pp, assume_a="sym").T
30
+ else:
31
+ inverse = np.linalg.pinv(s, hermitian=True)
32
+ require(
33
+ np.linalg.norm(innovation - s @ inverse @ innovation)
34
+ <= 1e-10 * max(1.0, np.linalg.norm(row)),
35
+ "deterministic-inconsistency",
36
+ "Observation contradicts a zero-variance direction",
37
+ )
38
+ gain = pp @ h.T @ inverse
39
+ x = prior + gain @ innovation
40
+ a = np.eye(n) - gain @ h
41
+ p = a @ pp @ a.T + gain @ measurement @ gain.T
42
+ p = covariance(p, n, "posterior_covariance")
43
+ states.append(x.copy())
44
+ covariances.append(p.copy())
45
+ innovations.append(innovation)
46
+ result = np.asarray(states)
47
+ details = dict(
48
+ covariances=np.asarray(covariances),
49
+ innovations=np.asarray(innovations),
50
+ innovation_ranks=ranks,
51
+ dt_s=dt_s,
52
+ state_rounding_tolerance=1e-10,
53
+ )
54
+ if nonnegative and np.any(result < -1e-10):
55
+ raise ScientificRefusal(
56
+ "negative-state",
57
+ "Unconstrained observer produces a negative physical state",
58
+ reference={"name": "unconstrained-linear-observer", "states": result, "diagnostics": details},
59
+ )
60
+ details["rounding_negative"] = bool(np.any(result < 0))
61
+ return NumericalResult(result, details, source_ids)
@@ -0,0 +1,65 @@
1
+ """Constrained Rosin-Rammler cumulative particle-size fit."""
2
+
3
+ import numpy as np
4
+ from scipy.optimize import least_squares
5
+ from ._validation import array, positive, require
6
+ from .results import NumericalResult, ScientificRefusal
7
+
8
+
9
+ def fit_rosin_rammler(sizes, cumulative_fraction, *, size_unit="um", max_nfev=2000, source_ids=()):
10
+ x, y = positive(sizes, "sizes"), array(cumulative_fraction, "cumulative_fraction", 1)
11
+ require(
12
+ x.ndim == 1 and x.shape == y.shape and len(x) >= 3,
13
+ "shape",
14
+ "At least three size/fraction pairs are required",
15
+ )
16
+ require(size_unit in {"um", "mm", "m"}, "units", "Declare a length unit")
17
+ require(
18
+ np.all(np.diff(x) > 0) and np.all(np.diff(y) >= 0) and np.all((y >= 0) & (y <= 1)),
19
+ "cumulative-domain",
20
+ "Sizes must increase and cumulative fractions must not decrease",
21
+ )
22
+ require(
23
+ np.ptp(y) > 0 and np.sum((y > 0) & (y < 1)) >= 2,
24
+ "identification",
25
+ "Insufficient uncensored particle-size information",
26
+ )
27
+ require(1 <= max_nfev <= 2000, "budget", "Fit budget cannot exceed 2000 evaluations")
28
+
29
+ def curve(params):
30
+ scale, shape = np.exp(params)
31
+ power = np.exp(np.clip(shape * np.log(x / scale), -700, 700))
32
+ return -np.expm1(-power)
33
+
34
+ bounds = ([np.log(x.min() * 1e-6), np.log(1e-6)], [np.log(x.max() * 1e6), np.log(100)])
35
+ opt = least_squares(
36
+ lambda p: curve(p) - y,
37
+ [np.log(np.median(x)), 0],
38
+ bounds=bounds,
39
+ max_nfev=max_nfev,
40
+ ftol=1e-12,
41
+ xtol=1e-12,
42
+ gtol=1e-12,
43
+ )
44
+ if not opt.success:
45
+ raise ScientificRefusal(
46
+ "nonconvergence", "Particle-size fit did not converge", details={"solver": opt.message}
47
+ )
48
+ rank = np.linalg.matrix_rank(opt.jac)
49
+ require(rank == 2, "identification", "Particle-size parameters are rank deficient")
50
+ scale, shape = np.exp(opt.x)
51
+ return NumericalResult(
52
+ curve(opt.x),
53
+ dict(
54
+ parameters={"scale": float(scale), "shape": float(shape)},
55
+ residuals=curve(opt.x) - y,
56
+ rank=int(rank),
57
+ condition=float(np.linalg.cond(opt.jac)),
58
+ parameterization="positive log scale and log shape",
59
+ nfev=int(opt.nfev),
60
+ bounds={"scale": [float(x.min() * 1e-6), float(x.max() * 1e6)], "shape": [1e-6, 100.0]},
61
+ p80=float(scale * (-np.log(0.2)) ** (1 / shape)),
62
+ ),
63
+ source_ids,
64
+ unit="fraction",
65
+ )