1use ndarray::Array1;
2use plotly::common::{Anchor, Mode};
3use plotly::layout::{
4 Annotation, AxisType, GridPattern, LayoutGrid, RowOrder, Shape, ShapeLayer, ShapeLine,
5 ShapeType,
6};
7use plotly::{Layout, Plot, Scatter};
8
9use crate::filter_color::filter_color;
10use crate::iir::{Biquad, BiquadFilterType};
11use crate::param_utils::{determine_filter_type, get_filter_params, num_filters};
12use crate::ref_lines::make_ref_lines;
13use crate::response::MIN_FILTER_RESPONSE_DB;
14
15fn make_freq_range_shapes(min_freq: f64, max_freq: f64) -> Vec<Shape> {
18 let mut shapes = Vec::new();
19
20 let y_ranges = [
22 (-10.0, 10.0), (-10.0, 10.0), (-5.0, 5.0), (-10.0, 10.0), ];
27
28 let axis_refs = [("x", "y"), ("x2", "y2"), ("x3", "y3"), ("x4", "y4")];
30
31 for ((x_ref, y_ref), (y_min, y_max)) in axis_refs.iter().zip(y_ranges.iter()) {
32 if min_freq > 20.0 {
34 let shape = Shape::new()
35 .shape_type(ShapeType::Rect)
36 .x_ref(x_ref)
37 .y_ref(y_ref)
38 .x0(20.0_f64.log10())
39 .x1(min_freq.log10())
40 .y0(*y_min)
41 .y1(*y_max)
42 .fill_color("rgba(144, 238, 144, 0.3)")
43 .layer(ShapeLayer::Below)
44 .line(ShapeLine::new().width(0.0));
45 shapes.push(shape);
46 }
47
48 if max_freq < 20000.0 {
50 let shape = Shape::new()
51 .shape_type(ShapeType::Rect)
52 .x_ref(x_ref)
53 .y_ref(y_ref)
54 .x0(max_freq.log10())
55 .x1(20000.0_f64.log10())
56 .y0(*y_min)
57 .y1(*y_max)
58 .fill_color("rgba(144, 238, 144, 0.3)")
59 .layer(ShapeLayer::Below)
60 .line(ShapeLine::new().width(0.0));
61 shapes.push(shape);
62 }
63 }
64
65 shapes
66}
67
68pub fn plot_filters(
73 config: &crate::PlotConfig,
74 input_curve: &crate::Curve,
75 target_curve: &crate::Curve,
76 deviation_curve: &crate::Curve,
77 optimized_params: &[f64],
78) -> plotly::Plot {
79 let freqs = input_curve.freq.clone();
80 let mut plot = Plot::new();
81
82 let peq_model = config.peq_model;
84 let filter_count = config
85 .num_filters
86 .min(num_filters(optimized_params, peq_model));
87 let mut filters: Vec<(usize, BiquadFilterType, f64, f64, f64)> = (0..filter_count)
88 .map(|i| {
89 let params = get_filter_params(optimized_params, i, peq_model);
90 (
91 i,
92 determine_filter_type(i, filter_count, peq_model, params.filter_type),
93 10f64.powf(params.freq),
94 params.q,
95 params.gain,
96 )
97 })
98 .collect();
99 filters.sort_by(|a, b| a.2.total_cmp(&b.2));
100
101 let mut combined_response: Array1<f64> = Array1::zeros(freqs.len());
103 for (display_idx, (orig_i, ftype, f0, q, gain)) in filters.iter().enumerate() {
104 let filter = Biquad::new(*ftype, *f0, config.sample_rate, *q, *gain);
105 let filter_response = filter
107 .np_log_result(&freqs)
108 .mapv(|db| db.max(MIN_FILTER_RESPONSE_DB));
109 combined_response += &filter_response;
110
111 let label = match *ftype {
112 BiquadFilterType::Highpass | BiquadFilterType::HighpassVariableQ => "HPQ",
113 BiquadFilterType::Lowpass => "LP",
114 BiquadFilterType::Lowshelf | BiquadFilterType::LowshelfOrf => "LS",
115 BiquadFilterType::Highshelf | BiquadFilterType::HighshelfOrf => "HS",
116 BiquadFilterType::Bandpass => "BP",
117 BiquadFilterType::Notch => "NO",
118 _ => "PK",
119 };
120 let individual_trace = Scatter::new(freqs.to_vec(), filter_response.to_vec())
121 .mode(Mode::Lines)
122 .name(format!("{} {} at {:5.0}Hz", label, orig_i + 1, f0))
123 .marker(
124 plotly::common::Marker::new()
125 .color(filter_color(display_idx))
126 .size(1),
127 );
128 plot.add_trace(individual_trace);
129 }
130
131 let iir_trace1 = Scatter::new(freqs.to_vec(), combined_response.to_vec())
133 .mode(Mode::Lines)
134 .name("autoEQ")
135 .line(plotly::common::Line::new().color("#000000").width(2.0));
136 plot.add_trace(iir_trace1);
137
138 let iir_trace2 = Scatter::new(freqs.to_vec(), combined_response.to_vec())
139 .mode(Mode::Lines)
140 .name("autoEQ")
141 .show_legend(false)
142 .x_axis("x2")
143 .y_axis("y2")
144 .line(plotly::common::Line::new().color("#000000").width(2.0));
145 plot.add_trace(iir_trace2);
146
147 let target_trace2 = Scatter::new(freqs.to_vec(), deviation_curve.spl.to_vec())
149 .mode(Mode::Lines)
150 .name("Deviation")
151 .x_axis("x2")
152 .y_axis("y2")
153 .line(plotly::common::Line::new().color(filter_color(0)));
154 plot.add_trace(target_trace2);
155
156 let error = &deviation_curve.spl - &combined_response;
157 let target_trace4 = Scatter::new(freqs.to_vec(), error.to_vec())
158 .mode(Mode::Lines)
159 .name("Error")
160 .x_axis("x3")
161 .y_axis("y3")
162 .line(plotly::common::Line::new().color(filter_color(1)));
163 plot.add_trace(target_trace4);
164
165 let target_trace4 = Scatter::new(freqs.to_vec(), target_curve.spl.to_vec())
167 .mode(Mode::Lines)
168 .name("Target")
169 .show_legend(false)
170 .x_axis("x4")
171 .y_axis("y4")
172 .line(
173 plotly::common::Line::new()
174 .color(filter_color(0))
175 .width(2.0),
176 );
177 plot.add_trace(target_trace4);
178
179 let input_trace = Scatter::new(input_curve.freq.to_vec(), input_curve.spl.to_vec())
180 .mode(Mode::Lines)
181 .name("Input")
182 .x_axis("x4")
183 .y_axis("y4")
184 .line(plotly::common::Line::new().color(filter_color(1)));
185 plot.add_trace(input_trace);
186
187 let input_plus_eq_trace = Scatter::new(
189 input_curve.freq.to_vec(),
190 (&input_curve.spl + &combined_response).to_vec(),
191 )
192 .mode(Mode::Lines)
193 .name("Input + EQ")
194 .x_axis("x4")
195 .y_axis("y4")
196 .line(
197 plotly::common::Line::new()
198 .color(filter_color(2))
199 .width(3.0),
200 );
201 plot.add_trace(input_plus_eq_trace);
202
203 let ref_lines3 = make_ref_lines("x3", "y3");
205 for ref_line in ref_lines3 {
206 plot.add_trace(Box::new(ref_line));
207 }
208
209 let mut layout = Layout::new()
211 .grid(
212 LayoutGrid::new()
213 .rows(2)
214 .columns(2)
215 .pattern(GridPattern::Independent)
216 .row_order(RowOrder::TopToBottom),
217 )
218 .width(1024)
219 .height(800)
220 .x_axis(
221 plotly::layout::Axis::new()
222 .title("Frequency (Hz)".to_string())
223 .type_(AxisType::Log)
224 .range(vec![1.301, 4.301])
225 .domain(&[0., 0.45]),
226 ) .y_axis(
228 plotly::layout::Axis::new()
229 .title("SPL (dB)".to_string())
230 .dtick(1.0)
231 .range(vec![-10.0, 10.0]),
232 )
233 .x_axis2(
234 plotly::layout::Axis::new()
235 .title("Frequency (Hz)".to_string())
236 .type_(AxisType::Log)
237 .range(vec![1.301, 4.301])
238 .domain(&[0.55, 1.0]),
239 ) .y_axis2(
241 plotly::layout::Axis::new()
242 .title("SPL (dB)".to_string())
243 .dtick(1.0)
244 .range(vec![-10.0, 10.0]),
245 )
246 .x_axis3(
247 plotly::layout::Axis::new()
248 .title("Frequency (Hz)".to_string())
249 .type_(AxisType::Log)
250 .range(vec![1.301, 4.301])
251 .domain(&[0., 0.45]),
252 )
253 .y_axis3(
254 plotly::layout::Axis::new()
255 .title("SPL (dB)".to_string())
256 .dtick(1.0)
257 .range(vec![-5.0, 5.0]),
258 )
259 .x_axis4(
260 plotly::layout::Axis::new()
261 .title("Frequency (Hz)".to_string())
262 .type_(AxisType::Log)
263 .range(vec![1.301, 4.301])
264 .domain(&[0.55, 1.0]),
265 )
266 .y_axis4(
267 plotly::layout::Axis::new()
268 .title("SPL (dB)".to_string())
269 .dtick(1.0)
270 .range(vec![-10.0, 10.0]),
271 );
272
273 layout.add_annotation(
274 Annotation::new()
275 .y_ref("y domain")
276 .y_anchor(Anchor::Bottom)
277 .y(1)
278 .text("IIR filters and Sum of filters")
279 .x_ref("x domain")
280 .x_anchor(Anchor::Center)
281 .x(0.5)
282 .show_arrow(false),
283 );
284
285 layout.add_annotation(
286 Annotation::new()
287 .y_ref("y2 domain")
288 .y_anchor(Anchor::Bottom)
289 .y(1)
290 .text("Autoeq v.s. Deviation from target")
291 .x_ref("x2 domain")
292 .x_anchor(Anchor::Center)
293 .x(0.5)
294 .show_arrow(false),
295 );
296
297 layout.add_annotation(
298 Annotation::new()
299 .y_ref("y3 domain")
300 .y_anchor(Anchor::Bottom)
301 .y(1)
302 .text("Error = Autoeq-Deviation (zoomed)")
303 .x_ref("x3 domain")
304 .x_anchor(Anchor::Center)
305 .x(0.5)
306 .show_arrow(false),
307 );
308
309 layout.add_annotation(
310 Annotation::new()
311 .y_ref("y4 domain")
312 .y_anchor(Anchor::Bottom)
313 .y(1)
314 .text("Response w/ autoEQ")
315 .x_ref("x4 domain")
316 .x_anchor(Anchor::Center)
317 .x(0.5)
318 .show_arrow(false),
319 );
320
321 let freq_shapes = make_freq_range_shapes(config.min_freq, config.max_freq);
323 for shape in freq_shapes {
324 layout.add_shape(shape);
325 }
326
327 plot.set_layout(layout);
328
329 plot
330}
331
332#[cfg(test)]
333mod tests {
334 use super::*;
335 use crate::PlotConfig;
336 use crate::param_utils::encode_filter_type;
337 use crate::{Curve, PeqModel};
338
339 #[test]
340 fn audit_plot_filters_decodes_free_model_layout() {
341 let curve = Curve {
342 freq: Array1::from_vec(vec![500.0, 1000.0, 2000.0]),
343 spl: Array1::zeros(3),
344 phase: None,
345 ..Default::default()
346 };
347 let config = PlotConfig {
348 speaker_name: None,
349 num_filters: 1,
350 sample_rate: 48_000.0,
351 peq_model: PeqModel::Free,
352 min_freq: 20.0,
353 max_freq: 20_000.0,
354 };
355 let params = vec![
356 encode_filter_type(BiquadFilterType::LowshelfOrf),
357 1000.0_f64.log10(),
358 0.7,
359 3.0,
360 ];
361 let plot = plot_filters(&config, &curve, &curve, &curve, ¶ms);
362 let json: serde_json::Value =
363 serde_json::from_str(&plot.to_json()).expect("valid Plotly JSON");
364 let name = json["data"][0]["name"].as_str().expect("trace name");
365
366 assert!(name.starts_with("LS 1 at"), "unexpected trace name: {name}");
367 assert!(name.ends_with("1000Hz"), "unexpected trace name: {name}");
368 }
369}