Skip to main content

autoeq_plot/
trend_lines.rs

1use ndarray::Array1;
2
3/// Calculate linear regression slope and intercept for a curve between two frequencies
4///
5/// # Arguments
6/// * `freqs` - Frequency points
7/// * `values` - Corresponding values (SPL)
8/// * `f_min` - Minimum frequency for regression (Hz)
9/// * `f_max` - Maximum frequency for regression (Hz)
10///
11/// # Returns
12/// Option<(slope, intercept)> where slope is in dB/octave and intercept is at 1kHz
13pub fn calculate_tonal_balance(
14    freqs: &Array1<f64>,
15    values: &Array1<f64>,
16    f_min: f64,
17    f_max: f64,
18) -> Option<(f64, f64)> {
19    let mut x_vals = Vec::new();
20    let mut y_vals = Vec::new();
21
22    // Collect points within the frequency range
23    for (i, &f) in freqs.iter().enumerate() {
24        if f >= f_min && f <= f_max {
25            // Use log2(f) for octave-based slope calculation
26            x_vals.push(f.log2());
27            y_vals.push(values[i]);
28        }
29    }
30
31    if x_vals.len() < 2 {
32        return None;
33    }
34
35    // Calculate linear regression: y = a*x + b
36    // where x is log2(f) and y is SPL
37    let n = x_vals.len() as f64;
38    let sum_x: f64 = x_vals.iter().sum();
39    let sum_y: f64 = y_vals.iter().sum();
40    let sum_xy: f64 = x_vals.iter().zip(y_vals.iter()).map(|(x, y)| x * y).sum();
41    let sum_x2: f64 = x_vals.iter().map(|x| x * x).sum();
42
43    let denom = n * sum_x2 - sum_x * sum_x;
44    if denom.abs() < 1e-12 {
45        return None;
46    }
47
48    let slope = (n * sum_xy - sum_x * sum_y) / denom;
49    let intercept = (sum_y * sum_x2 - sum_x * sum_xy) / denom;
50
51    // Convert slope from dB/log2(f) to dB/octave
52    let slope_octave = slope;
53
54    // Calculate intercept at 1kHz (log2(1000) = 9.965784...)
55    let intercept_1khz = intercept + slope * 1000f64.log2();
56
57    Some((slope_octave, intercept_1khz))
58}
59
60/// Generate points for a linear regression line
61///
62/// # Arguments
63/// * `slope` - Slope in dB/octave
64/// * `intercept` - Intercept at 1kHz
65/// * `freqs` - Frequency points to evaluate the line at
66///
67/// # Returns
68/// Array of SPL values for the regression line
69pub fn generate_regression_line(slope: f64, intercept: f64, freqs: &Array1<f64>) -> Array1<f64> {
70    freqs.mapv(|f| intercept + slope * (f / 1000.0).log2())
71}
72
73/// Create a scatter plot trace for a regression line
74///
75/// # Arguments
76/// * `freqs` - Frequency points
77/// * `values` - SPL values for the regression line
78/// * `name` - Name for the trace
79/// * `color` - Color for the line
80/// * `x_axis` - X axis identifier (optional)
81/// * `y_axis` - Y axis identifier (optional)
82///
83/// # Returns
84/// Scatter plot trace
85pub fn create_regression_trace(
86    freqs: &Array1<f64>,
87    values: &Array1<f64>,
88    name: &str,
89    color: &str,
90    x_axis: Option<&str>,
91    y_axis: Option<&str>,
92) -> plotly::Scatter<f64, f64> {
93    let mut trace = plotly::Scatter::new(freqs.to_vec(), values.to_vec())
94        .mode(plotly::common::Mode::Lines)
95        .name(name)
96        .line(
97            plotly::common::Line::new()
98                .color(color.to_string())
99                .width(3.0),
100        );
101
102    if let Some(axis) = x_axis {
103        trace = trace.x_axis(axis);
104    }
105
106    if let Some(axis) = y_axis {
107        trace = trace.y_axis(axis);
108    }
109
110    *trace
111}