metrology_insight 0.1.0

Embedded-first electrical metrology DSP library in Rust. Pre-compliance implementation of measurement algorithms derived from IEC 61000-4-30:2021 Class S and IEC 62053-21, fully no_std + alloc compatible.
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
//! Per-phase accuracy test harness and test point definitions (IEC 62053-21).
//!
// Copyright © 2026 Francisco Arcos.
// SPDX-License-Identifier: Apache-2.0

use crate::{
    CalibrationFactors, MetrologyInsight, MetrologyInsightConfig, PhaseConfig, PllConfig,
    SignalConfig, FREQ_NOMINAL_50, FREQ_NOMINAL_60, MAX_SIGNAL_SAMPLES,
};

/// Per-phase test configuration for polyphase accuracy tests.
#[derive(Debug, Clone, Copy)]
pub struct PhaseTestPoint {
    pub v_rms: f32,
    pub i_rms: f32,
    pub pf: f32,
}

/// Result of an accuracy test run.
pub struct AccuracyTestResult {
    pub v_rms: f32,
    pub i_rms: f32,
    pub pf: f32,
    pub freq: f32,
    pub cycles: u32,
    pub energy_ref_wh: f64,
    pub energy_meas_wh: f64,
    pub error_pct: f64,
}

/// Result of a polyphase accuracy test run.
pub struct PolyphaseTestResult {
    pub phases: [PhaseTestPoint; 3],
    pub freq: f32,
    pub cycles: u32,
    pub energy_ref_wh: f64,
    pub energy_meas_wh: f64,
    pub error_pct: f64,
}

/// Builds a test configuration derived from the sampling rate and signal frequency.
///
/// # Arguments
///
/// * `fs` - Sampling rate.
/// * `freq` - Signal frequency, used to select the nominal frequency and per-cycle settings.
///
/// # Returns
///
/// A fully populated `MetrologyInsightConfig` for accuracy testing.
fn make_test_config(fs: f32, freq: f32) -> MetrologyInsightConfig {
    let nominal = if (freq - FREQ_NOMINAL_50).abs() < 0.1 {
        FREQ_NOMINAL_50
    } else {
        FREQ_NOMINAL_60
    };
    MetrologyInsightConfig {
        avg_sec: (fs / freq).recip(),
        adc_samples_seconds: fs,
        adc_samples_per_cycle: (fs / freq) as f64,
        nominal_freq: nominal,
        min_amplitude_voltage: 1.0,
        min_amplitude_current: 0.0001,
        calibration: CalibrationFactors {
            v_gain: 1.0,
            i_gain: [1.0, 1.0, 1.0],
            phase_offset: [0.0, 0.0, 0.0],
            phase_delay_us: [0.0, 0.0, 0.0],
            temp_coeff: 0.0,
            v_lsb_to_phys: 1.0,
            i_lsb_to_phys: 1.0,
        },
        pll: PllConfig {
            kp: 0.002,
            ki: 0.00005,
            freq_min: nominal * 0.95,
            freq_max: nominal * 1.05,
            lock_threshold: 0.5,
            norm_threshold: 1.0,
            integrator_clamp: 0.1,
            lock_ema_alpha: 0.1,
        },
        phase: PhaseConfig {
            direction_deadband_deg: 10.0,
        },
        signal: SignalConfig {
            half_cycle_min_factor: 0.4,
            rms_consistency_min_guard: 1e-6,
            pll_error_accum_threshold: 0.5,
            sync_consistency_threshold: 0.001,
        },
        ..MetrologyInsightConfig::default()
    }
}

/// Copies one cycle of V and I samples into the insight's phase buffer.
///
/// # Arguments
///
/// * `insight` - The metrology instance to fill.
/// * `v_samples` - Voltage samples for the cycle.
/// * `i_samples` - Current samples for the cycle.
/// * `phase_idx` - Target phase index.
fn push_cycle(
    insight: &mut MetrologyInsight,
    v_samples: &[f32],
    i_samples: &[f32],
    phase_idx: usize,
) {
    let n = v_samples.len().min(i_samples.len()).min(MAX_SIGNAL_SAMPLES);
    let phase = &mut insight.socket.phases[phase_idx];
    phase.voltage.real_wave[..n].copy_from_slice(&v_samples[..n]);
    phase.voltage.real_wave_len = n;
    phase.current.real_wave[..n].copy_from_slice(&i_samples[..n]);
    phase.current.real_wave_len = n;
}

