gridlens 0.2.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.
Files changed (46) hide show
  1. gridlens-0.2.0/LICENSE +21 -0
  2. gridlens-0.2.0/PKG-INFO +109 -0
  3. gridlens-0.2.0/README.md +90 -0
  4. gridlens-0.2.0/gridlens/__init__.py +4 -0
  5. gridlens-0.2.0/gridlens/__main__.py +5 -0
  6. gridlens-0.2.0/gridlens/analysis/__init__.py +5 -0
  7. gridlens-0.2.0/gridlens/analysis/intervals.py +94 -0
  8. gridlens-0.2.0/gridlens/cli.py +151 -0
  9. gridlens-0.2.0/gridlens/events/__init__.py +3 -0
  10. gridlens-0.2.0/gridlens/events/voltage_events.py +66 -0
  11. gridlens-0.2.0/gridlens/generator/__init__.py +3 -0
  12. gridlens-0.2.0/gridlens/generator/waveforms.py +39 -0
  13. gridlens-0.2.0/gridlens/loaders/__init__.py +21 -0
  14. gridlens-0.2.0/gridlens/loaders/comtrade_loader.py +81 -0
  15. gridlens-0.2.0/gridlens/loaders/csv_loader.py +34 -0
  16. gridlens-0.2.0/gridlens/metrics/__init__.py +13 -0
  17. gridlens-0.2.0/gridlens/metrics/power_factor.py +45 -0
  18. gridlens-0.2.0/gridlens/metrics/rms.py +28 -0
  19. gridlens-0.2.0/gridlens/metrics/thd.py +26 -0
  20. gridlens-0.2.0/gridlens/py.typed +0 -0
  21. gridlens-0.2.0/gridlens/reports/__init__.py +5 -0
  22. gridlens-0.2.0/gridlens/reports/html_report.py +135 -0
  23. gridlens-0.2.0/gridlens/standards/__init__.py +31 -0
  24. gridlens-0.2.0/gridlens/standards/base.py +85 -0
  25. gridlens-0.2.0/gridlens/standards/en50160.py +164 -0
  26. gridlens-0.2.0/gridlens/standards/ieee519.py +69 -0
  27. gridlens-0.2.0/gridlens/standards/india.py +35 -0
  28. gridlens-0.2.0/gridlens/waveform.py +52 -0
  29. gridlens-0.2.0/gridlens.egg-info/PKG-INFO +109 -0
  30. gridlens-0.2.0/gridlens.egg-info/SOURCES.txt +44 -0
  31. gridlens-0.2.0/gridlens.egg-info/dependency_links.txt +1 -0
  32. gridlens-0.2.0/gridlens.egg-info/entry_points.txt +2 -0
  33. gridlens-0.2.0/gridlens.egg-info/requires.txt +11 -0
  34. gridlens-0.2.0/gridlens.egg-info/top_level.txt +1 -0
  35. gridlens-0.2.0/pyproject.toml +25 -0
  36. gridlens-0.2.0/setup.cfg +4 -0
  37. gridlens-0.2.0/tests/test_cli.py +25 -0
  38. gridlens-0.2.0/tests/test_comtrade_loader.py +28 -0
  39. gridlens-0.2.0/tests/test_csv_loader.py +45 -0
  40. gridlens-0.2.0/tests/test_events.py +54 -0
  41. gridlens-0.2.0/tests/test_intervals.py +32 -0
  42. gridlens-0.2.0/tests/test_power_factor.py +45 -0
  43. gridlens-0.2.0/tests/test_reports.py +35 -0
  44. gridlens-0.2.0/tests/test_rms.py +21 -0
  45. gridlens-0.2.0/tests/test_standards.py +67 -0
  46. gridlens-0.2.0/tests/test_thd.py +20 -0
