sci_rs/
plot.rs

1use std::io::Write;
2
3/// Debug utility function that will run a python script to plot the data.
4///
5/// This function generates a Python script to create plots of the input data and their autocorrelations.
6/// It then executes the script using the system's Python interpreter.
7///
8/// Note: This function will open a new window to display the plots and will block execution until the window is closed.
9/// It also suppresses stdout and stderr from the Python process.
10pub fn python_plot(xs: Vec<&[f32]>) {
11    let script = format!(
12        r#"
13import matplotlib.pyplot as plt
14import matplotlib.gridspec as gridspec
15from scipy.signal import correlate
16
17xs = {:?}
18fig = plt.figure(figsize=(12, 12))
19gs = gridspec.GridSpec(len(xs), 2)
20for i, x in enumerate(xs):
21    ax = plt.subplot(gs[i, 0])
22    ax.plot(x, label = f"C{{i}}")
23    ax.legend()
24    ax.set_xlabel("Samples")
25    ax = plt.subplot(gs[i, 1])
26    autocorr = correlate(x, x, mode='full')
27    normcorr = autocorr / autocorr.max()
28    offsets = range(-len(x) + 1, len(x))
29    ax.plot(offsets, normcorr, label = f"Autocorrelation of C{{i}}")
30    ax.legend()
31    ax.set_xlabel("Lag")
32plt.show()
33"#,
34        xs
35    );
36    // Run the script with python
37    let script = script.as_bytes();
38    let mut python = match std::process::Command::new("python")
39        .stdin(std::process::Stdio::piped())
40        .stdout(std::process::Stdio::null()) // noisy
41        .stderr(std::process::Stdio::null()) // noisy
42        .spawn()
43    {
44        Ok(p) => p,
45        Err(_) => return, // Return early if python fails to start
46    };
47
48    if let Some(mut stdin) = python.stdin.take() {
49        if stdin.write_all(script).is_err() {
50            return; // Return early if writing fails
51        }
52    } else {
53        return; // Return early if we can't get stdin
54    }
55
56    // Wait for the python process to finish, ignoring any errors
57    let _ = python.wait(); // Ignore errors as this may be called from CI
58}