/// Clears the buffered V/I samples for a given phase.
///
/// # Arguments
///
/// * `insight` - The metrology instance to clear.
/// * `phase_idx` - Phase index to clear.
fn clear_cycle(insight: &mut MetrologyInsight, phase_idx: usize) {
    insight.socket.phases[phase_idx].voltage.clear_samples();
    insight.socket.phases[phase_idx].current.clear_samples();
}

/// Computes the net active energy in Wh from the insight's accumulated metrics.
///
/// # Arguments
///
/// * `insight` - Metrology instance with updated energy metrics.
///
/// # Returns
///
/// The imported-minus-exported active energy in watt-hours.
fn energy_wh(insight: &MetrologyInsight) -> f64 {
    // imported() / exported() return kWh; convert to Wh
    (insight.socket.energy_metrics.active.imported()
        - insight.socket.energy_metrics.active.exported())
        * 1000.0
}

/// Generates one cycle of pure-sine voltage and current waveforms at the given power factor.
///
/// # Arguments
///
/// * `v_rms` - RMS voltage of the cycle.
/// * `i_rms` - RMS current of the cycle.
/// * `pf` - Power factor (cosine of the phase angle between V and I).
/// * `freq` - Fundamental frequency of the cycle.
/// * `fs` - Sampling rate.
///
/// # Returns
///
/// A tuple of the voltage and current sample vectors, each one full cycle long.
pub fn generate_cycle(
    v_rms: f32,
    i_rms: f32,
    pf: f32,
    freq: f32,
    fs: f32,
) -> (alloc::vec::Vec<f32>, alloc::vec::Vec<f32>) {
    let n = crate::math::round(fs / freq) as usize;
    let v_peak = v_rms * core::f32::consts::SQRT_2;
    let i_peak = i_rms * core::f32::consts::SQRT_2;
    let phi = crate::math::acos(pf);
    use core::f32::consts::PI;
    let v: alloc::vec::Vec<f32> = (0..n)
        .map(|i| v_peak * crate::math::sin(2.0 * PI * freq / fs * i as f32))
        .collect();
    let i: alloc::vec::Vec<f32> = (0..n)
        .map(|i| i_peak * crate::math::sin(2.0 * PI * freq / fs * i as f32 - phi))
        .collect();
    (v, i)
}

/// Harmonic content per IEC 62053-21 §9.4.4 typical test:
/// 3rd = 20 %, 5th = 10 %, 7th = 5 % of fundamental.
const HARMONIC_AMPS: &[(u32, f32)] = &[(3, 0.20), (5, 0.10), (7, 0.05)];

/// Generates one cycle of V (pure sine) and I (fundamental + harmonics) at PF=1.
///
/// # Arguments
///
/// * `v_rms` - RMS voltage of the cycle.
/// * `i_rms` - RMS current of the cycle.
/// * `freq` - Fundamental frequency.
/// * `fs` - Sampling rate.
///
/// # Returns
///
/// A tuple of the voltage and current sample vectors, each one full cycle long.
pub fn generate_cycle_with_harmonics(
    v_rms: f32,
    i_rms: f32,
    freq: f32,
    fs: f32,
) -> (alloc::vec::Vec<f32>, alloc::vec::Vec<f32>) {
    let n = crate::math::round(fs / freq) as usize;
    let v_peak = v_rms * core::f32::consts::SQRT_2;
    let i_peak = i_rms * core::f32::consts::SQRT_2;
    use core::f32::consts::PI;
    let v: alloc::vec::Vec<f32> = (0..n)
        .map(|i| v_peak * crate::math::sin(2.0 * PI * freq / fs * i as f32))
        .collect();
    let i: alloc::vec::Vec<f32> = (0..n)
        .map(|i| {
            let t = 2.0 * PI * freq / fs * i as f32;
            let fund = i_peak * crate::math::sin(t);
            let harm: f32 = HARMONIC_AMPS
                .iter()
                .map(|&(h, a)| i_peak * a * crate::math::sin(h as f32 * t))
                .sum();
            fund + harm
        })
        .collect();
    (v, i)
}

/// Generates one cycle with half-wave rectified current (DC component test).
///
/// # Arguments
///
/// * `v_rms` - RMS voltage of the cycle.
/// * `i_rms` - RMS current of the cycle.
/// * `pf` - Power factor (cosine of the phase angle between V and I).
/// * `freq` - Fundamental frequency.
/// * `fs` - Sampling rate.
///
/// # Returns
///
/// A tuple of the voltage and current sample vectors, with current zeroed on negative half-cycles.
pub fn generate_half_wave_cycle(
    v_rms: f32,
    i_rms: f32,
    pf: f32,
    freq: f32,
    fs: f32,
) -> (alloc::vec::Vec<f32>, alloc::vec::Vec<f32>) {
    let n = crate::math::round(fs / freq) as usize;
    let v_peak = v_rms * core::f32::consts::SQRT_2;
    let i_peak = i_rms * core::f32::consts::SQRT_2;
    let phi = crate::math::acos(pf);
    use core::f32::consts::PI;
    let v: alloc::vec::Vec<f32> = (0..n)
        .map(|i| v_peak * crate::math::sin(2.0 * PI * freq / fs * i as f32))
        .collect();
    let i: alloc::vec::Vec<f32> = (0..n)
        .map(|i| {
            let val = i_peak * crate::math::sin(2.0 * PI * freq / fs * i as f32 - phi);
            val.max(0.0)
        })
        .collect();
    (v, i)
}

