med64 0.0.2

Headless MED64 electrophysiology toolkit: .modat I/O, spike/burst analysis, assays, spike-rate maps, and CSV/HTML/SVG/HDF5 export
Documentation
//! Voltage / spectrum settings form (STFT settings).

use std::path::Path;

use serde::{Deserialize, Serialize};

use crate::error::{Med64Error, Result};
use crate::toolkit::spectrum::{
    default_fast_backend, HumNoiseRemoval, SpectrumBackend, SpectrumOptions, SpectrumWindow,
};
use crate::toolkit::voltage::{VoltageMapOptions, VoltageMapReport, VoltageStftReport};

#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct FftConfig {
    pub window_size: usize,
    pub step_size: usize,
    pub use_hann: bool,
    pub log_display: bool,
    pub ham_target_hz: f64,
    pub use_hum: bool,
}

impl Default for FftConfig {
    fn default() -> Self {
        Self {
            window_size: 2048,
            step_size: 1024,
            use_hann: true,
            log_display: false,
            ham_target_hz: 60.0,
            use_hum: false,
        }
    }
}

#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct SettingsFormParams {
    pub analysis_start_s: f64,
    pub analysis_end_s: f64,
    pub num_points_window: usize,
    pub y_axis_log: bool,
    pub min_band_hz: f64,
    pub max_band_hz: f64,
    pub window: String,
    pub window_overlap: f64,
    pub hum: String,
    pub mean_psd: bool,
}

impl Default for SettingsFormParams {
    fn default() -> Self {
        Self {
            analysis_start_s: 0.0,
            analysis_end_s: 0.0,
            num_points_window: 2048,
            y_axis_log: false,
            min_band_hz: 0.0,
            max_band_hz: 200.0,
            window: "hann".into(),
            window_overlap: 0.5,
            hum: "none".into(),
            mean_psd: true,
        }
    }
}

impl SettingsFormParams {
    pub fn apply_to(&self, options: &mut SpectrumOptions) {
        options.fft_size = self.num_points_window.max(32);
        options.overlap = self.window_overlap.clamp(0.0, 0.95);
        options.window = match self.window.to_ascii_lowercase().as_str() {
            "rectangular" | "rect" => SpectrumWindow::Rectangular,
            "hamming" => SpectrumWindow::Hamming,
            _ => SpectrumWindow::Hann,
        };
        options.hum = match self.hum.to_ascii_lowercase().as_str() {
            "50" | "50hz" => HumNoiseRemoval::FiftyHz,
            "60" | "60hz" => HumNoiseRemoval::SixtyHz,
            _ => HumNoiseRemoval::None,
        };
        options.backend = default_fast_backend();
    }

    pub fn apply_to_voltage(&self, options: &mut VoltageMapOptions) {
        options.stft_fft_size = self.num_points_window.max(32);
        options.stft_overlap = self.window_overlap.clamp(0.0, 0.95);
        options.f_min_hz = self.min_band_hz;
        options.f_max_hz = self.max_band_hz;
        options.window = match self.window.to_ascii_lowercase().as_str() {
            "rectangular" | "rect" => SpectrumWindow::Rectangular,
            "hamming" => SpectrumWindow::Hamming,
            _ => SpectrumWindow::Hann,
        };
        options.hum = match self.hum.to_ascii_lowercase().as_str() {
            "50" | "50hz" => HumNoiseRemoval::FiftyHz,
            "60" | "60hz" => HumNoiseRemoval::SixtyHz,
            _ => HumNoiseRemoval::None,
        };
        options.psd_reduce = if self.mean_psd {
            crate::toolkit::voltage::PsdReduce::Mean
        } else {
            crate::toolkit::voltage::PsdReduce::Max
        };
        options.trend_cut = true; // SettingsForm wires TrendCutter by default when applied
    }
}

impl FftConfig {
    pub fn apply_to(&self, options: &mut SpectrumOptions) {
        options.fft_size = self.window_size.max(32);
        let hop = self.step_size.max(1);
        options.overlap = 1.0 - (hop as f64 / options.fft_size as f64).clamp(0.05, 1.0);
        options.window =
            if self.use_hann { SpectrumWindow::Hann } else { SpectrumWindow::Rectangular };
        options.hum = if self.use_hum {
            if (self.ham_target_hz - 50.0).abs() < 5.0 {
                HumNoiseRemoval::FiftyHz
            } else {
                HumNoiseRemoval::SixtyHz
            }
        } else {
            HumNoiseRemoval::None
        };
        options.backend = default_fast_backend();
    }
}

