Source code for energy_methods.pv_device_reliability

"""PV tracker observability, censored survival and component-event scenarios.

Availability is not a hazard rate. Missing telemetry is not a confirmed failure.
Weather-station quality checks concern measurement validity, not equipment life.
"""

from __future__ import annotations

from dataclasses import asdict, dataclass

import numpy as np
import pandas as pd
from numpy.typing import ArrayLike, NDArray
from scipy.stats import norm

REFERENCE_IDS = (
    "martins_2026_tracker_availability",
    "bucher_2022_inverter_survival",
    "baschel_2018_reliability",
    "scipy_ecdf_reference",
)


def _vector(value: ArrayLike, name: str, *, missing: bool = False) -> NDArray[np.float64]:
    result = np.asarray(value, dtype=float)
    if result.ndim != 1 or not result.size or np.isinf(result).any():
        raise ValueError(f"{name} must be a nonempty one-dimensional vector without infinity")
    if not missing and not np.isfinite(result).all():
        raise ValueError(f"{name} must be finite")
    return result


def _mask(value: ArrayLike, length: int, name: str) -> NDArray[np.bool_]:
    result = np.asarray(value)
    if result.shape != (length,) or not np.isin(result, [False, True]).all():
        raise ValueError(f"{name} must contain one boolean/0/1 per interval")
    return result.astype(bool)


