mirror of
https://github.com/hubaldv/bioz-host-rs.git
synced 2026-03-10 01:20:31 +00:00
Added bode plots to GUI.
This commit is contained in:
203
src/app.rs
203
src/app.rs
@@ -1,5 +1,7 @@
|
||||
use log::info;
|
||||
|
||||
use std::f32::consts::PI;
|
||||
use std::ops::RangeInclusive;
|
||||
use std::sync::{Arc, Mutex};
|
||||
use std::sync::atomic::{AtomicBool, Ordering};
|
||||
|
||||
@@ -7,14 +9,14 @@ use atomic_float::AtomicF32;
|
||||
use tokio::{sync::mpsc::{Sender}};
|
||||
|
||||
use eframe::egui::{self, Button, CollapsingHeader, Color32, ComboBox, DragValue, Key, Label, Layout, Modifiers};
|
||||
use egui_plot::{Corner, Legend, Line, Plot, PlotPoints, Points, PlotBounds};
|
||||
use egui_plot::{Corner, GridInput, GridMark, Legend, Line, Plot, PlotBounds, PlotPoint, PlotPoints, Points};
|
||||
use egui_dock::{DockArea, DockState, Style};
|
||||
|
||||
use crate::plot::TimeSeriesPlot;
|
||||
use crate::plot::{TimeSeriesPlot, BodePlot};
|
||||
|
||||
use crate::signals::SingleFrequencySignal;
|
||||
use crate::signals::StartStopSignal;
|
||||
|
||||
use crate::icd::IcdDftNum;
|
||||
use crate::icd::{IcdDftNum, NumberOfPoints};
|
||||
|
||||
const DFTNUM_VARIANTS: [IcdDftNum; 13] = [
|
||||
IcdDftNum::Num4, IcdDftNum::Num8, IcdDftNum::Num16, IcdDftNum::Num32,
|
||||
@@ -33,11 +35,12 @@ enum TabActive {
|
||||
pub struct App {
|
||||
tree: DockState<String>,
|
||||
tab_viewer: TabViewer,
|
||||
run_impedancemeter_tx: Sender<SingleFrequencySignal>,
|
||||
run_impedancemeter_tx: Sender<StartStopSignal>,
|
||||
pub magnitude: Arc<Mutex<f32>>,
|
||||
pub phase: Arc<Mutex<f32>>,
|
||||
pub magnitude_series: Arc<Mutex<TimeSeriesPlot>>,
|
||||
pub phase_series: Arc<Mutex<TimeSeriesPlot>>,
|
||||
pub bode_plot: Arc<Mutex<BodePlot>>,
|
||||
pub connected: Arc<AtomicBool>,
|
||||
pub on: Arc<Mutex<bool>>,
|
||||
tab_active: TabActive,
|
||||
@@ -51,6 +54,7 @@ struct TabViewer {
|
||||
phase: Arc<Mutex<f32>>,
|
||||
magnitude_series: Arc<Mutex<TimeSeriesPlot>>,
|
||||
phase_series: Arc<Mutex<TimeSeriesPlot>>,
|
||||
bode_plot: Arc<Mutex<BodePlot>>,
|
||||
on: Arc<Mutex<bool>>,
|
||||
single_frequency: Arc<Mutex<u32>>,
|
||||
dft_num: Arc<Mutex<IcdDftNum>>,
|
||||
@@ -100,7 +104,7 @@ impl TabViewer {
|
||||
let available_height = ui.available_height();
|
||||
let half_height = available_height / 2.0-2.0;
|
||||
|
||||
// Plot pressure
|
||||
// Plot magnitude
|
||||
ui.allocate_ui_with_layout(
|
||||
egui::vec2(ui.available_width(), half_height),
|
||||
Layout::top_down(egui::Align::Min),
|
||||
@@ -119,7 +123,7 @@ impl TabViewer {
|
||||
});
|
||||
},
|
||||
);
|
||||
// Plot pressure
|
||||
// Plot phase
|
||||
ui.allocate_ui_with_layout(
|
||||
egui::vec2(ui.available_width(), half_height),
|
||||
Layout::top_down(egui::Align::Min),
|
||||
@@ -142,7 +146,99 @@ impl TabViewer {
|
||||
}
|
||||
|
||||
fn multi_tab(&mut self, ui: &mut egui::Ui) {
|
||||
ui.heading("Bode plots!");
|
||||
egui::Frame::default().inner_margin(5).show(ui, |ui| {
|
||||
let settings = CollapsingHeader::new("Settings")
|
||||
.open(self.show_settings_toggle)
|
||||
.show(ui, |ui| {
|
||||
if let Ok(on) = self.on.lock() {
|
||||
ui.add_enabled_ui(!*on, |ui| {
|
||||
ui.horizontal(|ui| {
|
||||
ui.label("ADC samples per DFT:");
|
||||
let mut dft_num = self.dft_num.lock().unwrap();
|
||||
let mut index = DFTNUM_VARIANTS.iter().position(|&x| x == *dft_num).unwrap_or(0);
|
||||
ComboBox::from_id_salt("Dftnum")
|
||||
.width(75.0)
|
||||
.show_index(ui, &mut index, DFTNUM_VARIANTS.len(), |i| {
|
||||
format!("{}", 1 << (2 + i)) // 2^2 = 4, 2^3 = 8, ..., 2^14 = 16384
|
||||
});
|
||||
let new_value = DFTNUM_VARIANTS[index];
|
||||
if *dft_num != new_value {
|
||||
*dft_num = new_value;
|
||||
info!("DFTNUM setting changed!");
|
||||
};
|
||||
});
|
||||
});
|
||||
}
|
||||
});
|
||||
|
||||
self.show_settings_toggle = None;
|
||||
self.show_settings = !settings.fully_closed();
|
||||
|
||||
ui.separator();
|
||||
|
||||
let available_height = ui.available_height();
|
||||
let half_height = available_height / 2.0-2.0;
|
||||
|
||||
// Bodeplot magnitude
|
||||
ui.allocate_ui_with_layout(
|
||||
egui::vec2(ui.available_width(), half_height),
|
||||
Layout::top_down(egui::Align::Min),
|
||||
|ui| {
|
||||
// Magnitude
|
||||
let bode_plot = self.bode_plot.lock().unwrap();
|
||||
Plot::new("bode_mag")
|
||||
.legend(Legend::default().position(Corner::LeftTop))
|
||||
.y_axis_label("Magnitude [Ω]")
|
||||
.x_grid_spacer(log10_grid_spacer)
|
||||
.x_axis_formatter(log10_axis_formatter)
|
||||
// .auto_bounds([true; 2].into())
|
||||
.y_axis_min_width(80.0)
|
||||
.default_x_bounds(0.0, 200_000_f64.log10())
|
||||
.label_formatter(log10x_formatter)
|
||||
.show(ui, |plot_ui| {
|
||||
plot_ui.line(
|
||||
Line::new("Magnitude", bode_plot.plot_magnitudes())
|
||||
.color(Color32::LIGHT_BLUE)
|
||||
);
|
||||
plot_ui.points(
|
||||
Points::new("Magnitude measurement", bode_plot.plot_magnitudes())
|
||||
.color(Color32::BLUE)
|
||||
.radius(1.5)
|
||||
);
|
||||
});
|
||||
},
|
||||
);
|
||||
|
||||
// Bodeplot phase
|
||||
ui.allocate_ui_with_layout(
|
||||
egui::vec2(ui.available_width(), half_height),
|
||||
Layout::top_down(egui::Align::Min),
|
||||
|ui| {
|
||||
// Phase
|
||||
let bode_plot = self.bode_plot.lock().unwrap();
|
||||
Plot::new("bode_phase")
|
||||
.legend(Legend::default().position(Corner::LeftTop))
|
||||
.y_axis_label("Phase [rad]")
|
||||
.x_grid_spacer(log10_grid_spacer)
|
||||
.x_axis_formatter(log10_axis_formatter)
|
||||
// .auto_bounds([true; 2].into())
|
||||
.y_axis_min_width(80.0)
|
||||
.default_x_bounds(0.0, 200_000_f64.log10())
|
||||
.label_formatter(log10x_formatter)
|
||||
.show(ui, |plot_ui| {
|
||||
plot_ui.line(
|
||||
Line::new("Phase", bode_plot.plot_phases())
|
||||
.color(Color32::LIGHT_RED)
|
||||
);
|
||||
plot_ui.points(
|
||||
Points::new("Phase measurement", bode_plot.plot_phases())
|
||||
.color(Color32::RED)
|
||||
.radius(1.5)
|
||||
);
|
||||
});
|
||||
},
|
||||
);
|
||||
});
|
||||
}
|
||||
|
||||
fn shortcuts(&mut self, ui: &mut egui::Ui) {
|
||||
@@ -154,6 +250,64 @@ impl TabViewer {
|
||||
}
|
||||
}
|
||||
|
||||
fn log10_grid_spacer(input: GridInput) -> Vec<GridMark> {
|
||||
let base = 10u32;
|
||||
assert!(base >= 2);
|
||||
let basef = base as f64;
|
||||
|
||||
let step_size = basef.powi(input.base_step_size.abs().log(basef).ceil() as i32);
|
||||
let (min, max) = input.bounds;
|
||||
let mut steps = vec![];
|
||||
|
||||
for step_size in [step_size, step_size * basef, step_size * basef * basef] {
|
||||
if step_size == basef.powi(-1) {
|
||||
// FIXME: float comparison
|
||||
let first = ((min / (step_size * basef)).floor() as i64) * base as i64;
|
||||
let last = (max / step_size).ceil() as i64;
|
||||
|
||||
let mut logs = vec![0.0; base as usize - 2];
|
||||
for (i, j) in logs.iter_mut().enumerate() {
|
||||
*j = basef * ((i + 2) as f64).log(basef);
|
||||
}
|
||||
|
||||
steps.extend((first..last).step_by(base as usize).flat_map(|j| {
|
||||
logs.iter().map(move |i| GridMark {
|
||||
value: (j as f64 + i) * step_size,
|
||||
step_size,
|
||||
})
|
||||
}));
|
||||
} else {
|
||||
let first = (min / step_size).ceil() as i64;
|
||||
let last = (max / step_size).ceil() as i64;
|
||||
|
||||
steps.extend((first..last).map(move |i| GridMark {
|
||||
value: (i as f64) * step_size,
|
||||
step_size,
|
||||
}));
|
||||
}
|
||||
}
|
||||
steps
|
||||
}
|
||||
|
||||
fn log10_axis_formatter(mark: GridMark, _range: &RangeInclusive<f64>) -> String {
|
||||
let base = 10u32;
|
||||
let basef = base as f64;
|
||||
let prec = (-mark.step_size.log10().round()).max(0.0) as usize;
|
||||
format!("{:.*e}", prec, basef.powf(mark.value))
|
||||
}
|
||||
|
||||
fn log10x_formatter(name: &str, value: &PlotPoint) -> String {
|
||||
let base = 10u32;
|
||||
let basef = base as f64;
|
||||
format!(
|
||||
"{}\nx: {:.d$e}\ny: {:.d$e}",
|
||||
name,
|
||||
basef.powf(value.x),
|
||||
value.y,
|
||||
d = 3
|
||||
)
|
||||
}
|
||||
|
||||
impl egui_dock::TabViewer for TabViewer {
|
||||
type Tab = String;
|
||||
|
||||
@@ -174,12 +328,13 @@ impl egui_dock::TabViewer for TabViewer {
|
||||
}
|
||||
|
||||
impl App {
|
||||
pub fn new(run_impedancemeter_tx: Sender<SingleFrequencySignal>) -> Self {
|
||||
pub fn new(run_impedancemeter_tx: Sender<StartStopSignal>) -> Self {
|
||||
// Step 1: Initialize shared fields first
|
||||
let magnitude = Arc::new(Mutex::new(0.0));
|
||||
let phase = Arc::new(Mutex::new(0.0));
|
||||
let magnitude_series = Arc::new(Mutex::new(TimeSeriesPlot::new()));
|
||||
let phase_series = Arc::new(Mutex::new(TimeSeriesPlot::new()));
|
||||
let bode_plot = Arc::new(Mutex::new(BodePlot::new()));
|
||||
let single_frequency = Arc::new(Mutex::new(50000));
|
||||
let dft_num = Arc::new(Mutex::new(IcdDftNum::Num2048));
|
||||
let on = Arc::new(Mutex::new(true));
|
||||
@@ -191,6 +346,7 @@ impl App {
|
||||
phase: phase.clone(),
|
||||
magnitude_series: magnitude_series.clone(),
|
||||
phase_series: phase_series.clone(),
|
||||
bode_plot: bode_plot.clone(),
|
||||
single_frequency: single_frequency.clone(),
|
||||
dft_num: dft_num.clone(),
|
||||
on: on.clone(),
|
||||
@@ -207,6 +363,7 @@ impl App {
|
||||
phase,
|
||||
magnitude_series,
|
||||
phase_series,
|
||||
bode_plot,
|
||||
connected: Arc::new(AtomicBool::new(false)),
|
||||
on,
|
||||
tab_active,
|
||||
@@ -215,6 +372,25 @@ impl App {
|
||||
dft_num,
|
||||
};
|
||||
|
||||
// For testing purposes, populate the Bode plot with a sample low-pass filter response
|
||||
let fc = 1000.0; // cutoff frequency in Hz
|
||||
|
||||
let freqs = NumberOfPoints::TwentyEight.values().to_vec();
|
||||
let magnitudes = freqs.iter()
|
||||
.map(|&f| {
|
||||
1.0 / (1.0 + (f / fc).powi(2)).sqrt()
|
||||
})
|
||||
.collect::<Vec<f32>>();
|
||||
let phases = freqs.iter()
|
||||
.map(|&f| {
|
||||
-(f / fc).atan() * 180.0 / PI
|
||||
})
|
||||
.collect::<Vec<f32>>();
|
||||
|
||||
app.bode_plot.lock().unwrap().update_magnitudes(magnitudes);
|
||||
app.bode_plot.lock().unwrap().update_phases(phases);
|
||||
|
||||
|
||||
app.update_start_stop();
|
||||
app
|
||||
}
|
||||
@@ -222,16 +398,17 @@ impl App {
|
||||
pub fn update_start_stop(&self) {
|
||||
match (self.tab_active, *self.on.lock().unwrap()) {
|
||||
(TabActive::Single, true) => {
|
||||
if let Err(e) = self.run_impedancemeter_tx.try_send(SingleFrequencySignal::Start(*self.single_frequency.lock().unwrap(), *self.dft_num.lock().unwrap())) {
|
||||
if let Err(e) = self.run_impedancemeter_tx.try_send(StartStopSignal::StartSingle(*self.single_frequency.lock().unwrap(), *self.dft_num.lock().unwrap())) {
|
||||
eprintln!("Failed to send start command: {:?}", e);
|
||||
}
|
||||
},
|
||||
(TabActive::Multi, true) => {
|
||||
// For future use
|
||||
info!("Multi frequency mode not implemented yet");
|
||||
if let Err(e) = self.run_impedancemeter_tx.try_send(StartStopSignal::StartMulti(*self.dft_num.lock().unwrap(), NumberOfPoints::TwentyEight)) {
|
||||
eprintln!("Failed to send start command: {:?}", e);
|
||||
}
|
||||
},
|
||||
(_, false) => {
|
||||
if let Err(e) = self.run_impedancemeter_tx.try_send(SingleFrequencySignal::Stop) {
|
||||
if let Err(e) = self.run_impedancemeter_tx.try_send(StartStopSignal::Stop) {
|
||||
eprintln!("Failed to send stop command: {:?}", e);
|
||||
}
|
||||
},
|
||||
|
||||
Reference in New Issue
Block a user