Sheldon Zheng commited on
Commit
d239d18
·
1 Parent(s): f09f203

Upload rural voltage anomaly detection datasets

Browse files

Datasets included:
- RuralVoltage/realistic_v2: 50K train + 10K test, 16 features, 9 anomaly types
- PSM: 132K train + 87K test, 25 features (public benchmark)
- KagglePQ: 9.6K train + 2.4K test, 128 samples (power quality)

Total size: 153MB

.gitattributes CHANGED
@@ -57,3 +57,4 @@ saved_model/**/* filter=lfs diff=lfs merge=lfs -text
57
  # Video files - compressed
58
  *.mp4 filter=lfs diff=lfs merge=lfs -text
59
  *.webm filter=lfs diff=lfs merge=lfs -text
 
 
57
  # Video files - compressed
58
  *.mp4 filter=lfs diff=lfs merge=lfs -text
59
  *.webm filter=lfs diff=lfs merge=lfs -text
60
+ *.csv filter=lfs diff=lfs merge=lfs -text
KagglePQ/PowerQualityDistributionDataset1.csv ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:d536bc9c4e670b8d7f9ca7998a30ce95bf9f49a46611d59f80c660bf11fbee77
3
+ size 19111658
KagglePQ/test.csv ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:d34997e171194d93dc4431b513ee6229931e520800a54dda4b717ed13cec1b5b
3
+ size 15220461
KagglePQ/test_label.csv ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:7223a553ece4e5cb554e47e6e69754da9f307d6804c860d12652c3a492bd817c
3
+ size 19202
KagglePQ/train.csv ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:523e254f76fd30c58ecd019abb78c93f84742f8ef424017609bbaf457531e684
3
+ size 3807103
PSM/test.csv ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:566bc50117d13f58793d830c14975c55f627cab63953265d7d6ce2dbcf2b0f80
3
+ size 42523490
PSM/test_label.csv ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:e5b6b0c716a9b3d52e3a1b06761527811f75a218790c37b8a5e806741aeb0676
3
+ size 966273
PSM/train.csv ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:816e0e2a5356b3b09d356925cd9a0fe1d327e3b350e9336d26ee3e650c72e112
3
+ size 63628087
README.md ADDED
@@ -0,0 +1,173 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ ---
2
+ license: mit
3
+ language:
4
+ - zh
5
+ - en
6
+ tags:
7
+ - time-series
8
+ - anomaly-detection
9
+ - voltage
10
+ - power-grid
11
+ - power-quality
12
+ size_categories:
13
+ - 10K<n<100K
14
+ task_categories:
15
+ - time-series-classification
16
+ ---
17
+
18
+ # Rural Voltage Anomaly Detection Datasets
19
+
20
+ 农村低压配电网电压异常检测实验数据集合集。
21
+
22
+ ## 🔗 相关链接
23
+
24
+ - **模型检查点**: [Sheldon123z/rural-voltage-detection-models](https://huggingface.co/Sheldon123z/rural-voltage-detection-models)
25
+ - **代码仓库**: [GitHub - Rural-Low-Voltage-Detection](https://github.com/sheldon123z/Rural-Low-Voltage-Detection)
26
+
27
+ ## 📊 数据集概览
28
+
29
+ | 数据集 | 训练集 | 测试集 | 特征数 | 异常比例 | 来源 |
30
+ |--------|:------:|:------:|:------:|:--------:|------|
31
+ | **RuralVoltage** | 50,000 | 10,000 | 16 | 14.6% | 自主生成 |
32
+ | **PSM** | 132,481 | 87,841 | 25 | 27.8% | 公开数据集 |
33
+ | **KagglePQ** | 9,598 | 2,400 | 128 | 80% | Kaggle |
34
+
35
+ ## 📁 目录结构
36
+
37
+ ```
38
+ ├── RuralVoltage/ # 农村电压数据集(本研究核心)
39
+ │ ├── realistic_v2/
40
+ │ │ ├── train.csv # 训练集(纯正常数据)
41
+ │ │ ├── test.csv # 测试集
42
+ │ │ └── test_label.csv # 测试标签
43
+ │ └── generate_realistic_data.py # 数据生成脚本
44
+ ├── PSM/ # 服务器机器数据集
45
+ │ ├── train.csv
46
+ │ ├── test.csv
47
+ │ └── test_label.csv
48
+ └── KagglePQ/ # Kaggle 电力质量数据集
49
+ ├── train.csv
50
+ ├── test.csv
51
+ ├── test_label.csv
52
+ └── PowerQualityDistributionDataset1.csv # 原始数据
53
+ ```
54
+
55
+ ---
56
+
57
+ ## 🔋 RuralVoltage 数据集(核心)
58
+
59
+ ### 特征说明(16维)
60
+
61
+ | 类别 | 特征 | 说明 |
62
+ |------|------|------|
63
+ | **三相电压** | `Va`, `Vb`, `Vc` | 瞬时电压值 (V) |
64
+ | **三相电流** | `Ia`, `Ib`, `Ic` | 瞬时电流值 (A) |
65
+ | **功率参数** | `P`, `Q`, `S`, `PF` | 有功/无功/视在功率,功率因数 |
66
+ | **谐波指标** | `THD_Va`, `THD_Vb`, `THD_Vc` | 三相电压谐波畸变率 (%) |
67
+ | **电能质量** | `Freq`, `V_unbalance`, `I_unbalance` | 频率、电压/电流不平衡度 |
68
+
69
+ ### 异常类型(9种)
70
+
71
+ | 异常类型 | 英文名 | 数量 | 说明 |
72
+ |----------|--------|:----:|------|
73
+ | 欠压 | Undervoltage | 353 | 电压低于额定值 10-15% |
74
+ | 谐波 | Harmonics | 348 | THD 超标 |
75
+ | 三相不平衡 | Unbalance | 243 | 三相电压/电流不平衡 |
76
+ | 过压 | Overvoltage | 225 | 电压高于额定值 10-15% |
77
+ | 三相暂降 | Voltage_Sag_3Phase | 105 | 三相同时暂降 |
78
+ | 复合异常 | Compound | 72 | 多种异常叠加 |
79
+ | 单相暂降 | Voltage_Sag_1Phase | 71 | 单相电压暂降 |
80
+ | 闪变 | Flicker | 22 | 电压波动 |
81
+ | 暂态 | Transient | 21 | 电机启动等暂态扰动 |
82
+
83
+ ### 数据生成特点
84
+
85
+ ✅ **真实噪声建模**
86
+ - 1/f 粉红噪声(比白噪声更真实)
87
+ - 50Hz 工频干扰及谐波
88
+ - 40dB 信噪比
89
+
90
+ ✅ **农村负荷特征**
91
+ - 早峰(6-8点):灌溉、牲畜喂养
92
+ - 晚峰(18-21点):居民用电
93
+ - 季节性变化
94
+
95
+ ✅ **渐变式异常注入**
96
+ - 非突变式异常(更真实)
97
+ - 电机启动暂态模拟
98
+ - 复合异常组合
99
+
100
+ ---
101
+
102
+ ## 🖥️ PSM 数据集
103
+
104
+ eBay 服务器机器异常检测公开数据集。
105
+
106
+ - **来源**: [OmniAnomaly](https://github.com/NetManAIOps/OmniAnomaly)
107
+ - **特征**: 25 维服务器指标
108
+ - **用途**: 基准对比实验
109
+
110
+ ---
111
+
112
+ ## ⚡ KagglePQ 数据集
113
+
114
+ Kaggle 电力质量分布数据集,包含 128 个采样点的电压波形。
115
+
116
+ - **来源**: [Kaggle - Power Quality Distribution](https://www.kaggle.com/datasets/...)
117
+ - **任务**: 电力质量分类(5类)
118
+ - **处理**: 已转换为异常检测格式(Class 3 为正常类)
119
+
120
+ ---
121
+
122
+ ## 📖 使用方法
123
+
124
+ ### 方法1: 使用 Hugging Face datasets 库
125
+
126
+ ```python
127
+ from datasets import load_dataset
128
+
129
+ # 加载 RuralVoltage 数据集
130
+ dataset = load_dataset("Sheldon123z/rural-voltage-datasets", data_dir="RuralVoltage/realistic_v2")
131
+
132
+ # 加载 PSM 数据集
133
+ dataset = load_dataset("Sheldon123z/rural-voltage-datasets", data_dir="PSM")
134
+ ```
135
+
136
+ ### 方法2: 直接下载
137
+
138
+ ```python
139
+ from huggingface_hub import hf_hub_download
140
+
141
+ # 下载单个文件
142
+ train_file = hf_hub_download(
143
+ repo_id="Sheldon123z/rural-voltage-datasets",
144
+ filename="RuralVoltage/realistic_v2/train.csv",
145
+ repo_type="dataset"
146
+ )
147
+ ```
148
+
149
+ ### 方法3: 克隆整个仓库
150
+
151
+ ```bash
152
+ git clone https://huggingface.co/datasets/Sheldon123z/rural-voltage-datasets
153
+ ```
154
+
155
+ ---
156
+
157
+ ## 📜 引用
158
+
159
+ 如果使用本数据集,请引用:
160
+
161
+ ```bibtex
162
+ @misc{ruralvoltage2024,
163
+ title={Rural Low-Voltage Distribution Network Voltage Anomaly Detection},
164
+ author={Zheng Xiaodong},
165
+ year={2024},
166
+ publisher={Hugging Face},
167
+ url={https://huggingface.co/datasets/Sheldon123z/rural-voltage-datasets}
168
+ }
169
+ ```
170
+
171
+ ## 📄 License
172
+
173
+ MIT License
RuralVoltage/generate_realistic_data.py ADDED
@@ -0,0 +1,925 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """
2
+ Realistic Rural Voltage Anomaly Detection Data Generator (V2.0)
3
+
4
+ Major improvements over V1.0:
5
+ 1. Realistic anomaly patterns with gradual transitions
6
+ 2. Compound anomalies (multiple types occurring together)
7
+ 3. Real-world noise models (1/f noise, power line interference)
8
+ 4. True three-phase relationships with phase angles
9
+ 5. Realistic rural load patterns (seasonal, weekly, daily)
10
+ 6. Proper harmonic modeling (3rd, 5th, 7th harmonics)
11
+ 7. Voltage flicker and transient events
12
+ 8. Equipment switching transients
13
+
14
+ Based on:
15
+ - GB/T 12325-2008 (Voltage deviation limits)
16
+ - GB/T 14549-1993 (Harmonic limits)
17
+ - GB/T 15543-2008 (Unbalance limits)
18
+ - IEC 61000-4-30 (Power quality measurement methods)
19
+
20
+ Usage:
21
+ python generate_realistic_data.py --train_samples 50000 --test_samples 10000 --anomaly_ratio 0.12
22
+ """
23
+
24
+ import numpy as np
25
+ import pandas as pd
26
+ import argparse
27
+ import os
28
+ from datetime import datetime, timedelta
29
+ from scipy import signal
30
+ from scipy.ndimage import gaussian_filter1d
31
+ import warnings
32
+ warnings.filterwarnings('ignore')
33
+
34
+
35
+ # =============================================================================
36
+ # Constants based on Chinese National Standards
37
+ # =============================================================================
38
+ NOMINAL_VOLTAGE = 220.0 # V (phase voltage)
39
+ NOMINAL_FREQUENCY = 50.0 # Hz
40
+ SAMPLING_RATE = 1.0 # Hz (1 sample per second)
41
+
42
+ # GB/T 12325-2008: Voltage deviation limits
43
+ VOLTAGE_UPPER_LIMIT = 242.0 # +10%
44
+ VOLTAGE_LOWER_LIMIT = 198.0 # -10%
45
+
46
+ # GB/T 14549-1993: THD limits
47
+ THD_LIMIT = 5.0 # %
48
+
49
+ # GB/T 15543-2008: Unbalance limits
50
+ UNBALANCE_LIMIT = 4.0 # %
51
+
52
+
53
+ # =============================================================================
54
+ # Noise Models
55
+ # =============================================================================
56
+ def generate_pink_noise(n_samples, scale=1.0):
57
+ """Generate 1/f (pink) noise - more realistic than white noise."""
58
+ # Generate white noise
59
+ white = np.random.randn(n_samples)
60
+ # Apply 1/f filter using FFT
61
+ fft = np.fft.rfft(white)
62
+ freqs = np.fft.rfftfreq(n_samples)
63
+ freqs[0] = 1e-10 # Avoid division by zero
64
+ # 1/f filter
65
+ fft = fft / np.sqrt(freqs)
66
+ pink = np.fft.irfft(fft, n_samples)
67
+ return pink * scale
68
+
69
+
70
+ def generate_power_line_interference(n_samples, amplitude=0.5):
71
+ """Generate 50Hz power line interference and harmonics."""
72
+ t = np.arange(n_samples) / SAMPLING_RATE
73
+ interference = amplitude * np.sin(2 * np.pi * 50 * t)
74
+ # Add 3rd and 5th harmonics
75
+ interference += 0.3 * amplitude * np.sin(2 * np.pi * 150 * t)
76
+ interference += 0.2 * amplitude * np.sin(2 * np.pi * 250 * t)
77
+ return interference
78
+
79
+
80
+ def generate_measurement_noise(n_samples, snr_db=40):
81
+ """Generate realistic measurement noise with given SNR."""
82
+ # Combine white noise, pink noise, and quantization noise
83
+ white = np.random.randn(n_samples)
84
+ pink = generate_pink_noise(n_samples)
85
+
86
+ # Mix: 60% pink, 40% white
87
+ noise = 0.6 * pink + 0.4 * white
88
+
89
+ # Scale to achieve target SNR (relative to nominal voltage)
90
+ signal_power = NOMINAL_VOLTAGE ** 2
91
+ noise_power = signal_power / (10 ** (snr_db / 10))
92
+ noise = noise * np.sqrt(noise_power) / np.std(noise)
93
+
94
+ return noise
95
+
96
+
97
+ # =============================================================================
98
+ # Load Pattern Models
99
+ # =============================================================================
100
+ def generate_rural_load_pattern(n_samples, season='summer', day_type='weekday'):
101
+ """
102
+ Generate realistic rural load pattern.
103
+
104
+ Rural characteristics:
105
+ - Morning peak: 6-8 AM (livestock feeding, irrigation pumps)
106
+ - Noon dip: 12-2 PM
107
+ - Evening peak: 6-9 PM (residential load)
108
+ - Night low: 11 PM - 5 AM
109
+
110
+ Seasonal variations:
111
+ - Summer: Higher evening load (AC), irrigation
112
+ - Winter: Higher morning/evening load (heating)
113
+ """
114
+ t = np.arange(n_samples)
115
+ hours = (t / 3600) % 24 # Hour of day
116
+
117
+ # Base daily pattern (normalized 0-1)
118
+ # Morning peak around 7 AM
119
+ morning_peak = 0.15 * np.exp(-((hours - 7) ** 2) / 2)
120
+ # Evening peak around 7 PM
121
+ evening_peak = 0.25 * np.exp(-((hours - 19) ** 2) / 3)
122
+ # Noon dip
123
+ noon_dip = -0.08 * np.exp(-((hours - 13) ** 2) / 2)
124
+ # Night base load
125
+ night_low = 0.05 * np.exp(-((hours - 3) ** 2) / 8)
126
+
127
+ # Combine patterns
128
+ base_pattern = 0.85 + morning_peak + evening_peak + noon_dip - night_low
129
+
130
+ # Seasonal adjustment
131
+ if season == 'summer':
132
+ # Higher evening load (cooling)
133
+ base_pattern += 0.1 * np.exp(-((hours - 15) ** 2) / 8)
134
+ # Irrigation pump cycles (random)
135
+ irrigation = 0.05 * (np.random.rand(n_samples) > 0.95).astype(float)
136
+ irrigation = gaussian_filter1d(irrigation, sigma=30)
137
+ base_pattern += irrigation
138
+ elif season == 'winter':
139
+ # Higher morning/evening heating load
140
+ base_pattern += 0.08 * np.exp(-((hours - 7) ** 2) / 2)
141
+ base_pattern += 0.12 * np.exp(-((hours - 19) ** 2) / 4)
142
+
143
+ # Weekend adjustment
144
+ if day_type == 'weekend':
145
+ # Shift morning peak later
146
+ base_pattern = np.roll(base_pattern, int(2 * 3600))
147
+ # Slightly lower overall
148
+ base_pattern *= 0.92
149
+
150
+ # Add slow random variations (weather, cloud cover effects on solar)
151
+ slow_variation = generate_pink_noise(n_samples, scale=0.02)
152
+ slow_variation = gaussian_filter1d(slow_variation, sigma=1000)
153
+ base_pattern += slow_variation
154
+
155
+ # Normalize to reasonable range
156
+ base_pattern = np.clip(base_pattern, 0.7, 1.15)
157
+
158
+ return base_pattern
159
+
160
+
161
+ # =============================================================================
162
+ # Three-Phase Voltage Generation
163
+ # =============================================================================
164
+ def generate_three_phase_voltage(n_samples, load_pattern, noise_level=2.0):
165
+ """
166
+ Generate realistic three-phase voltage with proper relationships.
167
+
168
+ Features:
169
+ - 120° phase separation (in phasor domain)
170
+ - Load-dependent voltage drop
171
+ - Natural slight unbalance
172
+ - Correlated noise between phases
173
+ """
174
+ t = np.arange(n_samples) / SAMPLING_RATE
175
+
176
+ # Voltage magnitude affected by load (voltage drop under load)
177
+ # Higher load -> lower voltage (simplified impedance model)
178
+ voltage_drop = 0.02 * (load_pattern - 1.0) # ~2% voltage regulation
179
+
180
+ # Base voltage magnitudes
181
+ V_base = NOMINAL_VOLTAGE * (1 - voltage_drop)
182
+
183
+ # Natural unbalance (random but persistent)
184
+ unbalance_a = np.random.uniform(-0.01, 0.01)
185
+ unbalance_b = np.random.uniform(-0.01, 0.01)
186
+ unbalance_c = -(unbalance_a + unbalance_b) * 0.5 # Partial compensation
187
+
188
+ # Slow unbalance drift
189
+ drift = generate_pink_noise(n_samples, scale=0.005)
190
+ drift = gaussian_filter1d(drift, sigma=5000)
191
+
192
+ Va = V_base * (1 + unbalance_a + drift)
193
+ Vb = V_base * (1 + unbalance_b + drift * 0.8)
194
+ Vc = V_base * (1 + unbalance_c - drift * 0.6)
195
+
196
+ # Add correlated and uncorrelated noise
197
+ common_noise = generate_measurement_noise(n_samples, snr_db=45)
198
+ Va += common_noise + generate_measurement_noise(n_samples, snr_db=50)
199
+ Vb += common_noise * 0.8 + generate_measurement_noise(n_samples, snr_db=50)
200
+ Vc += common_noise * 0.6 + generate_measurement_noise(n_samples, snr_db=50)
201
+
202
+ return Va, Vb, Vc
203
+
204
+
205
+ # =============================================================================
206
+ # Current and Power Generation
207
+ # =============================================================================
208
+ def generate_current(Va, Vb, Vc, load_pattern, base_current=15.0):
209
+ """Generate realistic current based on voltage and load."""
210
+ n_samples = len(Va)
211
+
212
+ # Current proportional to load and inversely to voltage
213
+ Ia = base_current * load_pattern * (NOMINAL_VOLTAGE / Va)
214
+ Ib = base_current * load_pattern * (NOMINAL_VOLTAGE / Vb)
215
+ Ic = base_current * load_pattern * (NOMINAL_VOLTAGE / Vc)
216
+
217
+ # Add load fluctuations
218
+ load_noise = generate_pink_noise(n_samples, scale=0.5)
219
+ load_noise = gaussian_filter1d(load_noise, sigma=10)
220
+
221
+ Ia += load_noise + np.random.normal(0, 0.3, n_samples)
222
+ Ib += load_noise * 0.9 + np.random.normal(0, 0.3, n_samples)
223
+ Ic += load_noise * 0.85 + np.random.normal(0, 0.3, n_samples)
224
+
225
+ # Ensure positive
226
+ Ia = np.maximum(Ia, 0.1)
227
+ Ib = np.maximum(Ib, 0.1)
228
+ Ic = np.maximum(Ic, 0.1)
229
+
230
+ return Ia, Ib, Ic
231
+
232
+
233
+ def generate_power_metrics(Va, Vb, Vc, Ia, Ib, Ic, power_factor_base=0.88):
234
+ """Generate power metrics with realistic relationships."""
235
+ n_samples = len(Va)
236
+
237
+ # Power factor varies with load
238
+ load_variation = (Ia + Ib + Ic) / (3 * 15.0) # Normalized load
239
+ pf_variation = 0.05 * (load_variation - 1.0) # PF drops slightly with load
240
+ PF = power_factor_base + pf_variation + np.random.normal(0, 0.02, n_samples)
241
+ PF = np.clip(PF, 0.7, 0.99)
242
+
243
+ # Active power (kW)
244
+ P = (Va * Ia + Vb * Ib + Vc * Ic) / 1000 * PF
245
+
246
+ # Reactive power (kVar)
247
+ Q = P * np.tan(np.arccos(PF))
248
+
249
+ # Apparent power (kVA)
250
+ S = np.sqrt(P**2 + Q**2)
251
+
252
+ return P, Q, S, PF
253
+
254
+
255
+ # =============================================================================
256
+ # Power Quality Metrics
257
+ # =============================================================================
258
+ def generate_harmonic_content(n_samples, base_thd=2.0):
259
+ """
260
+ Generate realistic harmonic content (THD).
261
+
262
+ Typical harmonic sources in rural areas:
263
+ - LED lighting: 3rd, 5th harmonics
264
+ - Motor drives: 5th, 7th harmonics
265
+ - Power electronics: Wide spectrum
266
+ """
267
+ # Base THD with slow variation
268
+ thd_base = base_thd + generate_pink_noise(n_samples, scale=0.5)
269
+ thd_base = gaussian_filter1d(thd_base, sigma=500)
270
+
271
+ # Occasional spikes (equipment switching)
272
+ spike_prob = 0.001
273
+ spikes = (np.random.rand(n_samples) < spike_prob).astype(float)
274
+ spikes = gaussian_filter1d(spikes, sigma=5) * 3
275
+
276
+ thd = thd_base + spikes + np.random.normal(0, 0.3, n_samples)
277
+ thd = np.clip(thd, 0.5, THD_LIMIT - 0.5) # Normal range
278
+
279
+ return thd
280
+
281
+
282
+ def calculate_unbalance(Va, Vb, Vc):
283
+ """Calculate voltage unbalance factor per IEC standards."""
284
+ V_avg = (Va + Vb + Vc) / 3
285
+ V_max_dev = np.maximum(
286
+ np.abs(Va - V_avg),
287
+ np.maximum(np.abs(Vb - V_avg), np.abs(Vc - V_avg))
288
+ )
289
+ return V_max_dev / (V_avg + 1e-8) * 100
290
+
291
+
292
+ def generate_frequency(n_samples, nominal=50.0):
293
+ """Generate realistic frequency variations."""
294
+ # Slow frequency drift (grid regulation)
295
+ drift = generate_pink_noise(n_samples, scale=0.02)
296
+ drift = gaussian_filter1d(drift, sigma=2000)
297
+
298
+ # Fast variations
299
+ fast = np.random.normal(0, 0.01, n_samples)
300
+
301
+ freq = nominal + drift + fast
302
+ return np.clip(freq, 49.5, 50.5)
303
+
304
+
305
+ # =============================================================================
306
+ # Anomaly Injection Functions (Realistic)
307
+ # =============================================================================
308
+ def inject_undervoltage_realistic(Va, Vb, Vc, start, duration, severity=0.12,
309
+ transition_time=10, affected_phases='all'):
310
+ """
311
+ Inject realistic undervoltage with gradual transitions.
312
+
313
+ Args:
314
+ severity: Voltage drop fraction (0.12 = 12% drop)
315
+ transition_time: Ramp time in samples
316
+ affected_phases: 'all', 'single', or 'two'
317
+ """
318
+ end = min(start + duration, len(Va))
319
+
320
+ # Create smooth transition envelope
321
+ envelope = np.ones(duration)
322
+
323
+ # Ramp down
324
+ ramp_down = np.linspace(1, 1 - severity, min(transition_time, duration // 4))
325
+ envelope[:len(ramp_down)] = ramp_down
326
+
327
+ # Ramp up (recovery)
328
+ ramp_up = np.linspace(1 - severity, 1, min(transition_time * 2, duration // 4))
329
+ envelope[-len(ramp_up):] = ramp_up
330
+
331
+ # Fill middle with sustained level + small variations
332
+ mid_start = len(ramp_down)
333
+ mid_end = len(envelope) - len(ramp_up)
334
+ if mid_end > mid_start:
335
+ mid_length = mid_end - mid_start
336
+ sustained = (1 - severity) + np.random.normal(0, severity * 0.1, mid_length)
337
+ envelope[mid_start:mid_end] = sustained
338
+
339
+ # Apply to phases
340
+ if affected_phases == 'all':
341
+ Va[start:end] *= envelope[:end-start]
342
+ Vb[start:end] *= envelope[:end-start]
343
+ Vc[start:end] *= envelope[:end-start]
344
+ elif affected_phases == 'single':
345
+ phase = np.random.randint(0, 3)
346
+ if phase == 0:
347
+ Va[start:end] *= envelope[:end-start]
348
+ elif phase == 1:
349
+ Vb[start:end] *= envelope[:end-start]
350
+ else:
351
+ Vc[start:end] *= envelope[:end-start]
352
+ else: # two phases
353
+ phases = np.random.choice([0, 1, 2], 2, replace=False)
354
+ for p in phases:
355
+ if p == 0:
356
+ Va[start:end] *= envelope[:end-start]
357
+ elif p == 1:
358
+ Vb[start:end] *= envelope[:end-start]
359
+ else:
360
+ Vc[start:end] *= envelope[:end-start]
361
+
362
+ return Va, Vb, Vc
363
+
364
+
365
+ def inject_overvoltage_realistic(Va, Vb, Vc, start, duration, severity=0.10,
366
+ transition_time=15):
367
+ """Inject realistic overvoltage with gradual transitions."""
368
+ end = min(start + duration, len(Va))
369
+
370
+ # Create smooth transition envelope
371
+ envelope = np.ones(duration)
372
+
373
+ # Gradual rise
374
+ ramp_up = np.linspace(1, 1 + severity, min(transition_time, duration // 4))
375
+ envelope[:len(ramp_up)] = ramp_up
376
+
377
+ # Gradual decline
378
+ ramp_down = np.linspace(1 + severity, 1, min(transition_time * 2, duration // 3))
379
+ envelope[-len(ramp_down):] = ramp_down
380
+
381
+ # Sustained level with fluctuations
382
+ mid_start = len(ramp_up)
383
+ mid_end = len(envelope) - len(ramp_down)
384
+ if mid_end > mid_start:
385
+ mid_length = mid_end - mid_start
386
+ sustained = (1 + severity) + np.random.normal(0, severity * 0.08, mid_length)
387
+ envelope[mid_start:mid_end] = sustained
388
+
389
+ # Apply to all phases
390
+ Va[start:end] *= envelope[:end-start]
391
+ Vb[start:end] *= envelope[:end-start]
392
+ Vc[start:end] *= envelope[:end-start]
393
+
394
+ return Va, Vb, Vc
395
+
396
+
397
+ def inject_voltage_sag_realistic(Va, Vb, Vc, start, duration, depth=0.25,
398
+ sag_type='three_phase'):
399
+ """
400
+ Inject realistic voltage sag based on IEC 61000-4-30.
401
+
402
+ Sag types:
403
+ - three_phase: All phases affected equally (fault on transmission)
404
+ - single_phase: One phase affected (single-phase fault)
405
+ - phase_to_phase: Two phases affected (line-to-line fault)
406
+ """
407
+ end = min(start + duration, len(Va))
408
+ actual_duration = end - start
409
+
410
+ # Characteristic sag shape: fast drop, slight recovery, fast restore
411
+ t = np.linspace(0, 1, actual_duration)
412
+
413
+ # Fast initial drop (10% of duration)
414
+ # Slight sag during sustained period
415
+ # Recovery with possible overshoot
416
+
417
+ drop_phase = int(actual_duration * 0.05)
418
+ sustain_phase = int(actual_duration * 0.8)
419
+ recovery_phase = actual_duration - drop_phase - sustain_phase
420
+
421
+ envelope = np.ones(actual_duration)
422
+
423
+ # Drop phase (exponential)
424
+ if drop_phase > 0:
425
+ envelope[:drop_phase] = 1 - depth * (1 - np.exp(-5 * t[:drop_phase] / t[drop_phase]))
426
+
427
+ # Sustain phase with point-on-wave variation
428
+ if sustain_phase > 0:
429
+ sustain_start = drop_phase
430
+ sustain_end = drop_phase + sustain_phase
431
+ base_level = 1 - depth
432
+ # Add realistic oscillation
433
+ osc = 0.02 * depth * np.sin(2 * np.pi * 3 * t[sustain_start:sustain_end])
434
+ envelope[sustain_start:sustain_end] = base_level + osc + np.random.normal(0, 0.01 * depth, sustain_phase)
435
+
436
+ # Recovery phase with possible overshoot
437
+ if recovery_phase > 0:
438
+ recovery_start = drop_phase + sustain_phase
439
+ t_recovery = np.linspace(0, 1, recovery_phase)
440
+ # Damped oscillation recovery
441
+ recovery = 1 + 0.03 * np.exp(-3 * t_recovery) * np.sin(10 * np.pi * t_recovery)
442
+ envelope[recovery_start:] = (1 - depth) + depth * (1 - np.exp(-5 * t_recovery)) * recovery[:len(envelope) - recovery_start]
443
+
444
+ # Apply based on sag type
445
+ if sag_type == 'three_phase':
446
+ Va[start:end] *= envelope
447
+ Vb[start:end] *= envelope
448
+ Vc[start:end] *= envelope
449
+ elif sag_type == 'single_phase':
450
+ phase = np.random.randint(0, 3)
451
+ if phase == 0:
452
+ Va[start:end] *= envelope
453
+ # Other phases see slight rise
454
+ Vb[start:end] *= (1 + 0.02 * depth)
455
+ Vc[start:end] *= (1 + 0.02 * depth)
456
+ elif phase == 1:
457
+ Vb[start:end] *= envelope
458
+ Va[start:end] *= (1 + 0.02 * depth)
459
+ Vc[start:end] *= (1 + 0.02 * depth)
460
+ else:
461
+ Vc[start:end] *= envelope
462
+ Va[start:end] *= (1 + 0.02 * depth)
463
+ Vb[start:end] *= (1 + 0.02 * depth)
464
+ else: # phase_to_phase
465
+ phases = np.random.choice([0, 1, 2], 2, replace=False)
466
+ for p in phases:
467
+ if p == 0:
468
+ Va[start:end] *= envelope
469
+ elif p == 1:
470
+ Vb[start:end] *= envelope
471
+ else:
472
+ Vc[start:end] *= envelope
473
+
474
+ return Va, Vb, Vc
475
+
476
+
477
+ def inject_harmonics_realistic(THD_Va, THD_Vb, THD_Vc, start, duration,
478
+ severity='moderate'):
479
+ """
480
+ Inject realistic harmonic distortion.
481
+
482
+ Severity levels:
483
+ - mild: THD 5-7%
484
+ - moderate: THD 7-10%
485
+ - severe: THD 10-15%
486
+ """
487
+ end = min(start + duration, len(THD_Va))
488
+
489
+ severity_ranges = {
490
+ 'mild': (5, 7),
491
+ 'moderate': (7, 10),
492
+ 'severe': (10, 15)
493
+ }
494
+ thd_min, thd_max = severity_ranges.get(severity, (7, 10))
495
+
496
+ # Gradual build-up and decay
497
+ actual_duration = end - start
498
+ t = np.linspace(0, np.pi, actual_duration)
499
+ envelope = np.sin(t) # Smooth rise and fall
500
+
501
+ # Base elevated THD
502
+ base_thd = np.random.uniform(thd_min, thd_max)
503
+
504
+ # Add realistic fluctuations
505
+ for i, (thd, phase_offset) in enumerate([(THD_Va, 0), (THD_Vb, 0.1), (THD_Vc, 0.2)]):
506
+ thd_increase = base_thd * envelope + np.random.normal(0, 0.5, actual_duration)
507
+ thd_increase = np.maximum(thd_increase, 0)
508
+
509
+ # Different phases can have different THD levels
510
+ phase_factor = 1 + np.random.uniform(-0.15, 0.15)
511
+ thd[start:end] = np.maximum(thd[start:end], thd_increase * phase_factor)
512
+
513
+ return THD_Va, THD_Vb, THD_Vc
514
+
515
+
516
+ def inject_unbalance_realistic(Va, Vb, Vc, start, duration, unbalance_percent=6.0):
517
+ """
518
+ Inject realistic three-phase unbalance.
519
+
520
+ Causes in rural areas:
521
+ - Single-phase loads
522
+ - Broken neutral
523
+ - Unequal transformer tap settings
524
+ """
525
+ end = min(start + duration, len(Va))
526
+ actual_duration = end - start
527
+
528
+ # Gradual development of unbalance
529
+ t = np.linspace(0, 1, actual_duration)
530
+ envelope = 1 - np.exp(-3 * t) # Gradual onset
531
+
532
+ # Recovery envelope
533
+ recovery_start = int(actual_duration * 0.8)
534
+ if recovery_start < actual_duration:
535
+ t_recovery = np.linspace(0, 1, actual_duration - recovery_start)
536
+ envelope[recovery_start:] *= np.exp(-2 * t_recovery)
537
+
538
+ # Unbalance pattern: one phase drops, one rises, one stays
539
+ unbalance_factor = unbalance_percent / 100
540
+ phase_effects = np.random.permutation([
541
+ -unbalance_factor, # Drop
542
+ unbalance_factor * 0.5, # Rise
543
+ unbalance_factor * 0.3 # Slight change
544
+ ])
545
+
546
+ Va[start:end] *= (1 + phase_effects[0] * envelope)
547
+ Vb[start:end] *= (1 + phase_effects[1] * envelope)
548
+ Vc[start:end] *= (1 + phase_effects[2] * envelope)
549
+
550
+ return Va, Vb, Vc
551
+
552
+
553
+ def inject_transient_realistic(Va, Vb, Vc, start, transient_type='motor_start'):
554
+ """
555
+ Inject realistic transient events.
556
+
557
+ Types:
558
+ - motor_start: Inrush current causing voltage dip
559
+ - capacitor_switch: Oscillatory transient
560
+ - load_switch: Step change with ringing
561
+ """
562
+ n_samples = len(Va)
563
+
564
+ if transient_type == 'motor_start':
565
+ # Motor starting: 3-6x inrush, voltage dips 10-20%
566
+ duration = np.random.randint(30, 100) # 30-100 seconds
567
+ end = min(start + duration, n_samples)
568
+ actual_duration = end - start
569
+
570
+ t = np.linspace(0, 1, actual_duration)
571
+ # Initial deep dip, gradual recovery
572
+ dip = 0.15 * np.exp(-3 * t) + 0.03 * np.exp(-0.5 * t) * np.sin(10 * np.pi * t)
573
+
574
+ Va[start:end] *= (1 - dip)
575
+ Vb[start:end] *= (1 - dip)
576
+ Vc[start:end] *= (1 - dip)
577
+
578
+ elif transient_type == 'capacitor_switch':
579
+ # Capacitor switching: oscillatory transient
580
+ duration = np.random.randint(5, 20)
581
+ end = min(start + duration, n_samples)
582
+ actual_duration = end - start
583
+
584
+ t = np.linspace(0, 1, actual_duration)
585
+ # Damped oscillation
586
+ osc = 0.3 * np.exp(-10 * t) * np.sin(100 * np.pi * t)
587
+
588
+ # Affects all phases but with phase shifts
589
+ Va[start:end] *= (1 + osc)
590
+ Vb[start:end] *= (1 + 0.8 * osc)
591
+ Vc[start:end] *= (1 + 0.6 * osc)
592
+
593
+ elif transient_type == 'load_switch':
594
+ # Load switching: step with ringing
595
+ duration = np.random.randint(10, 30)
596
+ end = min(start + duration, n_samples)
597
+ actual_duration = end - start
598
+
599
+ t = np.linspace(0, 1, actual_duration)
600
+ step = np.random.choice([-1, 1]) * 0.05 # Up or down
601
+ ringing = step * (1 + 0.3 * np.exp(-5 * t) * np.sin(20 * np.pi * t))
602
+
603
+ Va[start:end] *= (1 + ringing)
604
+ Vb[start:end] *= (1 + ringing * 0.9)
605
+ Vc[start:end] *= (1 + ringing * 0.85)
606
+
607
+ return Va, Vb, Vc
608
+
609
+
610
+ def inject_flicker_realistic(Va, Vb, Vc, start, duration, flicker_frequency=8.0):
611
+ """
612
+ Inject voltage flicker (cyclic voltage variation).
613
+
614
+ Common causes: Arc furnaces, welding, compressors
615
+ Flicker frequency typically 0.5-25 Hz, most sensitive at 8.8 Hz
616
+ """
617
+ end = min(start + duration, len(Va))
618
+ actual_duration = end - start
619
+
620
+ t = np.arange(actual_duration) / SAMPLING_RATE
621
+
622
+ # Modulating signal (flicker)
623
+ flicker_depth = np.random.uniform(0.02, 0.05) # 2-5% modulation
624
+
625
+ # Envelope for gradual onset/offset
626
+ envelope = np.ones(actual_duration)
627
+ ramp = min(actual_duration // 4, 50)
628
+ envelope[:ramp] = np.linspace(0, 1, ramp)
629
+ envelope[-ramp:] = np.linspace(1, 0, ramp)
630
+
631
+ modulation = 1 + flicker_depth * envelope * np.sin(2 * np.pi * flicker_frequency * t)
632
+
633
+ Va[start:end] *= modulation
634
+ Vb[start:end] *= modulation
635
+ Vc[start:end] *= modulation
636
+
637
+ return Va, Vb, Vc
638
+
639
+
640
+ # =============================================================================
641
+ # Compound Anomaly Generation
642
+ # =============================================================================
643
+ def inject_compound_anomaly(Va, Vb, Vc, THD_Va, THD_Vb, THD_Vc, start, duration):
644
+ """
645
+ Inject compound anomaly (multiple issues occurring together).
646
+
647
+ Common combinations in rural grids:
648
+ 1. Undervoltage + Harmonics (overloaded transformer)
649
+ 2. Unbalance + Voltage sag (single-phase fault)
650
+ 3. Flicker + Harmonics (arc welding)
651
+ """
652
+ end = min(start + duration, len(Va))
653
+
654
+ combination = np.random.choice(['uv_harmonic', 'unbal_sag', 'flicker_harmonic'])
655
+
656
+ if combination == 'uv_harmonic':
657
+ # Overloaded transformer scenario
658
+ Va, Vb, Vc = inject_undervoltage_realistic(
659
+ Va, Vb, Vc, start, duration, severity=0.08, transition_time=20
660
+ )
661
+ THD_Va, THD_Vb, THD_Vc = inject_harmonics_realistic(
662
+ THD_Va, THD_Vb, THD_Vc, start, duration, severity='moderate'
663
+ )
664
+
665
+ elif combination == 'unbal_sag':
666
+ # Single-phase fault scenario
667
+ Va, Vb, Vc = inject_voltage_sag_realistic(
668
+ Va, Vb, Vc, start, min(duration // 3, 50), depth=0.2, sag_type='single_phase'
669
+ )
670
+ Va, Vb, Vc = inject_unbalance_realistic(
671
+ Va, Vb, Vc, start + duration // 3, duration * 2 // 3, unbalance_percent=5.0
672
+ )
673
+
674
+ else: # flicker_harmonic
675
+ # Arc welding scenario
676
+ Va, Vb, Vc = inject_flicker_realistic(Va, Vb, Vc, start, duration)
677
+ THD_Va, THD_Vb, THD_Vc = inject_harmonics_realistic(
678
+ THD_Va, THD_Vb, THD_Vc, start, duration, severity='mild'
679
+ )
680
+
681
+ return Va, Vb, Vc, THD_Va, THD_Vb, THD_Vc
682
+
683
+
684
+ # =============================================================================
685
+ # Main Dataset Generation
686
+ # =============================================================================
687
+ def generate_realistic_dataset(n_samples, anomaly_ratio=0.0, seed=42,
688
+ season='mixed', include_compound=True):
689
+ """
690
+ Generate complete realistic dataset.
691
+
692
+ Args:
693
+ n_samples: Number of samples
694
+ anomaly_ratio: Fraction of anomalous samples (0-1)
695
+ seed: Random seed
696
+ season: 'summer', 'winter', or 'mixed'
697
+ include_compound: Include compound anomalies
698
+ """
699
+ np.random.seed(seed)
700
+
701
+ # Determine season distribution
702
+ if season == 'mixed':
703
+ # Assign random seasons to different parts
704
+ n_summer = n_samples // 2
705
+ n_winter = n_samples - n_summer
706
+ load_pattern_summer = generate_rural_load_pattern(n_summer, 'summer', 'weekday')
707
+ load_pattern_winter = generate_rural_load_pattern(n_winter, 'winter', 'weekday')
708
+ load_pattern = np.concatenate([load_pattern_summer, load_pattern_winter])
709
+ else:
710
+ load_pattern = generate_rural_load_pattern(n_samples, season, 'weekday')
711
+
712
+ # Generate base voltages
713
+ Va, Vb, Vc = generate_three_phase_voltage(n_samples, load_pattern)
714
+
715
+ # Generate currents
716
+ Ia, Ib, Ic = generate_current(Va, Vb, Vc, load_pattern)
717
+
718
+ # Generate power metrics
719
+ P, Q, S, PF = generate_power_metrics(Va, Vb, Vc, Ia, Ib, Ic)
720
+
721
+ # Generate quality metrics
722
+ THD_Va = generate_harmonic_content(n_samples)
723
+ THD_Vb = generate_harmonic_content(n_samples)
724
+ THD_Vc = generate_harmonic_content(n_samples)
725
+ Freq = generate_frequency(n_samples)
726
+
727
+ # Initialize labels
728
+ labels = np.zeros(n_samples, dtype=int)
729
+
730
+ # Inject anomalies
731
+ if anomaly_ratio > 0:
732
+ n_anomaly_samples = int(n_samples * anomaly_ratio)
733
+
734
+ # Anomaly types with realistic probabilities
735
+ anomaly_config = [
736
+ ('undervoltage', 0.20, lambda s, d: inject_undervoltage_realistic(Va, Vb, Vc, s, d)),
737
+ ('overvoltage', 0.15, lambda s, d: inject_overvoltage_realistic(Va, Vb, Vc, s, d)),
738
+ ('sag_3phase', 0.15, lambda s, d: inject_voltage_sag_realistic(Va, Vb, Vc, s, d, sag_type='three_phase')),
739
+ ('sag_1phase', 0.10, lambda s, d: inject_voltage_sag_realistic(Va, Vb, Vc, s, d, sag_type='single_phase')),
740
+ ('harmonics', 0.15, lambda s, d: (Va, Vb, Vc, *inject_harmonics_realistic(THD_Va, THD_Vb, THD_Vc, s, d))),
741
+ ('unbalance', 0.10, lambda s, d: inject_unbalance_realistic(Va, Vb, Vc, s, d)),
742
+ ('transient', 0.05, lambda s, d: inject_transient_realistic(Va, Vb, Vc, s, 'motor_start')),
743
+ ('flicker', 0.05, lambda s, d: inject_flicker_realistic(Va, Vb, Vc, s, d)),
744
+ ('compound', 0.05, lambda s, d: inject_compound_anomaly(Va, Vb, Vc, THD_Va, THD_Vb, THD_Vc, s, d)),
745
+ ]
746
+
747
+ if not include_compound:
748
+ # Remove compound and redistribute
749
+ anomaly_config = anomaly_config[:-1]
750
+ total_prob = sum(c[1] for c in anomaly_config)
751
+ anomaly_config = [(n, p/total_prob, f) for n, p, f in anomaly_config]
752
+
753
+ # Calculate number of events per type
754
+ events_per_type = []
755
+ remaining_samples = n_anomaly_samples
756
+
757
+ for name, prob, _ in anomaly_config:
758
+ n_events = int(n_anomaly_samples * prob / 50) # ~50 samples per event on average
759
+ n_events = max(1, n_events)
760
+ events_per_type.append(n_events)
761
+
762
+ # Generate anomalies
763
+ anomaly_type_id = 1
764
+ current_pos = int(n_samples * 0.05) # Start after initial period
765
+
766
+ for (name, prob, inject_func), n_events in zip(anomaly_config, events_per_type):
767
+ for _ in range(n_events):
768
+ if current_pos >= n_samples - 200:
769
+ break
770
+
771
+ # Variable duration based on anomaly type
772
+ if name in ['transient', 'flicker']:
773
+ duration = np.random.randint(10, 60)
774
+ elif name == 'sag_3phase' or name == 'sag_1phase':
775
+ duration = np.random.randint(5, 50)
776
+ else:
777
+ duration = np.random.randint(30, 150)
778
+
779
+ end = min(current_pos + duration, n_samples)
780
+
781
+ # Inject anomaly
782
+ result = inject_func(current_pos, duration)
783
+
784
+ # Update arrays if needed (for harmonics and compound)
785
+ if name == 'harmonics':
786
+ _, _, _, THD_Va, THD_Vb, THD_Vc = result[0], result[1], result[2], result[3], result[4], result[5] if len(result) > 5 else (THD_Va, THD_Vb, THD_Vc)
787
+ elif name == 'compound':
788
+ Va, Vb, Vc, THD_Va, THD_Vb, THD_Vc = result
789
+ else:
790
+ Va, Vb, Vc = result
791
+
792
+ # Update labels
793
+ labels[current_pos:end] = anomaly_type_id
794
+
795
+ # Gap between anomalies (random, ensuring some normal periods)
796
+ gap = np.random.randint(100, 500)
797
+ current_pos = end + gap
798
+
799
+ anomaly_type_id += 1
800
+
801
+ # Recalculate dependent metrics
802
+ Ia, Ib, Ic = generate_current(Va, Vb, Vc, load_pattern)
803
+ P, Q, S, PF = generate_power_metrics(Va, Vb, Vc, Ia, Ib, Ic)
804
+
805
+ # Calculate final unbalance
806
+ V_unbalance = calculate_unbalance(Va, Vb, Vc)
807
+ I_unbalance = calculate_unbalance(Ia, Ib, Ic)
808
+
809
+ # Generate timestamps
810
+ start_time = datetime(2024, 1, 1, 0, 0, 0)
811
+ timestamps = [start_time + timedelta(seconds=i) for i in range(n_samples)]
812
+
813
+ # Create DataFrame
814
+ df = pd.DataFrame({
815
+ 'timestamp': timestamps,
816
+ 'Va': Va,
817
+ 'Vb': Vb,
818
+ 'Vc': Vc,
819
+ 'Ia': Ia,
820
+ 'Ib': Ib,
821
+ 'Ic': Ic,
822
+ 'P': P,
823
+ 'Q': Q,
824
+ 'S': S,
825
+ 'PF': PF,
826
+ 'THD_Va': THD_Va,
827
+ 'THD_Vb': THD_Vb,
828
+ 'THD_Vc': THD_Vc,
829
+ 'Freq': Freq,
830
+ 'V_unbalance': V_unbalance,
831
+ 'I_unbalance': I_unbalance,
832
+ })
833
+
834
+ # Binary labels
835
+ binary_labels = (labels > 0).astype(int)
836
+
837
+ # Anomaly type names
838
+ anomaly_names = {
839
+ 0: 'Normal',
840
+ 1: 'Undervoltage',
841
+ 2: 'Overvoltage',
842
+ 3: 'Voltage_Sag_3Phase',
843
+ 4: 'Voltage_Sag_1Phase',
844
+ 5: 'Harmonics',
845
+ 6: 'Unbalance',
846
+ 7: 'Transient',
847
+ 8: 'Flicker',
848
+ 9: 'Compound'
849
+ }
850
+
851
+ return df, labels, binary_labels, anomaly_names
852
+
853
+
854
+ def main():
855
+ parser = argparse.ArgumentParser(description='Generate realistic voltage data')
856
+ parser.add_argument('--train_samples', type=int, default=50000,
857
+ help='Number of training samples')
858
+ parser.add_argument('--test_samples', type=int, default=10000,
859
+ help='Number of test samples')
860
+ parser.add_argument('--anomaly_ratio', type=float, default=0.12,
861
+ help='Ratio of anomalies in test data')
862
+ parser.add_argument('--output_dir', type=str, default='.',
863
+ help='Output directory')
864
+ parser.add_argument('--season', type=str, default='mixed',
865
+ choices=['summer', 'winter', 'mixed'],
866
+ help='Season for load pattern')
867
+ args = parser.parse_args()
868
+
869
+ print("=" * 60)
870
+ print("Realistic Rural Voltage Data Generator V2.0")
871
+ print("=" * 60)
872
+
873
+ # Generate training data (normal only)
874
+ print(f"\n[1/2] Generating training data ({args.train_samples} samples, normal only)...")
875
+ train_df, _, _, _ = generate_realistic_dataset(
876
+ args.train_samples, anomaly_ratio=0.0, seed=42, season=args.season
877
+ )
878
+ train_df.to_csv(os.path.join(args.output_dir, 'train.csv'), index=False)
879
+ print(f" Saved to train.csv")
880
+
881
+ # Generate test data (with anomalies)
882
+ print(f"\n[2/2] Generating test data ({args.test_samples} samples, {args.anomaly_ratio*100:.0f}% anomalies)...")
883
+ test_df, labels, binary_labels, anomaly_names = generate_realistic_dataset(
884
+ args.test_samples, anomaly_ratio=args.anomaly_ratio, seed=123, season=args.season
885
+ )
886
+ test_df.to_csv(os.path.join(args.output_dir, 'test.csv'), index=False)
887
+ print(f" Saved to test.csv")
888
+
889
+ # Save labels
890
+ label_df = pd.DataFrame({
891
+ 'timestamp': test_df['timestamp'],
892
+ 'label': binary_labels,
893
+ 'anomaly_type': labels,
894
+ 'anomaly_name': [anomaly_names.get(l, 'Unknown') for l in labels]
895
+ })
896
+ label_df.to_csv(os.path.join(args.output_dir, 'test_label.csv'), index=False)
897
+ print(f" Saved to test_label.csv")
898
+
899
+ # Print statistics
900
+ print("\n" + "=" * 60)
901
+ print("Dataset Statistics")
902
+ print("=" * 60)
903
+ print(f" Training samples: {len(train_df):,}")
904
+ print(f" Test samples: {len(test_df):,}")
905
+ print(f" Anomaly ratio: {np.mean(binary_labels)*100:.2f}%")
906
+ print(f"\n Anomaly type distribution:")
907
+ for i in range(10):
908
+ count = np.sum(labels == i)
909
+ if count > 0:
910
+ pct = count / len(labels) * 100
911
+ print(f" [{i}] {anomaly_names.get(i, 'Unknown'):20s}: {count:5d} ({pct:5.1f}%)")
912
+
913
+ # Voltage statistics
914
+ print(f"\n Voltage statistics (test set):")
915
+ print(f" Va: min={test_df['Va'].min():.1f}V, max={test_df['Va'].max():.1f}V, mean={test_df['Va'].mean():.1f}V")
916
+ print(f" Vb: min={test_df['Vb'].min():.1f}V, max={test_df['Vb'].max():.1f}V, mean={test_df['Vb'].mean():.1f}V")
917
+ print(f" Vc: min={test_df['Vc'].min():.1f}V, max={test_df['Vc'].max():.1f}V, mean={test_df['Vc'].mean():.1f}V")
918
+
919
+ print("\n" + "=" * 60)
920
+ print("Generation complete!")
921
+ print("=" * 60)
922
+
923
+
924
+ if __name__ == '__main__':
925
+ main()
RuralVoltage/realistic_v2/test.csv ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:e794b7cf8e704d36702e110567c15c24aed64e4d62b7d50e3fa234ba026c265e
3
+ size 2468175
RuralVoltage/realistic_v2/test_label.csv ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:e7846cbf4a32bc0c5d071e0307ca1c1f3d9b17664abfca294291551e9ba72f31
3
+ size 317399
RuralVoltage/realistic_v2/train.csv ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:8b3e8a54f7dc01e0e900a50b837a73e2e7897e7c52424fdcc5a74dad7d538da1
3
+ size 12215221