gridlens-0.2.0/LICENSE ADDED
@@ -0,0 +1,21 @@
1
+ MIT License
2
+
3
+ Copyright (c) 2026 Bhuvanesh Arun C T
4
+
5
+ Permission is hereby granted, free of charge, to any person obtaining a copy
6
+ of this software and associated documentation files (the "Software"), to deal
7
+ in the Software without restriction, including without limitation the rights
8
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9
+ copies of the Software, and to permit persons to whom the Software is
10
+ furnished to do so, subject to the following conditions:
11
+
12
+ The above copyright notice and this permission notice shall be included in all
13
+ copies or substantial portions of the Software.
14
+
15
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
21
+ SOFTWARE.
@@ -0,0 +1,109 @@
1
+ Metadata-Version: 2.4
2
+ Name: gridlens
3
+ Version: 0.2.0
4
+ Summary: Open-source power quality analysis toolkit
5
+ License: MIT
6
+ Requires-Python: >=3.10
7
+ Description-Content-Type: text/markdown
8
+ License-File: LICENSE
9
+ Requires-Dist: numpy
10
+ Requires-Dist: scipy
11
+ Requires-Dist: pandas
12
+ Requires-Dist: matplotlib
13
+ Provides-Extra: comtrade
14
+ Requires-Dist: comtrade; extra == "comtrade"
15
+ Provides-Extra: dev
16
+ Requires-Dist: pytest; extra == "dev"
17
+ Requires-Dist: ruff; extra == "dev"
18
+ Dynamic: license-file
19
+
20
+ # GridLens
21
+
22
+ [![CI](https://github.com/bhuvi-777/gridlens/actions/workflows/tests.yml/badge.svg)](https://github.com/bhuvi-777/gridlens/actions/workflows/tests.yml)
23
+ [![License](https://img.shields.io/github/license/bhuvi-777/gridlens)](LICENSE)
24
+
25
+ ![GridLens HTML compliance report screenshot](docs/images/report-preview.png)
26
+
27
+ Vendor-neutral Python power-quality analysis, standards checks, and reports from waveform files.
28
+
29
+ ## Quickstart
30
+
31
+ From a clone of this repository, run these three commands:
32
+
33
+ ```powershell
34
+ python -m pip install -e ".[dev]"
35
+ gridlens generate demo.csv --duration 60 --harmonic 5=0.04
36
+ gridlens analyze demo.csv --interval 10 --report report.html
37
+ ```
38
+
39
+ The generated report is indicative for this short demo recording. For a full
40
+ assessment, use an appropriately long recording and verify results against the
41
+ official standard and certified instruments.
42
+
43
+ ## Why GridLens?
44
+
45
+ Power-quality tools are often tied to a particular instrument. GridLens aims
46
+ to provide a free, scriptable layer for analyzing waveform data from multiple
47
+ sources, with reusable metrics, event detection, standards checks, and reports.
48
+
49
+ ## Python example
50
+
51
+ ```python
52
+ from gridlens.generator import sine_wave
53
+ from gridlens.metrics import power_factor, rms, thd
54
+
55
+ t, v = sine_wave(rms=230, harmonics={5: 0.08}) # 230 V with 8 % 5th harmonic
56
+ _, i = sine_wave(rms=10, phase=-0.5) # 10 A, lagging
57
+
58
+ print(f"Voltage RMS: {rms(v):.1f} V")
59
+ print(f"Voltage THD: {thd(v, fs=10_000):.2%}")
60
+ print(f"Power factor: {power_factor(v, i):.3f}")
61
+ ```
62
+
63
+ Load your own data:
64
+
65
+ ```python
66
+ from gridlens.loaders import load_csv
67
+
68
+ wave = load_csv("capture.csv", voltage_col="v", current_col="i", fs=10_000)
69
+ ```
70
+
71
+ ## Roadmap
72
+
73
+ - [x] Synthetic waveform generator
74
+ - [x] RMS, THD, active/reactive/apparent power, power factor
75
+ - [x] CSV loader
76
+ - [x] Sag, swell and interruption detection
77
+ - [x] EN 50160 and IEEE 519 voltage compliance checks
78
+ - [ ] Indian grid code limits
79
+ - [x] COMTRADE loading (optional `comtrade`)
80
+ - [x] HTML compliance reports
81
+ - [x] Command-line tool
82
+ - [ ] PDF report and web UI
83
+
84
+ ## Analyze a file
85
+
86
+ ```powershell
87
+ gridlens analyze capture.csv --standard en50160 --nominal 230 --freq 50
88
+ gridlens analyze capture.csv --standard ieee519 --bus-kv 11 --report report.html
89
+ ```
90
+
91
+ ## Standards supported
92
+
93
+ | Standard | Status |
94
+ | --- | --- |
95
+ | EN 50160 | Implemented for LV voltage, frequency, THD and harmonics |
96
+ | IEEE 519-2014/2022 | Voltage distortion implemented; current TDD planned |
97
+ | India CEA/grid code | Planned; limits are not implemented |
98
+
99
+ > Engineering guidance only. Compliance claims must be verified against the
100
+ > official standard text and edition, applicable system scope, and certified instruments.
101
+
102
+ ## Contributing
103
+
104
+ Issues and pull requests are welcome. See [CONTRIBUTING.md](CONTRIBUTING.md)
105
+ for setup and contribution steps. Pull requests must pass CI before merging.
106
+
107
+ ## License
108
+
109
+ MIT
@@ -0,0 +1,90 @@
1
+ # GridLens
2
+
3
+ [![CI](https://github.com/bhuvi-777/gridlens/actions/workflows/tests.yml/badge.svg)](https://github.com/bhuvi-777/gridlens/actions/workflows/tests.yml)
4
+ [![License](https://img.shields.io/github/license/bhuvi-777/gridlens)](LICENSE)
5
+
6
+ ![GridLens HTML compliance report screenshot](docs/images/report-preview.png)
7
+
8
+ Vendor-neutral Python power-quality analysis, standards checks, and reports from waveform files.
9
+
10
+ ## Quickstart
11
+
12
+ From a clone of this repository, run these three commands:
13
+
14
+ ```powershell
15
+ python -m pip install -e ".[dev]"
16
+ gridlens generate demo.csv --duration 60 --harmonic 5=0.04
17
+ gridlens analyze demo.csv --interval 10 --report report.html
18
+ ```
19
+
20
+ The generated report is indicative for this short demo recording. For a full
21
+ assessment, use an appropriately long recording and verify results against the
22
+ official standard and certified instruments.
23
+
24
+ ## Why GridLens?
25
+
26
+ Power-quality tools are often tied to a particular instrument. GridLens aims
27
+ to provide a free, scriptable layer for analyzing waveform data from multiple
28
+ sources, with reusable metrics, event detection, standards checks, and reports.
29
+
30
+ ## Python example
31
+
32
+ ```python
33
+ from gridlens.generator import sine_wave
34
+ from gridlens.metrics import power_factor, rms, thd
35
+
36
+ t, v = sine_wave(rms=230, harmonics={5: 0.08}) # 230 V with 8 % 5th harmonic
37
+ _, i = sine_wave(rms=10, phase=-0.5) # 10 A, lagging
38
+
39
+ print(f"Voltage RMS: {rms(v):.1f} V")
40
+ print(f"Voltage THD: {thd(v, fs=10_000):.2%}")
41
+ print(f"Power factor: {power_factor(v, i):.3f}")
42
+ ```
43
+
44
+ Load your own data:
45
+
46
+ ```python
47
+ from gridlens.loaders import load_csv
48
+
49
+ wave = load_csv("capture.csv", voltage_col="v", current_col="i", fs=10_000)
50
+ ```
51
+
52
+ ## Roadmap
53
+
54
+ - [x] Synthetic waveform generator
55
+ - [x] RMS, THD, active/reactive/apparent power, power factor
56
+ - [x] CSV loader
57
+ - [x] Sag, swell and interruption detection
58
+ - [x] EN 50160 and IEEE 519 voltage compliance checks
59
+ - [ ] Indian grid code limits
60
+ - [x] COMTRADE loading (optional `comtrade`)
61
+ - [x] HTML compliance reports
62
+ - [x] Command-line tool
63
+ - [ ] PDF report and web UI
64
+
65
+ ## Analyze a file
66
+
67
+ ```powershell
68
+ gridlens analyze capture.csv --standard en50160 --nominal 230 --freq 50
69
+ gridlens analyze capture.csv --standard ieee519 --bus-kv 11 --report report.html
70
+ ```
71
+
72
+ ## Standards supported
73
+
74
+ | Standard | Status |
75
+ | --- | --- |
76
+ | EN 50160 | Implemented for LV voltage, frequency, THD and harmonics |
77
+ | IEEE 519-2014/2022 | Voltage distortion implemented; current TDD planned |
78
+ | India CEA/grid code | Planned; limits are not implemented |
79
+
80
+ > Engineering guidance only. Compliance claims must be verified against the
81
+ > official standard text and edition, applicable system scope, and certified instruments.
82
+
83
+ ## Contributing
84
+
85
+ Issues and pull requests are welcome. See [CONTRIBUTING.md](CONTRIBUTING.md)
86
+ for setup and contribution steps. Pull requests must pass CI before merging.
87
+
88
+ ## License
89
+
90
+ MIT
@@ -0,0 +1,4 @@
1
+ from .waveform import Waveform
2
+
3
+ __version__ = "0.2.0"
4
+ __all__ = ["Waveform", "__version__"]
@@ -0,0 +1,5 @@
1
+ """Allow python -m gridlens."""
2
+
3
+ from .cli import main
4
+
5
+ raise SystemExit(main())
@@ -0,0 +1,5 @@
1
+ """Interval and recording analysis helpers."""
2
+
3
+ from .intervals import compute_intervals
4
+
5
+ __all__ = ["compute_intervals"]
@@ -0,0 +1,94 @@
1
+ """Interval-based power-quality analysis."""
2
+ from __future__ import annotations
3
+
4
+ import numpy as np
5
+ import pandas as pd
6
+
7
+ from ..waveform import Waveform
8
+
9
+
10
+ def _window_frequency(t: np.ndarray, voltage: np.ndarray, f0: float) -> float:
11
+ """Estimate frequency using rising-edge zero crossings."""
12
+ indices = np.flatnonzero((voltage[:-1] < 0.0) & (voltage[1:] >= 0.0))
13
+ if indices.size < 2:
14
+ return f0
15
+ cross = t[indices] - voltage[indices] * (
16
+ t[indices + 1] - t[indices]
17
+ ) / (voltage[indices + 1] - voltage[indices])
18
+ return float((cross.size - 1) / (cross[-1] - cross[0]))
19
+
20
+
21
+ def compute_intervals(
22
+ wave: Waveform,
23
+ interval_s: float = 600.0,
24
+ f0: float = 50.0,
25
+ max_harmonic: int = 40,
26
+ ) -> pd.DataFrame:
27
+ """Compute 10-cycle or 12-cycle window metrics and interval aggregates.
28
+
29
+ Harmonic magnitudes use the FFT bin nearest to ``order * f0`` Hz.
30
+ Each interval reports the mean of the window harmonic values and THD.
31
+ """
32
+ if interval_s <= 0:
33
+ raise ValueError("interval_s must be positive")
34
+ if f0 not in (50.0, 60.0):
35
+ raise ValueError("f0 must be 50 or 60 Hz")
36
+ fs = wave.fs
37
+ cycles = 12 if f0 == 60.0 else 10
38
+ samples_per_cycle = fs / f0
39
+ if not np.isclose(samples_per_cycle, round(samples_per_cycle), rtol=0.0, atol=1e-9):
40
+ raise ValueError(
41
+ "Sampling rate does not provide an integer number of samples per cycle; "
42
+ "call gridlens.waveform.resample() first"
43
+ )
44
+
45
+ window_size = cycles * round(samples_per_cycle)
46
+ windows = [
47
+ (start, start + window_size)
48
+ for start in range(0, len(wave.voltage) - window_size + 1, window_size)
49
+ ]
50
+ rows: list[dict[str, float]] = []
51
+ for start, stop in windows:
52
+ segment = np.asarray(wave.voltage[start:stop], dtype=float)
53
+ segment_t = np.asarray(wave.t[start:stop], dtype=float)
54
+ urms = float(np.sqrt(np.mean(segment**2)))
55
+ freq = _window_frequency(segment_t, segment, f0)
56
+ spectrum = np.abs(np.fft.rfft(segment))
57
+ df = fs / segment.size
58
+ fundamental = spectrum[round(f0 / df)]
59
+ if fundamental == 0:
60
+ harmonic_values = {f"h{order}": 0.0 for order in range(2, max_harmonic + 1)}
61
+ thd = 0.0
62
+ else:
63
+ harmonic_values = {}
64
+ harmonic_sum = 0.0
65
+ for order in range(2, max_harmonic + 1):
66
+ magnitude = spectrum[round(order * f0 / df)]
67
+ percent = 100.0 * magnitude / fundamental
68
+ harmonic_values[f"h{order}"] = percent
69
+ harmonic_sum += percent**2
70
+ thd = float(np.sqrt(harmonic_sum))
71
+ window_start = float(wave.t[start])
72
+ rows.append({
73
+ "start": window_start,
74
+ "urms": urms,
75
+ "freq": freq,
76
+ "thd": thd,
77
+ **harmonic_values,
78
+ })
79
+
80
+ if not rows:
81
+ return pd.DataFrame(
82
+ {"start": [], "urms": [], "freq": [], "thd": [],
83
+ **{f"h{order}": [] for order in range(2, max_harmonic + 1)}}
84
+ )
85
+
86
+ frame = pd.DataFrame(rows)
87
+ interval_starts = np.floor(frame["start"] / interval_s) * interval_s
88
+ frame["interval"] = interval_starts
89
+ aggregate_columns = ["urms", "freq", "thd"] + [
90
+ f"h{order}" for order in range(2, max_harmonic + 1)
91
+ ]
92
+ result = frame.groupby("interval", sort=True)[aggregate_columns].mean().reset_index()
93
+ result = result.rename(columns={"interval": "start"})
94
+ return result
@@ -0,0 +1,151 @@
1
+ """Command-line interface for GridLens."""
2
+ from __future__ import annotations
3
+
4
+ import argparse
5
+ import json
6
+ import sys
7
+ from pathlib import Path
8
+
9
+ import pandas as pd
10
+
11
+ from .analysis import compute_intervals
12
+ from .events import detect_events
13
+ from .generator import apply_event, sine_wave
14
+ from .loaders import load
15
+ from .reports import write_report
16
+ from .standards import check_en50160, check_ieee519_voltage
17
+
18
+
19
+ class _Parser(argparse.ArgumentParser):
20
+ def error(self, message: str) -> None:
21
+ raise ValueError(message)
22
+
23
+
24
+ def _build_parser() -> argparse.ArgumentParser:
25
+ parser = _Parser(prog="gridlens")
26
+ subparsers = parser.add_subparsers(
27
+ dest="command", required=True, parser_class=_Parser
28
+ )
29
+
30
+ analyze = subparsers.add_parser("analyze", help="Analyze a waveform file")
31
+ analyze.add_argument("file")
32
+ analyze.add_argument("--standard", choices=["en50160", "ieee519"], default="en50160")
33
+ analyze.add_argument("--nominal", type=float, default=230.0)
34
+ analyze.add_argument("--freq", type=float, default=50.0)
35
+ analyze.add_argument("--voltage-col", default="voltage")
36
+ analyze.add_argument("--current-col")
37
+ analyze.add_argument("--time-col", default="time")
38
+ analyze.add_argument("--fs", type=float)
39
+ analyze.add_argument("--interval", type=float, default=600.0)
40
+ analyze.add_argument("--bus-kv", type=float)
41
+ analyze.add_argument("--report")
42
+ analyze.add_argument("--json")
43
+
44
+ generate = subparsers.add_parser("generate", help="Generate a demo waveform")
45
+ generate.add_argument("out")
46
+ generate.add_argument("--duration", type=float, default=60.0)
47
+ generate.add_argument("--fs", type=float, default=10_000.0)
48
+ generate.add_argument("--rms", type=float, default=230.0)
49
+ generate.add_argument("--freq", type=float, default=50.0)
50
+ generate.add_argument("--harmonic", action="append", default=[], metavar="ORDER=RATIO")
51
+ generate.add_argument("--sag", action="append", default=[], metavar="START:DURATION:FACTOR")
52
+ generate.add_argument("--seed", type=int)
53
+ return parser
54
+
55
+
56
+ def _print_summary(result) -> None:
57
+ print(f"{result.standard}: {'PASS' if result.passed else 'FAIL'}")
58
+ print("Name | Limit | Measured | Unit | Status")
59
+ for check in result.checks:
60
+ print(
61
+ f"{check.name} | {check.limit} | {check.measured} | "
62
+ f"{check.unit} | {'PASS' if check.passed else 'FAIL'}"
63
+ )
64
+
65
+
66
+ def _generate(args: argparse.Namespace) -> int:
67
+ harmonics = {}
68
+ try:
69
+ for item in args.harmonic:
70
+ order, ratio = item.split("=", 1)
71
+ harmonics[int(order)] = float(ratio)
72
+ t, voltage = sine_wave(
73
+ freq=args.freq,
74
+ rms=args.rms,
75
+ fs=args.fs,
76
+ duration=args.duration,
77
+ harmonics=harmonics,
78
+ )
79
+ for item in args.sag:
80
+ start, duration, factor = item.split(":")
81
+ voltage = apply_event(
82
+ t, voltage, float(start), float(duration), float(factor)
83
+ )
84
+ except (ValueError, TypeError) as exc:
85
+ print(f"Error: {exc}", file=sys.stderr)
86
+ return 2
87
+
88
+ output = Path(args.out)
89
+ pd.DataFrame({"time": t, "voltage": voltage}).to_csv(output, index=False)
90
+ return 0
91
+
92
+
93
+ def _analyze(args: argparse.Namespace) -> int:
94
+ try:
95
+ suffix = Path(args.file).suffix.lower()
96
+ if suffix in (".cfg", ".dat"):
97
+ wave = load(args.file)
98
+ else:
99
+ wave = load(
100
+ args.file,
101
+ time_col=args.time_col,
102
+ voltage_col=args.voltage_col,
103
+ current_col=args.current_col,
104
+ fs=args.fs,
105
+ )
106
+ intervals = compute_intervals(
107
+ wave, interval_s=args.interval, f0=args.freq, max_harmonic=40
108
+ )
109
+ intervals.attrs["interval_s"] = args.interval
110
+ events = detect_events(
111
+ wave.voltage, wave.fs, nominal=args.nominal, f0=args.freq
112
+ )
113
+ if args.standard == "en50160":
114
+ result = check_en50160(
115
+ intervals, nominal=args.nominal, f0=args.freq, events=events
116
+ )
117
+ else:
118
+ if args.bus_kv is None:
119
+ raise ValueError("--bus-kv is required for the ieee519 standard")
120
+ result = check_ieee519_voltage(intervals, args.bus_kv)
121
+ _print_summary(result)
122
+ if args.report:
123
+ write_report(
124
+ args.report,
125
+ result,
126
+ wave=wave,
127
+ events=events,
128
+ intervals=intervals,
129
+ )
130
+ if args.json:
131
+ Path(args.json).write_text(
132
+ json.dumps(result.to_dict(), indent=2),
133
+ encoding="utf-8",
134
+ )
135
+ return 0 if result.passed else 1
136
+ except (OSError, KeyError, ValueError, ImportError) as exc:
137
+ print(f"Error: {exc}", file=sys.stderr)
138
+ return 2
139
+
140
+
141
+ def main(argv: list[str] | None = None) -> int:
142
+ """Run the GridLens command-line interface."""
143
+ parser = _build_parser()
144
+ try:
145
+ args = parser.parse_args(argv)
146
+ except ValueError as exc:
147
+ print(f"Error: {exc}", file=sys.stderr)
148
+ return 2
149
+ if args.command == "generate":
150
+ return _generate(args)
151
+ return _analyze(args)
@@ -0,0 +1,3 @@
1
+ from .voltage_events import VoltageEvent, detect_events
2
+
3
+ __all__ = ["VoltageEvent", "detect_events"]
@@ -0,0 +1,66 @@
1
+ """Detection of voltage sags, swells and interruptions."""
2
+ from dataclasses import dataclass
3
+
4
+ from ..metrics.rms import rms_half_cycle
5
+
6
+
7
+ @dataclass
8
+ class VoltageEvent:
9
+ """One detected event. Time resolution is half a cycle."""
10
+
11
+ kind: str # "sag", "swell" or "interruption"
12
+ start: float # start time in seconds
13
+ duration: float # duration in seconds
14
+ extreme: float # lowest (sag/interruption) or highest (swell) RMS, in volts
15
+ extreme_pct: float # the same value as a percentage of nominal
16
+
17
+
18
+ def _find_runs(urms, below, threshold, hysteresis):
19
+ """Return (start, stop) index pairs where urms crosses the threshold."""
20
+ runs = []
21
+ start = None
22
+ for k, u in enumerate(urms):
23
+ if start is None:
24
+ if (u < threshold) if below else (u > threshold):
25
+ start = k
26
+ else:
27
+ if below:
28
+ released = u >= threshold + hysteresis
29
+ else:
30
+ released = u <= threshold - hysteresis
31
+ if released:
32
+ runs.append((start, k))
33
+ start = None
34
+ if start is not None:
35
+ runs.append((start, len(urms)))
36
+ return runs
37
+
38
+
39
+ def detect_events(voltage, fs, nominal=230.0, f0=50.0, sag=0.90, swell=1.10,
40
+ interruption=0.05, hysteresis=0.02):
41
+ """Find sags, swells and interruptions in a voltage waveform.
42
+
43
+ Thresholds are fractions of the nominal RMS voltage. Events are
44
+ returned in time order.
45
+ """
46
+ if nominal <= 0:
47
+ raise ValueError("nominal must be positive")
48
+
49
+ urms, times = rms_half_cycle(voltage, fs, f0)
50
+ half_period = 0.5 / f0
51
+ hyst = hysteresis * nominal
52
+ events = []
53
+
54
+ for a, b in _find_runs(urms, True, sag * nominal, hyst):
55
+ low = float(urms[a:b].min())
56
+ kind = "interruption" if low < interruption * nominal else "sag"
57
+ events.append(VoltageEvent(kind, float(times[a]), (b - a) * half_period,
58
+ low, 100 * low / nominal))
59
+
60
+ for a, b in _find_runs(urms, False, swell * nominal, hyst):
61
+ high = float(urms[a:b].max())
62
+ events.append(VoltageEvent("swell", float(times[a]), (b - a) * half_period,
63
+ high, 100 * high / nominal))
64
+
65
+ events.sort(key=lambda e: e.start)
66
+ return events
@@ -0,0 +1,3 @@
1
+ from .waveforms import apply_event, sine_wave
2
+
3
+ __all__ = ["apply_event", "sine_wave"]
@@ -0,0 +1,39 @@
1
+ """Synthetic waveform generation for testing and teaching."""
2
+ import numpy as np
3
+
4
+
5
+ def sine_wave(freq=50.0, rms=230.0, fs=10_000.0, duration=0.2,
6
+ harmonics=None, phase=0.0):
7
+ """Generate a voltage waveform.
8
+
9
+ Parameters
10
+ ----------
11
+ freq : fundamental frequency in Hz
12
+ rms : RMS value of the fundamental component
13
+ fs : sampling rate in Hz
14
+ duration : length in seconds (use a whole number of cycles)
15
+ harmonics : dict {order: amplitude relative to fundamental},
16
+ e.g. {5: 0.1} adds a 5th harmonic at 10 % of the fundamental
17
+ phase : phase of the fundamental in radians
18
+
19
+ Returns
20
+ -------
21
+ t, signal : two numpy arrays
22
+ """
23
+ t = np.arange(round(fs * duration)) / fs
24
+ peak = rms * np.sqrt(2)
25
+ signal = np.sin(2 * np.pi * freq * t + phase)
26
+ for order, ratio in (harmonics or {}).items():
27
+ signal = signal + ratio * np.sin(2 * np.pi * order * freq * t)
28
+ return t, peak * signal
29
+
30
+
31
+ def apply_event(t, signal, start, duration, factor):
32
+ """Scale a signal by `factor` between start and start + duration (seconds).
33
+
34
+ factor < 1 makes a sag, factor > 1 a swell, factor = 0 an interruption.
35
+ """
36
+ out = np.array(signal, dtype=float, copy=True)
37
+ mask = (t >= start) & (t < start + duration)
38
+ out[mask] *= factor
39
+ return out
@@ -0,0 +1,21 @@
1
+ """Waveform loaders."""
2
+ from pathlib import Path
3
+
4
+ from .comtrade_loader import load_comtrade
5
+ from .csv_loader import load_csv
6
+
7
+
8
+ def load(path: str | Path, **kwargs):
9
+ """Load a supported waveform file by extension."""
10
+ suffix = Path(path).suffix.lower()
11
+ if suffix == ".csv":
12
+ return load_csv(path, **kwargs)
13
+ if suffix in (".cfg", ".dat"):
14
+ return load_comtrade(path, **kwargs)
15
+ raise ValueError(
16
+ f"Unsupported file format '{suffix or '(none)'}'. "
17
+ "Supported formats: .csv, .cfg, .dat"
18
+ )
19
+
20
+
21
+ __all__ = ["load", "load_comtrade", "load_csv"]