solarops 0.1.0__py3-none-any.whl
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- solarops/__init__.py +5 -0
- solarops/dataset.py +144 -0
- solarops/detection.py +179 -0
- solarops/exceptions.py +19 -0
- solarops/metrics.py +266 -0
- solarops/preprocessing.py +285 -0
- solarops/quality.py +230 -0
- solarops/reporting.py +298 -0
- solarops/visualization.py +249 -0
- solarops-0.1.0.dist-info/METADATA +150 -0
- solarops-0.1.0.dist-info/RECORD +14 -0
- solarops-0.1.0.dist-info/WHEEL +5 -0
- solarops-0.1.0.dist-info/licenses/LICENSE +21 -0
- solarops-0.1.0.dist-info/top_level.txt +1 -0
solarops/__init__.py
ADDED
solarops/dataset.py
ADDED
|
@@ -0,0 +1,144 @@
|
|
|
1
|
+
"""Interval-start solar measurements; validation never repairs input data."""
|
|
2
|
+
|
|
3
|
+
from dataclasses import dataclass, field
|
|
4
|
+
import copy
|
|
5
|
+
from zoneinfo import ZoneInfo, ZoneInfoNotFoundError
|
|
6
|
+
|
|
7
|
+
import pandas as pd
|
|
8
|
+
|
|
9
|
+
from .exceptions import AmbiguousTimeError, NonExistentTimeError
|
|
10
|
+
|
|
11
|
+
|
|
12
|
+
@dataclass(frozen=True)
|
|
13
|
+
class ValidationResult:
|
|
14
|
+
"""JSON-compatible metadata, counts and checks from one validation run."""
|
|
15
|
+
|
|
16
|
+
metadata: dict
|
|
17
|
+
counts: dict
|
|
18
|
+
checks: dict
|
|
19
|
+
|
|
20
|
+
details: dict = field(default_factory=dict)
|
|
21
|
+
coverage: dict = field(default_factory=dict)
|
|
22
|
+
warnings: list = field(default_factory=list)
|
|
23
|
+
detections: dict = field(default_factory=dict)
|
|
24
|
+
|
|
25
|
+
def to_dict(self):
|
|
26
|
+
report = {"metadata": self.metadata, "counts": self.counts,
|
|
27
|
+
"checks": self.checks, "details": self.details,
|
|
28
|
+
"coverage": self.coverage, "warnings": self.warnings}
|
|
29
|
+
if self.detections:
|
|
30
|
+
report["detections"] = self.detections
|
|
31
|
+
return copy.deepcopy(report)
|
|
32
|
+
|
|
33
|
+
def summary(self):
|
|
34
|
+
lines = [f"SolarOps: {self.counts['input_records']} records; "
|
|
35
|
+
f"{self.metadata['timezone']}; {self.metadata['unit']}; "
|
|
36
|
+
f"interval {self.metadata['interval']}"]
|
|
37
|
+
lines += [f"[{v['severity']}] {k} (count={v['count']}): {v['message']}"
|
|
38
|
+
for k, v in self.checks.items()]
|
|
39
|
+
lines += [f"{name}: {value:.2%}" for name, value in self.coverage.items()]
|
|
40
|
+
lines += [f"Note: {warning}" for warning in self.warnings]
|
|
41
|
+
lines += [f"Detection {name}: {len(report['findings'])} neutral findings"
|
|
42
|
+
for name, report in self.detections.items()]
|
|
43
|
+
return "\n".join(lines)
|
|
44
|
+
|
|
45
|
+
|
|
46
|
+
class SolarDataset:
|
|
47
|
+
"""One site, explicitly declared interval-average power in W or kW.
|
|
48
|
+
|
|
49
|
+
Use from_dataframe or from_csv. Analysis bounds are supplied to validate.
|
|
50
|
+
Original data is exposed as a defensive copy via original_data.
|
|
51
|
+
"""
|
|
52
|
+
|
|
53
|
+
def __init__(self, frame, *, timestamp_col, power_col, timezone, interval, unit,
|
|
54
|
+
measurement_type="interval_average_power"):
|
|
55
|
+
if measurement_type != "interval_average_power":
|
|
56
|
+
raise ValueError("Only measurement_type='interval_average_power' is supported; energy counters and instantaneous samples are unsupported")
|
|
57
|
+
if unit not in ("W", "kW"):
|
|
58
|
+
raise ValueError("unit must be explicitly declared as 'W' or 'kW'")
|
|
59
|
+
try:
|
|
60
|
+
ZoneInfo(timezone)
|
|
61
|
+
except (ZoneInfoNotFoundError, TypeError, ValueError) as exc:
|
|
62
|
+
raise ValueError("timezone must be an explicit IANA site timezone") from exc
|
|
63
|
+
try:
|
|
64
|
+
if isinstance(interval, (int, float, bool)):
|
|
65
|
+
raise ValueError("Use a duration string such as '15min'")
|
|
66
|
+
duration = pd.Timedelta(interval)
|
|
67
|
+
if pd.isna(duration) or duration <= pd.Timedelta(0):
|
|
68
|
+
raise ValueError("nonpositive interval")
|
|
69
|
+
except (ValueError, TypeError, OverflowError) as exc:
|
|
70
|
+
raise ValueError("interval must be a positive fixed duration, e.g. '15min'") from exc
|
|
71
|
+
if not isinstance(frame, pd.DataFrame):
|
|
72
|
+
raise TypeError("data must be a pandas DataFrame")
|
|
73
|
+
if not frame.columns.is_unique:
|
|
74
|
+
raise ValueError("DataFrame column names must be unique")
|
|
75
|
+
if timestamp_col == power_col or any(c not in frame for c in (timestamp_col, power_col)):
|
|
76
|
+
raise ValueError("timestamp_col and power_col must name distinct existing columns")
|
|
77
|
+
self._original = frame.copy(deep=True)
|
|
78
|
+
self.timestamp_col, self.power_col = timestamp_col, power_col
|
|
79
|
+
self.timezone, self.interval, self.unit = timezone, duration, unit
|
|
80
|
+
self.measurement_type = measurement_type
|
|
81
|
+
self._history = []
|
|
82
|
+
self._provenance = [{"source_rows": [row], "value_kind": "original", "inserted": False}
|
|
83
|
+
for row in range(len(frame))]
|
|
84
|
+
|
|
85
|
+
@classmethod
|
|
86
|
+
def from_dataframe(cls, frame, *, timestamp_col, power_col, timezone, interval, unit,
|
|
87
|
+
measurement_type="interval_average_power"):
|
|
88
|
+
return cls(frame, timestamp_col=timestamp_col, power_col=power_col,
|
|
89
|
+
timezone=timezone, interval=interval, unit=unit, measurement_type=measurement_type)
|
|
90
|
+
|
|
91
|
+
@classmethod
|
|
92
|
+
def from_csv(cls, path, *, timestamp_col, power_col, timezone, interval, unit,
|
|
93
|
+
measurement_type="interval_average_power", **read_csv_kwargs):
|
|
94
|
+
return cls.from_dataframe(pd.read_csv(path, **read_csv_kwargs),
|
|
95
|
+
timestamp_col=timestamp_col, power_col=power_col,
|
|
96
|
+
timezone=timezone, interval=interval, unit=unit,
|
|
97
|
+
measurement_type=measurement_type)
|
|
98
|
+
|
|
99
|
+
@property
|
|
100
|
+
def original_data(self):
|
|
101
|
+
return self._original.copy(deep=True)
|
|
102
|
+
|
|
103
|
+
@property
|
|
104
|
+
def history(self):
|
|
105
|
+
"""Serializable transformation records, returned as a defensive copy."""
|
|
106
|
+
return copy.deepcopy(self._history)
|
|
107
|
+
|
|
108
|
+
@property
|
|
109
|
+
def provenance(self):
|
|
110
|
+
"""One provenance mapping per current positional row, as a defensive copy."""
|
|
111
|
+
return copy.deepcopy(self._provenance)
|
|
112
|
+
|
|
113
|
+
def _timestamp(self, value):
|
|
114
|
+
if isinstance(value, (int, float, bool)):
|
|
115
|
+
raise ValueError("numeric timestamps are unsupported; use datetime strings")
|
|
116
|
+
stamp = pd.Timestamp(value)
|
|
117
|
+
if pd.isna(stamp):
|
|
118
|
+
raise ValueError("missing timestamp")
|
|
119
|
+
if stamp.tzinfo is None:
|
|
120
|
+
try:
|
|
121
|
+
stamp = stamp.tz_localize(self.timezone, ambiguous="raise", nonexistent="raise")
|
|
122
|
+
except Exception as exc:
|
|
123
|
+
# pandas 2 used timezone-backend exception types; pandas 3 can
|
|
124
|
+
# raise plain ValueError. Keep our documented diagnostics stable.
|
|
125
|
+
text = str(exc).lower()
|
|
126
|
+
if type(exc).__name__ == 'AmbiguousTimeError' or (
|
|
127
|
+
isinstance(exc, ValueError) and ('ambiguous' in text or 'cannot infer dst' in text)):
|
|
128
|
+
raise AmbiguousTimeError(f"Ambiguous local timestamp {value!s} in {self.timezone}; supply an aware timestamp with an explicit UTC offset") from exc
|
|
129
|
+
if type(exc).__name__ == 'NonExistentTimeError' or (
|
|
130
|
+
isinstance(exc, ValueError) and ('nonexistent' in text or 'nonexistent' in text.replace(' ', ''))):
|
|
131
|
+
raise NonExistentTimeError(f"Nonexistent local timestamp {value!s} in {self.timezone}; supply a valid aware timestamp") from exc
|
|
132
|
+
raise
|
|
133
|
+
return stamp.tz_convert(self.timezone)
|
|
134
|
+
|
|
135
|
+
def validate(self, *, analysis_start=None, analysis_end=None, minimum=None, maximum=None):
|
|
136
|
+
"""Validate without cleaning; optional bounds define [start, end).
|
|
137
|
+
|
|
138
|
+
Optional inclusive power limits report range findings independently
|
|
139
|
+
of numeric validity and usable-value coverage.
|
|
140
|
+
"""
|
|
141
|
+
from .quality import _analyze
|
|
142
|
+
|
|
143
|
+
return _analyze(self, start=analysis_start, end=analysis_end,
|
|
144
|
+
minimum=minimum, maximum=maximum)
|
solarops/detection.py
ADDED
|
@@ -0,0 +1,179 @@
|
|
|
1
|
+
"""Offline observations about patterns, without equipment-fault inference."""
|
|
2
|
+
|
|
3
|
+
from dataclasses import dataclass
|
|
4
|
+
import copy
|
|
5
|
+
|
|
6
|
+
import pandas as pd
|
|
7
|
+
from numbers import Number
|
|
8
|
+
|
|
9
|
+
from .preprocessing import _check_dataset, _timestamps, _unique
|
|
10
|
+
from .quality import _limit, _numeric, range_checks
|
|
11
|
+
from .exceptions import AnalysisBlockedError
|
|
12
|
+
|
|
13
|
+
__all__ = ["DetectionResult", "detect_flatlines", "detect_out_of_range"]
|
|
14
|
+
|
|
15
|
+
_NEUTRAL_NOTE = "Findings are data observations, not proof of an equipment fault or lost energy."
|
|
16
|
+
_ZERO_NOTE = "Zero periods are included; nighttime zero production can be normal. Daylight is not calculated."
|
|
17
|
+
|
|
18
|
+
|
|
19
|
+
@dataclass(frozen=True)
|
|
20
|
+
class DetectionResult:
|
|
21
|
+
"""Neutral findings with full evidence, configuration and limitations.
|
|
22
|
+
|
|
23
|
+
All row references use current dataset positions; evidence provenance carries
|
|
24
|
+
root source-row positions where available. to_dict returns an independent copy.
|
|
25
|
+
"""
|
|
26
|
+
|
|
27
|
+
metadata: dict
|
|
28
|
+
parameters: dict
|
|
29
|
+
counts: dict
|
|
30
|
+
findings: list
|
|
31
|
+
notes: list
|
|
32
|
+
|
|
33
|
+
def to_dict(self):
|
|
34
|
+
return copy.deepcopy({"metadata": self.metadata, "parameters": self.parameters,
|
|
35
|
+
"counts": self.counts, "findings": self.findings, "notes": self.notes})
|
|
36
|
+
|
|
37
|
+
def summary(self):
|
|
38
|
+
lines = [f"SolarOps {self.metadata['detector']}: {len(self.findings)} findings; "
|
|
39
|
+
f"{self.metadata['unit']}; {self.metadata['timezone']}"]
|
|
40
|
+
for finding in self.findings[:5]:
|
|
41
|
+
if finding["finding_type"] == "flatline":
|
|
42
|
+
lines.append(f"[{finding['start']}, {finding['end']}): "
|
|
43
|
+
f"{finding['measurement_count']} readings, duration {finding['duration']}, "
|
|
44
|
+
f"range {finding['minimum_value']} to {finding['maximum_value']} {finding['unit']}")
|
|
45
|
+
else:
|
|
46
|
+
lines.append(f"row {finding['row']}, timestamp {finding['timestamp']}: "
|
|
47
|
+
f"{finding['value']} {finding['unit']} outside configured limits")
|
|
48
|
+
if len(self.findings) > 5:
|
|
49
|
+
lines.append("Only the first 5 findings are displayed; findings/to_dict retain all evidence.")
|
|
50
|
+
lines += [f"{name}: {count}" for name, count in self.counts.items()]
|
|
51
|
+
lines += [f"Note: {note}" for note in self.notes]
|
|
52
|
+
return "\n".join(lines)
|
|
53
|
+
|
|
54
|
+
|
|
55
|
+
def _metadata(dataset, detector):
|
|
56
|
+
return {"detector": detector, "timezone": dataset.timezone, "unit": dataset.unit,
|
|
57
|
+
"interval": str(dataset.interval), "measurement_type": dataset.measurement_type,
|
|
58
|
+
"timestamp_convention": "interval_start", "history": dataset.history,
|
|
59
|
+
"value_source": "current_dataset_snapshot"}
|
|
60
|
+
|
|
61
|
+
|
|
62
|
+
def _evidence(dataset, row, stamp, value):
|
|
63
|
+
provenance = copy.deepcopy(dataset._provenance[row])
|
|
64
|
+
return {"row": row, "timestamp": stamp.isoformat() if stamp is not None else None,
|
|
65
|
+
"value": value, "provenance": provenance,
|
|
66
|
+
"is_derived": provenance["value_kind"] not in ("original", "inserted_missing")}
|
|
67
|
+
|
|
68
|
+
|
|
69
|
+
def _flatline_parameters(min_duration, tolerance):
|
|
70
|
+
try:
|
|
71
|
+
if isinstance(min_duration, Number) or min_duration is None:
|
|
72
|
+
raise ValueError("use a duration string")
|
|
73
|
+
duration = pd.Timedelta(min_duration)
|
|
74
|
+
if pd.isna(duration) or duration <= pd.Timedelta(0):
|
|
75
|
+
raise ValueError("duration must be positive")
|
|
76
|
+
except (ValueError, TypeError, OverflowError) as exc:
|
|
77
|
+
raise ValueError("min_duration must be a positive fixed duration, e.g. '2h'") from exc
|
|
78
|
+
tolerance = _limit(tolerance, "tolerance")
|
|
79
|
+
if tolerance is None or tolerance < 0:
|
|
80
|
+
raise ValueError("tolerance must be finite and nonnegative in the dataset's power unit")
|
|
81
|
+
return duration, tolerance
|
|
82
|
+
|
|
83
|
+
|
|
84
|
+
def detect_flatlines(dataset, *, min_duration, tolerance):
|
|
85
|
+
"""Greedy non-overlapping runs with total range <= tolerance.
|
|
86
|
+
|
|
87
|
+
Duration is count * interval; gaps/unavailable values break runs. Malformed,
|
|
88
|
+
duplicate or off-grid timestamps raise. Endpoints are [first, last + interval).
|
|
89
|
+
"""
|
|
90
|
+
_check_dataset(dataset)
|
|
91
|
+
duration, tolerance = _flatline_parameters(min_duration, tolerance)
|
|
92
|
+
stamps = _timestamps(dataset)
|
|
93
|
+
_unique(stamps)
|
|
94
|
+
order = sorted(range(len(stamps)), key=lambda row: stamps[row])
|
|
95
|
+
origin = stamps[order[0]] if order else None
|
|
96
|
+
for row in order:
|
|
97
|
+
if (stamps[row] - origin) % dataset.interval:
|
|
98
|
+
raise AnalysisBlockedError(f"Off-grid timestamp at row {row}; align timestamps to the declared interval before detection")
|
|
99
|
+
values = dataset._original[dataset.power_col].tolist()
|
|
100
|
+
findings, run = [], []
|
|
101
|
+
low = high = None
|
|
102
|
+
counts = {"input_records": len(values), "missing_power_values": 0, "invalid_power_values": 0,
|
|
103
|
+
"gap_breaks": 0, "flatline_periods": 0, "flatline_measurements": 0}
|
|
104
|
+
|
|
105
|
+
def flush():
|
|
106
|
+
if run and len(run) * dataset.interval >= duration:
|
|
107
|
+
first, last = stamps[run[0][0]], stamps[run[-1][0]]
|
|
108
|
+
evidence = [_evidence(dataset, row, stamps[row], value) for row, value in run]
|
|
109
|
+
findings.append({"finding_type": "flatline", "start": first.isoformat(),
|
|
110
|
+
"end": (last + dataset.interval).isoformat(), "end_exclusive": True,
|
|
111
|
+
"description": "Contiguous numeric readings vary by no more than configured tolerance",
|
|
112
|
+
"measurement_count": len(run), "minimum_value": min(v for _, v in run),
|
|
113
|
+
"maximum_value": max(v for _, v in run), "tolerance": tolerance,
|
|
114
|
+
"duration": str(len(run) * dataset.interval),
|
|
115
|
+
"duration_seconds": (len(run) * dataset.interval).total_seconds(),
|
|
116
|
+
"unit": dataset.unit, "contains_derived_values": any(e["is_derived"] for e in evidence),
|
|
117
|
+
"evidence": evidence, "notes": [_NEUTRAL_NOTE, _ZERO_NOTE]})
|
|
118
|
+
|
|
119
|
+
for row in order:
|
|
120
|
+
state, value = _numeric(values[row])
|
|
121
|
+
if state != "valid":
|
|
122
|
+
counts["missing_power_values" if state == "missing" else "invalid_power_values"] += 1
|
|
123
|
+
flush()
|
|
124
|
+
run, low, high = [], None, None
|
|
125
|
+
continue
|
|
126
|
+
if run:
|
|
127
|
+
gap = stamps[row] - stamps[run[-1][0]] != dataset.interval
|
|
128
|
+
if gap:
|
|
129
|
+
counts["gap_breaks"] += 1
|
|
130
|
+
if gap or max(high, value) - min(low, value) > tolerance:
|
|
131
|
+
flush()
|
|
132
|
+
run, low, high = [], None, None
|
|
133
|
+
low = value if low is None else min(low, value)
|
|
134
|
+
high = value if high is None else max(high, value)
|
|
135
|
+
run.append((row, value))
|
|
136
|
+
flush()
|
|
137
|
+
counts["flatline_periods"] = len(findings)
|
|
138
|
+
counts["flatline_measurements"] = sum(f["measurement_count"] for f in findings)
|
|
139
|
+
metadata = _metadata(dataset, "flatlines")
|
|
140
|
+
metadata["grid_origin"] = origin.isoformat() if origin is not None else None
|
|
141
|
+
return DetectionResult(metadata,
|
|
142
|
+
{"min_duration": str(duration), "tolerance": tolerance,
|
|
143
|
+
"candidate_policy": "greedy_nonoverlapping_total_range"}, counts, findings,
|
|
144
|
+
[_NEUTRAL_NOTE, _ZERO_NOTE,
|
|
145
|
+
"Runs use current values, including derived values; no interpolation or cleaning is performed.",
|
|
146
|
+
"Greedy segmentation does not enumerate every overlapping qualifying window; completeness outside observed bounds is unknown."])
|
|
147
|
+
|
|
148
|
+
|
|
149
|
+
def detect_out_of_range(dataset, *, minimum=None, maximum=None):
|
|
150
|
+
"""Finite values outside inclusive limits, reusing quality.range_checks.
|
|
151
|
+
|
|
152
|
+
Invalid timestamps do not discard numeric range evidence; row references,
|
|
153
|
+
raw timestamps and explicit limitations are retained. Duplicates are checked
|
|
154
|
+
independently as records; missing and invalid numeric counts are separate.
|
|
155
|
+
"""
|
|
156
|
+
_check_dataset(dataset)
|
|
157
|
+
report = range_checks(dataset, minimum=minimum, maximum=maximum)
|
|
158
|
+
# The range check already validated limits, numeric classification and times.
|
|
159
|
+
findings = []
|
|
160
|
+
for item in report.details["range"]:
|
|
161
|
+
row = item["row"]
|
|
162
|
+
stamp = pd.Timestamp(item["timestamp"]) if item["timestamp"] is not None else None
|
|
163
|
+
evidence = _evidence(dataset, row, stamp, item["value"])
|
|
164
|
+
limitation = ("Timestamp could not be parsed or localized unambiguously; use current row and root source-row references."
|
|
165
|
+
if stamp is None else None)
|
|
166
|
+
findings.append({**item, "finding_type": "out_of_range",
|
|
167
|
+
"description": "Finite numeric power outside caller-configured inclusive limits",
|
|
168
|
+
"provenance": evidence["provenance"], "is_derived": evidence["is_derived"],
|
|
169
|
+
"timestamp_limitation": limitation, "notes": [_NEUTRAL_NOTE]})
|
|
170
|
+
# Reuse numeric classification, independently of timestamp validity.
|
|
171
|
+
states = [_numeric(value)[0] for value in dataset._original[dataset.power_col]]
|
|
172
|
+
return DetectionResult(_metadata(dataset, "out_of_range"), report.metadata["range_limits"],
|
|
173
|
+
{"input_records": len(states), "out_of_range_values": len(findings),
|
|
174
|
+
"missing_power_values": states.count("missing"),
|
|
175
|
+
"invalid_power_values": states.count("invalid"),
|
|
176
|
+
"unparseable_finding_timestamps": sum(f["timestamp"] is None for f in findings)},
|
|
177
|
+
findings, [_NEUTRAL_NOTE,
|
|
178
|
+
"Missing, nonnumeric, boolean and nonfinite readings are not out-of-range values; inspect solarops.quality for row details.",
|
|
179
|
+
"Every input record is checked, including duplicates and records with malformed timestamps."])
|
solarops/exceptions.py
ADDED
|
@@ -0,0 +1,19 @@
|
|
|
1
|
+
"""Expected analysis failures that can safely become blocked report sections."""
|
|
2
|
+
|
|
3
|
+
|
|
4
|
+
class AnalysisBlockedError(ValueError):
|
|
5
|
+
"""Data quality or retained provenance prevents an unambiguous calculation."""
|
|
6
|
+
|
|
7
|
+
|
|
8
|
+
class AmbiguousTimeError(ValueError):
|
|
9
|
+
"""A naive local timestamp identifies multiple instants during a DST fold."""
|
|
10
|
+
|
|
11
|
+
|
|
12
|
+
class NonExistentTimeError(ValueError):
|
|
13
|
+
"""A naive local timestamp falls inside a daylight-saving clock gap."""
|
|
14
|
+
|
|
15
|
+
|
|
16
|
+
def _timestamp_error(exc):
|
|
17
|
+
"""Known parser/localization failures; do not disguise programming errors."""
|
|
18
|
+
return isinstance(exc, (ValueError, TypeError, OverflowError)) or type(exc).__name__ in (
|
|
19
|
+
'AmbiguousTimeError', 'NonExistentTimeError')
|
solarops/metrics.py
ADDED
|
@@ -0,0 +1,266 @@
|
|
|
1
|
+
"""Coverage-aware metrics for interval-start, interval-average power."""
|
|
2
|
+
|
|
3
|
+
from bisect import bisect_left
|
|
4
|
+
import copy
|
|
5
|
+
from dataclasses import dataclass
|
|
6
|
+
from datetime import date, datetime, timedelta
|
|
7
|
+
import math
|
|
8
|
+
from numbers import Real
|
|
9
|
+
import re
|
|
10
|
+
|
|
11
|
+
import pandas as pd
|
|
12
|
+
from pandas.api.types import is_bool
|
|
13
|
+
|
|
14
|
+
from .preprocessing import _check_dataset, _timestamps, _unique
|
|
15
|
+
from .quality import _numeric, _period
|
|
16
|
+
from .exceptions import AnalysisBlockedError
|
|
17
|
+
|
|
18
|
+
__all__ = ["MetricResult", "DailyEnergyResult", "calculate_energy", "daily_energy", "peak_power"]
|
|
19
|
+
|
|
20
|
+
|
|
21
|
+
@dataclass(frozen=True)
|
|
22
|
+
class MetricResult:
|
|
23
|
+
"""One period's metric, coverage, evidence and interpretation.
|
|
24
|
+
|
|
25
|
+
to_dict returns an independent JSON-compatible copy. No-data values use
|
|
26
|
+
None; numeric zero means observed zero, never an unavailable measurement.
|
|
27
|
+
"""
|
|
28
|
+
|
|
29
|
+
metadata: dict
|
|
30
|
+
values: dict
|
|
31
|
+
coverage: dict
|
|
32
|
+
evidence: list
|
|
33
|
+
notes: list
|
|
34
|
+
|
|
35
|
+
def to_dict(self):
|
|
36
|
+
return copy.deepcopy({"metadata": self.metadata, "values": self.values,
|
|
37
|
+
"coverage": self.coverage, "evidence": self.evidence, "notes": self.notes})
|
|
38
|
+
|
|
39
|
+
def summary(self):
|
|
40
|
+
if self.metadata["metric"] == "energy":
|
|
41
|
+
text = (f"observed energy {self.values['observed_energy_kwh']} kWh; "
|
|
42
|
+
f"accepted energy {self.values['accepted_energy_kwh']} kWh")
|
|
43
|
+
else:
|
|
44
|
+
text = (f"peak interval-average power {self.values['peak_power']} {self.metadata['power_unit']}; "
|
|
45
|
+
f"{len(self.values['timestamps'])} occurrence(s)")
|
|
46
|
+
return (f"SolarOps {self.metadata['metric']}: {self.values['status']}; {text}; "
|
|
47
|
+
f"coverage {self.coverage['coverage']:.2%}\n"
|
|
48
|
+
+ "\n".join(f"Note: {note}" for note in self.notes))
|
|
49
|
+
|
|
50
|
+
|
|
51
|
+
@dataclass(frozen=True)
|
|
52
|
+
class DailyEnergyResult:
|
|
53
|
+
"""Per-local-day MetricResults; to_dataframe gives a convenient table."""
|
|
54
|
+
|
|
55
|
+
metadata: dict
|
|
56
|
+
days: list
|
|
57
|
+
|
|
58
|
+
def to_dict(self):
|
|
59
|
+
return {"metadata": copy.deepcopy(self.metadata),
|
|
60
|
+
"days": [{"local_date": day.metadata["local_date"], **day.to_dict()} for day in self.days]}
|
|
61
|
+
|
|
62
|
+
def to_dataframe(self):
|
|
63
|
+
columns = ["local_date", "observed_energy_kwh", "accepted_energy_kwh", "expected_intervals",
|
|
64
|
+
"usable_intervals", "coverage", "complete", "status"]
|
|
65
|
+
return pd.DataFrame([{
|
|
66
|
+
"local_date": day.metadata["local_date"],
|
|
67
|
+
"observed_energy_kwh": day.values["observed_energy_kwh"],
|
|
68
|
+
"accepted_energy_kwh": day.values["accepted_energy_kwh"],
|
|
69
|
+
"expected_intervals": day.coverage["expected_intervals"],
|
|
70
|
+
"usable_intervals": day.coverage["usable_intervals"],
|
|
71
|
+
"coverage": day.coverage["coverage"], "complete": day.coverage["complete"],
|
|
72
|
+
"status": day.values["status"],
|
|
73
|
+
} for day in self.days], columns=columns)
|
|
74
|
+
|
|
75
|
+
def summary(self):
|
|
76
|
+
lines = [f"SolarOps daily energy: {len(self.days)} local days; {self.metadata['timezone']}"]
|
|
77
|
+
lines += [f"{day.metadata['local_date']}: {day.values['status']}; "
|
|
78
|
+
f"observed {day.values['observed_energy_kwh']} kWh; "
|
|
79
|
+
f"accepted {day.values['accepted_energy_kwh']} kWh; "
|
|
80
|
+
f"coverage {day.coverage['coverage']:.2%}" for day in self.days]
|
|
81
|
+
return "\n".join(lines)
|
|
82
|
+
|
|
83
|
+
|
|
84
|
+
def _threshold(min_coverage):
|
|
85
|
+
if (is_bool(min_coverage) or not isinstance(min_coverage, Real)
|
|
86
|
+
or not math.isfinite(min_coverage) or not 0 <= min_coverage <= 1):
|
|
87
|
+
raise ValueError("min_coverage must be a finite number between 0 and 1")
|
|
88
|
+
return float(min_coverage)
|
|
89
|
+
|
|
90
|
+
|
|
91
|
+
def _bounds(dataset, start, end):
|
|
92
|
+
_check_dataset(dataset)
|
|
93
|
+
if dataset.unit not in ("W", "kW"):
|
|
94
|
+
raise ValueError("Metrics support declared W or kW only")
|
|
95
|
+
if start is None or end is None:
|
|
96
|
+
raise ValueError("Explicit start and end are required")
|
|
97
|
+
return _period(dataset, start, end)
|
|
98
|
+
|
|
99
|
+
|
|
100
|
+
def _prepare(dataset, start, end):
|
|
101
|
+
# Invalid times anywhere are blocking: they cannot safely be assigned outside
|
|
102
|
+
# the requested period. Known non-overlapping records are deliberately ignored.
|
|
103
|
+
stamps = _timestamps(dataset)
|
|
104
|
+
rows = [row for row, stamp in enumerate(stamps)
|
|
105
|
+
if stamp < end and stamp + dataset.interval > start]
|
|
106
|
+
_unique([stamps[row] for row in rows])
|
|
107
|
+
for row in rows:
|
|
108
|
+
if (stamps[row] - start) % dataset.interval:
|
|
109
|
+
raise AnalysisBlockedError(f"Off-grid or partially overlapping interval at row {row}; align bounds and source starts without splitting intervals")
|
|
110
|
+
rows.sort(key=lambda row: stamps[row])
|
|
111
|
+
return [(stamps[row], row) for row in rows]
|
|
112
|
+
|
|
113
|
+
|
|
114
|
+
def _source_fraction(provenance):
|
|
115
|
+
fraction = provenance.get("coverage", 1.0)
|
|
116
|
+
if is_bool(fraction) or not isinstance(fraction, Real) or not math.isfinite(fraction) or not 0 <= fraction <= 1:
|
|
117
|
+
raise AnalysisBlockedError("Invalid source coverage in provenance")
|
|
118
|
+
if fraction < 1:
|
|
119
|
+
# Only the supported resampler retains enough information to interpret
|
|
120
|
+
# an available-only mean as covered-duration energy. Duplicate means
|
|
121
|
+
# of partially covered bins do not retain sufficient duration semantics.
|
|
122
|
+
if not all(key in provenance for key in ("bin_start", "bin_end", "expected_source_intervals", "usable_source_intervals")):
|
|
123
|
+
raise AnalysisBlockedError("Partial derived coverage lacks resampling duration evidence; calculate metrics on the original finer data")
|
|
124
|
+
expected = provenance["expected_source_intervals"]
|
|
125
|
+
usable = provenance["usable_source_intervals"]
|
|
126
|
+
if expected <= 0 or not math.isclose(usable / expected, fraction, rel_tol=0, abs_tol=1e-12):
|
|
127
|
+
raise AnalysisBlockedError("Inconsistent resampling coverage provenance; use the original finer data")
|
|
128
|
+
return float(fraction)
|
|
129
|
+
|
|
130
|
+
|
|
131
|
+
def _context(dataset, start, end, prepared):
|
|
132
|
+
left = bisect_left(prepared, (start, -1))
|
|
133
|
+
right = bisect_left(prepared, (end, -1))
|
|
134
|
+
selected = prepared[left:right]
|
|
135
|
+
expected = int((end - start) // dataset.interval)
|
|
136
|
+
hours = float(dataset.interval / pd.Timedelta('1h'))
|
|
137
|
+
evidence, missing, invalid, fractions = [], 0, 0, []
|
|
138
|
+
values = dataset._original[dataset.power_col]
|
|
139
|
+
for stamp, row in selected:
|
|
140
|
+
state, number = _numeric(values.iloc[row])
|
|
141
|
+
provenance = copy.deepcopy(dataset._provenance[row])
|
|
142
|
+
fraction = _source_fraction(provenance) if state == "valid" else 0.0
|
|
143
|
+
if state == "missing":
|
|
144
|
+
missing += 1
|
|
145
|
+
elif state == "invalid":
|
|
146
|
+
invalid += 1
|
|
147
|
+
if state == "valid":
|
|
148
|
+
fractions.append(fraction)
|
|
149
|
+
evidence.append({"row": row, "timestamp": stamp.isoformat(), "numeric_state": state,
|
|
150
|
+
"value": number, "raw_value": str(values.iloc[row]),
|
|
151
|
+
"source_coverage": fraction, "usable_duration_hours": hours * fraction,
|
|
152
|
+
"provenance": provenance,
|
|
153
|
+
"is_derived": provenance["value_kind"] not in ("original", "inserted_missing")})
|
|
154
|
+
equivalent_intervals = math.fsum(fractions)
|
|
155
|
+
complete = all(f == 1 for f in fractions) and len(fractions) == expected
|
|
156
|
+
coverage = {"expected_intervals": expected, "present_intervals": len(selected),
|
|
157
|
+
"missing_intervals": expected - len(selected), "usable_intervals": len(fractions),
|
|
158
|
+
"fully_usable_intervals": sum(f == 1 for f in fractions),
|
|
159
|
+
"missing_power_values": missing, "invalid_power_values": invalid,
|
|
160
|
+
"expected_duration_hours": float((end - start) / pd.Timedelta('1h')),
|
|
161
|
+
"usable_duration_hours": equivalent_intervals * hours,
|
|
162
|
+
"coverage": equivalent_intervals / expected,
|
|
163
|
+
"timestamp_presence": len(selected) / expected,
|
|
164
|
+
"numeric_value_coverage": len(fractions) / expected,
|
|
165
|
+
"complete": complete}
|
|
166
|
+
notes = ["Negative finite power is retained with its sign; no equipment-fault interpretation is applied.",
|
|
167
|
+
"Results describe the current interval-average input series; missing production is not zero or estimated."]
|
|
168
|
+
if not complete:
|
|
169
|
+
notes.append("Coverage is incomplete; observed energy is partial and the recorded peak may miss the true period peak.")
|
|
170
|
+
if any(e["is_derived"] for e in evidence):
|
|
171
|
+
notes.append("Derived values are included with provenance; this is not necessarily the original meter series or high-resolution peak.")
|
|
172
|
+
if any(0 < f < 1 for f in fractions):
|
|
173
|
+
notes.append("Partial resampled means contribute only their provenance-covered duration, never the full bin duration.")
|
|
174
|
+
metadata = {"start": start.isoformat(), "end": end.isoformat(), "end_exclusive": True,
|
|
175
|
+
"timezone": dataset.timezone, "power_unit": dataset.unit, "energy_unit": "kWh",
|
|
176
|
+
"interval": str(dataset.interval), "measurement_type": dataset.measurement_type,
|
|
177
|
+
"timestamp_convention": "interval_start", "grid_origin": start.isoformat(),
|
|
178
|
+
"input_records": len(dataset._original), "outside_period_records": len(dataset._original) - len(selected),
|
|
179
|
+
"history": dataset.history, "value_source": "current_dataset_snapshot",
|
|
180
|
+
"coverage_basis": "finite_numeric_duration_with_available_source_coverage"}
|
|
181
|
+
return metadata, coverage, evidence, notes
|
|
182
|
+
|
|
183
|
+
|
|
184
|
+
def _energy(dataset, start, end, threshold, prepared):
|
|
185
|
+
metadata, coverage, evidence, notes = _context(dataset, start, end, prepared)
|
|
186
|
+
metadata["metric"] = "energy"
|
|
187
|
+
usable = [e for e in evidence if e["numeric_state"] == "valid" and e["source_coverage"] > 0]
|
|
188
|
+
factor = 1 if dataset.unit == "kW" else 0.001
|
|
189
|
+
try:
|
|
190
|
+
observed = math.fsum((e["value"] * factor) * e["usable_duration_hours"] for e in usable) if usable else None
|
|
191
|
+
except OverflowError as exc:
|
|
192
|
+
raise AnalysisBlockedError("Energy calculation overflows; check power values and duration") from exc
|
|
193
|
+
if observed is not None and not math.isfinite(observed):
|
|
194
|
+
raise AnalysisBlockedError("Energy calculation overflows; check power values and duration")
|
|
195
|
+
accepted = observed is not None and coverage["coverage"] >= threshold
|
|
196
|
+
status = ("no_data" if observed is None else "complete" if coverage["complete"] else
|
|
197
|
+
"accepted_partial" if accepted else "insufficient_coverage")
|
|
198
|
+
explanation = ("No usable data; no energy total is available." if observed is None else
|
|
199
|
+
"Complete covered-duration energy." if coverage["complete"] else
|
|
200
|
+
"Observed partial energy accepted at caller threshold; not scaled to a full-period estimate." if accepted else
|
|
201
|
+
"Observed partial energy is below the required coverage; no accepted total.")
|
|
202
|
+
return MetricResult(metadata, {"observed_energy_kwh": observed,
|
|
203
|
+
"accepted_energy_kwh": observed if accepted else None,
|
|
204
|
+
"min_coverage": threshold, "accepted": accepted, "status": status,
|
|
205
|
+
"explanation": explanation}, coverage, evidence, notes)
|
|
206
|
+
|
|
207
|
+
|
|
208
|
+
def calculate_energy(dataset, *, start, end, min_coverage=1.0):
|
|
209
|
+
"""Observed and threshold-accepted energy in kWh over explicit [start, end)."""
|
|
210
|
+
threshold = _threshold(min_coverage)
|
|
211
|
+
start, end = _bounds(dataset, start, end)
|
|
212
|
+
return _energy(dataset, start, end, threshold, _prepare(dataset, start, end))
|
|
213
|
+
|
|
214
|
+
|
|
215
|
+
def _calendar_date(value):
|
|
216
|
+
if isinstance(value, date) and not isinstance(value, datetime):
|
|
217
|
+
return value
|
|
218
|
+
if isinstance(value, str) and re.fullmatch(r"\d{4}-\d{2}-\d{2}", value):
|
|
219
|
+
try:
|
|
220
|
+
return date.fromisoformat(value)
|
|
221
|
+
except ValueError:
|
|
222
|
+
pass
|
|
223
|
+
raise ValueError("Daily bounds must be local calendar dates (YYYY-MM-DD strings or datetime.date), not datetimes")
|
|
224
|
+
|
|
225
|
+
|
|
226
|
+
def daily_energy(dataset, *, start, end, min_coverage=1.0):
|
|
227
|
+
"""One energy result per site-local date, start-inclusive/end-exclusive."""
|
|
228
|
+
_check_dataset(dataset)
|
|
229
|
+
threshold = _threshold(min_coverage)
|
|
230
|
+
first, stop = _calendar_date(start), _calendar_date(end)
|
|
231
|
+
if stop <= first:
|
|
232
|
+
raise ValueError("Daily date range must be positive")
|
|
233
|
+
dates = [first + timedelta(days=n) for n in range((stop - first).days + 1)]
|
|
234
|
+
# Localize each calendar midnight independently: adding 24 elapsed hours
|
|
235
|
+
# would incorrectly construct 23/25-hour local days.
|
|
236
|
+
try:
|
|
237
|
+
boundaries = [dataset._timestamp(day.isoformat()) for day in dates]
|
|
238
|
+
except Exception as exc:
|
|
239
|
+
raise ValueError(f"Invalid site-local midnight boundary: {type(exc).__name__}: {exc}") from exc
|
|
240
|
+
for left, right in zip(boundaries[:-1], boundaries[1:]):
|
|
241
|
+
_bounds(dataset, left, right)
|
|
242
|
+
prepared = _prepare(dataset, boundaries[0], boundaries[-1])
|
|
243
|
+
results = []
|
|
244
|
+
for day, left, right in zip(dates[:-1], boundaries[:-1], boundaries[1:]):
|
|
245
|
+
result = _energy(dataset, left, right, threshold, prepared)
|
|
246
|
+
result.metadata["local_date"] = day.isoformat()
|
|
247
|
+
results.append(result)
|
|
248
|
+
return DailyEnergyResult({"start_date": first.isoformat(), "end_date": stop.isoformat(),
|
|
249
|
+
"end_exclusive": True, "timezone": dataset.timezone,
|
|
250
|
+
"power_unit": dataset.unit, "energy_unit": "kWh", "min_coverage": threshold,
|
|
251
|
+
"measurement_type": dataset.measurement_type, "history": dataset.history}, results)
|
|
252
|
+
|
|
253
|
+
|
|
254
|
+
def peak_power(dataset, *, start, end):
|
|
255
|
+
"""Maximum finite interval-average reading, with all tied occurrences."""
|
|
256
|
+
start, end = _bounds(dataset, start, end)
|
|
257
|
+
metadata, coverage, evidence, notes = _context(dataset, start, end, _prepare(dataset, start, end))
|
|
258
|
+
metadata["metric"] = "peak_power"
|
|
259
|
+
usable = [e for e in evidence if e["numeric_state"] == "valid"]
|
|
260
|
+
peak = max((e["value"] for e in usable), default=None)
|
|
261
|
+
occurrences = [e for e in usable if e["value"] == peak]
|
|
262
|
+
notes.append("Peak means maximum recorded interval-average power, not an instantaneous maximum; all equal maxima are returned.")
|
|
263
|
+
return MetricResult(metadata, {"peak_power": peak, "timestamps": [e["timestamp"] for e in occurrences],
|
|
264
|
+
"occurrences": copy.deepcopy(occurrences),
|
|
265
|
+
"status": "no_data" if peak is None else "complete" if coverage["complete"] else "partial"},
|
|
266
|
+
coverage, evidence, notes)
|