gridlens 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.
gridlens/__init__.py ADDED
@@ -0,0 +1,4 @@
1
+ from .waveform import Waveform
2
+
3
+ __version__ = "0.2.0"
4
+ __all__ = ["Waveform", "__version__"]
gridlens/__main__.py ADDED
@@ -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
gridlens/cli.py ADDED
@@ -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"]
@@ -0,0 +1,81 @@
1
+ """COMTRADE loader using the optional comtrade package."""
2
+ from __future__ import annotations
3
+
4
+ from pathlib import Path
5
+
6
+ import numpy as np
7
+
8
+ from ..waveform import Waveform
9
+
10
+
11
+ def _channel_index(comtrade_file: object, channel: str | int | None, prefix: str) -> int | None:
12
+ if channel is None:
13
+ return None
14
+ names = getattr(comtrade_file, "analog_channel_ids", [])
15
+ if isinstance(channel, int):
16
+ if channel < 0 or channel >= len(names):
17
+ raise ValueError(f"{prefix} channel index {channel} is out of range")
18
+ return channel
19
+ for index, value in enumerate(names):
20
+ if str(value).lower() == channel.lower():
21
+ return index
22
+ raise ValueError(f"{prefix} channel '{channel}' was not found")
23
+
24
+
25
+ def load_comtrade(
26
+ path: str | Path,
27
+ voltage_channel: str | int | None = None,
28
+ current_channel: str | int | None = None,
29
+ ) -> Waveform:
30
+ """Load voltage and optional current channels from COMTRADE files."""
31
+ try:
32
+ from comtrade import Comtrade
33
+ except ImportError as exc:
34
+ raise ImportError(
35
+ 'COMTRADE support requires the optional package. '
36
+ 'Install it with pip install "gridlens[comtrade]"'
37
+ ) from exc
38
+
39
+ path = Path(path)
40
+ cfg = path if path.suffix.lower() == ".cfg" else path.with_suffix(".cfg")
41
+ dat = path if path.suffix.lower() == ".dat" else path.with_suffix(".dat")
42
+ if not cfg.exists() or not dat.exists():
43
+ raise FileNotFoundError(f"COMTRADE cfg/dat pair not found for '{path}'")
44
+
45
+ reader = Comtrade()
46
+ reader.load(str(cfg), str(dat))
47
+ names = list(getattr(reader, "analog_channel_ids", []))
48
+ voltage_index = _channel_index(reader, voltage_channel, "Voltage")
49
+ current_index = _channel_index(reader, current_channel, "Current")
50
+ if voltage_index is None:
51
+ candidates = [
52
+ index for index, name in enumerate(names)
53
+ if "voltage" in str(name).lower() or str(name).lower().startswith("v")
54
+ ]
55
+ voltage_index = candidates[0] if candidates else 0
56
+ if not names:
57
+ raise ValueError("COMTRADE file contains no analog channels")
58
+
59
+ analog = getattr(reader, "analog", None)
60
+ if analog is not None:
61
+ raw = np.asarray(analog)
62
+ else:
63
+ raw_arrays = getattr(reader, "analog_channel_samples", None)
64
+ if raw_arrays is None:
65
+ raise ValueError("COMTRADE reader did not expose analog samples")
66
+ raw = np.asarray(raw_arrays)
67
+
68
+ def engineering(index: int) -> np.ndarray:
69
+ return np.asarray(raw[index], dtype=float)
70
+
71
+ time = getattr(reader, "time", None)
72
+ if time is None:
73
+ fs = float(getattr(reader, "sampling_frequency", 0.0))
74
+ if fs <= 0:
75
+ raise ValueError("COMTRADE file did not provide a time axis or sampling frequency")
76
+ t = np.arange(raw.shape[-1], dtype=float) / fs
77
+ else:
78
+ t = np.asarray(time, dtype=float)
79
+ voltage = engineering(voltage_index)
80
+ current = engineering(current_index) if current_index is not None else None
81
+ return Waveform(t=t, voltage=voltage, current=current)
@@ -0,0 +1,34 @@
1
+ """Load waveform data from CSV files."""
2
+ import numpy as np
3
+ import pandas as pd
4
+
5
+ from ..waveform import Waveform
6
+
7
+
8
+ def load_csv(path, time_col="time", voltage_col="voltage",
9
+ current_col=None, fs=None):
10
+ """Read a CSV file into a Waveform.
11
+
12
+ If the file has no time column, pass the sampling rate `fs` in Hz
13
+ and the time axis is built for you.
14
+ """
15
+ df = pd.read_csv(path)
16
+
17
+ for col in (voltage_col, current_col):
18
+ if col is not None and col not in df.columns:
19
+ raise KeyError(
20
+ f"Column '{col}' not found. Available columns: {list(df.columns)}"
21
+ )
22
+
23
+ if time_col in df.columns:
24
+ t = df[time_col].to_numpy(dtype=float)
25
+ elif fs is not None:
26
+ t = np.arange(len(df)) / fs
27
+ else:
28
+ raise ValueError(
29
+ f"No '{time_col}' column in the file. Pass fs=<sampling rate in Hz>."
30
+ )
31
+
32
+ voltage = df[voltage_col].to_numpy(dtype=float)
33
+ current = None if current_col is None else df[current_col].to_numpy(dtype=float)
34
+ return Waveform(t=t, voltage=voltage, current=current)
@@ -0,0 +1,13 @@
1
+ from .power_factor import active_power, apparent_power, power_factor, reactive_power
2
+ from .rms import rms, rms_half_cycle
3
+ from .thd import thd
4
+
5
+ __all__ = [
6
+ "active_power",
7
+ "apparent_power",
8
+ "power_factor",
9
+ "reactive_power",
10
+ "rms",
11
+ "rms_half_cycle",
12
+ "thd",
13
+ ]
@@ -0,0 +1,45 @@
1
+ """Power and power factor from sampled voltage and current."""
2
+ import numpy as np
3
+
4
+ from .rms import rms
5
+
6
+
7
+ def _prepare(voltage, current):
8
+ v = np.asarray(voltage, dtype=float)
9
+ i = np.asarray(current, dtype=float)
10
+ if v.shape != i.shape:
11
+ raise ValueError("voltage and current must have the same length")
12
+ return v, i
13
+
14
+
15
+ def active_power(voltage, current):
16
+ """Active (real) power P = mean(v * i), in watts.
17
+
18
+ Use a whole number of cycles for an exact result.
19
+ """
20
+ v, i = _prepare(voltage, current)
21
+ return float(np.mean(v * i))
22
+
23
+
24
+ def apparent_power(voltage, current):
25
+ """Apparent power S = Vrms * Irms, in volt-amperes."""
26
+ v, i = _prepare(voltage, current)
27
+ return rms(v) * rms(i)
28
+
29
+
30
+ def reactive_power(voltage, current):
31
+ """Non-active power Q = sqrt(S^2 - P^2), in var.
32
+
33
+ With distorted waveforms this also includes distortion power.
34
+ """
35
+ p = active_power(voltage, current)
36
+ s = apparent_power(voltage, current)
37
+ return float(np.sqrt(max(s**2 - p**2, 0.0)))
38
+
39
+
40
+ def power_factor(voltage, current):
41
+ """True power factor PF = P / S (between -1 and 1)."""
42
+ s = apparent_power(voltage, current)
43
+ if s == 0:
44
+ raise ValueError("Apparent power is zero, so power factor is undefined")
45
+ return active_power(voltage, current) / s
@@ -0,0 +1,28 @@
1
+ """RMS value of a sampled signal."""
2
+ import numpy as np
3
+
4
+
5
+ def rms(signal):
6
+ """Root mean square of a signal."""
7
+ x = np.asarray(signal, dtype=float)
8
+ return float(np.sqrt(np.mean(np.square(x))))
9
+
10
+
11
+ def rms_half_cycle(signal, fs, f0=50.0):
12
+ """RMS over one cycle, refreshed every half cycle (as in IEC 61000-4-30).
13
+
14
+ Returns (values, times): the RMS values and the time in seconds at
15
+ which each one-cycle window starts.
16
+ """
17
+ x = np.asarray(signal, dtype=float)
18
+ n = round(fs / f0) # samples per cycle
19
+ step = n // 2
20
+ if step < 1:
21
+ raise ValueError("Sampling rate is too low for this fundamental frequency")
22
+ if x.size < n:
23
+ raise ValueError("Signal is shorter than one cycle")
24
+
25
+ csum = np.concatenate(([0.0], np.cumsum(x**2)))
26
+ starts = np.arange(0, x.size - n + 1, step)
27
+ values = np.sqrt((csum[starts + n] - csum[starts]) / n)
28
+ return values, starts / fs
@@ -0,0 +1,26 @@
1
+ """Total harmonic distortion."""
2
+ import numpy as np
3
+
4
+
5
+ def thd(signal, fs, f0=50.0, max_harmonic=50):
6
+ """Total harmonic distortion as a ratio (multiply by 100 for %).
7
+
8
+ THD = sqrt(V2^2 + V3^2 + ... + Vn^2) / V1
9
+
10
+ The signal should contain a whole number of fundamental cycles,
11
+ otherwise spectral leakage will affect the result.
12
+ """
13
+ x = np.asarray(signal, dtype=float)
14
+ spectrum = np.abs(np.fft.rfft(x))
15
+ df = fs / x.size # frequency resolution
16
+
17
+ def magnitude(order):
18
+ return spectrum[round(order * f0 / df)]
19
+
20
+ top = min(max_harmonic, int((fs / 2) // f0))
21
+ fundamental = magnitude(1)
22
+ if fundamental == 0:
23
+ raise ValueError("No fundamental component found at f0")
24
+
25
+ harmonic_sum = sum(magnitude(h) ** 2 for h in range(2, top + 1))
26
+ return float(np.sqrt(harmonic_sum) / fundamental)
gridlens/py.typed ADDED
File without changes
@@ -0,0 +1,5 @@
1
+ """Report generation."""
2
+
3
+ from .html_report import build_report, write_report
4
+
5
+ __all__ = ["build_report", "write_report"]