"""Daily operational loss accounting and explicitly conditional repair economics.
Pure Python, no data access or agent dependencies. Inputs must share an asset,
currency, timezone and meter boundary. Event labels are associations, not causes.
"""
from __future__ import annotations
from dataclasses import dataclass
from datetime import date
from math import fsum, isfinite
from typing import Literal
Event = Literal["none", "equipment_fault", "curtailment"]
def _number(value: float, name: str, *, minimum: float | None = None) -> None:
if isinstance(value, bool) or not isinstance(value, (int, float)) or not isfinite(value):
raise ValueError(f"{name} must be finite")
if minimum is not None and value < minimum:
raise ValueError(f"{name} must be >= {minimum}")
[docs]
@dataclass(frozen=True)
class DailyEnergyRecord:
"""One local-calendar day; expected/actual are energy (MWh), never power.
A missing actual is None and excluded from both sides of the comparison.
Exactly one event is allowed; reconcile overlapping events before ingestion.
Prices are signed currency/MWh. Expected energy must represent the same meter
boundary and daily window as actual, before the supplied event's losses.
"""
day: str
expected_mwh: float
actual_mwh: float | None
price_per_mwh: float
event: Event = "none"
def __post_init__(self) -> None:
if not isinstance(self.day, str) or date.fromisoformat(self.day).isoformat() != self.day:
raise ValueError("day must be YYYY-MM-DD")
_number(self.expected_mwh, "expected_mwh", minimum=0)
if self.actual_mwh is not None:
_number(self.actual_mwh, "actual_mwh", minimum=0)
_number(self.price_per_mwh, "price_per_mwh")
if self.event not in {"none", "equipment_fault", "curtailment"}:
raise ValueError("Unknown event; reconcile overlapping events upstream")
[docs]
@dataclass(frozen=True)
class OperationsLedger:
"""Comparable-day totals; signed values preserve negative energy prices."""
observed_days: int
supplied_days: int
excluded_dates: tuple[str, ...]
missing_calendar_dates: tuple[str, ...]
coverage_fraction: float
expected_energy_coverage_fraction: float | None
expected_mwh: float
actual_mwh: float
deficit_mwh: float
surplus_mwh: float
signed_energy_gap_mwh: float
deficit_by_event_mwh: dict[str, float]
historical_deficit_value: float
signed_revenue_gap: float
fault_associated_value: float
conditional_recovery_mwh: float
conditional_gross_value: float
intervention_cost: float
conditional_net_value: float
[docs]
def analyze_daily_operations(
records: tuple[DailyEnergyRecord, ...],
*,
recovery_fraction: float,
intervention_cost: float,
) -> OperationsLedger:
"""Account daily deficits without netting surplus or repairing curtailment.
Conditional gross value = sum(fault-associated deficit * daily price) *
recovery_fraction. Net subtracts one intervention cost. This assumes recurrence
over an equivalent period, at identical prices, with the stated recoverability.
It is neither a forecast nor causal attribution, settlement or annual revenue.
Coverage includes missing calendar dates between the first and last supplied
dates. Unknown dates outside that window cannot be detected. Energy coverage
uses supplied expected energy only; omitted dates have unknown energy weight.
"""
_number(recovery_fraction, "recovery_fraction", minimum=0)
if recovery_fraction > 1:
raise ValueError("recovery_fraction must be <= 1")
_number(intervention_cost, "intervention_cost", minimum=0)
if not records:
raise ValueError("At least one daily record is required")
days = [date.fromisoformat(r.day) for r in records]
if len(set(days)) != len(days):
raise ValueError("Duplicate daily record")
first, last = min(days).toordinal(), max(days).toordinal()
if last - first > 36600:
raise ValueError("Daily review window must not exceed 100 years")
present = {d.toordinal() for d in days}
missing = tuple(
date.fromordinal(d).isoformat() for d in range(first, last + 1) if d not in present
)
valid = [r for r in records if r.actual_mwh is not None]
deficits = [
(r, max(0.0, r.expected_mwh - r.actual_mwh)) for r in valid if r.actual_mwh is not None
]
expected = fsum(r.expected_mwh for r in valid)
actual = fsum(r.actual_mwh for r in valid if r.actual_mwh is not None)
supplied_expected = fsum(r.expected_mwh for r in records)
grouped = {
label: fsum(loss for r, loss in deficits if r.event == event)
for label, event in (
("equipment_fault", "equipment_fault"),
("curtailment", "curtailment"),
("unresolved", "none"),
)
}
fault_value = fsum(
loss * r.price_per_mwh for r, loss in deficits if r.event == "equipment_fault"
)
gross = fault_value * recovery_fraction
return OperationsLedger(
observed_days=len(valid),
supplied_days=len(records),
excluded_dates=tuple(sorted(r.day for r in records if r.actual_mwh is None)),
missing_calendar_dates=missing,
coverage_fraction=len(valid) / (last - first + 1),
expected_energy_coverage_fraction=(
expected / supplied_expected if supplied_expected else None
),
expected_mwh=expected,
actual_mwh=actual,
deficit_mwh=fsum(loss for _, loss in deficits),
surplus_mwh=fsum(
max(0.0, r.actual_mwh - r.expected_mwh) for r in valid if r.actual_mwh is not None
),
signed_energy_gap_mwh=expected - actual,
deficit_by_event_mwh=grouped,
historical_deficit_value=fsum(loss * r.price_per_mwh for r, loss in deficits),
signed_revenue_gap=fsum(
(r.expected_mwh - r.actual_mwh) * r.price_per_mwh
for r in valid
if r.actual_mwh is not None
),
fault_associated_value=fault_value,
conditional_recovery_mwh=grouped["equipment_fault"] * recovery_fraction,
conditional_gross_value=gross,
intervention_cost=intervention_cost,
conditional_net_value=gross - intervention_cost,
)