autoeq_plot/
trend_lines.rs1use ndarray::Array1;
2
3pub 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 for (i, &f) in freqs.iter().enumerate() {
24 if f >= f_min && f <= f_max {
25 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 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 let slope_octave = slope;
53
54 let intercept_1khz = intercept + slope * 1000f64.log2();
56
57 Some((slope_octave, intercept_1khz))
58}
59
60pub 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
73pub 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}