238 lines
11 KiB
Python
238 lines
11 KiB
Python
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.3032, 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.3032], factor, 2.3, 0.3) == pytest.approx(540, abs=0.01)
|
|
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(540, abs=0.01)
|
|
assert samples[0].material_rate_kg_per_hour == pytest.approx(samples[0].application_g_m2 * 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(3.3032 * 0.376 * 5 * 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}'
|
|
assert separate.service._nominal_width_provider.fallback_nominal_width_m == 5.0
|
|
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(
|
|
0.376)
|
|
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(3.3032 * 0.376 * 5 / 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.3032, 2.3, 540),
|
|
(8.999, 4.999, 676.860172034407)])
|
|
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 == pytest.approx(0.376)
|
|
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, abs=0.01)
|
|
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.3032], 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.3032], 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(540, abs=0.01)
|
|
assert samples[1].application_g_m2 == pytest.approx(270, abs=0.01)
|
|
assert [sample.material_rate_kg_per_hour for sample in samples] == pytest.approx(
|
|
[3.3032 * 0.376 * 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.3032], 0.376, 2.3, threshold)
|