tanzim 0.1.0__tar.gz

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.
tanzim-0.1.0/PKG-INFO ADDED
@@ -0,0 +1,12 @@
1
+ Metadata-Version: 2.4
2
+ Name: tanzim
3
+ Version: 0.1.0
4
+ Summary: Offline-first silent-fault and energy-imbalance auditor for building BMS and industrial SCADA logs.
5
+ Author-email: Aslan Satary Dizaji <aslansatary@gmail.com>
6
+ License: MIT
7
+ Keywords: bms,scada,hvac,energy-audit,fault-detection,change-point
8
+ Requires-Python: >=3.10
9
+ Description-Content-Type: text/markdown
10
+ Provides-Extra: dev
11
+ Requires-Dist: pytest>=8.0; extra == "dev"
12
+ Requires-Dist: ruff>=0.6; extra == "dev"
@@ -0,0 +1,23 @@
1
+ [build-system]
2
+ requires = ["setuptools>=68"]
3
+ build-backend = "setuptools.build_meta"
4
+
5
+ [project]
6
+ name = "tanzim"
7
+ version = "0.1.0"
8
+ description = "Offline-first silent-fault and energy-imbalance auditor for building BMS and industrial SCADA logs."
9
+ readme = "README.md"
10
+ requires-python = ">=3.10"
11
+ license = { text = "MIT" }
12
+ authors = [{ name = "Aslan Satary Dizaji", email = "aslansatary@gmail.com" }]
13
+ keywords = ["bms", "scada", "hvac", "energy-audit", "fault-detection", "change-point"]
14
+ dependencies = []
15
+
16
+ [project.optional-dependencies]
17
+ dev = ["pytest>=8.0", "ruff>=0.6"]
18
+
19
+ [project.scripts]
20
+ tanzim = "tanzim.cli:main"
21
+
22
+ [tool.setuptools.packages.find]
23
+ where = ["src"]
tanzim-0.1.0/setup.cfg ADDED
@@ -0,0 +1,4 @@
1
+ [egg_info]
2
+ tag_build =
3
+ tag_date = 0
4
+
@@ -0,0 +1,17 @@
1
+ from .engine import __version__, audit_file, audit_records
2
+ from .llm_tickets import generate_work_order
3
+ from .schema import AuditConfig, AuditReport, Finding, Severity, TelemetryPoint
4
+ from .tariffs import IranTariffProfile
5
+
6
+ __all__ = [
7
+ "__version__",
8
+ "AuditConfig",
9
+ "AuditReport",
10
+ "Finding",
11
+ "IranTariffProfile",
12
+ "Severity",
13
+ "TelemetryPoint",
14
+ "audit_file",
15
+ "audit_records",
16
+ "generate_work_order",
17
+ ]
@@ -0,0 +1 @@
1
+ __version__ = "0.1.0"
@@ -0,0 +1,84 @@
1
+ from __future__ import annotations
2
+
3
+ import argparse
4
+ import json
5
+ from pathlib import Path
6
+
7
+ from .engine import audit_file
8
+ from .llm_tickets import generate_work_order
9
+ from .schema import AuditConfig, AuditReport
10
+ from .synthetic import generate_tehran_summer_bms, write_telemetry_csv
11
+
12
+
13
+ def _print_report(report: AuditReport) -> None:
14
+ print(f"tanzim v{report.tool_version} | source={report.source_path}")
15
+ print(f"sha256={report.source_sha256[:16]}... | records={report.record_count} (dt={report.timestep_hours:.2f}h)")
16
+ print(
17
+ f"energy={report.total_energy_kwh:,.1f} kWh | peak={report.peak_energy_kwh:,.1f} kWh | "
18
+ f"est_waste={report.total_estimated_waste_kwh:,.1f} kWh | "
19
+ f"est_savings={report.total_estimated_cost_irr:,.0f} IRR"
20
+ )
21
+ print("-" * 78)
22
+ if not report.findings:
23
+ print("OK: No silent BMS/SCADA energy faults detected.")
24
+ return
25
+ for f in report.findings:
26
+ print(f"[{f.severity.value.upper():8}] {f.code:<24} | {f.title}")
27
+ print(f" {f.summary}")
28
+ if f.estimated_waste_kwh > 0 or f.estimated_cost_irr > 0:
29
+ print(
30
+ f" impact: {f.estimated_waste_kwh:,.1f} kWh | "
31
+ f"{f.estimated_cost_irr:,.0f} IRR"
32
+ )
33
+
34
+
35
+ def main(argv: list[str] | None = None) -> int:
36
+ parser = argparse.ArgumentParser(prog="tanzim", description="Offline BMS/SCADA silent-fault auditor.")
37
+ sub = parser.add_subparsers(dest="cmd", required=True)
38
+
39
+ p_audit = sub.add_parser("audit", help="Audit a BMS/SCADA CSV or JSONL file.")
40
+ p_audit.add_argument("file", help="Path to telemetry .csv or .jsonl")
41
+ p_audit.add_argument("--demand-cap", type=float, default=None, help="Contracted peak demand cap (kW)")
42
+ p_audit.add_argument("--price-irr", type=float, default=12_000.0, help="Base electricity rate (IRR/kWh)")
43
+ p_audit.add_argument("--json-out", type=str, default=None, help="Write provenance JSON report to path")
44
+ p_audit.add_argument("--ticket", choices=("fa", "en"), default=None, help="Generate technician work order via Ollama")
45
+ p_audit.add_argument("--model", type=str, default="gemma3:12b", help="Local Ollama model name")
46
+
47
+ p_demo = sub.add_parser("demo", help="Generate a synthetic Tehran summer BMS dataset and audit it.")
48
+ p_demo.add_argument("--out-csv", type=str, default="tehran_bms_demo.csv")
49
+ p_demo.add_argument("--demand-cap", type=float, default=180.0)
50
+ p_demo.add_argument("--clean", action="store_true", help="Generate healthy baseline without injected faults")
51
+
52
+ args = parser.parse_args(argv)
53
+
54
+ if args.cmd == "demo":
55
+ pts = generate_tehran_summer_bms(days=14, step_minutes=5, inject_faults=not args.clean)
56
+ csv_path = write_telemetry_csv(pts, args.out_csv)
57
+ cfg = AuditConfig(contracted_demand_kw=args.demand_cap)
58
+ report = audit_file(csv_path, config=cfg)
59
+ _print_report(report)
60
+ return 0
61
+
62
+ if args.cmd == "audit":
63
+ cfg = AuditConfig(
64
+ contracted_demand_kw=args.demand_cap,
65
+ base_kwh_price_irr=args.price_irr,
66
+ )
67
+ report = audit_file(args.file, config=cfg)
68
+ _print_report(report)
69
+ if args.json_out:
70
+ Path(args.json_out).write_text(
71
+ json.dumps(report.to_dict(), ensure_ascii=False, indent=2),
72
+ encoding="utf-8",
73
+ )
74
+ print(f"\nSaved provenance report -> {args.json_out}")
75
+ if args.ticket:
76
+ print("\n" + "=" * 78)
77
+ print(generate_work_order(report, lang=args.ticket, model=args.model))
78
+ return 0
79
+
80
+ return 1
81
+
82
+
83
+ if __name__ == "__main__":
84
+ raise SystemExit(main())
@@ -0,0 +1,505 @@
1
+ from __future__ import annotations
2
+
3
+ import math
4
+ from collections import defaultdict
5
+ from datetime import date
6
+ from statistics import mean, median, variance
7
+
8
+ from .schema import AuditConfig, Finding, Severity, TelemetryPoint
9
+ from .tariffs import IranTariffProfile
10
+
11
+
12
+ def _is_occupied(p: TelemetryPoint, cfg: AuditConfig) -> bool:
13
+ return (
14
+ p.timestamp.weekday() not in cfg.weekend_weekdays
15
+ and cfg.occupied_start_hour <= p.timestamp.hour < cfg.occupied_end_hour
16
+ )
17
+
18
+
19
+ def infer_timestep_hours(points: list[TelemetryPoint]) -> float:
20
+ if len(points) < 2:
21
+ return 0.25
22
+ deltas = [
23
+ (points[i].timestamp - points[i - 1].timestamp).total_seconds() / 3600.0
24
+ for i in range(1, len(points))
25
+ ]
26
+ positive = [d for d in deltas if d > 0]
27
+ return median(positive) if positive else 0.25
28
+
29
+
30
+ def detect_simultaneous_heat_cool(
31
+ points: list[TelemetryPoint],
32
+ dt_h: float,
33
+ cfg: AuditConfig,
34
+ tariff: IranTariffProfile,
35
+ ) -> list[Finding]:
36
+ overlap_pts = [
37
+ p
38
+ for p in points
39
+ if p.heating_valve_pct is not None
40
+ and p.cooling_valve_pct is not None
41
+ and p.heating_valve_pct >= cfg.simultaneous_valve_pct
42
+ and p.cooling_valve_pct >= cfg.simultaneous_valve_pct
43
+ ]
44
+ overlap_hours = len(overlap_pts) * dt_h
45
+ if overlap_hours < cfg.simultaneous_min_hours:
46
+ return []
47
+
48
+ waste_kwh = sum(p.power_kw * dt_h * 0.35 for p in overlap_pts)
49
+ cost_irr = sum(
50
+ p.power_kw * dt_h * 0.35 * cfg.base_kwh_price_irr * tariff.multiplier_for(p.timestamp)
51
+ for p in overlap_pts
52
+ )
53
+ severity = Severity.CRITICAL if overlap_hours >= 4.0 else Severity.WARNING
54
+ return [
55
+ Finding(
56
+ code="SIMULTANEOUS_HEAT_COOL",
57
+ title="Simultaneous heating and cooling (valve fighting)",
58
+ severity=severity,
59
+ summary=(
60
+ f"Heating and cooling valves were both open (>={cfg.simultaneous_valve_pct:.0f}%) "
61
+ f"for {overlap_hours:.1f} hours across {len(overlap_pts)} intervals."
62
+ ),
63
+ estimated_waste_kwh=round(waste_kwh, 2),
64
+ estimated_cost_irr=round(cost_irr, 0),
65
+ start_time=overlap_pts[0].timestamp.isoformat(),
66
+ end_time=overlap_pts[-1].timestamp.isoformat(),
67
+ evidence={
68
+ "overlap_hours": round(overlap_hours, 2),
69
+ "max_heating_valve_pct": round(max(p.heating_valve_pct or 0.0 for p in overlap_pts), 1),
70
+ "max_cooling_valve_pct": round(max(p.cooling_valve_pct or 0.0 for p in overlap_pts), 1),
71
+ },
72
+ )
73
+ ]
74
+
75
+
76
+ def detect_phantom_baseload(
77
+ points: list[TelemetryPoint],
78
+ dt_h: float,
79
+ cfg: AuditConfig,
80
+ tariff: IranTariffProfile,
81
+ ) -> list[Finding]:
82
+ occ_kw = [p.power_kw for p in points if _is_occupied(p, cfg)]
83
+ night_pts = [
84
+ p
85
+ for p in points
86
+ if cfg.night_start_hour <= p.timestamp.hour < cfg.night_end_hour
87
+ ]
88
+ if len(occ_kw) < 4 or len(night_pts) < 4:
89
+ return []
90
+
91
+ med_occ = median(occ_kw)
92
+ if med_occ <= 1.0:
93
+ return []
94
+
95
+ by_night: dict[date, list[TelemetryPoint]] = defaultdict(list)
96
+ for p in night_pts:
97
+ by_night[p.timestamp.date()].append(p)
98
+
99
+ offending_nights: list[tuple[date, float]] = []
100
+ offending_pts: list[TelemetryPoint] = []
101
+ for d, pts in sorted(by_night.items()):
102
+ if len(pts) < 2:
103
+ continue
104
+ m_night = median(p.power_kw for p in pts)
105
+ if (m_night / med_occ) > cfg.phantom_baseload_ratio and m_night >= 5.0:
106
+ offending_nights.append((d, m_night))
107
+ offending_pts.extend(pts)
108
+
109
+ if not offending_pts or (len(offending_nights) < 2 and len(offending_nights) < len(by_night)):
110
+ return []
111
+
112
+ med_bad_night = median(p.power_kw for p in offending_pts)
113
+ ratio = med_bad_night / med_occ
114
+ target_night_kw = med_occ * cfg.phantom_target_ratio
115
+ waste_kwh = sum(max(0.0, p.power_kw - target_night_kw) * dt_h for p in offending_pts)
116
+ cost_irr = sum(
117
+ max(0.0, p.power_kw - target_night_kw)
118
+ * dt_h
119
+ * cfg.base_kwh_price_irr
120
+ * tariff.multiplier_for(p.timestamp)
121
+ for p in offending_pts
122
+ )
123
+ severity = Severity.CRITICAL if ratio >= 0.65 else Severity.WARNING
124
+ return [
125
+ Finding(
126
+ code="PHANTOM_BASELOAD",
127
+ title="Excessive unoccupied night baseload (schedule drift)",
128
+ severity=severity,
129
+ summary=(
130
+ f"Median night load ({med_bad_night:.1f} kW) across "
131
+ f"{len(offending_nights)}/{len(by_night)} nights is {ratio * 100:.0f}% of "
132
+ f"daytime occupied median ({med_occ:.1f} kW), exceeding the "
133
+ f"{cfg.phantom_baseload_ratio * 100:.0f}% threshold."
134
+ ),
135
+ estimated_waste_kwh=round(waste_kwh, 2),
136
+ estimated_cost_irr=round(cost_irr, 0),
137
+ start_time=offending_pts[0].timestamp.isoformat(),
138
+ end_time=offending_pts[-1].timestamp.isoformat(),
139
+ evidence={
140
+ "affected_nights": len(offending_nights),
141
+ "total_nights": len(by_night),
142
+ "median_occupied_kw": round(med_occ, 2),
143
+ "median_night_kw": round(med_bad_night, 2),
144
+ "night_to_day_ratio": round(ratio, 3),
145
+ "target_standby_kw": round(target_night_kw, 2),
146
+ },
147
+ )
148
+ ]
149
+
150
+
151
+ def detect_sensor_flatline(
152
+ points: list[TelemetryPoint],
153
+ dt_h: float,
154
+ cfg: AuditConfig,
155
+ ) -> list[Finding]:
156
+ channels = (
157
+ "supply_air_temp_c",
158
+ "chilled_water_supply_c",
159
+ "chilled_water_return_c",
160
+ "power_kw",
161
+ )
162
+ min_samples = max(4, int(math.ceil(cfg.flatline_min_hours / max(dt_h, 1e-6))))
163
+ findings: list[Finding] = []
164
+
165
+ for ch in channels:
166
+ best_run: list[TelemetryPoint] = []
167
+ current_run: list[TelemetryPoint] = []
168
+ last_val: float | None = None
169
+ last_ts = None
170
+
171
+ for p in points:
172
+ val = getattr(p, ch)
173
+ active = p.power_kw >= cfg.active_plant_kw_floor
174
+ gap_ok = (
175
+ last_ts is None
176
+ or ((p.timestamp - last_ts).total_seconds() / 3600.0) <= dt_h * 3.0
177
+ )
178
+ if val is not None and active and gap_ok and last_val is not None and abs(val - last_val) <= 1e-6:
179
+ current_run.append(p)
180
+ else:
181
+ if len(current_run) > len(best_run):
182
+ best_run = current_run
183
+ current_run = [p] if (val is not None and active) else []
184
+ last_val = val
185
+ last_ts = p.timestamp
186
+
187
+ if len(current_run) > len(best_run):
188
+ best_run = current_run
189
+
190
+ if len(best_run) >= min_samples:
191
+ dur_h = len(best_run) * dt_h
192
+ frozen_val = getattr(best_run[0], ch)
193
+ findings.append(
194
+ Finding(
195
+ code="SENSOR_FLATLINE",
196
+ title=f"Frozen sensor / flatlined telemetry on '{ch}'",
197
+ severity=Severity.WARNING,
198
+ summary=(
199
+ f"Channel '{ch}' stayed locked at {frozen_val:.2f} for {dur_h:.1f} hours "
200
+ f"while plant load was active, risking blind PID control."
201
+ ),
202
+ start_time=best_run[0].timestamp.isoformat(),
203
+ end_time=best_run[-1].timestamp.isoformat(),
204
+ evidence={
205
+ "channel": ch,
206
+ "frozen_value": round(float(frozen_val), 3),
207
+ "duration_hours": round(dur_h, 2),
208
+ "sample_count": len(best_run),
209
+ },
210
+ )
211
+ )
212
+ return findings
213
+
214
+
215
+ def detect_chiller_low_delta_t(
216
+ points: list[TelemetryPoint],
217
+ dt_h: float,
218
+ cfg: AuditConfig,
219
+ tariff: IranTariffProfile,
220
+ ) -> list[Finding]:
221
+ has_cooling_valve = any(p.cooling_valve_pct is not None for p in points)
222
+ night_kw = [
223
+ p.power_kw
224
+ for p in points
225
+ if cfg.night_start_hour <= p.timestamp.hour < cfg.night_end_hour
226
+ ]
227
+ standby_floor = (median(night_kw) + 15.0) if night_kw else cfg.active_plant_kw_floor
228
+ active_floor = max(cfg.active_plant_kw_floor, standby_floor)
229
+
230
+ active_chw: list[tuple[TelemetryPoint, float]] = []
231
+ for p in points:
232
+ if p.chilled_water_supply_c is None or p.chilled_water_return_c is None:
233
+ continue
234
+ plant_on = (
235
+ (p.cooling_valve_pct or 0.0) >= 15.0
236
+ if has_cooling_valve
237
+ else p.power_kw >= active_floor
238
+ )
239
+ if plant_on and p.power_kw >= cfg.active_plant_kw_floor:
240
+ active_chw.append((p, p.chilled_water_return_c - p.chilled_water_supply_c))
241
+
242
+ if len(active_chw) < 8:
243
+ return []
244
+
245
+ low_pts = [(p, dt) for p, dt in active_chw if dt < cfg.low_delta_t_c]
246
+ frac = len(low_pts) / len(active_chw)
247
+ if frac < cfg.low_delta_t_min_fraction or len(low_pts) < 4:
248
+ return []
249
+
250
+ avg_low_dt = mean(dt for _, dt in low_pts)
251
+ waste_kwh = sum(p.power_kw * dt_h * 0.15 for p, _ in low_pts)
252
+ cost_irr = sum(
253
+ p.power_kw * dt_h * 0.15 * cfg.base_kwh_price_irr * tariff.multiplier_for(p.timestamp)
254
+ for p, _ in low_pts
255
+ )
256
+ severity = Severity.CRITICAL if frac >= 0.35 else Severity.WARNING
257
+ return [
258
+ Finding(
259
+ code="CHILLER_LOW_DELTA_T",
260
+ title="Chiller Low-Delta-T syndrome (over-pumping / coil fouling)",
261
+ severity=severity,
262
+ summary=(
263
+ f"Chilled-water Delta-T fell below {cfg.low_delta_t_c:.1f} C during "
264
+ f"{frac * 100:.1f}% of active cooling hours (mean low Delta-T = {avg_low_dt:.2f} C)."
265
+ ),
266
+ estimated_waste_kwh=round(waste_kwh, 2),
267
+ estimated_cost_irr=round(cost_irr, 0),
268
+ start_time=low_pts[0][0].timestamp.isoformat(),
269
+ end_time=low_pts[-1][0].timestamp.isoformat(),
270
+ evidence={
271
+ "affected_fraction": round(frac, 3),
272
+ "mean_low_delta_t_c": round(avg_low_dt, 2),
273
+ "design_reference_delta_t_c": 5.5,
274
+ "affected_hours": round(len(low_pts) * dt_h, 2),
275
+ },
276
+ )
277
+ ]
278
+
279
+
280
+ def _weather_adjusted_residuals(points: list[TelemetryPoint]) -> list[float]:
281
+ """Subtract linear cooling/heating degree dependence on outdoor temperature."""
282
+ paired = [(i, p.outdoor_temp_c, p.power_kw) for i, p in enumerate(points) if p.outdoor_temp_c is not None]
283
+ if len(paired) < len(points) * 0.8 or len(paired) < 10:
284
+ avg_p = mean(p.power_kw for p in points)
285
+ return [p.power_kw - avg_p for p in points]
286
+
287
+ mean_oat = mean(t for _, t, _ in paired)
288
+ cooling_mode = mean_oat >= 18.0
289
+ xs = [max(0.0, t - 18.0) if cooling_mode else max(0.0, 16.0 - t) for _, t, _ in paired]
290
+ ys = [kw for _, _, kw in paired]
291
+
292
+ mx, my = mean(xs), mean(ys)
293
+ sxx = sum((x - mx) ** 2 for x in xs)
294
+ if sxx < 1e-6:
295
+ return [p.power_kw - my for p in points]
296
+
297
+ slope = sum((x - mx) * (y - my) for x, y in zip(xs, ys)) / sxx
298
+ intercept = my - slope * mx
299
+
300
+ residuals: list[float] = []
301
+ for p in points:
302
+ if p.outdoor_temp_c is None:
303
+ residuals.append(0.0)
304
+ else:
305
+ x = max(0.0, p.outdoor_temp_c - 18.0) if cooling_mode else max(0.0, 16.0 - p.outdoor_temp_c)
306
+ residuals.append(p.power_kw - (intercept + slope * x))
307
+ return residuals
308
+
309
+
310
+ def detect_regime_changepoint(
311
+ points: list[TelemetryPoint],
312
+ dt_h: float,
313
+ cfg: AuditConfig,
314
+ tariff: IranTariffProfile,
315
+ ) -> list[Finding]:
316
+ residuals = _weather_adjusted_residuals(points)
317
+ by_day: dict[date, list[float]] = defaultdict(list)
318
+ for p, r in zip(points, residuals):
319
+ by_day[p.timestamp.date()].append(r)
320
+
321
+ days = sorted(by_day.keys())
322
+ if len(days) < 6:
323
+ return []
324
+
325
+ daily_means = [mean(by_day[d]) for d in days]
326
+ best_k: int | None = None
327
+ best_score = 0.0
328
+ best_delta = 0.0
329
+
330
+ for k in range(2, len(days) - 1):
331
+ before = daily_means[:k]
332
+ after = daily_means[k:]
333
+ delta = mean(after) - mean(before)
334
+ if delta <= cfg.changepoint_min_delta_kw:
335
+ continue
336
+ v1 = variance(before) if len(before) > 1 else 0.0
337
+ v2 = variance(after) if len(after) > 1 else 0.0
338
+ se = math.sqrt(v1 / len(before) + v2 / len(after) + 1.0)
339
+ score = delta / se
340
+ if score > best_score:
341
+ best_score = score
342
+ best_k = k
343
+ best_delta = delta
344
+
345
+ if best_k is None or best_score < cfg.changepoint_min_z:
346
+ return []
347
+
348
+ shift_day = days[best_k]
349
+ post_pts = [p for p in points if p.timestamp.date() >= shift_day]
350
+ waste_kwh = best_delta * len(post_pts) * dt_h
351
+ cost_irr = sum(
352
+ best_delta * dt_h * cfg.base_kwh_price_irr * tariff.multiplier_for(p.timestamp)
353
+ for p in post_pts
354
+ )
355
+ return [
356
+ Finding(
357
+ code="REGIME_CHANGE_POINT",
358
+ title="Upward baseline load shift (weather-adjusted change-point)",
359
+ severity=Severity.CRITICAL,
360
+ summary=(
361
+ f"Detected a persistent +{best_delta:.1f} kW weather-adjusted load step-up "
362
+ f"starting on {shift_day.isoformat()} (z={best_score:.2f})."
363
+ ),
364
+ estimated_waste_kwh=round(waste_kwh, 2),
365
+ estimated_cost_irr=round(cost_irr, 0),
366
+ start_time=post_pts[0].timestamp.isoformat(),
367
+ end_time=post_pts[-1].timestamp.isoformat(),
368
+ evidence={
369
+ "changepoint_date": shift_day.isoformat(),
370
+ "step_increase_kw": round(best_delta, 2),
371
+ "z_score": round(best_score, 2),
372
+ "post_shift_days": len(days) - best_k,
373
+ },
374
+ )
375
+ ]
376
+
377
+
378
+ def detect_peak_tariff_exposure(
379
+ points: list[TelemetryPoint],
380
+ dt_h: float,
381
+ cfg: AuditConfig,
382
+ tariff: IranTariffProfile,
383
+ ) -> list[Finding]:
384
+ peak_all = [p for p in points if tariff.period_for(p.timestamp) == "peak"]
385
+ mid_all = [p for p in points if tariff.period_for(p.timestamp) == "mid_peak"]
386
+ occ_peak = [p for p in peak_all if _is_occupied(p, cfg)]
387
+ occ_mid = [p for p in mid_all if _is_occupied(p, cfg)]
388
+
389
+ # Compare occupied peak vs occupied mid-peak when occupied schedules overlap
390
+ use_occ = len(occ_peak) >= 4 and len(occ_mid) >= 4
391
+ peak_ref = occ_peak if use_occ else peak_all
392
+ mid_ref = occ_mid if use_occ else mid_all
393
+
394
+ if len(peak_ref) < 4 or len(mid_ref) < 4:
395
+ return []
396
+
397
+ avg_peak = mean(p.power_kw for p in peak_ref)
398
+ avg_mid = mean(p.power_kw for p in mid_ref)
399
+ max_peak = max(p.power_kw for p in peak_all)
400
+ ratio = avg_peak / max(avg_mid, 1.0)
401
+
402
+ cap_breach_pts = (
403
+ [p for p in peak_all if p.power_kw > cfg.contracted_demand_kw]
404
+ if cfg.contracted_demand_kw is not None
405
+ else []
406
+ )
407
+ if not cap_breach_pts and ratio <= cfg.peak_to_mid_ratio_limit:
408
+ return []
409
+
410
+ shiftable_kw = max(0.0, avg_peak - avg_mid)
411
+ shiftable_kwh = shiftable_kw * len(peak_ref) * dt_h
412
+ surcharge_delta = max(0.0, tariff.peak_multiplier - tariff.off_peak_multiplier)
413
+ avoidable_cost_irr = shiftable_kwh * cfg.base_kwh_price_irr * surcharge_delta
414
+
415
+ reasons: list[str] = []
416
+ if cap_breach_pts and cfg.contracted_demand_kw is not None:
417
+ reasons.append(
418
+ f"breached contracted demand cap ({cfg.contracted_demand_kw:.0f} kW) "
419
+ f"in {len(cap_breach_pts)} peak intervals (max {max_peak:.1f} kW)"
420
+ )
421
+ if ratio > cfg.peak_to_mid_ratio_limit:
422
+ reasons.append(
423
+ f"peak-window average ({avg_peak:.1f} kW) is {ratio:.2f}x mid-peak average ({avg_mid:.1f} kW)"
424
+ )
425
+
426
+ return [
427
+ Finding(
428
+ code="PEAK_TARIFF_EXPOSURE",
429
+ title="Iran peak-window overload & demand-cap exposure",
430
+ severity=Severity.CRITICAL if cap_breach_pts else Severity.WARNING,
431
+ summary="Facility " + " and ".join(reasons) + ".",
432
+ estimated_waste_kwh=0.0,
433
+ estimated_cost_irr=round(avoidable_cost_irr, 0),
434
+ start_time=peak_all[0].timestamp.isoformat(),
435
+ end_time=peak_all[-1].timestamp.isoformat(),
436
+ evidence={
437
+ "avg_peak_kw": round(avg_peak, 2),
438
+ "max_peak_kw": round(max_peak, 2),
439
+ "avg_mid_peak_kw": round(avg_mid, 2),
440
+ "peak_to_mid_ratio": round(ratio, 3),
441
+ "occupied_comparison": use_occ,
442
+ "contracted_demand_kw": cfg.contracted_demand_kw,
443
+ "cap_breach_intervals": len(cap_breach_pts),
444
+ "shiftable_peak_kwh": round(shiftable_kwh, 2),
445
+ },
446
+ )
447
+ ]
448
+
449
+
450
+ def detect_short_cycling(
451
+ points: list[TelemetryPoint],
452
+ dt_h: float,
453
+ cfg: AuditConfig,
454
+ ) -> list[Finding]:
455
+ # Short-cycling detection requires sub-20-minute telemetry
456
+ if dt_h > 0.34 or len(points) < 12:
457
+ return []
458
+
459
+ by_hour: dict[tuple[date, int], list[float]] = defaultdict(list)
460
+ for p in points:
461
+ by_hour[(p.timestamp.date(), p.timestamp.hour)].append(p.power_kw)
462
+
463
+ bad_hours: list[tuple[tuple[date, int], int, float]] = []
464
+ for key, vals in sorted(by_hour.items()):
465
+ if len(vals) < 6:
466
+ continue
467
+ lo, hi = min(vals), max(vals)
468
+ span = hi - lo
469
+ if span < cfg.short_cycle_min_swing_kw:
470
+ continue
471
+ high_th = lo + 0.65 * span
472
+ low_th = lo + 0.35 * span
473
+ is_on = vals[0] >= high_th
474
+ starts = 0
475
+ for v in vals[1:]:
476
+ if not is_on and v >= high_th:
477
+ is_on = True
478
+ starts += 1
479
+ elif is_on and v <= low_th:
480
+ is_on = False
481
+ if starts >= cfg.short_cycle_max_per_hour:
482
+ bad_hours.append((key, starts, round(span, 1)))
483
+
484
+ if not bad_hours:
485
+ return []
486
+
487
+ worst_key, worst_count, worst_span = max(bad_hours, key=lambda x: x[1])
488
+ return [
489
+ Finding(
490
+ code="SHORT_CYCLING",
491
+ title="Rapid compressor / equipment short-cycling",
492
+ severity=Severity.WARNING,
493
+ summary=(
494
+ f"Detected {len(bad_hours)} hour(s) with >={cfg.short_cycle_max_per_hour} "
495
+ f"ON/OFF swings/hour (worst: {worst_count} starts, {worst_span:.1f} kW swing at "
496
+ f"{worst_key[0].isoformat()} {worst_key[1]:02d}:00)."
497
+ ),
498
+ evidence={
499
+ "affected_hours": len(bad_hours),
500
+ "max_starts_per_hour": worst_count,
501
+ "worst_swing_kw": worst_span,
502
+ "worst_hour": f"{worst_key[0].isoformat()}T{worst_key[1]:02d}:00",
503
+ },
504
+ )
505
+ ]
@@ -0,0 +1,81 @@
1
+ from __future__ import annotations
2
+
3
+ from datetime import datetime, timezone
4
+ from pathlib import Path
5
+
6
+ from .detectors import (
7
+ detect_chiller_low_delta_t,
8
+ detect_peak_tariff_exposure,
9
+ detect_phantom_baseload,
10
+ detect_regime_changepoint,
11
+ detect_sensor_flatline,
12
+ detect_short_cycling,
13
+ detect_simultaneous_heat_cool,
14
+ infer_timestep_hours,
15
+ )
16
+ from .io import load_telemetry, sha256_dict, sha256_file
17
+ from .schema import AuditConfig, AuditReport, Severity, TelemetryPoint
18
+ from .tariffs import IranTariffProfile
19
+
20
+ __version__ = "0.1.0"
21
+
22
+ _SEVERITY_ORDER = {Severity.CRITICAL: 0, Severity.WARNING: 1, Severity.INFO: 2}
23
+
24
+
25
+ def audit_records(
26
+ points: list[TelemetryPoint],
27
+ config: AuditConfig | None = None,
28
+ tariff: IranTariffProfile | None = None,
29
+ source_path: str = "<in-memory>",
30
+ source_sha256: str = "",
31
+ ) -> AuditReport:
32
+ cfg = config or AuditConfig()
33
+ tar = tariff or IranTariffProfile()
34
+ dt_h = infer_timestep_hours(points)
35
+
36
+ findings = []
37
+ findings.extend(detect_simultaneous_heat_cool(points, dt_h, cfg, tar))
38
+ findings.extend(detect_phantom_baseload(points, dt_h, cfg, tar))
39
+ findings.extend(detect_sensor_flatline(points, dt_h, cfg))
40
+ findings.extend(detect_chiller_low_delta_t(points, dt_h, cfg, tar))
41
+ findings.extend(detect_regime_changepoint(points, dt_h, cfg, tar))
42
+ findings.extend(detect_peak_tariff_exposure(points, dt_h, cfg, tar))
43
+ findings.extend(detect_short_cycling(points, dt_h, cfg))
44
+
45
+ findings.sort(key=lambda f: (_SEVERITY_ORDER[f.severity], -f.estimated_cost_irr, f.code))
46
+
47
+ total_kwh = sum(p.power_kw * dt_h for p in points)
48
+ peak_kwh = sum(p.power_kw * dt_h for p in points if tar.period_for(p.timestamp) == "peak")
49
+ total_waste_kwh = sum(f.estimated_waste_kwh for f in findings)
50
+ total_cost_irr = sum(f.estimated_cost_irr for f in findings)
51
+
52
+ return AuditReport(
53
+ tool_version=__version__,
54
+ audited_at_utc=datetime.now(timezone.utc).isoformat(),
55
+ source_path=source_path,
56
+ source_sha256=source_sha256,
57
+ config_sha256=sha256_dict(cfg.to_dict()),
58
+ record_count=len(points),
59
+ timestep_hours=dt_h,
60
+ total_energy_kwh=total_kwh,
61
+ peak_energy_kwh=peak_kwh,
62
+ total_estimated_waste_kwh=total_waste_kwh,
63
+ total_estimated_cost_irr=total_cost_irr,
64
+ findings=findings,
65
+ )
66
+
67
+
68
+ def audit_file(
69
+ path: str | Path,
70
+ config: AuditConfig | None = None,
71
+ tariff: IranTariffProfile | None = None,
72
+ ) -> AuditReport:
73
+ p = Path(path)
74
+ points = load_telemetry(p)
75
+ return audit_records(
76
+ points=points,
77
+ config=config,
78
+ tariff=tariff,
79
+ source_path=str(p),
80
+ source_sha256=sha256_file(p),
81
+ )
@@ -0,0 +1,119 @@
1
+ from __future__ import annotations
2
+
3
+ import csv
4
+ import hashlib
5
+ import json
6
+ from datetime import datetime
7
+ from pathlib import Path
8
+ from typing import Any
9
+
10
+ from .schema import TelemetryPoint
11
+
12
+ COLUMN_ALIASES: dict[str, tuple[str, ...]] = {
13
+ "timestamp": ("timestamp", "time", "datetime", "ts", "date_time"),
14
+ "power_kw": ("power_kw", "kw", "active_power_kw", "load_kw", "elec_kw"),
15
+ "outdoor_temp_c": ("outdoor_temp_c", "oat", "t_out", "ambient_temp_c"),
16
+ "supply_air_temp_c": ("supply_air_temp_c", "sat", "t_sa"),
17
+ "chilled_water_supply_c": ("chilled_water_supply_c", "chws", "chw_supply_c"),
18
+ "chilled_water_return_c": ("chilled_water_return_c", "chwr", "chw_return_c"),
19
+ "heating_valve_pct": ("heating_valve_pct", "hw_valve", "heat_valve_pct"),
20
+ "cooling_valve_pct": ("cooling_valve_pct", "cw_valve", "cool_valve_pct"),
21
+ "gas_m3_hr": ("gas_m3_hr", "gas_flow", "gas_m3h"),
22
+ }
23
+
24
+
25
+ def sha256_file(path: Path) -> str:
26
+ h = hashlib.sha256()
27
+ with path.open("rb") as f:
28
+ for chunk in iter(lambda: f.read(65_536), b""):
29
+ h.update(chunk)
30
+ return h.hexdigest()
31
+
32
+
33
+ def sha256_dict(payload: dict[str, Any]) -> str:
34
+ raw = json.dumps(payload, sort_keys=True, separators=(",", ":")).encode("utf-8")
35
+ return hashlib.sha256(raw).hexdigest()
36
+
37
+
38
+ def _parse_float(raw: Any) -> float | None:
39
+ if raw is None:
40
+ return None
41
+ text = str(raw).strip()
42
+ if text == "" or text.lower() in {"na", "nan", "null", "none"}:
43
+ return None
44
+ return float(text)
45
+
46
+
47
+ def _parse_ts(raw: str) -> datetime:
48
+ text = raw.strip()
49
+ if text.endswith("Z"):
50
+ text = text[:-1] + "+00:00"
51
+ return datetime.fromisoformat(text)
52
+
53
+
54
+ def _resolve_columns(fieldnames: list[str]) -> dict[str, str]:
55
+ lowered = {c.strip().lower(): c for c in fieldnames}
56
+ mapping: dict[str, str] = {}
57
+ for canonical, aliases in COLUMN_ALIASES.items():
58
+ for alias in aliases:
59
+ if alias in lowered:
60
+ mapping[canonical] = lowered[alias]
61
+ break
62
+ return mapping
63
+
64
+
65
+ def _row_to_point(row: dict[str, Any], col_map: dict[str, str]) -> TelemetryPoint | None:
66
+ ts_raw = row.get(col_map["timestamp"])
67
+ kw_raw = _parse_float(row.get(col_map["power_kw"]))
68
+ if not ts_raw or kw_raw is None:
69
+ return None
70
+
71
+ def opt(field_name: str) -> float | None:
72
+ src = col_map.get(field_name)
73
+ return _parse_float(row.get(src)) if src else None
74
+
75
+ return TelemetryPoint(
76
+ timestamp=_parse_ts(str(ts_raw)),
77
+ power_kw=kw_raw,
78
+ outdoor_temp_c=opt("outdoor_temp_c"),
79
+ supply_air_temp_c=opt("supply_air_temp_c"),
80
+ chilled_water_supply_c=opt("chilled_water_supply_c"),
81
+ chilled_water_return_c=opt("chilled_water_return_c"),
82
+ heating_valve_pct=opt("heating_valve_pct"),
83
+ cooling_valve_pct=opt("cooling_valve_pct"),
84
+ gas_m3_hr=opt("gas_m3_hr"),
85
+ )
86
+
87
+
88
+ def load_telemetry(path: str | Path) -> list[TelemetryPoint]:
89
+ p = Path(path)
90
+ suffix = p.suffix.lower()
91
+ rows: list[dict[str, Any]] = []
92
+
93
+ if suffix == ".csv":
94
+ with p.open("r", encoding="utf-8-sig", newline="") as f:
95
+ reader = csv.DictReader(f)
96
+ if not reader.fieldnames:
97
+ raise ValueError(f"Empty CSV header in {p}")
98
+ col_map = _resolve_columns(list(reader.fieldnames))
99
+ rows = list(reader)
100
+ elif suffix in {".jsonl", ".ndjson"}:
101
+ with p.open("r", encoding="utf-8") as f:
102
+ for line in f:
103
+ if line.strip():
104
+ rows.append(json.loads(line))
105
+ if not rows:
106
+ raise ValueError(f"No records found in {p}")
107
+ col_map = _resolve_columns(list(rows[0].keys()))
108
+ else:
109
+ raise ValueError(f"Unsupported telemetry format '{suffix}'. Use .csv or .jsonl.")
110
+
111
+ if "timestamp" not in col_map or "power_kw" not in col_map:
112
+ raise ValueError(
113
+ "Telemetry must contain timestamp and power_kw columns "
114
+ f"(resolved: {list(col_map.keys())})."
115
+ )
116
+
117
+ points = [pt for row in rows if (pt := _row_to_point(row, col_map)) is not None]
118
+ points.sort(key=lambda x: x.timestamp)
119
+ return points
@@ -0,0 +1,70 @@
1
+ from __future__ import annotations
2
+
3
+ import json
4
+ import urllib.error
5
+ import urllib.request
6
+
7
+ from .schema import AuditReport
8
+
9
+
10
+ def _fallback_ticket(report: AuditReport, lang: str) -> str:
11
+ if lang == "fa":
12
+ lines = [
13
+ f"گزارش دستور کار نگهداری و بهینه‌سازی انرژی (tanzim v{report.tool_version})",
14
+ f"کل انرژی بررسی‌شده: {report.total_energy_kwh:,.1f} kWh | اتلاف برآوردی: {report.total_estimated_waste_kwh:,.1f} kWh",
15
+ "",
16
+ ]
17
+ for idx, f in enumerate(report.findings, 1):
18
+ lines.append(f"{idx}. [{f.severity.value.upper()}] {f.code} — {f.title}")
19
+ lines.append(f" شرح فنی: {f.summary}")
20
+ lines.append(f" برآورد هزینه قابل صرفه‌جویی: {f.estimated_cost_irr:,.0f} ریال")
21
+ return "\n".join(lines)
22
+
23
+ lines = [
24
+ f"Maintenance & Energy Optimization Work Order (tanzim v{report.tool_version})",
25
+ f"Audited energy: {report.total_energy_kwh:,.1f} kWh | Estimated waste: {report.total_estimated_waste_kwh:,.1f} kWh",
26
+ "",
27
+ ]
28
+ for idx, f in enumerate(report.findings, 1):
29
+ lines.append(f"{idx}. [{f.severity.value.upper()}] {f.code} — {f.title}")
30
+ lines.append(f" Details: {f.summary}")
31
+ return "\n".join(lines)
32
+
33
+
34
+ def generate_work_order(
35
+ report: AuditReport,
36
+ lang: str = "fa",
37
+ model: str = "gemma3:12b",
38
+ ollama_url: str = "http://localhost:11434/api/generate",
39
+ timeout_sec: int = 45,
40
+ ) -> str:
41
+ """Turn deterministic audit findings into a technician work order via local Ollama."""
42
+ if not report.findings:
43
+ return "هیچ خطای پنهان انرژی شناسایی نشد." if lang == "fa" else "No silent energy faults detected."
44
+
45
+ language_directive = (
46
+ "Write a clear, concise maintenance work order in natural Persian (Farsi) for a Tehran building facility engineer."
47
+ if lang == "fa"
48
+ else "Write a clear, concise maintenance work order in English for a building facility engineer."
49
+ )
50
+ prompt = (
51
+ f"{language_directive}\n"
52
+ "For each finding, list: (1) Root cause to inspect on-site, (2) Immediate corrective step, "
53
+ "(3) Expected energy/tariff benefit. Do not invent numbers outside the JSON.\n\n"
54
+ f"AUDIT JSON:\n{json.dumps(report.to_dict(), ensure_ascii=False, indent=2)}"
55
+ )
56
+
57
+ payload = json.dumps({"model": model, "prompt": prompt, "stream": False}).encode("utf-8")
58
+ req = urllib.request.Request(
59
+ ollama_url,
60
+ data=payload,
61
+ headers={"Content-Type": "application/json"},
62
+ method="POST",
63
+ )
64
+ try:
65
+ with urllib.request.urlopen(req, timeout=timeout_sec) as resp:
66
+ body = json.loads(resp.read().decode("utf-8"))
67
+ text = str(body.get("response", "")).strip()
68
+ return text or _fallback_ticket(report, lang)
69
+ except (urllib.error.URLError, TimeoutError, ValueError):
70
+ return _fallback_ticket(report, lang)
@@ -0,0 +1,103 @@
1
+ from __future__ import annotations
2
+
3
+ from dataclasses import asdict, dataclass, field
4
+ from datetime import datetime
5
+ from enum import Enum
6
+ from typing import Any
7
+
8
+
9
+ class Severity(str, Enum):
10
+ INFO = "info"
11
+ WARNING = "warning"
12
+ CRITICAL = "critical"
13
+
14
+
15
+ @dataclass(frozen=True)
16
+ class TelemetryPoint:
17
+ timestamp: datetime
18
+ power_kw: float
19
+ outdoor_temp_c: float | None = None
20
+ supply_air_temp_c: float | None = None
21
+ chilled_water_supply_c: float | None = None
22
+ chilled_water_return_c: float | None = None
23
+ heating_valve_pct: float | None = None
24
+ cooling_valve_pct: float | None = None
25
+ gas_m3_hr: float | None = None
26
+
27
+
28
+ @dataclass(frozen=True)
29
+ class Finding:
30
+ code: str
31
+ title: str
32
+ severity: Severity
33
+ summary: str
34
+ estimated_waste_kwh: float = 0.0
35
+ estimated_cost_irr: float = 0.0
36
+ start_time: str | None = None
37
+ end_time: str | None = None
38
+ evidence: dict[str, Any] = field(default_factory=dict)
39
+
40
+ def to_dict(self) -> dict[str, Any]:
41
+ data = asdict(self)
42
+ data["severity"] = self.severity.value
43
+ return data
44
+
45
+
46
+ @dataclass(frozen=True)
47
+ class AuditConfig:
48
+ occupied_start_hour: int = 8
49
+ occupied_end_hour: int = 17
50
+ night_start_hour: int = 0
51
+ night_end_hour: int = 5
52
+ # Iran weekends: Friday (weekday() == 4) and optionally Thursday afternoon
53
+ weekend_weekdays: tuple[int, ...] = (4,)
54
+ simultaneous_valve_pct: float = 15.0
55
+ simultaneous_min_hours: float = 1.0
56
+ phantom_baseload_ratio: float = 0.45
57
+ phantom_target_ratio: float = 0.25
58
+ flatline_min_hours: float = 2.0
59
+ low_delta_t_c: float = 2.5
60
+ low_delta_t_min_fraction: float = 0.20
61
+ active_plant_kw_floor: float = 15.0
62
+ changepoint_min_z: float = 3.5
63
+ changepoint_min_delta_kw: float = 10.0
64
+ short_cycle_max_per_hour: int = 4
65
+ short_cycle_min_swing_kw: float = 25.0
66
+ contracted_demand_kw: float | None = None
67
+ peak_to_mid_ratio_limit: float = 1.30
68
+ base_kwh_price_irr: float = 12_000.0 # Configurable commercial/industrial IRR/kWh
69
+
70
+ def to_dict(self) -> dict[str, Any]:
71
+ return asdict(self)
72
+
73
+
74
+ @dataclass(frozen=True)
75
+ class AuditReport:
76
+ tool_version: str
77
+ audited_at_utc: str
78
+ source_path: str
79
+ source_sha256: str
80
+ config_sha256: str
81
+ record_count: int
82
+ timestep_hours: float
83
+ total_energy_kwh: float
84
+ peak_energy_kwh: float
85
+ total_estimated_waste_kwh: float
86
+ total_estimated_cost_irr: float
87
+ findings: list[Finding]
88
+
89
+ def to_dict(self) -> dict[str, Any]:
90
+ return {
91
+ "tool_version": self.tool_version,
92
+ "audited_at_utc": self.audited_at_utc,
93
+ "source_path": self.source_path,
94
+ "source_sha256": self.source_sha256,
95
+ "config_sha256": self.config_sha256,
96
+ "record_count": self.record_count,
97
+ "timestep_hours": round(self.timestep_hours, 4),
98
+ "total_energy_kwh": round(self.total_energy_kwh, 2),
99
+ "peak_energy_kwh": round(self.peak_energy_kwh, 2),
100
+ "total_estimated_waste_kwh": round(self.total_estimated_waste_kwh, 2),
101
+ "total_estimated_cost_irr": round(self.total_estimated_cost_irr, 0),
102
+ "findings": [f.to_dict() for f in self.findings],
103
+ }
@@ -0,0 +1,118 @@
1
+ from __future__ import annotations
2
+
3
+ import csv
4
+ import math
5
+ import random
6
+ from datetime import datetime, timedelta
7
+ from pathlib import Path
8
+
9
+ from .schema import TelemetryPoint
10
+
11
+
12
+ def generate_tehran_summer_bms(
13
+ days: int = 14,
14
+ step_minutes: int = 10,
15
+ inject_faults: bool = True,
16
+ seed: int = 42,
17
+ ) -> list[TelemetryPoint]:
18
+ """Generate realistic Tehran summer commercial chiller/BMS telemetry."""
19
+ rng = random.Random(seed)
20
+ start = datetime(2026, 7, 1, 0, 0, 0)
21
+ total_steps = int((days * 24 * 60) / step_minutes)
22
+ points: list[TelemetryPoint] = []
23
+
24
+ for i in range(total_steps):
25
+ ts = start + timedelta(minutes=i * step_minutes)
26
+ day_idx = (ts - start).days
27
+ hour_f = ts.hour + ts.minute / 60.0
28
+
29
+ # Tehran July outdoor temperature cycle (~24C at 05:00 -> ~39C at 15:30)
30
+ oat = 31.5 - 7.5 * math.cos(2 * math.pi * (hour_f - 4.0) / 24.0) + rng.gauss(0, 0.3)
31
+
32
+ occupied = (ts.weekday() != 4) and (8 <= ts.hour < 17)
33
+ base_kw = 22.0 + rng.gauss(0, 0.8)
34
+ cooling_kw = max(0.0, (oat - 18.0) * 4.2) if occupied else 0.0
35
+ occ_internal_kw = 28.0 if occupied else 0.0
36
+ power_kw = base_kw + cooling_kw + occ_internal_kw
37
+
38
+ sat = 13.5 + rng.gauss(0, 0.25)
39
+ chws = 7.2 + rng.gauss(0, 0.12)
40
+ chwr = chws + (5.8 if occupied else 1.2) + rng.gauss(0, 0.15)
41
+ heat_v = 0.0
42
+ cool_v = min(100.0, max(0.0, (oat - 18.0) * 4.0)) if occupied else 0.0
43
+
44
+ if inject_faults:
45
+ # 1. Simultaneous heat/cool on Days 3-4 (09:00-15:00)
46
+ if day_idx in (3, 4) and 9 <= ts.hour < 15:
47
+ heat_v = 45.0
48
+ cool_v = 82.0
49
+ power_kw += 24.0
50
+
51
+ # 2. Frozen supply-air temperature sensor on Day 5 (08:00-14:00)
52
+ if day_idx == 5 and 8 <= ts.hour < 14:
53
+ sat = 13.40
54
+
55
+ # 3. Persistent +38 kW regime shift + phantom night baseload from Day 7 onward
56
+ if day_idx >= 7:
57
+ power_kw += 38.0
58
+ if 0 <= ts.hour < 5:
59
+ power_kw += 36.0 # Chiller/AHU left in manual hand mode overnight
60
+
61
+ # 4. Low Delta-T syndrome on Days 9-12
62
+ if day_idx in (9, 10, 11, 12) and occupied:
63
+ chwr = chws + 1.6 + rng.gauss(0, 0.08)
64
+
65
+ # 5. Severe summer peak overload (14:00-18:00) from Day 8 onward
66
+ if day_idx >= 8 and 14 <= ts.hour < 18:
67
+ power_kw += 55.0
68
+
69
+ # 6. Rapid compressor short-cycling on Day 12 (10:00-11:00) -> 6 cycles/hr at 10-min step?
70
+ # Use 10-min step: alternating ON/OFF every sample gives 3 starts; let's inject on 5-min or flag >=3
71
+ if day_idx == 12 and 10 <= ts.hour < 12:
72
+ power_kw = 155.0 if (i % 2 == 0) else 25.0
73
+
74
+ points.append(
75
+ TelemetryPoint(
76
+ timestamp=ts,
77
+ power_kw=round(max(0.0, power_kw), 2),
78
+ outdoor_temp_c=round(oat, 2),
79
+ supply_air_temp_c=round(sat, 2),
80
+ chilled_water_supply_c=round(chws, 2),
81
+ chilled_water_return_c=round(chwr, 2),
82
+ heating_valve_pct=round(heat_v, 1),
83
+ cooling_valve_pct=round(cool_v, 1),
84
+ )
85
+ )
86
+ return points
87
+
88
+
89
+ def write_telemetry_csv(points: list[TelemetryPoint], path: str | Path) -> Path:
90
+ out = Path(path)
91
+ out.parent.mkdir(parents=True, exist_ok=True)
92
+ fields = [
93
+ "timestamp",
94
+ "power_kw",
95
+ "outdoor_temp_c",
96
+ "supply_air_temp_c",
97
+ "chilled_water_supply_c",
98
+ "chilled_water_return_c",
99
+ "heating_valve_pct",
100
+ "cooling_valve_pct",
101
+ ]
102
+ with out.open("w", encoding="utf-8", newline="") as f:
103
+ writer = csv.DictWriter(f, fieldnames=fields)
104
+ writer.writeheader()
105
+ for p in points:
106
+ writer.writerow(
107
+ {
108
+ "timestamp": p.timestamp.isoformat(),
109
+ "power_kw": p.power_kw,
110
+ "outdoor_temp_c": p.outdoor_temp_c,
111
+ "supply_air_temp_c": p.supply_air_temp_c,
112
+ "chilled_water_supply_c": p.chilled_water_supply_c,
113
+ "chilled_water_return_c": p.chilled_water_return_c,
114
+ "heating_valve_pct": p.heating_valve_pct,
115
+ "cooling_valve_pct": p.cooling_valve_pct,
116
+ }
117
+ )
118
+ return out
@@ -0,0 +1,53 @@
1
+ from __future__ import annotations
2
+
3
+ from dataclasses import dataclass
4
+ from datetime import datetime
5
+
6
+
7
+ @dataclass(frozen=True)
8
+ class TariffWindow:
9
+ peak_hours: tuple[int, int] # [start, end)
10
+ off_peak_hours: tuple[int, int] # [start, end)
11
+
12
+
13
+ @dataclass(frozen=True)
14
+ class IranTariffProfile:
15
+ """Configurable seasonal Time-of-Use (ToU) schedule for Iranian commercial/industrial meters."""
16
+
17
+ spring: TariffWindow = TariffWindow(peak_hours=(21, 22), off_peak_hours=(1, 9))
18
+ summer: TariffWindow = TariffWindow(peak_hours=(14, 18), off_peak_hours=(3, 8))
19
+ autumn: TariffWindow = TariffWindow(peak_hours=(18, 21), off_peak_hours=(1, 9))
20
+ winter: TariffWindow = TariffWindow(peak_hours=(18, 21), off_peak_hours=(1, 9))
21
+
22
+ peak_multiplier: float = 2.5
23
+ mid_multiplier: float = 1.0
24
+ off_peak_multiplier: float = 0.5
25
+
26
+ def season_for(self, ts: datetime) -> str:
27
+ m = ts.month
28
+ if m in (3, 4, 5):
29
+ return "spring"
30
+ if m in (6, 7, 8):
31
+ return "summer"
32
+ if m in (9, 10, 11):
33
+ return "autumn"
34
+ return "winter"
35
+
36
+ def period_for(self, ts: datetime) -> str:
37
+ window: TariffWindow = getattr(self, self.season_for(ts))
38
+ h = ts.hour
39
+ p_start, p_end = window.peak_hours
40
+ o_start, o_end = window.off_peak_hours
41
+ if p_start <= h < p_end:
42
+ return "peak"
43
+ if o_start <= h < o_end:
44
+ return "off_peak"
45
+ return "mid_peak"
46
+
47
+ def multiplier_for(self, ts: datetime) -> float:
48
+ period = self.period_for(ts)
49
+ if period == "peak":
50
+ return self.peak_multiplier
51
+ if period == "off_peak":
52
+ return self.off_peak_multiplier
53
+ return self.mid_multiplier
@@ -0,0 +1,12 @@
1
+ Metadata-Version: 2.4
2
+ Name: tanzim
3
+ Version: 0.1.0
4
+ Summary: Offline-first silent-fault and energy-imbalance auditor for building BMS and industrial SCADA logs.
5
+ Author-email: Aslan Satary Dizaji <aslansatary@gmail.com>
6
+ License: MIT
7
+ Keywords: bms,scada,hvac,energy-audit,fault-detection,change-point
8
+ Requires-Python: >=3.10
9
+ Description-Content-Type: text/markdown
10
+ Provides-Extra: dev
11
+ Requires-Dist: pytest>=8.0; extra == "dev"
12
+ Requires-Dist: ruff>=0.6; extra == "dev"
@@ -0,0 +1,18 @@
1
+ pyproject.toml
2
+ src/tanzim/__init__.py
3
+ src/tanzim/__version__.py
4
+ src/tanzim/cli.py
5
+ src/tanzim/detectors.py
6
+ src/tanzim/engine.py
7
+ src/tanzim/io.py
8
+ src/tanzim/llm_tickets.py
9
+ src/tanzim/schema.py
10
+ src/tanzim/synthetic.py
11
+ src/tanzim/tariffs.py
12
+ src/tanzim.egg-info/PKG-INFO
13
+ src/tanzim.egg-info/SOURCES.txt
14
+ src/tanzim.egg-info/dependency_links.txt
15
+ src/tanzim.egg-info/entry_points.txt
16
+ src/tanzim.egg-info/requires.txt
17
+ src/tanzim.egg-info/top_level.txt
18
+ tests/test_tanzim.py
@@ -0,0 +1,2 @@
1
+ [console_scripts]
2
+ tanzim = tanzim.cli:main
@@ -0,0 +1,4 @@
1
+
2
+ [dev]
3
+ pytest>=8.0
4
+ ruff>=0.6
@@ -0,0 +1 @@
1
+ tanzim
@@ -0,0 +1,35 @@
1
+ from __future__ import annotations
2
+
3
+ from pathlib import Path
4
+
5
+ from tanzim import AuditConfig, audit_file, audit_records
6
+ from tanzim.synthetic import generate_tehran_summer_bms, write_telemetry_csv
7
+
8
+
9
+ def test_clean_tehran_plant_has_zero_false_positives() -> None:
10
+ pts = generate_tehran_summer_bms(days=14, step_minutes=5, inject_faults=False, seed=7)
11
+ report = audit_records(pts, config=AuditConfig(contracted_demand_kw=180.0))
12
+ assert report.findings == []
13
+ assert report.total_energy_kwh > 0
14
+
15
+
16
+ def test_faulted_tehran_plant_catches_all_seven_faults(tmp_path: Path) -> None:
17
+ pts = generate_tehran_summer_bms(days=14, step_minutes=5, inject_faults=True, seed=42)
18
+ csv_path = write_telemetry_csv(pts, tmp_path / "faulted.csv")
19
+
20
+ report = audit_file(csv_path, config=AuditConfig(contracted_demand_kw=180.0))
21
+ codes = {f.code for f in report.findings}
22
+
23
+ expected = {
24
+ "SIMULTANEOUS_HEAT_COOL",
25
+ "PHANTOM_BASELOAD",
26
+ "SENSOR_FLATLINE",
27
+ "CHILLER_LOW_DELTA_T",
28
+ "REGIME_CHANGE_POINT",
29
+ "PEAK_TARIFF_EXPOSURE",
30
+ "SHORT_CYCLING",
31
+ }
32
+ assert expected.issubset(codes)
33
+ assert len(report.source_sha256) == 64
34
+ assert report.total_estimated_waste_kwh > 0
35
+ assert report.total_estimated_cost_irr > 0