diff --git a/config/bento1-material-consumption.yaml b/config/bento1-material-consumption.yaml index 8431d82..3661d2a 100644 --- a/config/bento1-material-consumption.yaml +++ b/config/bento1-material-consumption.yaml @@ -1,4 +1,4 @@ -# Fresh bentonite only: the recycled/recovered third spreader is excluded. +# Fresh bentonite only: spreader 3 is a separate material source and is excluded. calculations: - id: bento1-fresh-bentonite-consumption type: material_consumption diff --git a/config/bento1-spreader3-material-consumption.yaml b/config/bento1-spreader3-material-consumption.yaml new file mode 100644 index 0000000..e8f49a8 --- /dev/null +++ b/config/bento1-spreader3-material-consumption.yaml @@ -0,0 +1,19 @@ +# Bentonite calibration only. Material identity is not inferred; no total aggregation. +calculations: + - id: bento1-spreader3-consumption + type: material_consumption + version: "1" + machine_ref: 5f42a4f6-9ca0-4f6f-9786-40d50a35b230 + process_application_calculation_id: bento1-spreader3-application + source_mode: linear_signal_discharge + application_signal_refs: + - c5611859-275c-44c4-aec0-dfaccc87d478 + calibration_ref: bento1-spreader-3-bentonite + gate_signal_ref: fef41976-1103-4090-b780-eaeecc02fdfa + gate_threshold: 0.3 + max_sample_gap_seconds: 20.0 + erp_workplace: Bento 1 + production_order_format: "Bento 1-{production_order}" + output_metric: material_consumption + output_unit: kg + group_by: production_order diff --git a/config/material-calibrations.yaml b/config/material-calibrations.yaml index 948ea1d..0796e84 100644 --- a/config/material-calibrations.yaml +++ b/config/material-calibrations.yaml @@ -12,3 +12,14 @@ calibrations: signal_values: left: 1.65 right: 1.75 + bento1-spreader-3-bentonite: + type: linear_signal_discharge + value: 0.4691089108910891 + unit: kg_per_signal_unit_m + calibrated_at: 2026-09-08 + method: gravimetric_tray + description: Bento 1 spreader 3, bentonite + reference: + measured_application_g_m2: 618 + signal_value: 3.03 + line_speed_m_min: 2.3 diff --git a/docs/bento1-fresh-bentonite.md b/docs/bento1-fresh-bentonite.md index 799e1bc..5a831dc 100644 --- a/docs/bento1-fresh-bentonite.md +++ b/docs/bento1-fresh-bentonite.md @@ -3,8 +3,7 @@ ## Three distinct quantities -All **fresh bentonite** values exclude the third recycled/recovered-material -scatterer. Only the two actual rpm signals listed below are used; no SET signals +All **fresh bentonite** values exclude the separate spreader 3. Only the two actual rpm signals listed below are used; no SET signals are introduced. The specific discharge is central calibration data: **2.75 kg/(revolution × metre product width)**. @@ -56,7 +55,7 @@ Scope Grafana queries by calculation ID and `material_snapshot_timestamp` for auditability. `config/bento1-material-consumption.yaml` opts into process snapshots through -`process_application_calculation_id`. This generic option requires rotational +`process_application_calculation_id`. This generic option requires calibrated sources and a positive speed gate. Both outputs reuse the same configured ACT signals, discharge factor and samples. Process points use source timestamps, including bootstrap samples from disjoint runs; no interpolation or hold-forward @@ -103,7 +102,7 @@ cleanup was performed as part of this implementation. `config/bento1-material-consumption.yaml` defines `bento1-fresh-bentonite-consumption`, an estimate of **fresh bentonite consumption** from actual spreader roll speeds. Both needle rolls apply sequentially across the -full web width. The recycled/recovered third spreader is excluded. +full web width. Spreader 3 is excluded. The generic `rotational_discharge` source converts one or more rpm signals to the existing integrator's kg/h: `sum(rpm) × nominal_width_m × specific_discharge_kg_per_rev_m × 60`. @@ -155,6 +154,83 @@ and persistence semantics. Tests use realistic rpm values and synthetic samples, including disjoint-run bootstrap and persisted resume. They are not a new replay of recorded ENLYZE data. +## Separate spreader 3 material source + +Spreader 1+2 remains fresh bentonite from actual roll rpm, calibrated at +**2.75 kg/(rev*m)**. Spreader 3 is a separate material source: it can contain +bentonite or sand depending on the product. No material identity is inferred, +and no spreader-3 value is added to fresh-bentonite consumption or efficiency. +No total-bentonite aggregate or sand calibration is implemented. + +`config/bento1-spreader3-material-consumption.yaml` uses generic +`linear_signal_discharge` with central calibration +`bento1-spreader-3-bentonite`: **0.4691089108910891 kg/(signal_unit*m)**, +gravimetric tray, 2026-09-08. Reference: **3.03 signal @ 2.3 m/min → 618 g/m²**. +The exact factor is `618 * 2.3 / (3.03 * 1000) = 2369/5050`; the supplied +approximation 0.4693069307 differs from this measurement-derived value. +Source `c5611859-275c-44c4-aec0-dfaccc87d478`, display name +“Austragsbehälter Austragsschnecke Geschwindigkeit Istwert”, origin +`AUFSTREUUNG_2/DischargeHopper_Output_Screw/ACT_Speed`. +ENLYZE's kg/m² metadata is not used as physical truth. Observed values on +2026-09-09 were around 3.0 during operation and 0.0 when inactive. + +- Application: `signal_sum * factor * 1000 / line_speed_m_min`, independent of width. +- Consumption rate: `signal_sum * factor * nominal_width_m` in kg/min, + multiplied by 60 for the existing kg/h integrator. This equals + `application_g_m2 * nominal_width_m * line_speed_m_min / 1000`. +- Same ERP nominal-width provider, `Bento 1-{production_order}` formatting, + gate signal `fef41976-1103-4090-b780-eaeecc02fdfa` strictly > 0.3 m/min, + previous-value integration, 20-second maximum gap, and disjoint-run boundaries. +- Application points are emitted only while the gate is active; zero source + signal emits zero application during production. + +| Calculation ID | Persistence | +| --- | --- | +| `bento1-spreader3-application` | `material_application_snapshots.application_g_m2` | +| `bento1-spreader3-consumption` | `material_consumption_snapshots.consumption_kg` | + +The new linear source namespaces JSON checkpoints under +`//`; existing 1+2 and K7 +checkpoint paths remain unchanged. Use a separate supervised consumption runner +with the spreader-3 config. No schema changes are needed if the existing generic +snapshot tables are present; otherwise apply `db/schema.sql` before starting it. +Do not reset 1+2 state. No migration, deployment, or service restart was performed. + +Production validation, 30 Sep 2026 10:00–13:00 Europe/Berlin, order `12026000984`, +article `180205` (Bfix NSP 4900, 5,00 x 40 m): `8.999 @ 4.999 m/min` gives +**844.471112 g/m²**. Adding the measured 1+2 average of 3915.961 gives +**4760.432112 g/m²**, within the expected 4400–4800 range. + +Before redeployment, stop the spreader 3 runner and back up its checkpoints and +snapshots. Clear only its consumption checkpoint directory: +`/c8d0426504f2ce2ff214818e4ffa9b4daf4182131c0af3c5a1cca23a3dee566a/`. +With the default state root this is +`/opt/git-projects/production-analytics/data/state/material/c8d0426504f2ce2ff214818e4ffa9b4daf4182131c0af3c5a1cca23a3dee566a/`. +There is no separate application checkpoint directory. Clear all affected snapshot +rows, across orders and timestamps, using these exact predicates: + +```sql +DELETE FROM material_application_snapshots +WHERE calculation_id = 'bento1-spreader3-application' + AND machine_id = '5f42a4f6-9ca0-4f6f-9786-40d50a35b230'; +DELETE FROM material_consumption_snapshots +WHERE calculation_id = 'bento1-spreader3-consumption' + AND machine_id = '5f42a4f6-9ca0-4f6f-9786-40d50a35b230'; +``` + +Perform cleanup before restarting with the corrected model; arrange a replay for +historical orders if corrected history is needed. Snapshot writes use +`ON CONFLICT DO NOTHING`, so existing application rows cannot correct themselves. +Leave spreaders 1+2 and K7 checkpoints and snapshots intact. These are instructions +only; no stored data has been deleted by this code change. + +This calibration is valid only for bentonite. Enable this runner only for +validated bentonite operation; until reliable material identification is available, +its output is a bentonite-calibrated estimate, not material-aware consumption. +Future sand support needs independently measured calibration and reliable +material/order attribution, with explicit handling of material changes and +checkpoint/history separation. Current ERP width is assumed constant per order. + ## Historical migration from SET to rpm: review before execution The following records the earlier source-model migration, **not a prerequisite diff --git a/docs/material-calibrations.md b/docs/material-calibrations.md index 7a52bd5..2fb881d 100644 --- a/docs/material-calibrations.md +++ b/docs/material-calibrations.md @@ -2,7 +2,7 @@ Process calibration values live in the version-controlled `config/material-calibrations.yaml`. Calculations refer to opaque IDs; IDs have -no special meaning to the parser. The current entry is: +no special meaning to the parser. The spreader 1+2 entry is: ```yaml calibrations: @@ -40,7 +40,7 @@ consumption; the calculation algorithms are unchanged. There is no unit conversi Missing/unreadable files, missing IDs, invalid metadata and incompatible type or unit raise `CalculationConfigError` before a runner starts. Existing direct numeric configurations remain supported; specifying both a reference and a direct factor -is rejected. References are currently supported by rotational discharge consumers. +is rejected. References are supported by rotational discharge and linear signal application consumers. K7 uses direct mass rate and does not load or require a calibration file. ## Updating a calibration @@ -67,7 +67,37 @@ On 2026-09-08, an independent gravimetric tray measurement found 4068 g/m² at rounded factor **2.75 kg/(rev*m)**. The original measurement remains recorded, without fitting or adjusting the runtime value to reproduce it exactly. -Only fresh-bentonite spreaders 1 and 2 are included. Before adding spreader 3, -confirm its material scope, actual signal units, independent calibration and -whether its output belongs in the fresh-material KPIs. No spreader 3 support is -included here. +Spreader 3 has an independent entry in the same registry: + +```yaml + bento1-spreader-3-bentonite: + type: linear_signal_discharge + value: 0.4691089108910891 + unit: kg_per_signal_unit_m + calibrated_at: 2026-09-08 + method: gravimetric_tray + description: Bento 1 spreader 3, bentonite + reference: + measured_application_g_m2: 618 + signal_value: 3.03 + line_speed_m_min: 2.3 +``` + +The generic linear consumer requires type `linear_signal_discharge`, unit +`kg_per_signal_unit_m`, a positive value, and an explicit calibration reference. +It resolves `specific_discharge_kg_per_signal_unit_m`; this runtime field cannot +be configured directly as a substitute for the central reference. +Calibration measurement: **3.03 signal @ 2.3 m/min → 618 g/m²**. +The exact derived discharge factor is `618 * 2.3 / (3.03 * 1000) = 2369/5050`, +stored at float precision as **0.4691089108910891 kg/(signal_unit*m)**. +The previously supplied approximation 0.4693069307 does not equal that expression. +Application is `signal_sum * factor * 1000 / line_speed_m_min`, independent of width. +Mass flow is `signal_sum * factor * nominal_width_m` kg/min, independent of speed; +the existing kg/h integrator receives this discharge multiplied by 60. + +This measured bentonite calibration does not establish physical units from +ENLYZE metadata and must not be used for sand. Spreader 3 may carry sand on other +products. Its application, consumption and checkpoints remain separate from +fresh-bentonite spreaders 1+2, with no inferred material identity or automatic +sum. See [Bento material documentation](bento1-fresh-bentonite.md) for configuration, +formulas and operating assumptions. diff --git a/src/production_analytics/calculations/config.py b/src/production_analytics/calculations/config.py index 855a551..0ddbc67 100644 --- a/src/production_analytics/calculations/config.py +++ b/src/production_analytics/calculations/config.py @@ -59,6 +59,7 @@ class MaterialCalculationConfig: rotational_speed_signal_refs: tuple[str, ...] = () specific_discharge_kg_per_rev_m: float | None = None calibration_ref: str | None = None + specific_discharge_kg_per_signal_unit_m: float | None = None erp_workplace: str = "" production_order_format: str = "" process_application_calculation_id: str | None = None @@ -92,10 +93,11 @@ def load_material_calculation( raise CalculationConfigError(f"{prefix}.type: only 'material_consumption' is supported") area = entry.get("source_mode", "direct_mass_rate") == "area_application" rotational = entry.get("source_mode") == "rotational_discharge" + linear = entry.get("source_mode") == "linear_signal_discharge" if rotational: entry.setdefault("gate_signal_ref", None) entry.setdefault("gate_threshold", 0.0) - if area or rotational: + if area or rotational or linear: entry.setdefault("rate_signal_ref", "unused") missing = required - entry.keys() if missing: @@ -121,9 +123,10 @@ def load_material_calculation( mode = entry.get("source_mode", "direct_mass_rate") if not isinstance(mode, str) or mode not in { "direct_mass_rate", "area_application", "rotational_discharge", + "linear_signal_discharge", }: raise CalculationConfigError("Unsupported material source_mode") - if area or rotational: + if area or rotational or linear: refs_name = "rotational_speed_signal_refs" if rotational else "application_signal_refs" other = "application_signal_refs" if rotational else "rotational_speed_signal_refs" if other in entry: @@ -152,8 +155,8 @@ def load_material_calculation( )): raise CalculationConfigError("Width context fields require a width-based source mode") if "calibration_ref" in entry: - if not rotational: - raise CalculationConfigError("calibration_ref requires rotational_discharge") + if not (rotational or linear): + raise CalculationConfigError("calibration_ref requires a calibrated source mode") if "specific_discharge_kg_per_rev_m" in entry: raise CalculationConfigError( "Specify calibration_ref or direct specific discharge, not both" @@ -166,9 +169,23 @@ def load_material_calculation( calibrations = load_calibrations(Path(path).parent / "material-calibrations.yaml") calibration = resolve_calibration( calibrations, entry["calibration_ref"], - expected_type="rotational_discharge", expected_unit="kg_per_rev_m", + expected_type=mode, + expected_unit="kg_per_signal_unit_m" if linear else "kg_per_rev_m", ) - entry["specific_discharge_kg_per_rev_m"] = calibration.value + factor_name = ("specific_discharge_kg_per_signal_unit_m" if linear + else "specific_discharge_kg_per_rev_m") + if factor_name in entry: + raise CalculationConfigError("Specify calibration_ref only, not a direct factor") + entry[factor_name] = calibration.value + if linear: + if "calibration_ref" not in entry: + raise CalculationConfigError("linear_signal_discharge requires calibration_ref") + entry["specific_discharge_kg_per_signal_unit_m"] = finite_number( + entry["specific_discharge_kg_per_signal_unit_m"], + "specific_discharge_kg_per_signal_unit_m", positive=True, + ) + elif "specific_discharge_kg_per_signal_unit_m" in entry: + raise CalculationConfigError("Signal discharge factor requires linear_signal_discharge") if rotational: entry["specific_discharge_kg_per_rev_m"] = finite_number( entry.get("specific_discharge_kg_per_rev_m"), @@ -183,9 +200,10 @@ def load_material_calculation( raise CalculationConfigError( "process application ID must be a distinct non-empty string" ) - if not rotational or not entry["gate_signal_ref"] or entry["gate_threshold"] <= 0: + if (not (rotational or linear) or not entry["gate_signal_ref"] + or entry["gate_threshold"] <= 0): raise CalculationConfigError( - "Process application requires rotational_discharge and a positive speed gate" + "Process application requires a calibrated source and a positive speed gate" ) if entry["id"] in instances: raise CalculationConfigError("Calculation ids must be unique") diff --git a/src/production_analytics/calculations/material_application.py b/src/production_analytics/calculations/material_application.py index 83c2627..a732111 100644 --- a/src/production_analytics/calculations/material_application.py +++ b/src/production_analytics/calculations/material_application.py @@ -1,4 +1,4 @@ -"""Width-independent process application from actual rotational speeds.""" +"""Width-independent process application from calibrated source signals.""" from collections.abc import Iterable from math import isfinite @@ -23,3 +23,15 @@ def rotational_application_g_m2( if not isfinite(value): raise ValueError("derived application must be finite") return value + + + +def linear_signal_discharge_g_m2( + signal_values: Iterable[float], specific_discharge_kg_per_signal_unit_m: float, + line_speed_m_min: float, gate_threshold: float, +) -> float | None: + """Derive speed-normalized application from calibrated signal discharge.""" + return rotational_application_g_m2( + signal_values, specific_discharge_kg_per_signal_unit_m, + line_speed_m_min, gate_threshold, + ) diff --git a/src/production_analytics/calculations/material_consumption.py b/src/production_analytics/calculations/material_consumption.py index 475a5cb..bdbee0d 100644 --- a/src/production_analytics/calculations/material_consumption.py +++ b/src/production_analytics/calculations/material_consumption.py @@ -138,3 +138,13 @@ def rotational_discharge_rate_kg_per_hour( if not isfinite(rate): raise ValueError("derived material rate must be finite") return rate + + +def linear_signal_discharge_rate_kg_per_hour( + signal_values: Iterable[float], nominal_width_m: float, + specific_discharge_kg_per_signal_unit_m: float, +) -> float: + """Convert calibrated signal discharge to kg/h, independently of line speed.""" + return rotational_discharge_rate_kg_per_hour( + signal_values, nominal_width_m, specific_discharge_kg_per_signal_unit_m, + ) diff --git a/src/production_analytics/enlyze/gateway.py b/src/production_analytics/enlyze/gateway.py index 111745e..beefb8a 100644 --- a/src/production_analytics/enlyze/gateway.py +++ b/src/production_analytics/enlyze/gateway.py @@ -165,6 +165,7 @@ class EnlyzeApiGateway: rotational_speed_variable_ids: tuple[str, ...] = (), specific_discharge_kg_per_rev_m: float | None = None, process_application_gate_threshold: float | None = None, + specific_discharge_kg_per_signal_unit_m: float | None = None, ) -> list[MaterialSample]: for name, value in (("start", start), ("end", end)): if value.tzinfo is None or value.utcoffset() is None: @@ -175,6 +176,8 @@ class EnlyzeApiGateway: raise ValueError("Material source modes are mutually exclusive") if gate_variable_id is None and not rotational_speed_variable_ids: raise ValueError("This source requires a gate signal") + if specific_discharge_kg_per_signal_unit_m is not None and not application_variable_ids: + raise ValueError("Signal discharge requires source signals") source_ids = ( rotational_speed_variable_ids or application_variable_ids or (rate_variable_id,) ) @@ -223,6 +226,16 @@ class EnlyzeApiGateway: nominal_width_m, specific_discharge_kg_per_rev_m, ) + elif specific_discharge_kg_per_signal_unit_m is not None: + from production_analytics.calculations.material_consumption import ( + linear_signal_discharge_rate_kg_per_hour, + ) + + if nominal_width_m is None: + raise ValueError("signal discharge requires nominal width") + rate = linear_signal_discharge_rate_kg_per_hour( + sources, nominal_width_m, specific_discharge_kg_per_signal_unit_m, + ) elif application_variable_ids: if nominal_width_m is None: raise ValueError("area application requires nominal width") @@ -231,18 +244,30 @@ class EnlyzeApiGateway: rate = sources[0] application = None if process_application_gate_threshold is not None: - if not rotational_speed_variable_ids or gate_variable_id is None: - raise ValueError("Process application requires rpm and speed gate") + if specific_discharge_kg_per_signal_unit_m is not None: + from production_analytics.calculations.material_application import ( + linear_signal_discharge_g_m2, + ) + + application = linear_signal_discharge_g_m2( + sources, specific_discharge_kg_per_signal_unit_m, + gate, process_application_gate_threshold, + ) + elif not rotational_speed_variable_ids or gate_variable_id is None: + raise ValueError( + "Process application requires discharge and speed gate" + ) from production_analytics.calculations.material_application import ( rotational_application_g_m2, ) - application = rotational_application_g_m2( - sources, - specific_discharge_kg_per_rev_m, - gate, - process_application_gate_threshold, - ) + if rotational_speed_variable_ids: + application = rotational_application_g_m2( + sources, + specific_discharge_kg_per_rev_m, + gate, + process_application_gate_threshold, + ) samples.append( MaterialSample( timestamp=_parse_timestamp(record[time_index]), diff --git a/src/production_analytics/service/material_polling.py b/src/production_analytics/service/material_polling.py index 0314a74..1b1acdf 100644 --- a/src/production_analytics/service/material_polling.py +++ b/src/production_analytics/service/material_polling.py @@ -61,15 +61,21 @@ class MaterialPollingService: nominal_width_provider: Callable[[str], float] | None = None, process_application_calculation_id: str | None = None, application_writer: MaterialApplicationWriter | None = None, + specific_discharge_kg_per_signal_unit_m: float | None = None, ) -> None: if application_variable_ids and rotational_speed_variable_ids: raise ValueError("Material source modes are mutually exclusive") + if specific_discharge_kg_per_signal_unit_m is not None and not application_variable_ids: + raise ValueError("Signal discharge requires source signals") + self._signal_discharge = specific_discharge_kg_per_signal_unit_m if process_application_calculation_id is not None and ( - not rotational_speed_variable_ids or not gate_variable_id + not (rotational_speed_variable_ids + or specific_discharge_kg_per_signal_unit_m is not None) + or not gate_variable_id or gate_threshold <= 0 or application_writer is None ): raise ValueError( - "Process application requires rotational source, positive gate and writer" + "Process application requires calibrated source, positive gate and writer" ) self._process_application_calculation_id = process_application_calculation_id self._application_writer = application_writer @@ -171,6 +177,8 @@ class MaterialPollingService: source_options = dict( application_variable_ids=self._application_variable_ids, nominal_width_m=width, ) + if self._signal_discharge is not None: + source_options["specific_discharge_kg_per_signal_unit_m"] = self._signal_discharge if self._rotational_speed_variable_ids: source_options = dict( rotational_speed_variable_ids=self._rotational_speed_variable_ids, diff --git a/src/production_analytics/service/material_runtime.py b/src/production_analytics/service/material_runtime.py index 618a902..c5a86ed 100644 --- a/src/production_analytics/service/material_runtime.py +++ b/src/production_analytics/service/material_runtime.py @@ -3,6 +3,7 @@ import math import os import tempfile +from hashlib import sha256 from pathlib import Path from urllib.parse import urlsplit @@ -76,7 +77,9 @@ def build_material_runner( ) from exc postgres_settings = PostgresSettings.from_environment(environment) source_options = {} - if calculation.source_mode in {"area_application", "rotational_discharge"}: + if calculation.source_mode in { + "area_application", "rotational_discharge", "linear_signal_discharge", + }: source_options = dict( application_variable_ids=calculation.application_signal_refs, nominal_width_provider=ErpNominalWidthProvider( @@ -85,6 +88,12 @@ def build_material_runner( format_template=calculation.production_order_format, ), ) + if calculation.source_mode == "linear_signal_discharge": + source_options["specific_discharge_kg_per_signal_unit_m"] = ( + calculation.specific_discharge_kg_per_signal_unit_m + ) + # Legacy runners retain their checkpoints; new calibrated sources are isolated. + state_directory = state_directory / sha256(calculation.id.encode("utf-8")).hexdigest() if calculation.source_mode == "rotational_discharge": source_options.pop("application_variable_ids") source_options.update( diff --git a/tests/test_linear_signal_material.py b/tests/test_linear_signal_material.py new file mode 100644 index 0000000..d0a3fbf --- /dev/null +++ b/tests/test_linear_signal_material.py @@ -0,0 +1,236 @@ +from datetime import UTC, datetime, timedelta +from fractions import Fraction +from hashlib import sha256 +from pathlib import Path +from unittest.mock import Mock, patch + +import pytest +import yaml + +from production_analytics.calculations.config import ( + CalculationConfigError, + load_material_calculation, +) +from production_analytics.calculations.material_application import linear_signal_discharge_g_m2 +from production_analytics.calculations.material_consumption import ( + MaterialConsumptionIntegrator, + MaterialIntegratorConfig, +) +from production_analytics.enlyze.gateway import EnlyzeApiGateway, EnlyzeProductionRun +from production_analytics.service.material_runtime import build_material_runner + +CONFIG = 'config/bento1-spreader3-material-consumption.yaml' +NOW = datetime(2026, 9, 9, tzinfo=UTC) + + +def configured_samples(width=5, gates=None): + config = load_material_calculation(CONFIG) + client = Mock() + times = [0, 10, 20, 40, 61, 71] + gates = gates if gates is not None else [2.3, 0.3, 0, 2.3, 2.3, 2.3] + client.post_json.return_value.body = {'data': { + 'columns': ['time', *config.application_signal_refs, config.gate_signal_ref], + 'records': [[(NOW + timedelta(seconds=t)).isoformat(), 3.03, gate] + for t, gate in zip(times, gates, strict=True)], + }} + samples = EnlyzeApiGateway(client).get_material_samples( + machine_id=config.machine_ref, rate_variable_id='unused', + gate_variable_id=config.gate_signal_ref, start=NOW, end=NOW + timedelta(seconds=71), + application_variable_ids=config.application_signal_refs, nominal_width_m=width, + specific_discharge_kg_per_signal_unit_m=config.specific_discharge_kg_per_signal_unit_m, + process_application_gate_threshold=config.gate_threshold, + ) + assert client.post_json.call_args.args[1]['variables'] == [ + {'uuid': ref} for ref in (*config.application_signal_refs, config.gate_signal_ref)] + return samples + + +def test_reference_and_zero(): + config = load_material_calculation(CONFIG) + assert config.calibration_ref == 'bento1-spreader-3-bentonite' + factor = config.specific_discharge_kg_per_signal_unit_m + assert linear_signal_discharge_g_m2([3.03], factor, 2.3, 0.3) == pytest.approx(618, abs=0.002) + assert linear_signal_discharge_g_m2([0], factor, 2.3, 0.3) == 0 + + +@pytest.mark.parametrize('width', [1, 4.85, 5, 100]) +def test_application_independent_of_width_and_consumption_formula(width): + samples = configured_samples(width) + assert samples[0].application_g_m2 == pytest.approx(618) + assert samples[0].material_rate_kg_per_hour == pytest.approx(618 * width * 2.3 / 1000 * 60) + assert samples[1].application_g_m2 is None + assert samples[2].application_g_m2 is None + + +def test_gate_and_gap(): + state = MaterialConsumptionIntegrator(MaterialIntegratorConfig(0.3, 20)).process_many( + configured_samples()) + # 0→10 and 61→71 only: inactive preceding gates and the 21s gap are excluded. + assert state.integrated_running_seconds == 20 + assert state.cumulative_consumption_kg == pytest.approx(618 * 5 * 2.3 / 1000 * 20 / 60) + + +@pytest.mark.parametrize('field,value,message', [ + ('type', 'rotational_discharge', 'incompatible type'), + ('unit', 'kg_per_rev_m', 'incompatible unit'), + ('value', 0, 'greater than zero'), + ('value', -1, 'greater than zero'), + ('value', float('nan'), 'finite'), + ('value', float('inf'), 'finite'), + ('value', True, 'finite number'), +]) +def test_incompatible_calibration(tmp_path, field, value, message): + document = yaml.safe_load(Path('config/material-calibrations.yaml').read_text()) + document['calibrations']['bento1-spreader-3-bentonite'][field] = value + (tmp_path / 'material-calibrations.yaml').write_text(yaml.safe_dump(document)) + path = tmp_path / 'config.yaml' + path.write_text(Path(CONFIG).read_text()) + with pytest.raises(CalculationConfigError, match=message): + load_material_calculation(path) + + +def test_missing_calibration_reference(tmp_path): + document = yaml.safe_load(Path(CONFIG).read_text()) + del document['calculations'][0]['calibration_ref'] + path = tmp_path / 'config.yaml' + path.write_text(yaml.safe_dump(document)) + with pytest.raises(CalculationConfigError, match='requires calibration_ref'): + load_material_calculation(path) + + +def test_runtime_isolation_and_disjoint_runs(tmp_path, monkeypatch): + monkeypatch.setenv('ENLYZE_BASE_URL', 'https://example.invalid/api/') + for key, value in dict(HOST='localhost', PORT='5432', DB='analytics', + USER='user', PASSWORD='test').items(): + monkeypatch.setenv(f'POSTGRES_{key}', value) + secrets = tmp_path / 'secret.env' + secrets.write_text('ENLYZE_API_KEY=test\n') + configs = [load_material_calculation(path) for path in ( + CONFIG, 'config/bento1-material-consumption.yaml', 'config/k7-material-consumption.yaml')] + with patch('production_analytics.service.material_runtime.ErpSettings'): + runners = [build_material_runner(c, poll_interval_seconds=10, + state_directory=tmp_path / 'state', secrets_file=secrets) for c in configs] + separate, fresh, k7 = runners + assert separate.calculation_id == 'bento1-spreader3-consumption' + assert fresh.service._specific_discharge == 2.75 + assert fresh.service._rotational_speed_variable_ids == configs[1].rotational_speed_signal_refs + assert fresh.service._signal_discharge is None + assert k7.service._signal_discharge is None + assert k7.service._process_application_calculation_id is None + assert separate.service._signal_discharge == ( + configs[0].specific_discharge_kg_per_signal_unit_m) + assert separate.service._nominal_width_provider.format_template == 'Bento 1-{production_order}' + machine = configs[0].machine_ref + order = 'Bento 1-test' + separate_path = separate.service._state_store.store._path(machine, order) + fresh_path = fresh.service._state_store.store._path(machine, order) + assert separate_path != fresh_path + assert separate_path.parent.name == sha256(configs[0].id.encode()).hexdigest() + gateway = Mock() + old = EnlyzeProductionRun('old', machine, None, order, NOW, NOW + timedelta(seconds=10)) + current = EnlyzeProductionRun('new', machine, None, order, + NOW + timedelta(seconds=15), None) + gateway.get_open_production_run.return_value = current + gateway.get_production_runs.return_value = [old, current] + samples = configured_samples() + + def window(**kwargs): + assert kwargs['specific_discharge_kg_per_signal_unit_m'] == pytest.approx( + 618 * 2.3 / (3.03 * 1000)) + from dataclasses import replace + return [replace(samples[0], timestamp=kwargs['start']), + replace(samples[0], timestamp=kwargs['end'])] + + gateway.get_material_samples.side_effect = window + service = separate.service + service._gateway = gateway + service._nominal_width_provider = lambda order: 5 + service._application_writer = Mock() + result = service.poll_once(now=NOW + timedelta(seconds=25)) + assert result.state.integrated_running_seconds == 20 # no bridging the 5s run gap + assert result.state.cumulative_consumption_kg == pytest.approx(618 * 5 * 2.3 / 1000 / 3) + assert not fresh_path.exists() # no fresh-bentonite state or aggregation written + written_ids = {c.kwargs['calculation_id'] + for c in service._application_writer.write.call_args_list} + assert written_ids == {'bento1-spreader3-application'} + + +@pytest.mark.parametrize('signals,factor', [ + ([], 1), ([float('nan')], 1), ([1], 0), ([1], float('inf')), ([1e308], 10), +]) +def test_invalid_linear_inputs(signals, factor): + with pytest.raises(ValueError): + linear_signal_discharge_g_m2(signals, factor, 2.3, 0.3) + + +@pytest.mark.parametrize('signal,speed,expected', [(3.03, 2.3, 618), + (8.999, 4.999, 844.471112044191)]) +def test_discharge_physics(signal, speed, expected): + from production_analytics.calculations.material_consumption import ( + linear_signal_discharge_rate_kg_per_hour, + ) + + factor = load_material_calculation(CONFIG).specific_discharge_kg_per_signal_unit_m + assert factor == float(Fraction(2369, 5050)) + width = 5 + flow = linear_signal_discharge_rate_kg_per_hour([signal], width, factor) / 60 + application = linear_signal_discharge_g_m2([signal], factor, speed, 0.3) + assert application == pytest.approx(expected) + assert flow == pytest.approx(application * width * speed / 1000) + faster_application = linear_signal_discharge_g_m2([signal], factor, speed * 2, 0.3) + assert faster_application == pytest.approx(application / 2) + assert faster_application * width * speed * 2 / 1000 == pytest.approx(flow) + assert linear_signal_discharge_rate_kg_per_hour([0], width, factor) == 0 + assert linear_signal_discharge_rate_kg_per_hour([signal / 2, signal / 2], width, + factor) / 60 == pytest.approx(flow) + + +@pytest.mark.parametrize('speed', [0, -1, 0.3]) +def test_inactive_speed(speed): + factor = load_material_calculation(CONFIG).specific_discharge_kg_per_signal_unit_m + assert linear_signal_discharge_g_m2([3.03], factor, speed, 0.3) is None + + +@pytest.mark.parametrize('speed', [float('nan'), float('inf')]) +def test_invalid_speed(speed): + factor = load_material_calculation(CONFIG).specific_discharge_kg_per_signal_unit_m + with pytest.raises(ValueError, match='line speed'): + linear_signal_discharge_g_m2([3.03], factor, speed, 0.3) + + +@pytest.mark.parametrize('gate', [None, '', 0]) +def test_missing_gate_config(tmp_path, gate): + document = yaml.safe_load(Path(CONFIG).read_text()) + document['calculations'][0]['gate_signal_ref'] = gate + path = tmp_path / 'config.yaml' + path.write_text(yaml.safe_dump(document)) + with pytest.raises(CalculationConfigError, match='gate_signal_ref'): + load_material_calculation(path) + + + +def test_gateway_speed_changes_only_application(): + samples = configured_samples(gates=[2.3, 4.6, 0, -1, 0.3, 2.3]) + assert samples[0].application_g_m2 == pytest.approx(618) + assert samples[1].application_g_m2 == pytest.approx(309) + assert [sample.material_rate_kg_per_hour for sample in samples] == pytest.approx( + [3.03 * (2369 / 5050) * 5 * 60] * 6) + assert all(sample.application_g_m2 is None for sample in samples[2:5]) + + +@pytest.mark.parametrize('speed', [None, True, float('nan'), float('inf')]) +def test_gateway_invalid_speed(speed): + with pytest.raises(ValueError, match='rate and gate must be'): + configured_samples(gates=[speed] * 6) + + +@pytest.mark.parametrize('width', [None, 0, -1, float('nan'), float('inf')]) +def test_gateway_requires_valid_width(width): + with pytest.raises(ValueError, match='width'): + configured_samples(width=width) + + +@pytest.mark.parametrize('threshold', [0, -1, float('nan'), float('inf')]) +def test_invalid_speed_threshold(threshold): + with pytest.raises(ValueError, match='speed gate threshold'): + linear_signal_discharge_g_m2([3.03], 2369 / 5050, 2.3, threshold)