historecon 0.2.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.
- historecon/__init__.py +40 -0
- historecon/alerting.py +250 -0
- historecon/baseline.py +151 -0
- historecon/classifier.py +24 -0
- historecon/config.py +127 -0
- historecon/dashboard.py +272 -0
- historecon/engine.py +182 -0
- historecon/incidents.py +114 -0
- historecon/model_monitor.py +169 -0
- historecon/models.py +66 -0
- historecon/normalize.py +60 -0
- historecon/notifications.py +327 -0
- historecon/observability.py +73 -0
- historecon/postgres_store.py +126 -0
- historecon/regression.py +483 -0
- historecon/settings.py +56 -0
- historecon/worker.py +37 -0
- historecon-0.2.0.dist-info/METADATA +466 -0
- historecon-0.2.0.dist-info/RECORD +21 -0
- historecon-0.2.0.dist-info/WHEEL +4 -0
- historecon-0.2.0.dist-info/licenses/LICENSE +17 -0
historecon/__init__.py
ADDED
|
@@ -0,0 +1,40 @@
|
|
|
1
|
+
"""Explainable diagnostics for industrial time-series data."""
|
|
2
|
+
|
|
3
|
+
from .config import DiagnosticConfig, StatusProfile
|
|
4
|
+
from .engine import DiagnosticEngine
|
|
5
|
+
from .model_monitor import ModelMonitor
|
|
6
|
+
from .alerting import AlertManager
|
|
7
|
+
from .notifications import (
|
|
8
|
+
NotificationDispatcher, NotificationRetryWorker,
|
|
9
|
+
SlackWebhookAdapter, TeamsWebhookAdapter, WebhookAdapter, WebhookDeliveryError,
|
|
10
|
+
)
|
|
11
|
+
from .dashboard import DashboardConfig, render_dashboard
|
|
12
|
+
from .settings import HistoreconSettings
|
|
13
|
+
from .observability import JsonLogFormatter, WorkerMetrics, configure_logging
|
|
14
|
+
from .postgres_store import PostgresEventStore
|
|
15
|
+
from .models import Finding, DiagnosticReport, StatusCategory
|
|
16
|
+
|
|
17
|
+
__all__ = [
|
|
18
|
+
"DiagnosticConfig",
|
|
19
|
+
"StatusProfile",
|
|
20
|
+
"DiagnosticEngine",
|
|
21
|
+
"ModelMonitor",
|
|
22
|
+
"AlertManager",
|
|
23
|
+
"NotificationDispatcher",
|
|
24
|
+
"NotificationRetryWorker",
|
|
25
|
+
"SlackWebhookAdapter",
|
|
26
|
+
"TeamsWebhookAdapter",
|
|
27
|
+
"WebhookAdapter",
|
|
28
|
+
"WebhookDeliveryError",
|
|
29
|
+
"HistoreconSettings",
|
|
30
|
+
"JsonLogFormatter",
|
|
31
|
+
"WorkerMetrics",
|
|
32
|
+
"configure_logging",
|
|
33
|
+
"PostgresEventStore",
|
|
34
|
+
"DashboardConfig",
|
|
35
|
+
"render_dashboard",
|
|
36
|
+
"Finding",
|
|
37
|
+
"DiagnosticReport",
|
|
38
|
+
"StatusCategory",
|
|
39
|
+
]
|
|
40
|
+
__version__ = "0.2.0"
|
historecon/alerting.py
ADDED
|
@@ -0,0 +1,250 @@
|
|
|
1
|
+
"""Persistent, deduplicated model-health alert lifecycle."""
|
|
2
|
+
|
|
3
|
+
from datetime import datetime, timezone
|
|
4
|
+
import json
|
|
5
|
+
import os
|
|
6
|
+
import uuid
|
|
7
|
+
|
|
8
|
+
|
|
9
|
+
class AlertManager:
|
|
10
|
+
"""Maintain alert state and an append-only event log.
|
|
11
|
+
|
|
12
|
+
Alerts are deduplicated by model identity and rule. Acknowledgement is a
|
|
13
|
+
state transition, not a deletion; recovery closes an active or acknowledged
|
|
14
|
+
alert while retaining its full event history.
|
|
15
|
+
"""
|
|
16
|
+
|
|
17
|
+
def __init__(self, event_path=None, distribution_shift_runs=3, event_store=None):
|
|
18
|
+
if distribution_shift_runs < 1:
|
|
19
|
+
raise ValueError("distribution_shift_runs must be >= 1")
|
|
20
|
+
self.event_path = os.fspath(event_path) if event_path is not None else None
|
|
21
|
+
self.distribution_shift_runs = int(distribution_shift_runs)
|
|
22
|
+
self.event_store = event_store
|
|
23
|
+
self._events = self._load_events()
|
|
24
|
+
self._alerts = {}
|
|
25
|
+
self._rebuild()
|
|
26
|
+
|
|
27
|
+
def evaluate(self, snapshots, history):
|
|
28
|
+
"""Evaluate current snapshots and append alert lifecycle events."""
|
|
29
|
+
created = []
|
|
30
|
+
current_keys = set()
|
|
31
|
+
for snapshot in snapshots:
|
|
32
|
+
key = snapshot.get("model_key")
|
|
33
|
+
if not key:
|
|
34
|
+
continue
|
|
35
|
+
current_keys.add(key)
|
|
36
|
+
model_history = [row for row in history if row.get("model_key") == key]
|
|
37
|
+
streak = _consecutive_shift_runs(model_history)
|
|
38
|
+
alert_key = _alert_key(key, "PERSISTENT_DISTRIBUTION_SHIFT")
|
|
39
|
+
active = self._alerts.get(alert_key)
|
|
40
|
+
if streak >= self.distribution_shift_runs:
|
|
41
|
+
if active is None or active["status"] == "RECOVERED":
|
|
42
|
+
created.append(self._emit(
|
|
43
|
+
"OPENED", alert_key, key, snapshot,
|
|
44
|
+
details={
|
|
45
|
+
"rule": "PERSISTENT_DISTRIBUTION_SHIFT",
|
|
46
|
+
"consecutive_runs": streak,
|
|
47
|
+
"threshold_runs": self.distribution_shift_runs,
|
|
48
|
+
"reliability_status": snapshot.get("reliability_status"),
|
|
49
|
+
},
|
|
50
|
+
))
|
|
51
|
+
elif active is not None and active["status"] in ("OPEN", "ACKNOWLEDGED"):
|
|
52
|
+
if snapshot.get("reliability_status") != "DISTRIBUTION_SHIFT_SUSPECTED":
|
|
53
|
+
created.append(self._emit(
|
|
54
|
+
"RECOVERED", alert_key, key, snapshot,
|
|
55
|
+
details={
|
|
56
|
+
"recovered_from": active["status"],
|
|
57
|
+
"reliability_status": snapshot.get("reliability_status"),
|
|
58
|
+
},
|
|
59
|
+
))
|
|
60
|
+
return created
|
|
61
|
+
|
|
62
|
+
def acknowledge(self, alert_id, acknowledged_by=None, note=None, acknowledged_at=None):
|
|
63
|
+
"""Acknowledge an open alert. Returns the new event or None if not open."""
|
|
64
|
+
alert = self._find_alert(alert_id)
|
|
65
|
+
if alert is None or alert["status"] != "OPEN":
|
|
66
|
+
return None
|
|
67
|
+
return self._emit(
|
|
68
|
+
"ACKNOWLEDGED", alert["alert_key"], alert["model_key"],
|
|
69
|
+
{"tag": alert.get("tag"), "operating_mode_key": alert.get("operating_mode_key"),
|
|
70
|
+
"run_id": alert.get("last_run_id"), "recorded_at": _timestamp(acknowledged_at)},
|
|
71
|
+
details={"acknowledged_by": acknowledged_by, "note": note},
|
|
72
|
+
event_time=_timestamp(acknowledged_at),
|
|
73
|
+
)
|
|
74
|
+
|
|
75
|
+
def alerts(self, status=None, model_key=None):
|
|
76
|
+
"""Return latest alert state, optionally filtered."""
|
|
77
|
+
values = list(self._alerts.values())
|
|
78
|
+
if status is not None:
|
|
79
|
+
values = [item for item in values if item["status"] == status]
|
|
80
|
+
if model_key is not None:
|
|
81
|
+
values = [item for item in values if item["model_key"] == model_key]
|
|
82
|
+
return [dict(item) for item in sorted(values, key=lambda x: x["created_at"])]
|
|
83
|
+
|
|
84
|
+
def events(self, alert_id=None):
|
|
85
|
+
"""Return immutable lifecycle events in append order."""
|
|
86
|
+
return [dict(item) for item in self._events
|
|
87
|
+
if alert_id is None or item["alert_id"] == alert_id]
|
|
88
|
+
|
|
89
|
+
def _find_alert(self, alert_id):
|
|
90
|
+
for alert in self._alerts.values():
|
|
91
|
+
if alert["alert_id"] == alert_id:
|
|
92
|
+
return alert
|
|
93
|
+
return None
|
|
94
|
+
|
|
95
|
+
def _emit(self, event_type, alert_key, model_key, snapshot, details=None, event_time=None):
|
|
96
|
+
previous = self._alerts.get(alert_key)
|
|
97
|
+
if event_type == "OPENED":
|
|
98
|
+
alert_id = str(uuid.uuid4())
|
|
99
|
+
created_at = event_time or snapshot.get("recorded_at") or _timestamp(None)
|
|
100
|
+
status = "OPEN"
|
|
101
|
+
else:
|
|
102
|
+
if previous is None:
|
|
103
|
+
return None
|
|
104
|
+
alert_id = previous["alert_id"]
|
|
105
|
+
created_at = previous["created_at"]
|
|
106
|
+
status = "ACKNOWLEDGED" if event_type == "ACKNOWLEDGED" else "RECOVERED"
|
|
107
|
+
event = {
|
|
108
|
+
"event_id": str(uuid.uuid4()),
|
|
109
|
+
"alert_id": alert_id,
|
|
110
|
+
"event_type": event_type,
|
|
111
|
+
"alert_key": alert_key,
|
|
112
|
+
"model_key": model_key,
|
|
113
|
+
"tag": snapshot.get("tag"),
|
|
114
|
+
"operating_mode_key": snapshot.get("operating_mode_key"),
|
|
115
|
+
"run_id": snapshot.get("run_id"),
|
|
116
|
+
"occurred_at": event_time or snapshot.get("recorded_at") or _timestamp(None),
|
|
117
|
+
"details": details or {},
|
|
118
|
+
}
|
|
119
|
+
self._events.append(event)
|
|
120
|
+
if status == "RECOVERED":
|
|
121
|
+
state = dict(previous)
|
|
122
|
+
state.update({
|
|
123
|
+
"status": "RECOVERED",
|
|
124
|
+
"recovered_at": event["occurred_at"],
|
|
125
|
+
"last_event_id": event["event_id"],
|
|
126
|
+
"last_run_id": snapshot.get("run_id"),
|
|
127
|
+
})
|
|
128
|
+
elif event_type == "ACKNOWLEDGED":
|
|
129
|
+
state = dict(previous)
|
|
130
|
+
state.update({
|
|
131
|
+
"status": "ACKNOWLEDGED",
|
|
132
|
+
"acknowledged_at": event["occurred_at"],
|
|
133
|
+
"acknowledged_by": (details or {}).get("acknowledged_by"),
|
|
134
|
+
"acknowledgement_note": (details or {}).get("note"),
|
|
135
|
+
"last_event_id": event["event_id"],
|
|
136
|
+
})
|
|
137
|
+
else:
|
|
138
|
+
state = {
|
|
139
|
+
"alert_id": alert_id,
|
|
140
|
+
"alert_key": alert_key,
|
|
141
|
+
"model_key": model_key,
|
|
142
|
+
"tag": snapshot.get("tag"),
|
|
143
|
+
"operating_mode_key": snapshot.get("operating_mode_key"),
|
|
144
|
+
"rule": (details or {}).get("rule"),
|
|
145
|
+
"status": "OPEN",
|
|
146
|
+
"created_at": created_at,
|
|
147
|
+
"acknowledged_at": None,
|
|
148
|
+
"acknowledged_by": None,
|
|
149
|
+
"acknowledgement_note": None,
|
|
150
|
+
"recovered_at": None,
|
|
151
|
+
"last_run_id": snapshot.get("run_id"),
|
|
152
|
+
"last_event_id": event["event_id"],
|
|
153
|
+
"details": details or {},
|
|
154
|
+
}
|
|
155
|
+
self._alerts[alert_key] = state
|
|
156
|
+
self._append(event)
|
|
157
|
+
return dict(event)
|
|
158
|
+
|
|
159
|
+
def _rebuild(self):
|
|
160
|
+
for event in self._events:
|
|
161
|
+
key = event["alert_key"]
|
|
162
|
+
previous = self._alerts.get(key)
|
|
163
|
+
kind = event["event_type"]
|
|
164
|
+
if kind == "OPENED":
|
|
165
|
+
details = event.get("details") or {}
|
|
166
|
+
self._alerts[key] = {
|
|
167
|
+
"alert_id": event["alert_id"], "alert_key": key,
|
|
168
|
+
"model_key": event["model_key"], "tag": event.get("tag"),
|
|
169
|
+
"operating_mode_key": event.get("operating_mode_key"),
|
|
170
|
+
"rule": details.get("rule"), "status": "OPEN",
|
|
171
|
+
"created_at": event["occurred_at"], "acknowledged_at": None,
|
|
172
|
+
"acknowledged_by": None, "acknowledgement_note": None,
|
|
173
|
+
"recovered_at": None, "last_run_id": event.get("run_id"),
|
|
174
|
+
"last_event_id": event["event_id"], "details": details,
|
|
175
|
+
}
|
|
176
|
+
elif previous is not None:
|
|
177
|
+
previous["last_event_id"] = event["event_id"]
|
|
178
|
+
previous["last_run_id"] = event.get("run_id")
|
|
179
|
+
if kind == "ACKNOWLEDGED":
|
|
180
|
+
previous["status"] = "ACKNOWLEDGED"
|
|
181
|
+
previous["acknowledged_at"] = event["occurred_at"]
|
|
182
|
+
previous["acknowledged_by"] = (event.get("details") or {}).get("acknowledged_by")
|
|
183
|
+
previous["acknowledgement_note"] = (event.get("details") or {}).get("note")
|
|
184
|
+
elif kind == "RECOVERED":
|
|
185
|
+
previous["status"] = "RECOVERED"
|
|
186
|
+
previous["recovered_at"] = event["occurred_at"]
|
|
187
|
+
|
|
188
|
+
def _load_events(self):
|
|
189
|
+
if self.event_store is not None:
|
|
190
|
+
return self.event_store.alert_events()
|
|
191
|
+
if not self.event_path or not os.path.exists(self.event_path):
|
|
192
|
+
return []
|
|
193
|
+
events = []
|
|
194
|
+
with open(self.event_path, "r", encoding="utf-8") as stream:
|
|
195
|
+
for line_number, line in enumerate(stream, start=1):
|
|
196
|
+
if not line.strip():
|
|
197
|
+
continue
|
|
198
|
+
try:
|
|
199
|
+
item = json.loads(line)
|
|
200
|
+
except json.JSONDecodeError as exc:
|
|
201
|
+
raise ValueError("Invalid alert event JSONL at line {}".format(line_number)) from exc
|
|
202
|
+
required = ("event_id", "alert_id", "event_type", "alert_key", "model_key", "occurred_at")
|
|
203
|
+
if not isinstance(item, dict) or any(name not in item for name in required):
|
|
204
|
+
raise ValueError("Invalid alert event at line {}".format(line_number))
|
|
205
|
+
events.append(item)
|
|
206
|
+
return events
|
|
207
|
+
|
|
208
|
+
def _append(self, event):
|
|
209
|
+
if self.event_store is not None:
|
|
210
|
+
self.event_store.append_alert_event(event)
|
|
211
|
+
return
|
|
212
|
+
if not self.event_path:
|
|
213
|
+
return
|
|
214
|
+
directory = os.path.dirname(os.path.abspath(self.event_path))
|
|
215
|
+
os.makedirs(directory, exist_ok=True)
|
|
216
|
+
with open(self.event_path, "a", encoding="utf-8") as stream:
|
|
217
|
+
stream.write(json.dumps(event, sort_keys=True, allow_nan=False) + "\n")
|
|
218
|
+
|
|
219
|
+
|
|
220
|
+
def _alert_key(model_key, rule):
|
|
221
|
+
return "{}|{}".format(model_key, rule)
|
|
222
|
+
|
|
223
|
+
|
|
224
|
+
def _consecutive_shift_runs(history):
|
|
225
|
+
"""Count consecutive distinct run IDs ending in suspected shift."""
|
|
226
|
+
ordered = sorted(history, key=lambda item: item.get("recorded_at", ""))
|
|
227
|
+
count = 0
|
|
228
|
+
seen = set()
|
|
229
|
+
for row in reversed(ordered):
|
|
230
|
+
if row.get("reliability_status") != "DISTRIBUTION_SHIFT_SUSPECTED":
|
|
231
|
+
break
|
|
232
|
+
run_id = row.get("run_id")
|
|
233
|
+
identity = ("run", run_id) if run_id is not None else ("time", row.get("recorded_at"))
|
|
234
|
+
if identity in seen:
|
|
235
|
+
continue
|
|
236
|
+
seen.add(identity)
|
|
237
|
+
count += 1
|
|
238
|
+
return count
|
|
239
|
+
|
|
240
|
+
|
|
241
|
+
def _timestamp(value):
|
|
242
|
+
if value is None:
|
|
243
|
+
value = datetime.now(timezone.utc)
|
|
244
|
+
elif isinstance(value, str):
|
|
245
|
+
value = datetime.fromisoformat(value.replace("Z", "+00:00"))
|
|
246
|
+
if not isinstance(value, datetime):
|
|
247
|
+
raise TypeError("timestamp must be a datetime, ISO-8601 string, or None")
|
|
248
|
+
if value.tzinfo is None:
|
|
249
|
+
value = value.replace(tzinfo=timezone.utc)
|
|
250
|
+
return value.astimezone(timezone.utc).isoformat()
|
historecon/baseline.py
ADDED
|
@@ -0,0 +1,151 @@
|
|
|
1
|
+
"""Historical reference baselines, segmented by operating mode."""
|
|
2
|
+
|
|
3
|
+
from collections import defaultdict
|
|
4
|
+
from statistics import median
|
|
5
|
+
|
|
6
|
+
from .classifier import classify_status
|
|
7
|
+
from .models import Finding, StatusCategory
|
|
8
|
+
|
|
9
|
+
|
|
10
|
+
def _mad(values, center):
|
|
11
|
+
return median([abs(value - center) for value in values])
|
|
12
|
+
|
|
13
|
+
|
|
14
|
+
def _quantile(values, fraction):
|
|
15
|
+
ordered = sorted(values)
|
|
16
|
+
if len(ordered) == 1:
|
|
17
|
+
return ordered[0]
|
|
18
|
+
position = (len(ordered) - 1) * fraction
|
|
19
|
+
lower = int(position)
|
|
20
|
+
upper = min(lower + 1, len(ordered) - 1)
|
|
21
|
+
weight = position - lower
|
|
22
|
+
return ordered[lower] * (1.0 - weight) + ordered[upper] * weight
|
|
23
|
+
|
|
24
|
+
|
|
25
|
+
def _scale(values, center):
|
|
26
|
+
"""Return a robust standard-deviation estimate, preferring MAD to IQR."""
|
|
27
|
+
mad = _mad(values, center)
|
|
28
|
+
if mad > 0:
|
|
29
|
+
return 1.4826 * mad, "MAD"
|
|
30
|
+
iqr = _quantile(values, 0.75) - _quantile(values, 0.25)
|
|
31
|
+
if iqr > 0:
|
|
32
|
+
return iqr / 1.349, "IQR"
|
|
33
|
+
return 0.0, "ZERO_SPREAD"
|
|
34
|
+
|
|
35
|
+
|
|
36
|
+
def _mode_key(mode):
|
|
37
|
+
return None if mode is None else mode.strip().casefold()
|
|
38
|
+
|
|
39
|
+
|
|
40
|
+
def _load_band(load, width):
|
|
41
|
+
if load is None or width is None:
|
|
42
|
+
return None
|
|
43
|
+
return int(load // width)
|
|
44
|
+
|
|
45
|
+
|
|
46
|
+
def historical_baseline_findings(current, historical, config):
|
|
47
|
+
"""Compare values only with matching tag, operating mode and load band."""
|
|
48
|
+
baseline_values = defaultdict(list)
|
|
49
|
+
baseline_labels = {}
|
|
50
|
+
for row in historical:
|
|
51
|
+
category = classify_status(row.status, config)
|
|
52
|
+
if not row.is_recorded or category not in {StatusCategory.GOOD, StatusCategory.NOT_PROVIDED}:
|
|
53
|
+
continue
|
|
54
|
+
if _is_number(row.value):
|
|
55
|
+
key = (row.tag, _mode_key(row.operating_mode), _load_band(row.operating_load, config.baseline_load_band_width))
|
|
56
|
+
baseline_values[key].append(float(row.value))
|
|
57
|
+
baseline_labels[key] = row.operating_mode
|
|
58
|
+
|
|
59
|
+
current_values = defaultdict(list)
|
|
60
|
+
current_labels = {}
|
|
61
|
+
for row in current:
|
|
62
|
+
category = classify_status(row.status, config)
|
|
63
|
+
if not row.is_recorded or category not in {StatusCategory.GOOD, StatusCategory.NOT_PROVIDED}:
|
|
64
|
+
continue
|
|
65
|
+
if _is_number(row.value):
|
|
66
|
+
key = (row.tag, _mode_key(row.operating_mode), _load_band(row.operating_load, config.baseline_load_band_width))
|
|
67
|
+
current_values[key].append(row)
|
|
68
|
+
current_labels[key] = row.operating_mode
|
|
69
|
+
|
|
70
|
+
findings = []
|
|
71
|
+
for key, rows in current_values.items():
|
|
72
|
+
tag, mode_key, load_band = key
|
|
73
|
+
values = baseline_values.get(key, [])
|
|
74
|
+
if len(values) < config.baseline_min_points:
|
|
75
|
+
# Never fall back to a pooled tag baseline: it can mix unlike operating states.
|
|
76
|
+
continue
|
|
77
|
+
center = median(values)
|
|
78
|
+
scale, scale_method = _scale(values, center)
|
|
79
|
+
deviations = []
|
|
80
|
+
for row in sorted(rows, key=lambda item: item.timestamp):
|
|
81
|
+
value = float(row.value)
|
|
82
|
+
delta = value - center
|
|
83
|
+
if scale > 0:
|
|
84
|
+
score = abs(delta) / scale
|
|
85
|
+
anomalous = score >= config.baseline_z_threshold and abs(delta) >= config.baseline_min_deviation
|
|
86
|
+
else:
|
|
87
|
+
score = None
|
|
88
|
+
anomalous = abs(delta) >= max(config.baseline_min_deviation, config.baseline_zero_spread_tolerance) and abs(delta) > 0
|
|
89
|
+
if anomalous:
|
|
90
|
+
deviations.append((row, delta, score))
|
|
91
|
+
|
|
92
|
+
windows = []
|
|
93
|
+
active = []
|
|
94
|
+
for item in deviations:
|
|
95
|
+
if active and (item[0].timestamp - active[0][0].timestamp).total_seconds() > config.baseline_incident_gap_seconds:
|
|
96
|
+
windows.append(active)
|
|
97
|
+
active = []
|
|
98
|
+
active.append(item)
|
|
99
|
+
if active:
|
|
100
|
+
windows.append(active)
|
|
101
|
+
|
|
102
|
+
for incident_number, window in enumerate(windows, start=1):
|
|
103
|
+
observed = [float(item[0].value) for item in window]
|
|
104
|
+
deltas = [item[1] for item in window]
|
|
105
|
+
scores = [item[2] for item in window if item[2] is not None]
|
|
106
|
+
direction = "ABOVE_BASELINE" if median(deltas) > 0 else "BELOW_BASELINE"
|
|
107
|
+
findings.append(Finding(
|
|
108
|
+
diagnostic_type="HISTORICAL_BASELINE_DEVIATION",
|
|
109
|
+
severity="medium",
|
|
110
|
+
affected_tags=(tag,),
|
|
111
|
+
first_observed=window[0][0].timestamp,
|
|
112
|
+
last_observed=window[-1][0].timestamp,
|
|
113
|
+
evidence={
|
|
114
|
+
"baseline_point_count": len(values),
|
|
115
|
+
"current_deviation_point_count": len(window),
|
|
116
|
+
"operating_mode": baseline_labels.get(key) or current_labels.get(key),
|
|
117
|
+
"operating_mode_key": mode_key,
|
|
118
|
+
"operating_load_band_index": load_band,
|
|
119
|
+
"operating_load_band_min": (load_band * config.baseline_load_band_width) if load_band is not None else None,
|
|
120
|
+
"operating_load_band_max": ((load_band + 1) * config.baseline_load_band_width) if load_band is not None else None,
|
|
121
|
+
"operating_load_band_width": config.baseline_load_band_width,
|
|
122
|
+
"baseline_median": center,
|
|
123
|
+
"baseline_robust_scale": scale,
|
|
124
|
+
"scale_method": scale_method,
|
|
125
|
+
"median_absolute_z_score": median(scores) if scores else None,
|
|
126
|
+
"median_deviation": median(deltas),
|
|
127
|
+
"deviation_direction": direction,
|
|
128
|
+
"observed_min": min(observed),
|
|
129
|
+
"observed_max": max(observed),
|
|
130
|
+
"minimum_z_score": config.baseline_z_threshold,
|
|
131
|
+
"minimum_absolute_deviation": config.baseline_min_deviation,
|
|
132
|
+
"incident_number_for_tag_and_mode": incident_number,
|
|
133
|
+
"recorded_values_only": True,
|
|
134
|
+
"baseline_segmentation": "tag_operating_mode_and_load_band",
|
|
135
|
+
"interpretation": "Deviation from the historical reference for this operating mode and load band; investigate process context before attributing cause.",
|
|
136
|
+
},
|
|
137
|
+
confidence="moderate" if len(window) > 1 else "low",
|
|
138
|
+
suggested_owner="OPERATIONS",
|
|
139
|
+
recommended_action="Compare the deviation with operating mode, setpoint changes, maintenance activity and the tag's historical context.",
|
|
140
|
+
))
|
|
141
|
+
return findings
|
|
142
|
+
|
|
143
|
+
|
|
144
|
+
def _is_number(value):
|
|
145
|
+
if value is None or isinstance(value, bool):
|
|
146
|
+
return False
|
|
147
|
+
try:
|
|
148
|
+
import math
|
|
149
|
+
return math.isfinite(float(value))
|
|
150
|
+
except (TypeError, ValueError):
|
|
151
|
+
return False
|
historecon/classifier.py
ADDED
|
@@ -0,0 +1,24 @@
|
|
|
1
|
+
from .config import DiagnosticConfig, StatusProfile
|
|
2
|
+
from .models import StatusCategory
|
|
3
|
+
|
|
4
|
+
|
|
5
|
+
def classify_status(status, config: DiagnosticConfig, profile: StatusProfile = None) -> StatusCategory:
|
|
6
|
+
if status is None or not str(status).strip():
|
|
7
|
+
return StatusCategory.NOT_PROVIDED
|
|
8
|
+
raw = str(status).strip().casefold()
|
|
9
|
+
selected_profile = profile or config.status_profile
|
|
10
|
+
if selected_profile is not None and raw in selected_profile.mappings:
|
|
11
|
+
return selected_profile.mappings[raw]
|
|
12
|
+
if raw in config.good_statuses:
|
|
13
|
+
return StatusCategory.GOOD
|
|
14
|
+
if raw in config.bad_statuses:
|
|
15
|
+
return StatusCategory.BAD_QUALITY
|
|
16
|
+
if raw in config.questionable_statuses:
|
|
17
|
+
return StatusCategory.QUESTIONABLE_QUALITY
|
|
18
|
+
if raw in config.communication_statuses:
|
|
19
|
+
return StatusCategory.COMMUNICATION_FAILURE
|
|
20
|
+
if raw in config.equipment_statuses:
|
|
21
|
+
return StatusCategory.EQUIPMENT_FAILURE
|
|
22
|
+
if raw in config.access_statuses:
|
|
23
|
+
return StatusCategory.ACCESS_OR_CONFIGURATION
|
|
24
|
+
return StatusCategory.UNKNOWN
|
historecon/config.py
ADDED
|
@@ -0,0 +1,127 @@
|
|
|
1
|
+
from dataclasses import dataclass, field
|
|
2
|
+
from typing import Dict, FrozenSet, Optional
|
|
3
|
+
|
|
4
|
+
from .models import StatusCategory
|
|
5
|
+
|
|
6
|
+
|
|
7
|
+
@dataclass
|
|
8
|
+
class StatusProfile:
|
|
9
|
+
"""Named, explicit mapping of source labels to Historecon status categories."""
|
|
10
|
+
|
|
11
|
+
name: str
|
|
12
|
+
mappings: Dict[str, StatusCategory] = field(default_factory=dict)
|
|
13
|
+
owner_overrides: Dict[str, str] = field(default_factory=dict)
|
|
14
|
+
action_overrides: Dict[str, str] = field(default_factory=dict)
|
|
15
|
+
severity_overrides: Dict[str, str] = field(default_factory=dict)
|
|
16
|
+
|
|
17
|
+
def __post_init__(self):
|
|
18
|
+
if not self.name or not self.name.strip():
|
|
19
|
+
raise ValueError("StatusProfile name cannot be empty")
|
|
20
|
+
normalized = {}
|
|
21
|
+
for label, category in self.mappings.items():
|
|
22
|
+
key = str(label).strip().casefold()
|
|
23
|
+
if not key:
|
|
24
|
+
raise ValueError("Status profile labels cannot be empty")
|
|
25
|
+
try:
|
|
26
|
+
normalized[key] = category if isinstance(category, StatusCategory) else StatusCategory(str(category).upper())
|
|
27
|
+
except ValueError as exc:
|
|
28
|
+
raise ValueError("Unsupported status category for {!r}".format(label)) from exc
|
|
29
|
+
self.mappings = normalized
|
|
30
|
+
self.owner_overrides = {str(k).strip().upper(): str(v) for k, v in self.owner_overrides.items()}
|
|
31
|
+
self.action_overrides = {str(k).strip().upper(): str(v) for k, v in self.action_overrides.items()}
|
|
32
|
+
self.severity_overrides = {str(k).strip().upper(): str(v) for k, v in self.severity_overrides.items()}
|
|
33
|
+
|
|
34
|
+
|
|
35
|
+
@dataclass
|
|
36
|
+
class DiagnosticConfig:
|
|
37
|
+
"""Configuration for source-specific status semantics and diagnostic thresholds."""
|
|
38
|
+
|
|
39
|
+
good_statuses: FrozenSet[str] = field(default_factory=lambda: frozenset({"good"}))
|
|
40
|
+
bad_statuses: FrozenSet[str] = field(
|
|
41
|
+
default_factory=lambda: frozenset({"bad", "bad input", "bad quality", "bad_quality"})
|
|
42
|
+
)
|
|
43
|
+
questionable_statuses: FrozenSet[str] = field(
|
|
44
|
+
default_factory=lambda: frozenset({"doubtful", "questionable"})
|
|
45
|
+
)
|
|
46
|
+
communication_statuses: FrozenSet[str] = field(
|
|
47
|
+
default_factory=lambda: frozenset({"comm fail", "not connect", "i/o timeout"})
|
|
48
|
+
)
|
|
49
|
+
equipment_statuses: FrozenSet[str] = field(default_factory=lambda: frozenset({"equip fail"}))
|
|
50
|
+
access_statuses: FrozenSet[str] = field(
|
|
51
|
+
default_factory=lambda: frozenset({"accessdenied", "access denied"})
|
|
52
|
+
)
|
|
53
|
+
status_profile: Optional[StatusProfile] = None
|
|
54
|
+
incident_gap_seconds: float = 300.0
|
|
55
|
+
stale_after_seconds: Optional[float] = None
|
|
56
|
+
frozen_after_seconds: Optional[float] = None
|
|
57
|
+
frozen_min_points: int = 4
|
|
58
|
+
frozen_tolerance: float = 0.0
|
|
59
|
+
noisy_min_points: int = 5
|
|
60
|
+
noisy_stddev_threshold: Optional[float] = None
|
|
61
|
+
rate_of_change_threshold: Optional[float] = None
|
|
62
|
+
correlation_window_seconds: float = 300.0
|
|
63
|
+
baseline_min_points: int = 20
|
|
64
|
+
baseline_z_threshold: float = 3.5
|
|
65
|
+
baseline_min_deviation: float = 0.0
|
|
66
|
+
baseline_zero_spread_tolerance: float = 0.0
|
|
67
|
+
baseline_incident_gap_seconds: float = 300.0
|
|
68
|
+
baseline_load_band_width: Optional[float] = 5.0
|
|
69
|
+
baseline_regression_enabled: bool = False
|
|
70
|
+
baseline_regression_min_points: int = 30
|
|
71
|
+
baseline_regression_z_threshold: float = 3.5
|
|
72
|
+
baseline_regression_min_deviation: float = 0.0
|
|
73
|
+
baseline_regression_zero_spread_tolerance: float = 0.0
|
|
74
|
+
baseline_regression_nonlinear_improvement: float = 0.15
|
|
75
|
+
baseline_regression_min_r_squared: float = 0.5
|
|
76
|
+
baseline_regression_variance_ratio_threshold: float = 3.0
|
|
77
|
+
baseline_regression_prediction_interval_coverage: float = 0.95
|
|
78
|
+
baseline_regression_interval_min_points: int = 20
|
|
79
|
+
baseline_regression_shift_min_points: int = 5
|
|
80
|
+
baseline_regression_shift_z_threshold: float = 3.5
|
|
81
|
+
range_violation_severity: str = "high"
|
|
82
|
+
|
|
83
|
+
def __post_init__(self):
|
|
84
|
+
for name in (
|
|
85
|
+
"good_statuses", "bad_statuses", "questionable_statuses",
|
|
86
|
+
"communication_statuses", "equipment_statuses", "access_statuses"
|
|
87
|
+
):
|
|
88
|
+
values = getattr(self, name)
|
|
89
|
+
setattr(self, name, frozenset(str(v).strip().casefold() for v in values))
|
|
90
|
+
if self.frozen_min_points < 2:
|
|
91
|
+
raise ValueError("frozen_min_points must be at least 2")
|
|
92
|
+
if self.noisy_min_points < 2:
|
|
93
|
+
raise ValueError("noisy_min_points must be at least 2")
|
|
94
|
+
if self.incident_gap_seconds < 0:
|
|
95
|
+
raise ValueError("incident_gap_seconds cannot be negative")
|
|
96
|
+
if self.correlation_window_seconds < 0:
|
|
97
|
+
raise ValueError("correlation_window_seconds cannot be negative")
|
|
98
|
+
if self.baseline_min_points < 2:
|
|
99
|
+
raise ValueError("baseline_min_points must be at least 2")
|
|
100
|
+
if self.baseline_z_threshold <= 0:
|
|
101
|
+
raise ValueError("baseline_z_threshold must be positive")
|
|
102
|
+
if self.baseline_min_deviation < 0 or self.baseline_zero_spread_tolerance < 0:
|
|
103
|
+
raise ValueError("baseline deviation tolerances cannot be negative")
|
|
104
|
+
if self.baseline_incident_gap_seconds < 0:
|
|
105
|
+
raise ValueError("baseline_incident_gap_seconds cannot be negative")
|
|
106
|
+
if self.baseline_load_band_width is not None and self.baseline_load_band_width <= 0:
|
|
107
|
+
raise ValueError("baseline_load_band_width must be positive or None")
|
|
108
|
+
if self.baseline_regression_min_points < 3:
|
|
109
|
+
raise ValueError("baseline_regression_min_points must be at least 3")
|
|
110
|
+
if self.baseline_regression_z_threshold <= 0:
|
|
111
|
+
raise ValueError("baseline_regression_z_threshold must be positive")
|
|
112
|
+
if self.baseline_regression_min_deviation < 0 or self.baseline_regression_zero_spread_tolerance < 0:
|
|
113
|
+
raise ValueError("regression deviation tolerances cannot be negative")
|
|
114
|
+
if not 0 <= self.baseline_regression_nonlinear_improvement < 1:
|
|
115
|
+
raise ValueError("baseline_regression_nonlinear_improvement must be in [0, 1)")
|
|
116
|
+
if not -1 <= self.baseline_regression_min_r_squared <= 1:
|
|
117
|
+
raise ValueError("baseline_regression_min_r_squared must be in [-1, 1]")
|
|
118
|
+
if self.baseline_regression_variance_ratio_threshold <= 1:
|
|
119
|
+
raise ValueError("baseline_regression_variance_ratio_threshold must be greater than 1")
|
|
120
|
+
if not 0.5 < self.baseline_regression_prediction_interval_coverage < 1:
|
|
121
|
+
raise ValueError("baseline_regression_prediction_interval_coverage must be between 0.5 and 1")
|
|
122
|
+
if self.baseline_regression_interval_min_points < 5:
|
|
123
|
+
raise ValueError("baseline_regression_interval_min_points must be at least 5")
|
|
124
|
+
if self.baseline_regression_shift_min_points < 3:
|
|
125
|
+
raise ValueError("baseline_regression_shift_min_points must be at least 3")
|
|
126
|
+
if self.baseline_regression_shift_z_threshold <= 0:
|
|
127
|
+
raise ValueError("baseline_regression_shift_z_threshold must be positive")
|