[docs] @dataclass(frozen=True) class AvailabilityEvidence: """Time-weighted bounds; unknown intervals are not silently imputed. Bounds address missing-state uncertainty only, not sampling uncertainty or model error. No eligible/observed hours produces NaN for the relevant ratio. """ eligible_hours: float available_hours: float unavailable_hours: float unknown_hours: float excluded_hours: float unknown_eligibility_hours: float @property def lower(self) -> float: return self.available_hours / self.eligible_hours if self.eligible_hours else float("nan") @property def upper(self) -> float: return ( (self.available_hours + self.unknown_hours) / self.eligible_hours if self.eligible_hours else float("nan") ) @property def observed(self) -> float: known = self.available_hours + self.unavailable_hours return self.available_hours / known if known else float("nan") @property def coverage(self) -> float: return 1 - self.unknown_hours / self.eligible_hours if self.eligible_hours else float("nan")
[docs] def to_dict(self) -> dict[str, float]: """Hours and the four distinct ratios for exports.""" return dict( asdict(self), lower=self.lower, upper=self.upper, observed=self.observed, coverage=self.coverage, )
[docs] def tracker_availability( actual_angle: ArrayLike, reference_angle: ArrayLike, poa_w_m2: ArrayLike, interval_hours: ArrayLike, *, expected_stow: ArrayLike | None = None, core_tracking: ArrayLike | None = None, threshold_deg: float = 5, ) -> AvailabilityEvidence: """Martins (2026) angle KPI with explicit missing-data bounds. Eligible when POA > 0 and the optional core mask is true. Confirmed expected stows count as available, including missing angles, following the paper. Absolute deviations > threshold are unavailable; equality is available. Inputs must share the same aligned intervals, angle sign convention and geometry. Durations are explicit: never bridge a telemetry gap by carrying the last state forward. Unknown POA is reported separately, outside bounds. A deviation is an operational symptom, not a diagnosed mechanical failure. """ actual = _vector(actual_angle, "actual_angle", missing=True) reference = _vector(reference_angle, "reference_angle", missing=True) poa = _vector(poa_w_m2, "poa_w_m2", missing=True) hours = _vector(interval_hours, "interval_hours") if any(x.shape != actual.shape for x in [reference, poa, hours]): raise ValueError("All interval vectors must be aligned and have equal shapes") if np.any(hours <= 0) or not np.isfinite(threshold_deg) or threshold_deg <= 0: raise ValueError("Durations and angle threshold must be positive and finite") core = ( np.ones(actual.size, dtype=bool) if core_tracking is None else _mask(core_tracking, actual.size, "core_tracking") ) stow = ( np.zeros(actual.size, dtype=bool) if expected_stow is None else _mask(expected_stow, actual.size, "expected_stow") ) eligible = core & (poa > 0) known = np.isfinite(actual) & np.isfinite(reference) available = eligible & (stow | (known & (np.abs(actual - reference) <= threshold_deg))) unavailable = eligible & ~stow & known & ~available unknown = eligible & ~available & ~unavailable uncertain_eligibility = core & np.isnan(poa) excluded = ~eligible & ~uncertain_eligibility return AvailabilityEvidence( *( float(hours[mask].sum()) for mask in [eligible, available, unavailable, unknown, excluded, uncertain_eligibility] ) )
[docs] def sensor_serviceability( readings: ArrayLike, interval_hours: ArrayLike, *, quality_valid: ArrayLike ) -> dict[str, float]: """Separate WST channel completeness from externally assessed validity. Caller supplies QC (reference comparison/calibration/physical checks). Invalid measurements and absent data do not become hardware-failure events. Every scheduled interval must be represented, including missing samples. """ values = _vector(readings, "readings", missing=True) hours = _vector(interval_hours, "interval_hours") valid = _mask(quality_valid, values.size, "quality_valid") if hours.shape != values.shape or np.any(hours <= 0): raise ValueError("Positive durations must align with sensor readings") present = np.isfinite(values) total = float(hours.sum()) return { "scheduled_hours": total, "data_coverage": float(hours[present].sum() / total), "valid_data_fraction": float(hours[present & valid].sum() / total), "invalid_observed_hours": float(hours[present & ~valid].sum()), "missing_hours": float(hours[~present].sum()), }
[docs] def kaplan_meier_survival( age: ArrayLike, failed: ArrayLike, *, confidence: float = 0.95 ) -> pd.DataFrame: """First-event KM table with Greenwood log-log pointwise intervals. Ages start at commissioning; all surviving devices must be included. Failures precede censoring at ties. No delayed entry, interval censoring, competing-risk model, recurrent events, weighting, or tail extrapolation. Independent censoring is assumed. Boundary CIs at S=0 or S=1 are undefined (NaN), avoiding an impression of certainty in small/zero-failure cohorts. """ times = _vector(age, "age") failures = _mask(failed, times.size, "failed") if np.any(times <= 0) or not np.isfinite(confidence) or not 0 < confidence < 1: raise ValueError("Ages must be positive; confidence must be between 0 and 1") survival, greenwood = 1.0, 0.0 z = norm.ppf((1 + confidence) / 2) records = [] for t in np.unique(times): risk = int((times >= t).sum()) events = int(((times == t) & failures).sum()) censored = int(((times == t) & ~failures).sum()) survival *= 1 - events / risk if events and events < risk: greenwood += events / (risk * (risk - events)) lower = upper = float("nan") if 0 < survival < 1: log_s = np.log(survival) se = np.sqrt(greenwood) / abs(log_s) center = np.log(-log_s) # Exponent clipping evaluates the limits without overflow warnings. lower = float(np.exp(-np.exp(np.clip(center + z * se, -745, 709)))) upper = float(np.exp(-np.exp(np.clip(center - z * se, -745, 709)))) records.append( dict( age=float(t), at_risk=risk, failures=events, censored=censored, survival=survival, lower=lower, upper=upper, ) ) return pd.DataFrame(records)
[docs] def assembly_event_scenario( rates_per_operating_hour: ArrayLike, counts: ArrayLike, *, operating_hours_per_year: float ) -> dict[str, float]: """Independent constant-rate parts: expected events and any-event probability. Use disjoint physical parts in one assembly (e.g. CBX fuses, terminals, monitoring unit). A fuse event is NOT assumed to disconnect the whole box. Do not include a parent assembly rate alongside its children or substitute 8760 calendar hours for a source's operating-hour basis without justification. No repair cost, downtime, or confidence interval is invented. """ rates, n = _vector(rates_per_operating_hour, "rates"), _vector(counts, "counts") if rates.shape != n.shape or np.any(rates < 0) or np.any(n < 0) or np.any(n != np.floor(n)): raise ValueError("Rates and integer counts must align and be nonnegative") if not np.isfinite(operating_hours_per_year) or not 0 < operating_hours_per_year <= 8784: raise ValueError("Operating hours must be in (0, 8784]") rate = float(np.dot(rates, n)) expected = rate * operating_hours_per_year return { "assembly_event_rate_per_operating_hour": rate, "expected_events_per_year": expected, "probability_at_least_one_event": float(-np.expm1(-expected)), }