pub fn load_fft_settings_properties(path: impl AsRef<Path>) -> Result<SettingsFormParams> {
    let path = path.as_ref();
    let text = std::fs::read_to_string(path)
        .map_err(|source| Med64Error::Io { path: path.to_path_buf(), source })?;
    let mut p = SettingsFormParams::default();
    for line in text.lines() {
        let line = line.trim();
        if line.is_empty() || line.starts_with('#') {
            continue;
        }
        let Some((k, v)) = line.split_once('=') else {
            continue;
        };
        match k.trim() {
            "analysisStartS" => p.analysis_start_s = v.trim().parse().unwrap_or(p.analysis_start_s),
            "analysisEndS" => p.analysis_end_s = v.trim().parse().unwrap_or(p.analysis_end_s),
            "numPointsWindow" => {
                p.num_points_window = v.trim().parse().unwrap_or(p.num_points_window)
            }
            "yAxisLog" => {
                p.y_axis_log =
                    matches!(v.trim().to_ascii_lowercase().as_str(), "1" | "true" | "yes")
            }
            "minBandHz" => p.min_band_hz = v.trim().parse().unwrap_or(p.min_band_hz),
            "maxBandHz" => p.max_band_hz = v.trim().parse().unwrap_or(p.max_band_hz),
            "window" => p.window = v.trim().to_string(),
            "windowOverlap" => p.window_overlap = v.trim().parse().unwrap_or(p.window_overlap),
            "hum" => p.hum = v.trim().to_string(),
            "meanPsd" => {
                p.mean_psd = matches!(v.trim().to_ascii_lowercase().as_str(), "1" | "true" | "yes")
            }
            _ => {}
        }
    }
    Ok(p)
}

pub fn write_fft_settings_properties(
    params: &SettingsFormParams,
    path: impl AsRef<Path>,
) -> Result<()> {
    let path = path.as_ref();
    let body = format!(
        "# Voltage/Spectrum SettingsForm\n\
analysisStartS={}\n\
analysisEndS={}\n\
numPointsWindow={}\n\
yAxisLog={}\n\
minBandHz={}\n\
maxBandHz={}\n\
window={}\n\
windowOverlap={}\n\
hum={}\n\
meanPsd={}\n",
        params.analysis_start_s,
        params.analysis_end_s,
        params.num_points_window,
        params.y_axis_log,
        params.min_band_hz,
        params.max_band_hz,
        params.window,
        params.window_overlap,
        params.hum,
        params.mean_psd,
    );
    std::fs::write(path, body)
        .map_err(|source| Med64Error::WriteIo { path: path.to_path_buf(), source })
}

/// Interactive Prefer HTML: colormap lo/hi + log toggle over an existing map/STFT.
pub fn write_voltage_panel_html(
    map: Option<&VoltageMapReport>,
    stft: Option<&VoltageStftReport>,
    path: impl AsRef<Path>,
) -> Result<()> {
    let path = path.as_ref();
    let map_json = map
        .map(|m| {
            serde_json::json!({
                "min_mv": m.min_mv,
                "max_mv": m.max_mv,
                "cells": m.cells.iter().map(|c| c.value_mv).collect::<Vec<_>>(),
            })
        })
        .unwrap_or(serde_json::json!(null));
    let stft_json = stft
        .map(|s| {
            serde_json::json!({
                "n_frames": s.frames.len(),
                "first": s.frames.first().map(|f| f.cells.iter().map(|c| c.value_mv).collect::<Vec<_>>()),
            })
        })
        .unwrap_or(serde_json::json!(null));
    let html = format!(
        r#"<!DOCTYPE html><html><head><meta charset="utf-8"><title>Voltage Prefer</title>
<style>body{{font-family:system-ui;margin:1rem}}label{{margin-right:1rem}}.g{{display:grid;grid-template-columns:repeat(8,24px);gap:2px}}</style>
</head><body>
<h1>Voltage Prefer</h1>
<label>lo <input id="lo" type="number" step="0.01" value="0"></label>
<label>hi <input id="hi" type="number" step="0.01" value="1"></label>
<label><input id="log" type="checkbox"> log display</label>
<div id="g" class="g"></div>
<script>
const map={map_json};
const stft={stft_json};
const cells=(map&&map.cells)||(stft&&stft.first)||[];
const g=document.getElementById('g');
function render(){{
  const lo=+document.getElementById('lo').value, hi=+document.getElementById('hi').value;
  const useLog=document.getElementById('log').checked;
  g.innerHTML='';
  for(const v of cells){{
    let t=v;
    if(useLog) t=Math.log10(Math.max(v,1e-12));
    const span=Math.max(hi-lo,1e-12);
    const n=Math.max(0,Math.min(1,(t-lo)/span));
    const d=document.createElement('div');
    d.style.cssText=`width:24px;height:24px;background:rgb(${{Math.round(255*n)}},40,${{Math.round(255*(1-n))}})`;
    g.appendChild(d);
  }}
}}
['lo','hi','log'].forEach(id=>document.getElementById(id).addEventListener('input',render));
if(map){{document.getElementById('lo').value=map.min_mv;document.getElementById('hi').value=map.max_mv;}}
render();
</script></body></html>"#
    );
    std::fs::write(path, html)
        .map_err(|source| Med64Error::WriteIo { path: path.to_path_buf(), source })?;
    let _ = SpectrumBackend::Welch; // keep import used on all cfgs
    Ok(())
}