/// Runs a polyphase accuracy test over three phases and returns the measured vs. reference error.
///
/// # Arguments
///
/// * `phases` - Per-phase test points (V RMS, I RMS, PF).
/// * `freq` - Nominal signal frequency.
/// * `cycles` - Number of cycles to integrate.
///
/// # Returns
///
/// The polyphase test result with reference/measured energy and percent error.
pub fn run_polyphase_accuracy_test(
    phases: [PhaseTestPoint; 3],
    freq: f32,
    cycles: u32,
) -> PolyphaseTestResult {
    let fs = 8000.0;
    let mut cfg = make_test_config(fs, freq);
    cfg.standard_values.un_v = phases[0].v_rms;
    cfg.standard_values.in_a = phases[0].i_rms;
    cfg.standard_values.fn_hz = freq;

    let mut insight = MetrologyInsight::new(cfg);

    let dt_s = 1.0 / freq;
    let time_s = dt_s as f64 * cycles as f64;

    for _ in 0..cycles {
        for (p, ph) in phases.iter().enumerate() {
            let (v, i) = generate_cycle(ph.v_rms, ph.i_rms, ph.pf, freq, fs);
            push_cycle(&mut insight, &v, &i, p);
        }
        insight.process_and_update_metrics(3);
        for p in 0..3 {
            clear_cycle(&mut insight, p);
        }
    }

    let energy_meas_wh = energy_wh(&insight);

    let energy_ref_wh: f64 = phases
        .iter()
        .map(|ph| (ph.v_rms as f64) * (ph.i_rms as f64) * (ph.pf as f64) * time_s / 3600.0)
        .sum();

    let error_pct = if energy_ref_wh.abs() > 1e-12 {
        (energy_meas_wh - energy_ref_wh) / energy_ref_wh * 100.0
    } else {
        0.0
    };

    PolyphaseTestResult {
        phases,
        freq,
        cycles,
        energy_ref_wh,
        energy_meas_wh,
        error_pct,
    }
}

/// Runs a single-phase accuracy test and returns the measured vs. reference error.
///
/// # Arguments
///
/// * `v_rms` - RMS voltage.
/// * `i_rms` - RMS current.
/// * `pf` - Power factor.
/// * `freq` - Nominal signal frequency.
/// * `cycles` - Number of cycles to integrate.
///
/// # Returns
///
/// The accuracy test result with reference/measured energy and percent error.
pub fn run_accuracy_test(
    v_rms: f32,
    i_rms: f32,
    pf: f32,
    freq: f32,
    cycles: u32,
) -> AccuracyTestResult {
    let fs = 8000.0;
    let mut insight = make_test_config(fs, freq);
    insight.standard_values.un_v = v_rms;
    insight.standard_values.in_a = i_rms;
    insight.standard_values.fn_hz = freq;

    let mut insight = MetrologyInsight::new(insight);

    let dt_s = 1.0 / freq;
    let time_s = dt_s as f64 * cycles as f64;

    for _ in 0..cycles {
        let (v, i) = generate_cycle(v_rms, i_rms, pf, freq, fs);
        for p in 0..insight.active_phases {
            push_cycle(&mut insight, &v, &i, p);
        }
        insight.process_and_update_metrics(insight.active_phases);
        for p in 0..insight.active_phases {
            clear_cycle(&mut insight, p);
        }
    }

    let energy_meas_wh = energy_wh(&insight);
    let energy_ref_wh = (v_rms as f64) * (i_rms as f64) * (pf as f64) * time_s / 3600.0;

    let error_pct = if energy_ref_wh.abs() > 1e-12 {
        (energy_meas_wh - energy_ref_wh) / energy_ref_wh * 100.0
    } else {
        0.0
    };

    AccuracyTestResult {
        v_rms,
        i_rms,
        pf,
        freq,
        cycles,
        energy_ref_wh,
        energy_meas_wh,
        error_pct,
    }
}

