power-system-noise-statistics 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.
@@ -0,0 +1,21 @@
1
+ MIT License
2
+
3
+ Copyright (c) 2026 Amr Ahmed
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,9 @@
1
+ # Licensing scope
2
+
3
+ The MIT License in LICENSE applies to the newly developed PowerNoise Python package (src/powernoise), its tests, examples, package configuration, CI workflows, output-checking script and newly written software documentation, to the extent that the maintainer has rights to license those materials.
4
+
5
+ The original research report PDF, Assets.zip, original MATLAB and Python research scripts, and original research competition notes are excluded from this license pending confirmation of rights and any coauthor permissions. Public visibility does not grant redistribution rights. Contact the repository owner for permission to reuse excluded materials.
6
+
7
+ Third-party dependencies remain under their own licenses. Nothing here changes the copyright or licensing of third-party material.
8
+
9
+ The installable package is the intended MIT-licensed software distribution. Research artifacts are retained separately as historical reference materials.
@@ -0,0 +1,9 @@
1
+ include README.md LICENSE LICENSE-SCOPE.md
2
+ include pyproject.toml
3
+ recursive-include src *.py
4
+ recursive-include tests *.py
5
+ exclude Assets.zip
6
+ exclude power_systems_probability_research_competition_final.pdf
7
+ exclude power_systems_probability_research_competition_verification.py
8
+ exclude power_systems_probability_research_competition.m
9
+ exclude research_day_competition_notes.txt
@@ -0,0 +1,187 @@
1
+ Metadata-Version: 2.4
2
+ Name: power-system-noise-statistics
3
+ Version: 0.1.0
4
+ Summary: Reproducible stochastic power-system waveform analysis and transient detection
5
+ License-Expression: MIT
6
+ Project-URL: Repository, https://github.com/amrahmmed/power-system-noise-statistics
7
+ Project-URL: Issues, https://github.com/amrahmmed/power-system-noise-statistics/issues
8
+ Keywords: power systems,signal processing,power quality,Monte Carlo
9
+ Classifier: Development Status :: 3 - Alpha
10
+ Classifier: Intended Audience :: Science/Research
11
+ Classifier: Programming Language :: Python :: 3
12
+ Classifier: Topic :: Scientific/Engineering
13
+ Requires-Python: >=3.10
14
+ Description-Content-Type: text/markdown
15
+ License-File: LICENSE
16
+ License-File: LICENSE-SCOPE.md
17
+ Requires-Dist: numpy>=1.24
18
+ Requires-Dist: scipy>=1.10
19
+ Provides-Extra: test
20
+ Requires-Dist: pytest>=7; extra == "test"
21
+ Provides-Extra: research
22
+ Requires-Dist: pandas>=1.5; extra == "research"
23
+ Requires-Dist: matplotlib>=3.7; extra == "research"
24
+ Dynamic: license-file
25
+
26
+ # Power System Noise Statistics
27
+
28
+ Reproducible Python and MATLAB simulations for stochastic electrical power-system waveforms, measurement uncertainty, and probabilistic transient detection.
29
+
30
+ ## Overview
31
+
32
+ Power-system measurements are affected by harmonics, switching transients, stochastic load and renewable generation variations, and sensor noise. This research project combines analytical probability models with Monte Carlo simulation to quantify measurement accuracy and detection reliability.
33
+
34
+ ### Capabilities
35
+
36
+ - Synthetic 50 Hz waveforms with fifth and seventh harmonics.
37
+ - Decaying 600 Hz transient and Gaussian measurement noise.
38
+ - AR(1) models for slow load and renewable variations.
39
+ - RMS, variance, mean-square error (MSE), and one-cycle correlation.
40
+ - Welch power spectral density (PSD).
41
+ - Rice-distribution amplitude estimation error probability.
42
+ - Residual-energy transient detection using central and noncentral chi-square distributions.
43
+ - Monte Carlo verification with 95% confidence intervals and a nominal 5% false-alarm target.
44
+
45
+ ## Reusable Python package (development version)
46
+
47
+ The new `powernoise` package provides a lightweight API and CLI without running the full research simulation on import. The original Python and MATLAB research scripts remain available for reproducing the paper. The package is a development preview, not yet a published PyPI release.
48
+
49
+ To install the software from a clean clone (the development branch is available in pull request #1 until merged):
50
+
51
+ ```bash
52
+ git clone https://github.com/amrahmmed/power-system-noise-statistics.git
53
+ cd power-system-noise-statistics
54
+ # Before PR #1 is merged: git switch fix/readme-portable-outputs
55
+ python -m pip install -e ".[test]"
56
+ python -m pytest -q
57
+ powernoise simulate --output demo.csv --f0 60 --fs 12000 --seed 7
58
+ powernoise analyze demo.csv --fs 12000 --f0 60 --sigma 0.070710678
59
+ python examples/synthetic_transient.py
60
+ python examples/detection_benchmark.py > detector_benchmark.csv
61
+ ```
62
+
63
+ `simulate` generates synthetic data with the fundamental, fifth and seventh harmonics, and Gaussian noise. `analyze` accepts a uniformly sampled numeric CSV containing a `value` column and prints JSON with RMS, fitted peak harmonic amplitudes, selected-order THD and (optionally) a residual-energy test. Supply the actual sampling frequency; when a `time_s` column is present, its spacing is checked against that frequency. THD is a fraction, not a percentage, and is not a complete standards-compliance measurement.
64
+
65
+ ### Python API
66
+
67
+ ```python
68
+ from powernoise import synthesize, fit_harmonics, residual_detector, noise_sigma
69
+
70
+ t, clean, x = synthesize(fs=12000, f0=60, duration=1, snr_db=20,
71
+ harmonics={5: (0.05, 0.4), 7: (0.03, -0.8)}, seed=7)
72
+ fit = fit_harmonics(x, fs=12000, f0=60)
73
+ print(fit['amplitudes'], fit['thd_fraction'])
74
+ print(residual_detector(x, fs=12000, f0=60, sigma=noise_sigma(20)))
75
+ ```
76
+
77
+ The detector assumes independent Gaussian measurement noise of known standard deviation, a known nominal frequency, and a correctly specified harmonic model. A rejection indicates unexplained residual energy, not a diagnosis of a specific disturbance. See [numerical assumptions](docs/numerical-methods.md) for interpretation and the [API reference](docs/api.md) for function signatures.
78
+
79
+ ### Verification and maintenance
80
+
81
+ - The test suite checks harmonic recovery at 50/60 Hz, deterministic seeds, noise power, stationary AR(1), transient onset, Monte Carlo calibration, Rice-model probability, invalid inputs and the CSV workflow.
82
+ - [GitHub Actions](https://github.com/amrahmmed/power-system-noise-statistics/actions) is configured to test Python 3.10 and 3.12 across Linux, Windows and macOS. Check actual run status before claiming successful validation.
83
+ - A reproducible Monte Carlo detector benchmark reports empirical and theoretical probabilities, false-alarm calibration and Wilson confidence intervals. See [validation guide](docs/validation.md).
84
+ - See [CONTRIBUTING](CONTRIBUTING.md), [ROADMAP](ROADMAP.md) and [CHANGELOG](CHANGELOG.md).
85
+
86
+ ## Quick start: Python (original research script)
87
+
88
+ Use Python 3.10 or newer. Clone the repository, then install the scientific computing dependencies:
89
+
90
+ ```bash
91
+ git clone https://github.com/amrahmmed/power-system-noise-statistics.git
92
+ cd power-system-noise-statistics
93
+ python -m pip install numpy scipy pandas matplotlib
94
+ python power_systems_probability_research_competition_verification.py
95
+ ```
96
+
97
+ An isolated virtual environment is recommended. Alternatively, from the package root, install the research dependencies with `python -m pip install ".[research]"`. The script writes its generated figures and tables to `power_probability_python_outputs/` beside the script. No MATLAB installation is needed for the Python workflow.
98
+
99
+ ## Quick start: MATLAB
100
+
101
+ Open the repository in MATLAB. The script uses Signal Processing Toolbox and Statistics and Machine Learning Toolbox functions. A release supporting `exportgraphics` (R2020a or later) is required.
102
+
103
+ ```matlab
104
+ run('power_systems_probability_research_competition.m')
105
+ ```
106
+
107
+ Results are saved in `power_probability_outputs/` beside the MATLAB script. MATLAB and Python use independent random-number generators, so individual realizations need not match exactly.
108
+
109
+ ## Mathematical model
110
+
111
+ The measured waveform is modeled as:
112
+
113
+ ```math
114
+ x[k] = s[k] + h[k] + \tau[k] + \delta[k] + n[k]
115
+ ```
116
+
117
+ | Term | Description |
118
+ | --- | --- |
119
+ | s | Nominal fundamental waveform |
120
+ | h | Harmonic distortion |
121
+ | tau | Decaying transient disturbance |
122
+ | delta | Slow stochastic operating variations |
123
+ | n | Additive Gaussian measurement noise |
124
+
125
+ The simulations compare empirical MSE with a theoretical expectation model, amplitude-error risk with a Rice distribution, and transient detection probability with a noncentral chi-square model.
126
+
127
+ ## Default simulation configuration
128
+
129
+ | Parameter | Value |
130
+ | --- | --- |
131
+ | Fundamental frequency | 50 Hz |
132
+ | Sampling frequency | 10 kHz |
133
+ | Record length | 1 s (10,000 samples) |
134
+ | Fundamental amplitude | 1 pu |
135
+ | Harmonics | Fifth: 5%; seventh: 3% |
136
+ | Transient | 600 Hz, 0.2 pu, starting at 0.62 s |
137
+ | SNR sweep | 30, 20, 15, 10, 5 dB |
138
+ | Monte Carlo trials | 250 descriptive, 300 MSE per SNR, 5,000 probability trials per SNR |
139
+ | False-alarm target | 5% |
140
+ | Amplitude-error tolerance | 1% |
141
+
142
+ ## Generated outputs
143
+
144
+ Both workflows generate six figures covering the waveform, noise histogram, PSD, MSE, amplitude-estimation risk, and detection probability. CSV tables summarize parameters and empirical/theoretical comparisons. The Python script additionally writes a JSON summary.
145
+
146
+ | Output | Purpose |
147
+ | --- | --- |
148
+ | `fig1_waveform.png` | Representative waveform and transient |
149
+ | `fig2_noise_hist.png` | Noise distribution |
150
+ | `fig3_psd.png` | Power spectral density |
151
+ | `fig4_mse_vs_snr.png` | MSE versus SNR |
152
+ | `fig5_amp_probability.png` | Amplitude-estimation risk |
153
+ | `fig6_detector_probability.png` | Detection probability |
154
+ | `table3_probability_summary.csv` | Main numerical comparisons |
155
+ | `results_summary.txt` | Human-readable numerical summary |
156
+
157
+ ## Repository contents
158
+
159
+ - [Python verification script](power_systems_probability_research_competition_verification.py)
160
+ - [MATLAB simulation](power_systems_probability_research_competition.m)
161
+ - [Research report](power_systems_probability_research_competition_final.pdf)
162
+ - [Research notes](research_day_competition_notes.txt)
163
+ - [Archived research assets](Assets.zip)
164
+
165
+ ## Reproducibility and limitations
166
+
167
+ The simulations use fixed random seeds and synthetic waveforms. They are research and educational demonstrations, not validated field-data models or certified protection algorithms. The analytical detector assumes white Gaussian measurement noise and a specified harmonic basis; actual grid disturbances may violate these assumptions. The theoretical slow-variation power model is an approximation for finite, mean-centered AR(1) records.
168
+
169
+ ## Development roadmap
170
+
171
+ The development preview introduces a reusable API, CSV workflow and test suite. Remaining milestones and proposed improvements are tracked in [ROADMAP.md](ROADMAP.md).
172
+
173
+ ## Feedback and contributions
174
+
175
+ Use [GitHub Issues](https://github.com/amrahmmed/power-system-noise-statistics/issues) to report reproducibility problems or suggest improvements. Include your Python or MATLAB version, operating system, and the steps needed to reproduce the problem.
176
+
177
+ ## How to cite
178
+
179
+ For software citation, use [CITATION.cff](CITATION.cff) and record the exact commit or tagged version used. Cite the original [research report](power_systems_probability_research_competition_final.pdf) separately using its listed authors.
180
+
181
+ ## Release and security
182
+
183
+ See the [release readiness checklist](docs/release-checklist.md) and [responsible use and security guidance](SECURITY.md). The package has not been published to PyPI.
184
+
185
+ ## License
186
+
187
+ The new PowerNoise software package is available under the [MIT License](LICENSE). The original research scripts, report, archived assets, and research notes are excluded pending confirmation of rights. See [licensing scope](LICENSE-SCOPE.md) for details. Third-party dependencies retain their own licenses.
@@ -0,0 +1,162 @@
1
+ # Power System Noise Statistics
2
+
3
+ Reproducible Python and MATLAB simulations for stochastic electrical power-system waveforms, measurement uncertainty, and probabilistic transient detection.
4
+
5
+ ## Overview
6
+
7
+ Power-system measurements are affected by harmonics, switching transients, stochastic load and renewable generation variations, and sensor noise. This research project combines analytical probability models with Monte Carlo simulation to quantify measurement accuracy and detection reliability.
8
+
9
+ ### Capabilities
10
+
11
+ - Synthetic 50 Hz waveforms with fifth and seventh harmonics.
12
+ - Decaying 600 Hz transient and Gaussian measurement noise.
13
+ - AR(1) models for slow load and renewable variations.
14
+ - RMS, variance, mean-square error (MSE), and one-cycle correlation.
15
+ - Welch power spectral density (PSD).
16
+ - Rice-distribution amplitude estimation error probability.
17
+ - Residual-energy transient detection using central and noncentral chi-square distributions.
18
+ - Monte Carlo verification with 95% confidence intervals and a nominal 5% false-alarm target.
19
+
20
+ ## Reusable Python package (development version)
21
+
22
+ The new `powernoise` package provides a lightweight API and CLI without running the full research simulation on import. The original Python and MATLAB research scripts remain available for reproducing the paper. The package is a development preview, not yet a published PyPI release.
23
+
24
+ To install the software from a clean clone (the development branch is available in pull request #1 until merged):
25
+
26
+ ```bash
27
+ git clone https://github.com/amrahmmed/power-system-noise-statistics.git
28
+ cd power-system-noise-statistics
29
+ # Before PR #1 is merged: git switch fix/readme-portable-outputs
30
+ python -m pip install -e ".[test]"
31
+ python -m pytest -q
32
+ powernoise simulate --output demo.csv --f0 60 --fs 12000 --seed 7
33
+ powernoise analyze demo.csv --fs 12000 --f0 60 --sigma 0.070710678
34
+ python examples/synthetic_transient.py
35
+ python examples/detection_benchmark.py > detector_benchmark.csv
36
+ ```
37
+
38
+ `simulate` generates synthetic data with the fundamental, fifth and seventh harmonics, and Gaussian noise. `analyze` accepts a uniformly sampled numeric CSV containing a `value` column and prints JSON with RMS, fitted peak harmonic amplitudes, selected-order THD and (optionally) a residual-energy test. Supply the actual sampling frequency; when a `time_s` column is present, its spacing is checked against that frequency. THD is a fraction, not a percentage, and is not a complete standards-compliance measurement.
39
+
40
+ ### Python API
41
+
42
+ ```python
43
+ from powernoise import synthesize, fit_harmonics, residual_detector, noise_sigma
44
+
45
+ t, clean, x = synthesize(fs=12000, f0=60, duration=1, snr_db=20,
46
+ harmonics={5: (0.05, 0.4), 7: (0.03, -0.8)}, seed=7)
47
+ fit = fit_harmonics(x, fs=12000, f0=60)
48
+ print(fit['amplitudes'], fit['thd_fraction'])
49
+ print(residual_detector(x, fs=12000, f0=60, sigma=noise_sigma(20)))
50
+ ```
51
+
52
+ The detector assumes independent Gaussian measurement noise of known standard deviation, a known nominal frequency, and a correctly specified harmonic model. A rejection indicates unexplained residual energy, not a diagnosis of a specific disturbance. See [numerical assumptions](docs/numerical-methods.md) for interpretation and the [API reference](docs/api.md) for function signatures.
53
+
54
+ ### Verification and maintenance
55
+
56
+ - The test suite checks harmonic recovery at 50/60 Hz, deterministic seeds, noise power, stationary AR(1), transient onset, Monte Carlo calibration, Rice-model probability, invalid inputs and the CSV workflow.
57
+ - [GitHub Actions](https://github.com/amrahmmed/power-system-noise-statistics/actions) is configured to test Python 3.10 and 3.12 across Linux, Windows and macOS. Check actual run status before claiming successful validation.
58
+ - A reproducible Monte Carlo detector benchmark reports empirical and theoretical probabilities, false-alarm calibration and Wilson confidence intervals. See [validation guide](docs/validation.md).
59
+ - See [CONTRIBUTING](CONTRIBUTING.md), [ROADMAP](ROADMAP.md) and [CHANGELOG](CHANGELOG.md).
60
+
61
+ ## Quick start: Python (original research script)
62
+
63
+ Use Python 3.10 or newer. Clone the repository, then install the scientific computing dependencies:
64
+
65
+ ```bash
66
+ git clone https://github.com/amrahmmed/power-system-noise-statistics.git
67
+ cd power-system-noise-statistics
68
+ python -m pip install numpy scipy pandas matplotlib
69
+ python power_systems_probability_research_competition_verification.py
70
+ ```
71
+
72
+ An isolated virtual environment is recommended. Alternatively, from the package root, install the research dependencies with `python -m pip install ".[research]"`. The script writes its generated figures and tables to `power_probability_python_outputs/` beside the script. No MATLAB installation is needed for the Python workflow.
73
+
74
+ ## Quick start: MATLAB
75
+
76
+ Open the repository in MATLAB. The script uses Signal Processing Toolbox and Statistics and Machine Learning Toolbox functions. A release supporting `exportgraphics` (R2020a or later) is required.
77
+
78
+ ```matlab
79
+ run('power_systems_probability_research_competition.m')
80
+ ```
81
+
82
+ Results are saved in `power_probability_outputs/` beside the MATLAB script. MATLAB and Python use independent random-number generators, so individual realizations need not match exactly.
83
+
84
+ ## Mathematical model
85
+
86
+ The measured waveform is modeled as:
87
+
88
+ ```math
89
+ x[k] = s[k] + h[k] + \tau[k] + \delta[k] + n[k]
90
+ ```
91
+
92
+ | Term | Description |
93
+ | --- | --- |
94
+ | s | Nominal fundamental waveform |
95
+ | h | Harmonic distortion |
96
+ | tau | Decaying transient disturbance |
97
+ | delta | Slow stochastic operating variations |
98
+ | n | Additive Gaussian measurement noise |
99
+
100
+ The simulations compare empirical MSE with a theoretical expectation model, amplitude-error risk with a Rice distribution, and transient detection probability with a noncentral chi-square model.
101
+
102
+ ## Default simulation configuration
103
+
104
+ | Parameter | Value |
105
+ | --- | --- |
106
+ | Fundamental frequency | 50 Hz |
107
+ | Sampling frequency | 10 kHz |
108
+ | Record length | 1 s (10,000 samples) |
109
+ | Fundamental amplitude | 1 pu |
110
+ | Harmonics | Fifth: 5%; seventh: 3% |
111
+ | Transient | 600 Hz, 0.2 pu, starting at 0.62 s |
112
+ | SNR sweep | 30, 20, 15, 10, 5 dB |
113
+ | Monte Carlo trials | 250 descriptive, 300 MSE per SNR, 5,000 probability trials per SNR |
114
+ | False-alarm target | 5% |
115
+ | Amplitude-error tolerance | 1% |
116
+
117
+ ## Generated outputs
118
+
119
+ Both workflows generate six figures covering the waveform, noise histogram, PSD, MSE, amplitude-estimation risk, and detection probability. CSV tables summarize parameters and empirical/theoretical comparisons. The Python script additionally writes a JSON summary.
120
+
121
+ | Output | Purpose |
122
+ | --- | --- |
123
+ | `fig1_waveform.png` | Representative waveform and transient |
124
+ | `fig2_noise_hist.png` | Noise distribution |
125
+ | `fig3_psd.png` | Power spectral density |
126
+ | `fig4_mse_vs_snr.png` | MSE versus SNR |
127
+ | `fig5_amp_probability.png` | Amplitude-estimation risk |
128
+ | `fig6_detector_probability.png` | Detection probability |
129
+ | `table3_probability_summary.csv` | Main numerical comparisons |
130
+ | `results_summary.txt` | Human-readable numerical summary |
131
+
132
+ ## Repository contents
133
+
134
+ - [Python verification script](power_systems_probability_research_competition_verification.py)
135
+ - [MATLAB simulation](power_systems_probability_research_competition.m)
136
+ - [Research report](power_systems_probability_research_competition_final.pdf)
137
+ - [Research notes](research_day_competition_notes.txt)
138
+ - [Archived research assets](Assets.zip)
139
+
140
+ ## Reproducibility and limitations
141
+
142
+ The simulations use fixed random seeds and synthetic waveforms. They are research and educational demonstrations, not validated field-data models or certified protection algorithms. The analytical detector assumes white Gaussian measurement noise and a specified harmonic basis; actual grid disturbances may violate these assumptions. The theoretical slow-variation power model is an approximation for finite, mean-centered AR(1) records.
143
+
144
+ ## Development roadmap
145
+
146
+ The development preview introduces a reusable API, CSV workflow and test suite. Remaining milestones and proposed improvements are tracked in [ROADMAP.md](ROADMAP.md).
147
+
148
+ ## Feedback and contributions
149
+
150
+ Use [GitHub Issues](https://github.com/amrahmmed/power-system-noise-statistics/issues) to report reproducibility problems or suggest improvements. Include your Python or MATLAB version, operating system, and the steps needed to reproduce the problem.
151
+
152
+ ## How to cite
153
+
154
+ For software citation, use [CITATION.cff](CITATION.cff) and record the exact commit or tagged version used. Cite the original [research report](power_systems_probability_research_competition_final.pdf) separately using its listed authors.
155
+
156
+ ## Release and security
157
+
158
+ See the [release readiness checklist](docs/release-checklist.md) and [responsible use and security guidance](SECURITY.md). The package has not been published to PyPI.
159
+
160
+ ## License
161
+
162
+ The new PowerNoise software package is available under the [MIT License](LICENSE). The original research scripts, report, archived assets, and research notes are excluded pending confirmation of rights. See [licensing scope](LICENSE-SCOPE.md) for details. Third-party dependencies retain their own licenses.
@@ -0,0 +1,37 @@
1
+ [build-system]
2
+ requires = ["setuptools>=77"]
3
+ build-backend = "setuptools.build_meta"
4
+
5
+ [project]
6
+ name = "power-system-noise-statistics"
7
+ version = "0.1.0"
8
+ license = "MIT"
9
+ license-files = ["LICENSE", "LICENSE-SCOPE.md"]
10
+ keywords = ["power systems", "signal processing", "power quality", "Monte Carlo"]
11
+ classifiers = [
12
+ "Development Status :: 3 - Alpha",
13
+ "Intended Audience :: Science/Research",
14
+ "Programming Language :: Python :: 3",
15
+ "Topic :: Scientific/Engineering",
16
+ ]
17
+ description = "Reproducible stochastic power-system waveform analysis and transient detection"
18
+ readme = "README.md"
19
+ requires-python = ">=3.10"
20
+ dependencies = ["numpy>=1.24", "scipy>=1.10"]
21
+
22
+ [project.optional-dependencies]
23
+ test = ["pytest>=7"]
24
+ research = ["pandas>=1.5", "matplotlib>=3.7"]
25
+
26
+ [project.scripts]
27
+ powernoise = "powernoise.cli:main"
28
+
29
+ [project.urls]
30
+ Repository = "https://github.com/amrahmmed/power-system-noise-statistics"
31
+ Issues = "https://github.com/amrahmmed/power-system-noise-statistics/issues"
32
+
33
+ [tool.setuptools.packages.find]
34
+ where = ["src"]
35
+
36
+ [tool.pytest.ini_options]
37
+ testpaths = ["tests"]
@@ -0,0 +1,4 @@
1
+ [egg_info]
2
+ tag_build =
3
+ tag_date = 0
4
+
@@ -0,0 +1,187 @@
1
+ Metadata-Version: 2.4
2
+ Name: power-system-noise-statistics
3
+ Version: 0.1.0
4
+ Summary: Reproducible stochastic power-system waveform analysis and transient detection
5
+ License-Expression: MIT
6
+ Project-URL: Repository, https://github.com/amrahmmed/power-system-noise-statistics
7
+ Project-URL: Issues, https://github.com/amrahmmed/power-system-noise-statistics/issues
8
+ Keywords: power systems,signal processing,power quality,Monte Carlo
9
+ Classifier: Development Status :: 3 - Alpha
10
+ Classifier: Intended Audience :: Science/Research
11
+ Classifier: Programming Language :: Python :: 3
12
+ Classifier: Topic :: Scientific/Engineering
13
+ Requires-Python: >=3.10
14
+ Description-Content-Type: text/markdown
15
+ License-File: LICENSE
16
+ License-File: LICENSE-SCOPE.md
17
+ Requires-Dist: numpy>=1.24
18
+ Requires-Dist: scipy>=1.10
19
+ Provides-Extra: test
20
+ Requires-Dist: pytest>=7; extra == "test"
21
+ Provides-Extra: research
22
+ Requires-Dist: pandas>=1.5; extra == "research"
23
+ Requires-Dist: matplotlib>=3.7; extra == "research"
24
+ Dynamic: license-file
25
+
26
+ # Power System Noise Statistics
27
+
28
+ Reproducible Python and MATLAB simulations for stochastic electrical power-system waveforms, measurement uncertainty, and probabilistic transient detection.
29
+
30
+ ## Overview
31
+
32
+ Power-system measurements are affected by harmonics, switching transients, stochastic load and renewable generation variations, and sensor noise. This research project combines analytical probability models with Monte Carlo simulation to quantify measurement accuracy and detection reliability.
33
+
34
+ ### Capabilities
35
+
36
+ - Synthetic 50 Hz waveforms with fifth and seventh harmonics.
37
+ - Decaying 600 Hz transient and Gaussian measurement noise.
38
+ - AR(1) models for slow load and renewable variations.
39
+ - RMS, variance, mean-square error (MSE), and one-cycle correlation.
40
+ - Welch power spectral density (PSD).
41
+ - Rice-distribution amplitude estimation error probability.
42
+ - Residual-energy transient detection using central and noncentral chi-square distributions.
43
+ - Monte Carlo verification with 95% confidence intervals and a nominal 5% false-alarm target.
44
+
45
+ ## Reusable Python package (development version)
46
+
47
+ The new `powernoise` package provides a lightweight API and CLI without running the full research simulation on import. The original Python and MATLAB research scripts remain available for reproducing the paper. The package is a development preview, not yet a published PyPI release.
48
+
49
+ To install the software from a clean clone (the development branch is available in pull request #1 until merged):
50
+
51
+ ```bash
52
+ git clone https://github.com/amrahmmed/power-system-noise-statistics.git
53
+ cd power-system-noise-statistics
54
+ # Before PR #1 is merged: git switch fix/readme-portable-outputs
55
+ python -m pip install -e ".[test]"
56
+ python -m pytest -q
57
+ powernoise simulate --output demo.csv --f0 60 --fs 12000 --seed 7
58
+ powernoise analyze demo.csv --fs 12000 --f0 60 --sigma 0.070710678
59
+ python examples/synthetic_transient.py
60
+ python examples/detection_benchmark.py > detector_benchmark.csv
61
+ ```
62
+
63
+ `simulate` generates synthetic data with the fundamental, fifth and seventh harmonics, and Gaussian noise. `analyze` accepts a uniformly sampled numeric CSV containing a `value` column and prints JSON with RMS, fitted peak harmonic amplitudes, selected-order THD and (optionally) a residual-energy test. Supply the actual sampling frequency; when a `time_s` column is present, its spacing is checked against that frequency. THD is a fraction, not a percentage, and is not a complete standards-compliance measurement.
64
+
65
+ ### Python API
66
+
67
+ ```python
68
+ from powernoise import synthesize, fit_harmonics, residual_detector, noise_sigma
69
+
70
+ t, clean, x = synthesize(fs=12000, f0=60, duration=1, snr_db=20,
71
+ harmonics={5: (0.05, 0.4), 7: (0.03, -0.8)}, seed=7)
72
+ fit = fit_harmonics(x, fs=12000, f0=60)
73
+ print(fit['amplitudes'], fit['thd_fraction'])
74
+ print(residual_detector(x, fs=12000, f0=60, sigma=noise_sigma(20)))
75
+ ```
76
+
77
+ The detector assumes independent Gaussian measurement noise of known standard deviation, a known nominal frequency, and a correctly specified harmonic model. A rejection indicates unexplained residual energy, not a diagnosis of a specific disturbance. See [numerical assumptions](docs/numerical-methods.md) for interpretation and the [API reference](docs/api.md) for function signatures.
78
+
79
+ ### Verification and maintenance
80
+
81
+ - The test suite checks harmonic recovery at 50/60 Hz, deterministic seeds, noise power, stationary AR(1), transient onset, Monte Carlo calibration, Rice-model probability, invalid inputs and the CSV workflow.
82
+ - [GitHub Actions](https://github.com/amrahmmed/power-system-noise-statistics/actions) is configured to test Python 3.10 and 3.12 across Linux, Windows and macOS. Check actual run status before claiming successful validation.
83
+ - A reproducible Monte Carlo detector benchmark reports empirical and theoretical probabilities, false-alarm calibration and Wilson confidence intervals. See [validation guide](docs/validation.md).
84
+ - See [CONTRIBUTING](CONTRIBUTING.md), [ROADMAP](ROADMAP.md) and [CHANGELOG](CHANGELOG.md).
85
+
86
+ ## Quick start: Python (original research script)
87
+
88
+ Use Python 3.10 or newer. Clone the repository, then install the scientific computing dependencies:
89
+
90
+ ```bash
91
+ git clone https://github.com/amrahmmed/power-system-noise-statistics.git
92
+ cd power-system-noise-statistics
93
+ python -m pip install numpy scipy pandas matplotlib
94
+ python power_systems_probability_research_competition_verification.py
95
+ ```
96
+
97
+ An isolated virtual environment is recommended. Alternatively, from the package root, install the research dependencies with `python -m pip install ".[research]"`. The script writes its generated figures and tables to `power_probability_python_outputs/` beside the script. No MATLAB installation is needed for the Python workflow.
98
+
99
+ ## Quick start: MATLAB
100
+
101
+ Open the repository in MATLAB. The script uses Signal Processing Toolbox and Statistics and Machine Learning Toolbox functions. A release supporting `exportgraphics` (R2020a or later) is required.
102
+
103
+ ```matlab
104
+ run('power_systems_probability_research_competition.m')
105
+ ```
106
+
107
+ Results are saved in `power_probability_outputs/` beside the MATLAB script. MATLAB and Python use independent random-number generators, so individual realizations need not match exactly.
108
+
109
+ ## Mathematical model
110
+
111
+ The measured waveform is modeled as:
112
+
113
+ ```math
114
+ x[k] = s[k] + h[k] + \tau[k] + \delta[k] + n[k]
115
+ ```
116
+
117
+ | Term | Description |
118
+ | --- | --- |
119
+ | s | Nominal fundamental waveform |
120
+ | h | Harmonic distortion |
121
+ | tau | Decaying transient disturbance |
122
+ | delta | Slow stochastic operating variations |
123
+ | n | Additive Gaussian measurement noise |
124
+
125
+ The simulations compare empirical MSE with a theoretical expectation model, amplitude-error risk with a Rice distribution, and transient detection probability with a noncentral chi-square model.
126
+
127
+ ## Default simulation configuration
128
+
129
+ | Parameter | Value |
130
+ | --- | --- |
131
+ | Fundamental frequency | 50 Hz |
132
+ | Sampling frequency | 10 kHz |
133
+ | Record length | 1 s (10,000 samples) |
134
+ | Fundamental amplitude | 1 pu |
135
+ | Harmonics | Fifth: 5%; seventh: 3% |
136
+ | Transient | 600 Hz, 0.2 pu, starting at 0.62 s |
137
+ | SNR sweep | 30, 20, 15, 10, 5 dB |
138
+ | Monte Carlo trials | 250 descriptive, 300 MSE per SNR, 5,000 probability trials per SNR |
139
+ | False-alarm target | 5% |
140
+ | Amplitude-error tolerance | 1% |
141
+
142
+ ## Generated outputs
143
+
144
+ Both workflows generate six figures covering the waveform, noise histogram, PSD, MSE, amplitude-estimation risk, and detection probability. CSV tables summarize parameters and empirical/theoretical comparisons. The Python script additionally writes a JSON summary.
145
+
146
+ | Output | Purpose |
147
+ | --- | --- |
148
+ | `fig1_waveform.png` | Representative waveform and transient |
149
+ | `fig2_noise_hist.png` | Noise distribution |
150
+ | `fig3_psd.png` | Power spectral density |
151
+ | `fig4_mse_vs_snr.png` | MSE versus SNR |
152
+ | `fig5_amp_probability.png` | Amplitude-estimation risk |
153
+ | `fig6_detector_probability.png` | Detection probability |
154
+ | `table3_probability_summary.csv` | Main numerical comparisons |
155
+ | `results_summary.txt` | Human-readable numerical summary |
156
+
157
+ ## Repository contents
158
+
159
+ - [Python verification script](power_systems_probability_research_competition_verification.py)
160
+ - [MATLAB simulation](power_systems_probability_research_competition.m)
161
+ - [Research report](power_systems_probability_research_competition_final.pdf)
162
+ - [Research notes](research_day_competition_notes.txt)
163
+ - [Archived research assets](Assets.zip)
164
+
165
+ ## Reproducibility and limitations
166
+
167
+ The simulations use fixed random seeds and synthetic waveforms. They are research and educational demonstrations, not validated field-data models or certified protection algorithms. The analytical detector assumes white Gaussian measurement noise and a specified harmonic basis; actual grid disturbances may violate these assumptions. The theoretical slow-variation power model is an approximation for finite, mean-centered AR(1) records.
168
+
169
+ ## Development roadmap
170
+
171
+ The development preview introduces a reusable API, CSV workflow and test suite. Remaining milestones and proposed improvements are tracked in [ROADMAP.md](ROADMAP.md).
172
+
173
+ ## Feedback and contributions
174
+
175
+ Use [GitHub Issues](https://github.com/amrahmmed/power-system-noise-statistics/issues) to report reproducibility problems or suggest improvements. Include your Python or MATLAB version, operating system, and the steps needed to reproduce the problem.
176
+
177
+ ## How to cite
178
+
179
+ For software citation, use [CITATION.cff](CITATION.cff) and record the exact commit or tagged version used. Cite the original [research report](power_systems_probability_research_competition_final.pdf) separately using its listed authors.
180
+
181
+ ## Release and security
182
+
183
+ See the [release readiness checklist](docs/release-checklist.md) and [responsible use and security guidance](SECURITY.md). The package has not been published to PyPI.
184
+
185
+ ## License
186
+
187
+ The new PowerNoise software package is available under the [MIT License](LICENSE). The original research scripts, report, archived assets, and research notes are excluded pending confirmation of rights. See [licensing scope](LICENSE-SCOPE.md) for details. Third-party dependencies retain their own licenses.
@@ -0,0 +1,18 @@
1
+ LICENSE
2
+ LICENSE-SCOPE.md
3
+ MANIFEST.in
4
+ README.md
5
+ pyproject.toml
6
+ src/power_system_noise_statistics.egg-info/PKG-INFO
7
+ src/power_system_noise_statistics.egg-info/SOURCES.txt
8
+ src/power_system_noise_statistics.egg-info/dependency_links.txt
9
+ src/power_system_noise_statistics.egg-info/entry_points.txt
10
+ src/power_system_noise_statistics.egg-info/requires.txt
11
+ src/power_system_noise_statistics.egg-info/top_level.txt
12
+ src/powernoise/__init__.py
13
+ src/powernoise/benchmark.py
14
+ src/powernoise/cli.py
15
+ src/powernoise/core.py
16
+ tests/test_benchmark.py
17
+ tests/test_cli.py
18
+ tests/test_core.py
@@ -0,0 +1,2 @@
1
+ [console_scripts]
2
+ powernoise = powernoise.cli:main
@@ -0,0 +1,9 @@
1
+ numpy>=1.24
2
+ scipy>=1.10
3
+
4
+ [research]
5
+ pandas>=1.5
6
+ matplotlib>=3.7
7
+
8
+ [test]
9
+ pytest>=7
@@ -0,0 +1,10 @@
1
+ """Tools for reproducible power-system signal experiments."""
2
+ from .core import (
3
+ ar1, synthesize, noise_sigma, fit_harmonics, rms, mse,
4
+ residual_detector, detection_probability, amplitude_error_probability,
5
+ )
6
+
7
+ __all__ = [
8
+ "ar1", "synthesize", "noise_sigma", "fit_harmonics", "rms", "mse",
9
+ "residual_detector", "detection_probability", "amplitude_error_probability",
10
+ ]
@@ -0,0 +1,79 @@
1
+ """Reproducible one-cycle detection benchmark for a synthetic disturbance."""
2
+ import math
3
+ import numpy as np
4
+ from scipy.stats import chi2
5
+ from .core import _basis, detection_probability, noise_sigma, synthesize
6
+
7
+
8
+ def wilson_interval(successes, trials, z=1.959963984540054):
9
+ """Approximate 95% binomial confidence interval (Wilson score)."""
10
+ if not isinstance(trials, (int, np.integer)) or trials < 1:
11
+ raise ValueError("trials must be a positive integer")
12
+ if not isinstance(successes, (int, np.integer)) or not 0 <= successes <= trials:
13
+ raise ValueError("successes must be an integer in [0, trials]")
14
+ if not math.isfinite(z) or z <= 0:
15
+ raise ValueError("z must be finite and positive")
16
+ p = successes / trials
17
+ d = 1 + z*z/trials
18
+ center = (p + z*z/(2*trials))/d
19
+ half = z*math.sqrt(p*(1-p)/trials + z*z/(4*trials*trials))/d
20
+ # Exact binomial boundary cases avoid cancellation/rounding at p=0 or 1.
21
+ if successes == 0:
22
+ return 0.0, z*z/(trials+z*z)
23
+ if successes == trials:
24
+ return trials/(trials+z*z), 1.0
25
+ return max(0.0, center-half), min(1.0, center+half)
26
+
27
+
28
+ def detection_benchmark(*, fs=12000, f0=50, snr_db=(5, 10, 15, 20, 30),
29
+ trials=5000, alpha=.05, seed=20260414):
30
+ """Compare analytical and empirical detection on one synthetic cycle.
31
+
32
+ The event starts 40% into the record, with peak scale 0.2, frequency
33
+ 600 Hz and exponential decay 120/s. A fitted 1/5/7 harmonic basis and
34
+ known white Gaussian noise are assumed. Noise is shared between the
35
+ null and event experiments within each trial. Confidence intervals
36
+ are marginal binomial intervals, not simultaneous confidence bands.
37
+ """
38
+ if not isinstance(trials, (int, np.integer)) or trials < 1:
39
+ raise ValueError("trials must be a positive integer")
40
+ if not 0 < alpha < 1:
41
+ raise ValueError("alpha must lie between zero and one")
42
+ if not math.isfinite(f0) or f0 <= 0:
43
+ raise ValueError("f0 must be finite and positive")
44
+ common = dict(fs=fs, f0=f0, duration=1/f0, snr_db=None,
45
+ harmonics={5: (.05, .4), 7: (.03, -.8)})
46
+ _, _, base = synthesize(**common)
47
+ _, _, event = synthesize(**common, transient=(.4/f0, .2, 600, 120))
48
+ disturbance = event - base
49
+ n = len(base)
50
+ h = _basis(n, fs, f0, (1, 5, 7))
51
+ q, _ = np.linalg.qr(h, mode="reduced")
52
+ dof = n - q.shape[1]
53
+ threshold = chi2.isf(alpha, dof)
54
+ rng = np.random.default_rng(seed)
55
+ rows = []
56
+ for snr in snr_db:
57
+ sigma = noise_sigma(float(snr))
58
+ fa = detected = 0
59
+ # Bound memory even for large trial counts.
60
+ batch = max(1, min(512, 1_000_000 // n))
61
+ for start in range(0, trials, batch):
62
+ size = min(batch, trials-start)
63
+ noise = rng.normal(0, sigma, (size, n))
64
+ for i, waveform in enumerate((base, event)):
65
+ x = noise + waveform
66
+ residual = x - (x @ q) @ q.T
67
+ flags = int(np.count_nonzero(np.sum(residual**2, axis=1)/sigma**2 > threshold))
68
+ if i == 0:
69
+ fa += flags
70
+ else:
71
+ detected += flags
72
+ fa_lo, fa_hi = wilson_interval(fa, trials)
73
+ pd_lo, pd_hi = wilson_interval(detected, trials)
74
+ rows.append(dict(snr_db=float(snr), samples=n, trials=int(trials),
75
+ p_fa_target=float(alpha), p_fa_empirical=fa/trials,
76
+ p_fa_ci_low=fa_lo, p_fa_ci_high=fa_hi,
77
+ p_d_theoretical=detection_probability(disturbance, fs, sigma, f0, alpha=alpha),
78
+ p_d_empirical=detected/trials, p_d_ci_low=pd_lo, p_d_ci_high=pd_hi))
79
+ return rows
@@ -0,0 +1,60 @@
1
+ """Command-line entry point for synthetic experiments and CSV analysis."""
2
+ import argparse
3
+ import json
4
+ from pathlib import Path
5
+ import numpy as np
6
+ from .core import synthesize, fit_harmonics, rms, mse, residual_detector
7
+
8
+
9
+ def main(argv=None):
10
+ p = argparse.ArgumentParser(description=__doc__)
11
+ commands = p.add_subparsers(dest="command", required=True)
12
+ demo = commands.add_parser("simulate", help="generate a synthetic waveform CSV")
13
+ demo.add_argument("--output", type=Path, required=True)
14
+ demo.add_argument("--fs", type=float, default=10000)
15
+ demo.add_argument("--f0", type=float, default=50)
16
+ demo.add_argument("--duration", type=float, default=1)
17
+ demo.add_argument("--snr-db", type=float, default=20)
18
+ demo.add_argument("--seed", type=int, default=0)
19
+ analysis = commands.add_parser("analyze", help="analyze a CSV with a value column")
20
+ analysis.add_argument("input", type=Path)
21
+ analysis.add_argument("--fs", type=float, required=True)
22
+ analysis.add_argument("--f0", type=float, default=50)
23
+ analysis.add_argument("--orders", type=int, nargs="+", default=[1, 5, 7])
24
+ analysis.add_argument("--sigma", type=float, help="known AWGN standard deviation")
25
+ analysis.add_argument("--alpha", type=float, default=0.05)
26
+ args = p.parse_args(argv)
27
+ try:
28
+ if args.command == "simulate":
29
+ t, clean, x = synthesize(fs=args.fs, f0=args.f0, duration=args.duration,
30
+ harmonics={5: (0.05, 0.4), 7: (0.03, -0.8)},
31
+ snr_db=args.snr_db, seed=args.seed)
32
+ args.output.parent.mkdir(parents=True, exist_ok=True)
33
+ np.savetxt(args.output, np.column_stack((t, clean, x)), delimiter=",",
34
+ header="time_s,clean,value", comments="")
35
+ print(json.dumps({"samples": len(x), "mse": mse(x, clean), "output": str(args.output)}))
36
+ else:
37
+ data = np.genfromtxt(args.input, delimiter=",", names=True, dtype=float, encoding="utf-8")
38
+ if data.dtype.names is None or "value" not in data.dtype.names:
39
+ raise ValueError("CSV must have a header with a value column")
40
+ x = np.atleast_1d(data["value"])
41
+ if not np.isfinite(args.fs) or args.fs <= 0:
42
+ raise ValueError("fs must be finite and positive")
43
+ if "time_s" in data.dtype.names:
44
+ times = np.atleast_1d(data["time_s"])
45
+ if not np.isfinite(times).all() or not np.allclose(
46
+ np.diff(times), 1 / args.fs, rtol=1e-4, atol=0):
47
+ raise ValueError("time_s must be uniformly spaced at the declared fs")
48
+ fit = fit_harmonics(x, args.fs, args.f0, args.orders)
49
+ result = {"samples": len(x), "rms": rms(x), "amplitudes": fit["amplitudes"],
50
+ "thd_fraction": fit["thd_fraction"]}
51
+ if args.sigma is not None:
52
+ result["residual_test"] = residual_detector(x, args.fs, args.sigma,
53
+ args.f0, args.orders, args.alpha)
54
+ print(json.dumps(result, allow_nan=False))
55
+ except (ValueError, OSError) as exc:
56
+ p.error(str(exc))
57
+
58
+
59
+ if __name__ == "__main__":
60
+ main()
@@ -0,0 +1,185 @@
1
+ """Numerical tools for synthetic waveforms and calibrated Gaussian-noise tests.
2
+
3
+ Amplitudes are peak values, frequencies in Hz, and time in seconds.
4
+ Use consistent physical units or per-unit values throughout.
5
+ """
6
+ import math
7
+ import numpy as np
8
+ from scipy.signal import lfilter
9
+ from scipy.stats import chi2, ncx2, rice
10
+
11
+
12
+ def _positive(value, name):
13
+ if not math.isfinite(value) or value <= 0:
14
+ raise ValueError(f"{name} must be finite and positive")
15
+
16
+
17
+ def _vector(x):
18
+ x = np.asarray(x, dtype=float)
19
+ if x.ndim != 1 or x.size == 0 or not np.isfinite(x).all():
20
+ raise ValueError("expected a nonempty finite one-dimensional signal")
21
+ return x
22
+
23
+
24
+ def _orders(orders, fs, f0):
25
+ _positive(fs, "fs")
26
+ _positive(f0, "f0")
27
+ orders = tuple(orders)
28
+ if not orders or any(not isinstance(h, (int, np.integer)) or h < 1 for h in orders):
29
+ raise ValueError("harmonic orders must be positive integers")
30
+ if len(set(orders)) != len(orders) or max(orders) * f0 >= fs / 2:
31
+ raise ValueError("orders must be distinct and below Nyquist")
32
+ return orders
33
+
34
+
35
+ def ar1(n, rho, std, *, seed=None):
36
+ """Generate a stationary Gaussian AR(1) process, without demeaning."""
37
+ if not isinstance(n, (int, np.integer)) or n < 1:
38
+ raise ValueError("n must be a positive integer")
39
+ if not math.isfinite(rho) or abs(rho) >= 1:
40
+ raise ValueError("abs(rho) must be below 1")
41
+ if not math.isfinite(std) or std < 0:
42
+ raise ValueError("std must be finite and nonnegative")
43
+ rng = np.random.default_rng(seed)
44
+ initial = rng.normal(0, std)
45
+ innovations = rng.normal(0, std * math.sqrt(1 - rho*rho), n)
46
+ innovations[0] = initial
47
+ return lfilter([1.0], [1.0, -rho], innovations)
48
+
49
+
50
+ def noise_sigma(snr_db, amplitude=1.0):
51
+ """AWGN standard deviation relative to a sinusoid's average power A²/2."""
52
+ _positive(amplitude, "amplitude")
53
+ if not math.isfinite(snr_db):
54
+ raise ValueError("SNR must be finite")
55
+ try:
56
+ sigma = amplitude / math.sqrt(2) * 10.0 ** (-snr_db / 20)
57
+ except OverflowError as exc:
58
+ raise ValueError("SNR outside representable range") from exc
59
+ _positive(sigma, "noise standard deviation")
60
+ return sigma
61
+
62
+
63
+ def synthesize(*, fs=10000, f0=50, duration=1.0, amplitude=1.0,
64
+ harmonics=None, snr_db=20.0, transient=None, seed=0):
65
+ """Return time, clean fundamental and measured waveform arrays.
66
+
67
+ harmonics maps order to (relative peak amplitude, phase in radians).
68
+ transient is (start_seconds, peak_scale, frequency_hz, decay_per_second).
69
+ snr_db=None disables measurement noise. No real grid data are implied.
70
+ """
71
+ _positive(duration, "duration")
72
+ _positive(amplitude, "amplitude")
73
+ harmonics = {} if harmonics is None else dict(harmonics)
74
+ if 1 in harmonics:
75
+ raise ValueError("fundamental already supplied")
76
+ _orders((1, *harmonics), fs, f0)
77
+ n = round(fs * duration)
78
+ if n < 2:
79
+ raise ValueError("duration must contain at least two samples")
80
+ t = np.arange(n) / fs
81
+ clean = amplitude * np.sin(2 * np.pi * f0 * t)
82
+ measured = clean.copy()
83
+ for h, (relative, phase) in harmonics.items():
84
+ if not math.isfinite(relative) or relative < 0 or not math.isfinite(phase):
85
+ raise ValueError("invalid harmonic amplitude or phase")
86
+ measured += amplitude * relative * np.sin(2*np.pi*h*f0*t + phase)
87
+ if transient is not None:
88
+ start, scale, freq, decay = transient
89
+ if not all(math.isfinite(v) for v in transient):
90
+ raise ValueError("transient parameters must be finite")
91
+ if not 0 <= start < n / fs or not 0 < freq < fs / 2 or decay < 0:
92
+ raise ValueError("invalid transient onset, frequency or decay")
93
+ mask = t >= start
94
+ dt = t[mask] - start
95
+ measured[mask] += amplitude * scale * np.exp(-decay*dt) * np.sin(2*np.pi*freq*dt)
96
+ if snr_db is not None:
97
+ measured += np.random.default_rng(seed).normal(0, noise_sigma(snr_db, amplitude), n)
98
+ return t, clean, measured
99
+
100
+
101
+ def rms(x):
102
+ """Root mean square, including any DC component."""
103
+ return float(np.sqrt(np.mean(_vector(x)**2)))
104
+
105
+
106
+ def mse(x, reference):
107
+ """Mean squared error between equal-length signals."""
108
+ x, reference = _vector(x), _vector(reference)
109
+ if x.shape != reference.shape:
110
+ raise ValueError("signals must have equal lengths")
111
+ return float(np.mean((x-reference)**2))
112
+
113
+
114
+ def _basis(n, fs, f0, orders):
115
+ orders = _orders(orders, fs, f0)
116
+ if n <= 2 * len(orders):
117
+ raise ValueError("need more samples than fitted coefficients")
118
+ t = np.arange(n) / fs
119
+ h = np.column_stack([col for order in orders for col in
120
+ (np.sin(2*np.pi*order*f0*t), np.cos(2*np.pi*order*f0*t))])
121
+ if np.linalg.matrix_rank(h) != h.shape[1]:
122
+ raise ValueError("rank-deficient harmonic basis")
123
+ return h
124
+
125
+
126
+ def fit_harmonics(x, fs, f0=50, orders=(1, 5, 7)):
127
+ """Least-squares harmonic fit; peak amplitudes and selected-order THD.
128
+
129
+ THD is a fraction, not a percent, and covers only the requested orders.
130
+ No DC term is fitted. Unknown harmonics and DC remain in the residual.
131
+ """
132
+ x = _vector(x)
133
+ orders = tuple(orders)
134
+ h = _basis(len(x), fs, f0, orders)
135
+ coef = np.linalg.lstsq(h, x, rcond=None)[0]
136
+ amps = dict(zip(orders, np.hypot(coef[::2], coef[1::2]).tolist()))
137
+ fundamental = amps.get(1, 0.0)
138
+ thd = (math.sqrt(sum(v*v for k, v in amps.items() if k != 1)) / fundamental
139
+ if fundamental > np.finfo(float).eps * rms(x) else None)
140
+ return {"amplitudes": amps, "thd_fraction": thd, "residual": x - h @ coef}
141
+
142
+
143
+ def residual_detector(x, fs, sigma, f0=50, orders=(1, 5, 7), alpha=0.05):
144
+ """Residual-energy test with known AWGN sigma and a full-rank basis.
145
+
146
+ Under the null, sum(residual²)/sigma² is chi-square with n-2K degrees
147
+ of freedom. A rejection is an unexplained residual, not proof of a
148
+ specific transient or a certified protection decision.
149
+ """
150
+ _positive(sigma, "sigma")
151
+ if not 0 < alpha < 1:
152
+ raise ValueError("alpha must be between zero and one")
153
+ x = _vector(x)
154
+ orders = tuple(orders)
155
+ res = fit_harmonics(x, fs, f0, orders)["residual"]
156
+ dof = len(x) - 2 * len(orders)
157
+ statistic = float(np.dot(res, res) / sigma**2)
158
+ threshold = float(chi2.isf(alpha, dof))
159
+ return {"statistic": statistic, "threshold": threshold, "dof": dof,
160
+ "p_value": float(chi2.sf(statistic, dof)), "detected": statistic > threshold}
161
+
162
+
163
+ def detection_probability(disturbance, fs, sigma, f0=50, orders=(1, 5, 7), alpha=0.05):
164
+ """Analytical power for a known additive deterministic disturbance."""
165
+ d = _vector(disturbance)
166
+ result = residual_detector(d, fs, sigma, f0, orders, alpha)
167
+ return float(ncx2.sf(result["threshold"], result["dof"], result["statistic"]))
168
+
169
+
170
+ def amplitude_error_probability(amplitude, sigma, n, relative_tolerance=0.01):
171
+ """Rice-model risk for orthogonal sine/cosine fits on complete cycles.
172
+
173
+ Assumes white Gaussian noise, known frequency, and equal-norm orthogonal
174
+ regressors of squared norm n/2. Not valid for arbitrary partial cycles.
175
+ """
176
+ _positive(amplitude, "amplitude")
177
+ _positive(sigma, "sigma")
178
+ if not isinstance(n, (int, np.integer)) or n < 3:
179
+ raise ValueError("n must be an integer of at least three")
180
+ if not 0 < relative_tolerance < 1:
181
+ raise ValueError("relative tolerance must be between zero and one")
182
+ scale = sigma * math.sqrt(2/n)
183
+ b = amplitude / scale
184
+ lo, hi = amplitude*(1-relative_tolerance), amplitude*(1+relative_tolerance)
185
+ return float(rice.cdf(lo, b, scale=scale) + rice.sf(hi, b, scale=scale))
@@ -0,0 +1,34 @@
1
+ import pytest
2
+ from powernoise.benchmark import detection_benchmark, wilson_interval
3
+
4
+
5
+ def test_wilson_boundaries():
6
+ lo, hi = wilson_interval(0, 100)
7
+ assert lo == 0.0
8
+ assert 0 < hi < .05
9
+ lo, hi = wilson_interval(100, 100)
10
+ assert .95 < lo < 1
11
+ assert hi == 1.0
12
+ with pytest.raises(ValueError):
13
+ wilson_interval(101, 100)
14
+
15
+
16
+ @pytest.mark.parametrize("n", [1, 100, 2000, 5000])
17
+ def test_wilson_exact_boundary_and_contains_observed(n):
18
+ for successes in {0, n//2, n}:
19
+ lo, hi = wilson_interval(successes, n)
20
+ assert 0 <= lo <= successes/n <= hi <= 1
21
+ assert wilson_interval(0, n)[0] == 0.0
22
+ assert wilson_interval(n, n)[1] == 1.0
23
+
24
+
25
+ @pytest.mark.parametrize("f0", [50, 60])
26
+ def test_benchmark_calibration(f0):
27
+ settings = dict(f0=f0, trials=2000, snr_db=[10, 20], seed=31)
28
+ rows = detection_benchmark(**settings)
29
+ assert rows == detection_benchmark(**settings)
30
+ for row in rows:
31
+ assert row["p_fa_empirical"] == pytest.approx(.05, abs=.025)
32
+ assert row["p_d_empirical"] == pytest.approx(row["p_d_theoretical"], abs=.045)
33
+ assert row["p_d_ci_low"] <= row["p_d_empirical"] <= row["p_d_ci_high"]
34
+ assert rows[1]["p_d_theoretical"] > rows[0]["p_d_theoretical"]
@@ -0,0 +1,25 @@
1
+ import json
2
+ from powernoise.cli import main
3
+
4
+
5
+ def test_csv_roundtrip(tmp_path, capsys):
6
+ out = tmp_path / "nested" / "wave.csv"
7
+ main(["simulate", "--output", str(out), "--duration", ".1"])
8
+ assert json.loads(capsys.readouterr().out)["samples"] == 1000
9
+ assert out.is_file()
10
+ main(["analyze", str(out), "--fs", "10000", "--sigma", "0.070710678"])
11
+ result = json.loads(capsys.readouterr().out)
12
+ assert result["samples"] == 1000
13
+ assert abs(result["amplitudes"]["1"] - 1) < .03
14
+ assert result["residual_test"]["dof"] == 994
15
+
16
+
17
+ def test_reject_mismatched_timestamps(tmp_path, capsys):
18
+ import pytest
19
+ out = tmp_path / "wave.csv"
20
+ main(["simulate", "--output", str(out), "--duration", ".1"])
21
+ capsys.readouterr()
22
+ with pytest.raises(SystemExit) as exc:
23
+ main(["analyze", str(out), "--fs", "12000"])
24
+ assert exc.value.code == 2
25
+ assert "uniformly spaced" in capsys.readouterr().err
@@ -0,0 +1,81 @@
1
+ import numpy as np
2
+ import pytest
3
+ from powernoise import (ar1, synthesize, noise_sigma, fit_harmonics, rms, mse,
4
+ residual_detector, detection_probability, amplitude_error_probability)
5
+
6
+
7
+ @pytest.mark.parametrize("f0", [50, 60])
8
+ def test_clean_signal_and_harmonic_recovery(f0):
9
+ _, clean, x = synthesize(fs=12000, f0=f0, snr_db=None,
10
+ harmonics={5: (0.05, 0.4), 7: (0.03, -0.8)})
11
+ assert rms(clean) == pytest.approx(1 / np.sqrt(2))
12
+ fit = fit_harmonics(x, 12000, f0)
13
+ assert fit["amplitudes"] == pytest.approx({1: 1, 5: .05, 7: .03})
14
+ assert fit["thd_fraction"] == pytest.approx(np.hypot(.05, .03))
15
+ assert rms(fit["residual"]) < 1e-12
16
+ assert mse(x, clean) == pytest.approx((.05**2 + .03**2)/2)
17
+
18
+
19
+ def test_seed_and_awgn_power():
20
+ _, s, x = synthesize(duration=10, snr_db=20, seed=4)
21
+ _, _, y = synthesize(duration=10, snr_db=20, seed=4)
22
+ assert np.array_equal(x, y)
23
+ assert mse(x, s) == pytest.approx(noise_sigma(20)**2, rel=.03)
24
+ assert noise_sigma(20, 2) == pytest.approx(2*noise_sigma(20))
25
+
26
+
27
+ def test_stationary_ar1():
28
+ x = ar1(50000, .8, .4, seed=22)
29
+ assert np.std(x) == pytest.approx(.4, rel=.04)
30
+ assert np.corrcoef(x[:-1], x[1:])[0, 1] == pytest.approx(.8, abs=.02)
31
+ assert np.array_equal(ar1(10, .8, .4, seed=9), ar1(10, .8, .4, seed=9))
32
+
33
+
34
+ def test_transient_onset():
35
+ t, s, x = synthesize(snr_db=None, transient=(.1, .2, 600, 120))
36
+ assert np.array_equal(x[t < .1], s[t < .1])
37
+ assert np.max(np.abs(x[t >= .1] - s[t >= .1])) > .1
38
+
39
+
40
+ def test_detector_calibration_and_power():
41
+ fs, sigma = 10000, .07
42
+ t, base, _ = synthesize(fs=fs, duration=.02, snr_db=None)
43
+ _, _, event = synthesize(fs=fs, duration=.02, snr_db=None,
44
+ transient=(.008, .2, 600, 120))
45
+ disturbance = event-base
46
+ rng = np.random.default_rng(85)
47
+ null_count = event_count = 0
48
+ trials = 2000
49
+ for noise in rng.normal(0, sigma, (trials, len(t))):
50
+ null_count += residual_detector(base+noise, fs, sigma)["detected"]
51
+ event_count += residual_detector(event+noise, fs, sigma)["detected"]
52
+ theoretical = detection_probability(disturbance, fs, sigma)
53
+ assert null_count/trials == pytest.approx(.05, abs=.02)
54
+ assert event_count/trials == pytest.approx(theoretical, abs=.04)
55
+ assert detection_probability(np.zeros_like(t), fs, sigma) == pytest.approx(.05)
56
+
57
+
58
+ def test_rice_probability_matches_monte_carlo():
59
+ n, sigma = 200, .07
60
+ t = np.arange(n)/10000
61
+ h = np.column_stack((np.sin(2*np.pi*50*t), np.cos(2*np.pi*50*t)))
62
+ rng = np.random.default_rng(3)
63
+ y = h[:, 0, None] + rng.normal(0, sigma, (n, 10000))
64
+ coeff = (2/n)*h.T @ y
65
+ empirical = np.mean(np.abs(np.hypot(*coeff)-1) > .01)
66
+ assert empirical == pytest.approx(amplitude_error_probability(1, sigma, n), abs=.02)
67
+
68
+
69
+ @pytest.mark.parametrize("fn", [
70
+ lambda: synthesize(fs=100, f0=50),
71
+ lambda: synthesize(harmonics={1: (.1, 0)}),
72
+ lambda: fit_harmonics([1, 2], 10000),
73
+ lambda: rms([float("nan")]),
74
+ lambda: mse([1, 2], [1]),
75
+ lambda: ar1(10, 1, .1),
76
+ lambda: residual_detector(np.zeros(200), 10000, 0),
77
+ lambda: amplitude_error_probability(1, .1, 2),
78
+ ])
79
+ def test_invalid_inputs(fn):
80
+ with pytest.raises(ValueError):
81
+ fn()