Add channel material and downtime analytics

This commit is contained in:
admin committed 2026-10-01 12:27:47 +02:00
1 parent 5452dc035b
commit 640ec53330
24 files changed
+2362 -76

No files matched your search

+344 -12
View File
@@ -3,7 +3,9 @@
from dataclasses import dataclass
from datetime import UTC, datetime
from math import isfinite
from typing import TYPE_CHECKING
from production_analytics.calculations.channel_material import DosingChannelSample
from production_analytics.calculations.material_consumption import (
MaterialSample,
area_application_rate_kg_per_hour,
@@ -11,6 +13,9 @@ from production_analytics.calculations.material_consumption import (
)
from production_analytics.enlyze.exploration import ExplorationClient
if TYPE_CHECKING:
from production_analytics.service.channel_material import ChannelDefinition
@dataclass(frozen=True, slots=True)
class EnlyzeProductionRun:
@@ -22,6 +27,24 @@ class EnlyzeProductionRun:
end: datetime | None
@dataclass(frozen=True, slots=True)
class EnlyzeDowntime:
"""ENLYZE downtime source record. ``end`` and ``reason`` are deliberately nullable."""
uuid: str
machine_id: str
source_type: str
start: datetime
end: datetime | None
comment: str | None
reason_id: str | None
reason_name: str | None
reason_description: str | None
reason_group: str | None
reason_category: str | None
source_updated_at: datetime | None
class EnlyzeApiGateway:
def __init__(self, client: ExplorationClient) -> None:
self._client = client
@@ -60,11 +83,16 @@ class EnlyzeApiGateway:
end = _parse_timestamp(item["end"]) if item["end"] is not None else None
if end is not None and end < start:
raise ValueError("run end must not precede start")
runs.append(EnlyzeProductionRun(
uuid=item["uuid"], machine_id=item["machine"],
product_id=item.get("product"), production_order=item["production_order"],
start=start, end=end,
))
runs.append(
EnlyzeProductionRun(
uuid=item["uuid"],
machine_id=item["machine"],
product_id=item.get("product"),
production_order=item["production_order"],
start=start,
end=end,
)
)
next_cursor = None
if "metadata" in response.body:
metadata = response.body["metadata"]
@@ -85,6 +113,45 @@ class EnlyzeApiGateway:
except (KeyError, TypeError, ValueError) as exc:
raise ValueError(f"Invalid production-run response on page {page}: {exc}") from exc
def get_downtimes(
self,
machine_id: str,
*,
start: datetime | None = None,
) -> list[EnlyzeDowntime]:
"""Retrieve machine downtimes and follow ENLYZE cursor pagination.
``start`` is an inclusive source-time lookback; callers use it for reconciliation,
not as a claim that records before it cannot subsequently be edited.
"""
if start is not None and (start.tzinfo is None or start.utcoffset() is None):
raise ValueError("start must be timezone-aware")
params = {"machine": machine_id}
if start is not None:
params["start"] = start.astimezone(UTC).isoformat()
result: list[EnlyzeDowntime] = []
cursors: set[str] = set()
page = 1
while True:
response = self._client.get("/v2/downtimes", params)
try:
if not isinstance(response.body, dict) or not isinstance(
response.body["data"], list
):
raise ValueError("body data must be a list")
for item in response.body["data"]:
result.append(_parse_downtime(item, machine_id))
cursor = _next_cursor(response.body)
if cursor is None:
return result
if cursor in cursors:
raise ValueError("next_cursor has already been followed")
cursors.add(cursor)
params = {**params, "cursor": cursor}
page += 1
except (KeyError, TypeError, ValueError) as exc:
raise ValueError(f"Invalid downtime response on page {page}: {exc}") from exc
def get_material_samples(
self,
*,
@@ -152,7 +219,9 @@ class EnlyzeApiGateway:
if nominal_width_m is None or specific_discharge_kg_per_rev_m is None:
raise ValueError("rotational discharge requires width and factor")
rate = rotational_discharge_rate_kg_per_hour(
sources, nominal_width_m, specific_discharge_kg_per_rev_m,
sources,
nominal_width_m,
specific_discharge_kg_per_rev_m,
)
elif application_variable_ids:
if nominal_width_m is None:
@@ -167,15 +236,21 @@ class EnlyzeApiGateway:
from production_analytics.calculations.material_application import (
rotational_application_g_m2,
)
application = rotational_application_g_m2(
sources, specific_discharge_kg_per_rev_m, gate,
sources,
specific_discharge_kg_per_rev_m,
gate,
process_application_gate_threshold,
)
samples.append(MaterialSample(
timestamp=_parse_timestamp(record[time_index]),
material_rate_kg_per_hour=float(rate), gate_value=float(gate),
application_g_m2=application,
))
samples.append(
MaterialSample(
timestamp=_parse_timestamp(record[time_index]),
material_rate_kg_per_hour=float(rate),
gate_value=float(gate),
application_g_m2=application,
)
)
except (TypeError, ValueError) as exc:
raise ValueError(f"malformed record {index}: {exc}") from exc
next_cursor = None
@@ -198,6 +273,199 @@ class EnlyzeApiGateway:
except (KeyError, TypeError, ValueError) as exc:
raise ValueError(f"Invalid timeseries response on page {page}: {exc}") from exc
def get_dosing_channel_samples(
self,
*,
machine_id: str,
channels: tuple["ChannelDefinition", ...],
start: datetime,
end: datetime,
) -> dict[str, list[DosingChannelSample]]:
"""Read configured dosing channels through the gateway only.
Configurations name stable PLC origins; ENLYZE UUIDs are resolved at poll
time and must be unique, preventing a silently stale variable mapping.
"""
if (
start.tzinfo is None
or start.utcoffset() is None
or end.tzinfo is None
or end.utcoffset() is None
):
raise ValueError("dosing channel window must be timezone-aware")
if end < start:
raise ValueError("end must not precede start")
resolved = self.resolve_dosing_channel_signal_refs(
machine_id=machine_id,
channels=channels,
)
variable_ids = list(
dict.fromkeys(
variable_id
for references in resolved.values()
for variable_id in references
if variable_id is not None
)
)
body = {
"machine": machine_id,
"start": start.astimezone(UTC).isoformat(),
"end": end.astimezone(UTC).isoformat(),
"variables": [{"uuid": x} for x in variable_ids],
}
result = {key: [] for key in resolved}
cursors: set[str] = set()
while True:
response = self._client.post_json("/v2/timeseries", body)
try:
data = response.body["data"]
columns = data["columns"]
if not isinstance(columns, list) or any(
columns.count(x) != 1 for x in ("time", *variable_ids)
):
raise ValueError("required columns must occur exactly once")
if not isinstance(data["records"], list):
raise ValueError("records must be a list")
for row in data["records"]:
if not isinstance(row, list) or len(row) != len(columns):
raise ValueError("record must match columns")
timestamp = _parse_timestamp(row[columns.index("time")])
for key, (total, status, percentage, screw, material) in resolved.items():
sample = self._dosing_sample(
row, columns, timestamp, total, status, percentage, screw, material
)
if sample is not None:
result[key].append(sample)
cursor = _next_cursor(response.body)
if cursor is None:
return result
if cursor in cursors:
raise ValueError("next_cursor has already been followed")
cursors.add(cursor)
body = {**body, "cursor": cursor}
except (KeyError, TypeError, ValueError) as exc:
raise ValueError(f"Invalid dosing timeseries response: {exc}") from exc
def resolve_dosing_channel_signal_refs(
self,
*,
machine_id: str,
channels: tuple["ChannelDefinition", ...],
) -> dict[str, tuple[str, str, str, str, str | None]]:
"""Resolve configured PLC origins without reading samples or writing state."""
origins = self._variables_by_origin(machine_id)
resolved: dict[str, tuple[str, str, str, str, str | None]] = {}
for channel in channels:
refs = (
channel.total_rate_signal_ref,
channel.status_signal_ref,
channel.percentage_signal_ref,
channel.screw_speed_signal_ref,
)
ids = tuple(self._unique_origin(origins, ref) for ref in refs)
material = (
self._unique_origin(origins, channel.material_number_signal_ref)
if channel.material_number_signal_ref
else None
)
key = channel.channel + "\0" + channel.extruder
resolved[key] = (*ids, material)
return resolved
@staticmethod
def _dosing_sample(
row: list[object],
columns: list[object],
timestamp: datetime,
total: str,
status: str,
percentage: str,
screw: str,
material: str | None,
) -> DosingChannelSample | None:
def numeric(variable: str) -> float:
value = row[columns.index(variable)]
if (
isinstance(value, bool)
or not isinstance(value, (int, float))
or not isfinite(value)
):
raise ValueError("dosing values must be finite numeric")
return float(value)
for variable in (total, percentage, screw):
if row[columns.index(variable)] is None:
return None
status_value = row[columns.index(status)]
if status_value is None:
enabled = False
elif isinstance(status_value, bool):
enabled = status_value
elif (
isinstance(status_value, (int, float))
and not isinstance(status_value, bool)
and isfinite(status_value)
):
enabled = status_value != 0
else:
raise ValueError("dosing status must be boolean or numeric")
material_value = None if material is None else row[columns.index(material)]
if material_value is not None and not isinstance(material_value, (str, int, float)):
raise ValueError("material assignment must be scalar or null")
return DosingChannelSample(
timestamp,
numeric(total),
enabled,
numeric(percentage),
numeric(screw),
None if material_value is None else str(material_value),
)
def _variables_by_origin(self, machine_id: str) -> dict[str, list[str]]:
params = {"machine": machine_id}
result: dict[str, list[str]] = {}
cursors: set[str] = set()
while True:
response = self._client.get("/v2/variables", params)
try:
items = response.body["data"]
if not isinstance(items, list):
raise ValueError("data must be a list")
for item in items:
uuid = item["uuid"]
if not isinstance(uuid, str):
raise ValueError("variable uuid must be a string")
details = item.get("details")
if not isinstance(details, dict):
raise ValueError("variable details must be an object")
origin_identifier = details.get("origin_identifier")
if origin_identifier is None:
# Derived ENLYZE variables do not have a PLC origin.
continue
if not isinstance(origin_identifier, dict):
raise ValueError("variable origin_identifier must be an object")
code = origin_identifier.get("code")
if not isinstance(code, str):
raise ValueError("variable origin must be a string")
result.setdefault(code, []).append(uuid)
cursor = _next_cursor(response.body)
if cursor is None:
return result
if cursor in cursors:
raise ValueError("next_cursor has already been followed")
cursors.add(cursor)
params = {**params, "cursor": cursor}
except (KeyError, TypeError, ValueError) as exc:
raise ValueError(f"Invalid variable response: {exc}") from exc
@staticmethod
def _unique_origin(origins: dict[str, list[str]], origin: str) -> str:
matches = origins.get(origin, [])
if len(matches) != 1:
raise ValueError(f"Configured PLC origin {origin!r} is unavailable or ambiguous")
return matches[0]
def _parse_timestamp(value: str) -> datetime:
if not isinstance(value, str):
@@ -206,3 +474,67 @@ def _parse_timestamp(value: str) -> datetime:
if timestamp.tzinfo is None or timestamp.utcoffset() is None:
raise ValueError("timestamp must be timezone-aware")
return timestamp.astimezone(UTC)
def _next_cursor(body: dict[object, object]) -> str | None:
if "metadata" not in body:
return None
metadata = body["metadata"]
if not isinstance(metadata, dict) or "next_cursor" not in metadata:
raise ValueError("metadata must be an object with a next_cursor field")
cursor = metadata["next_cursor"]
if cursor is not None and (not isinstance(cursor, str) or not cursor):
raise ValueError("next_cursor must be null or a non-empty string")
return cursor
def _nullable_text(value: object, name: str) -> str | None:
if value is not None and not isinstance(value, str):
raise ValueError(f"{name} must be a string or null")
return value
def _parse_downtime(item: object, machine_id: str) -> EnlyzeDowntime:
if not isinstance(item, dict):
raise ValueError("downtime must be an object")
for key in ("uuid", "machine", "type", "start"):
if not isinstance(item.get(key), str) or not item[key]:
raise ValueError(f"{key} must be a non-empty string")
if item["machine"] != machine_id:
raise ValueError("downtime machine does not match requested machine")
start = _parse_timestamp(item["start"])
end_value = item.get("end")
end = _parse_timestamp(end_value) if end_value is not None else None
if end is not None and end < start:
raise ValueError("downtime end must not precede start")
reason = item.get("reason")
if reason is not None and not isinstance(reason, dict):
raise ValueError("reason must be an object or null")
if reason is not None:
for key in ("uuid", "name", "category"):
if not isinstance(reason.get(key), str) or not reason[key]:
raise ValueError(f"reason {key} must be a non-empty string")
updated = item.get("updated")
if updated is not None and not isinstance(updated, dict):
raise ValueError("updated must be an object or null")
updated_at = None
if updated is not None:
updated_at = _parse_timestamp(updated.get("timestamp"))
return EnlyzeDowntime(
uuid=item["uuid"],
machine_id=machine_id,
source_type=item["type"],
start=start,
end=end,
comment=_nullable_text(item.get("comment"), "comment"),
reason_id=None if reason is None else reason["uuid"],
reason_name=None if reason is None else reason["name"],
reason_description=None
if reason is None
else _nullable_text(reason.get("description"), "reason description"),
reason_group=None
if reason is None
else _nullable_text(reason.get("group"), "reason group"),
reason_category=None if reason is None else reason["category"],
source_updated_at=updated_at,
)