#[cfg(test)]
mod tests {
    use super::*;

    /// Checks that the polyphase accuracy error is below 1 % for a balanced load.
    #[test]
    fn test_polyphase_balanced() {
        let ph = PhaseTestPoint {
            v_rms: 230.0,
            i_rms: 5.0,
            pf: 1.0,
        };
        let r = run_polyphase_accuracy_test([ph, ph, ph], 50.0, 100);
        assert!(
            r.error_pct.abs() < 1.0,
            "Balanced 3-phase error: {:.4}%",
            r.error_pct
        );
    }

    /// Checks the polyphase accuracy error when only phase 0 is loaded.
    #[test]
    fn test_polyphase_unbalanced_phase0_only() {
        let loaded = PhaseTestPoint {
            v_rms: 230.0,
            i_rms: 5.0,
            pf: 1.0,
        };
        let unloaded = PhaseTestPoint {
            v_rms: 230.0,
            i_rms: 0.0,
            pf: 1.0,
        };
        let r = run_polyphase_accuracy_test([loaded, unloaded, unloaded], 50.0, 200);
        assert!(
            r.error_pct.abs() < 1.0,
            "Unbalanced (only phase 0 loaded) error: {:.4}%",
            r.error_pct
        );
    }

    /// Checks the polyphase accuracy error for three phases with different loads and power factors.
    #[test]
    fn test_polyphase_unbalanced_uneven() {
        let ph0 = PhaseTestPoint {
            v_rms: 230.0,
            i_rms: 5.0,
            pf: 1.0,
        };
        let ph1 = PhaseTestPoint {
            v_rms: 230.0,
            i_rms: 2.5,
            pf: 0.8,
        };
        let ph2 = PhaseTestPoint {
            v_rms: 230.0,
            i_rms: 1.0,
            pf: 0.5,
        };
        let r = run_polyphase_accuracy_test([ph0, ph1, ph2], 50.0, 200);
        assert!(
            r.error_pct.abs() < 1.0,
            "Uneven 3-phase error: {:.4}%",
            r.error_pct
        );
    }

    /// Checks the single-phase accuracy error at 50 Hz with PF=1.
    #[test]
    fn test_balanced_reference_50hz() {
        let r = run_accuracy_test(230.0, 5.0, 1.0, 50.0, 100);
        assert!(
            r.error_pct.abs() < 1.0,
            "Error at reference (PF=1.0): {:.4}%",
            r.error_pct
        );
    }

    /// Checks the single-phase accuracy error at 60 Hz with PF=1.
    #[test]
    fn test_balanced_reference_60hz() {
        let r = run_accuracy_test(230.0, 5.0, 1.0, 60.0, 120);
        assert!(
            r.error_pct.abs() < 1.0,
            "Error at reference 60 Hz: {:.4}%",
            r.error_pct
        );
    }

    /// Checks the accuracy error at inductive PF=0.5.
    #[test]
    fn test_inductive_pf_05() {
        let r = run_accuracy_test(230.0, 5.0, 0.5, 50.0, 100);
        assert!(
            r.error_pct.abs() < 1.5,
            "Error at PF=0.5 inductive: {:.4}%",
            r.error_pct
        );
    }

    /// Checks the accuracy error at capacitive PF=0.8.
    #[test]
    fn test_capacitive_pf_08() {
        let r = run_accuracy_test(230.0, 5.0, 0.8, 50.0, 100);
        assert!(
            r.error_pct.abs() < 1.5,
            "Error at PF=0.8 capacitive: {:.4}%",
            r.error_pct
        );
    }

    /// Checks the accuracy error at 5 % of nominal current (0.25 A).
    #[test]
    fn test_low_current_5pct() {
        let r = run_accuracy_test(230.0, 0.25, 1.0, 50.0, 200);
        assert!(
            r.error_pct.abs() < 2.0,
            "Error at 5% In (0.25 A): {:.4}%",
            r.error_pct
        );
    }

    /// Checks that repeated runs of the same test produce consistent errors.
    #[test]
    fn test_error_repeatability() {
        let results: alloc::vec::Vec<f64> = (0..5)
            .map(|_| run_accuracy_test(230.0, 5.0, 1.0, 50.0, 50).error_pct)
            .collect();
        let mean = results.iter().copied().sum::<f64>() / results.len() as f64;
        let variance = results
            .iter()
            .map(|&x| crate::math::powi64(x - mean, 2))
            .sum::<f64>()
            / results.len() as f64;
        let std_dev = crate::math::sqrt64(variance);
        assert!(
            std_dev < 0.05,
            "Repeatability std_dev too high: {:.6}%",
            std_dev
        );
    }
}