Files
rustytorch/demos/ui/src-tauri/src/lib.rs
T
2026-03-04 00:08:42 +00:00

520 lines
24 KiB
Rust

//! RustyTorch++ Medical Demos - Tauri Backend
//!
//! This crate provides the Tauri backend for RustyTorch++ medical PINN demos.
//! It exposes IPC commands that connect the React frontend to the hemodynamics,
//! MRE elastography, and SlideScope pathology engines.
//!
//! # Architecture
//!
//! ```text
//! ┌─────────────────────┐ ┌──────────────────────┐
//! │ React Frontend │ │ Tauri Backend │
//! │ (Canvas/WebGL) │────▶│ (This crate) │
//! └─────────────────────┘ └──────────┬───────────┘
//! │
//! ┌───────────────────────────┼───────────────────────────┐
//! │ │ │
//! │ ┌───────────┴───────────┐ │
//! ┌──────────▼───────────┐ │ │ ┌──────────▼───────────┐
//! │ rtx-hemodynamics │ │ ┌──────────────┐ │ │ rtx-slidescope │
//! │ (Navier-Stokes) │ │ │ │ │ │ (NMF Pathology) │
//! └──────────────────────┘ │ ▼ ▼ │ └──────────────────────┘
//! ┌─────────────▼────────┐ ┌──────▼───────────┐
//! │ rtx-mre │ │ rtx-bioheat │
//! │ (Inv. Helmholtz) │ │ (Pennes Bioheat) │
//! └──────────────────────┘ └──────────────────┘
//! ```
//!
//! # IPC Commands
//!
//! ## Hemodynamics Commands
//!
//! - `initialize` - Initialize simulation with vessel parameters
//! - `reset` - Reset simulation state
//! - `get_status` - Get current simulation status
//! - `query_fields` - Query velocity/pressure at specific points
//! - `query_grid` - Query fields on a regular grid (for visualization)
//! - `modify_geometry` - Modify vessel geometry (add stenosis, etc.)
//! - `get_metrics` - Get performance metrics
//! - `get_simulation_state` - Get detailed simulation state
//! - `sample_interior` - Sample interior points from geometry
//! - `sample_boundary` - Sample boundary points from geometry
//!
//! ## MRE Elastography Commands
//!
//! - `mre_initialize_phantom` - Initialize with synthetic phantom data
//! - `mre_step` - Run single training step
//! - `mre_train` - Run multiple training steps
//! - `mre_snapshot` - Get visualization snapshot
//! - `mre_reset` - Reset solver state
//! - `mre_status` - Get current solver status
//!
//! ## Thermal Ablation Bioheat Commands
//!
//! - `bioheat_initialize` - Initialize with simulation parameters
//! - `bioheat_initialize_default` - Initialize with default liver parameters
//! - `bioheat_step` - Run single training step
//! - `bioheat_train` - Run multiple training steps
//! - `bioheat_snapshot` - Get 3D visualization snapshot
//! - `bioheat_get_slice` - Get 2D slice at position
//! - `bioheat_update_probe` - Update probe geometry
//! - `bioheat_update_power` - Update probe power
//! - `bioheat_advance_time` - Advance simulation time
//! - `bioheat_set_time` - Set simulation time directly
//! - `bioheat_status` - Get current solver status
//! - `bioheat_loss_history` - Get loss history
//! - `bioheat_reset` - Reset solver state
//!
//! ## SlideScope Pathology Commands
//!
//! - `slidescope_initialize` - Initialize with workspace directory
//! - `slidescope_import_slide` - Import a pathology slide
//! - `slidescope_list_slides` - List all slides with optional filter
//! - `slidescope_get_slide` - Get slide metadata by ID
//! - `slidescope_get_tile` - Get a tile from a slide pyramid
//! - `slidescope_queue_processing` - Queue NMF stain separation
//! - `slidescope_job_status` - Get job processing status
//! - `slidescope_get_result` - Get NMF processing result
//! - `slidescope_status` - Get service status
//! - `slidescope_reset` - Reset service state
//! - `slidescope_delete_slide` - Delete a slide
//!
//! ## Neural Operator Demo Commands
//!
//! - `neural_operator_initialize` - Initialize FNO model with PDE type and resolution
//! - `neural_operator_solve` - Solve PDE with given input field
//! - `neural_operator_get_metrics` - Get performance metrics
//! - `neural_operator_get_model_info` - Get model information
//! - `neural_operator_reset` - Reset demo state
//! - `neural_operator_is_initialized` - Check if model is initialized
//! - `neural_operator_start_training` - Start FNO training in background
//! - `neural_operator_training_progress` - Get current training progress
//! - `neural_operator_cancel_training` - Cancel ongoing training
//! - `neural_operator_is_training` - Check if training is active
//!
//! ## PIDDM (Physics-Informed Diffusion) Demo Commands
//!
//! - `piddm_initialize` - Initialize PIDDM model with PDE type and scheduler
//! - `piddm_reset` - Reset PIDDM model
//! - `piddm_start_training` - Start PIDDM training
//! - `piddm_training_progress` - Get training progress
//! - `piddm_training_result` - Get training result
//! - `piddm_cancel_training` - Cancel training
//! - `piddm_start_sampling` - Start generating samples
//! - `piddm_sampling_progress` - Get sampling progress
//! - `piddm_sampling_result` - Get generated samples
//!
//! ## Digital Twin Demo Commands
//!
//! - `digital_twin_initialize` - Initialize digital twin with geometry preset
//! - `digital_twin_reset` - Reset digital twin
//! - `digital_twin_start_simulation` - Start thermal simulation
//! - `digital_twin_simulation_progress` - Get simulation progress
//! - `digital_twin_simulation_result` - Get simulation result
//! - `digital_twin_what_if` - Run what-if analysis
//! - `digital_twin_get_slice` - Get slice data for visualization
//!
//! ## Image Classifier Commands
//!
//! - `image_classifier_initialize` - Initialize classifier with model architecture
//! - `image_classifier_reset` - Reset classifier state
//! - `image_classifier_classify` - Classify a base64-encoded image
//! - `image_classifier_status` - Get classifier status
//! - `image_classifier_metrics` - Get performance metrics
//! - `image_classifier_is_initialized` - Check if classifier is ready
//!
//! ## Time Series Forecast Commands
//!
//! - `timeseries_initialize` - Initialize time series forecaster
//! - `timeseries_reset` - Reset forecaster state
//! - `timeseries_fit` - Fit model to time series data
//! - `timeseries_forecast` - Generate forecasts from fitted model
//! - `timeseries_status` - Get forecaster status
//! - `timeseries_is_initialized` - Check if forecaster is ready
//! - `timeseries_generate_sample` - Generate sample dataset
//! - `timeseries_get_sample_datasets` - Get available sample datasets
//! - `timeseries_get_model_types` - Get available model types
//!
//! ## FNO Benchmark Commands
//!
//! - `benchmark_run_classical` - Run FDM/FEM benchmarks for comparison
//! - `benchmark_run_all` - Run all benchmarks including FNO (if model trained)
//! - `benchmark_run_with_stats` - Run benchmarks with statistical analysis
//! - `benchmark_quick` - Quick single-resolution benchmark
//!
//! ## RustyNeuro MEG/EEG Commands
//!
//! ### File I/O
//! - `neuro_load_edf` - Load an EDF/BDF recording file
//! - `neuro_load_brainvision` - Load a BrainVision recording (.vhdr)
//! - `neuro_load_fif` - Load an Elekta/Neuromag FIF file (.fif)
//! - `neuro_get_recording_info` - Get metadata about a recording
//! - `neuro_get_data_chunk` - Get time-series data for visualization
//! - `neuro_get_events` - Get event markers from recording
//! - `neuro_list_recordings` - List all loaded recordings
//! - `neuro_close_recording` - Close a specific recording
//!
//! ### Signal Processing
//! - `neuro_apply_filter` - Apply bandpass/notch filters
//! - `neuro_create_epochs` - Create epochs from events
//! - `neuro_compute_average` - Compute evoked response (average)
//!
//! ### Time-Frequency Analysis
//! - `neuro_compute_tfr` - Compute time-frequency representation (Morlet/STFT)
//! - `neuro_compute_psd` - Compute power spectral density (Welch/Multitaper)
//! - `neuro_compute_tfr_epochs` - Compute TFR averaged over epochs
//!
//! ### Forward Modeling
//! - `neuro_create_forward_model` - Create spherical MEG/EEG forward model
//! - `neuro_get_forward_model` - Get forward model info
//! - `neuro_list_forward_models` - List all forward models
//!
//! ### Inverse Solutions
//! - `neuro_create_inverse_operator` - Create MNE/dSPM/sLORETA inverse operator
//! - `neuro_apply_inverse` - Apply inverse to get source estimates
//! - `neuro_create_beamformer` - Create LCMV beamformer (planned for future release)
//! - `neuro_gnn_predict` - Run GNN prediction on brain connectivity graph
//! - `neuro_gnn_explain` - Explain GNN predictions with gradient attribution
//! - `neuro_list_inverse_operators` - List all inverse operators
//!
//! ### Connectivity Analysis
//! - `neuro_compute_connectivity` - Compute coherence/PLV/wPLI/dwPLI
//! - `neuro_compute_pac` - Compute phase-amplitude coupling
//!
//! ### Artifact Removal (SSP/ICA)
//! - `neuro_compute_ssp` - Compute SSP projectors from artifact epochs
//! - `neuro_apply_ssp` - Apply SSP projectors to recording
//! - `neuro_fit_ica` - Fit FastICA model to recording
//! - `neuro_get_ica_sources` - Get ICA independent components
//! - `neuro_apply_ica` - Remove ICA components from recording
//! - `neuro_list_ica_models` - List all ICA models
//!
//! ### Statistical Analysis
//! - `neuro_permutation_test` - Perform permutation test on epochs
//! - `neuro_ttest` - Perform t-test on epochs
//! - `neuro_correct_pvalues` - Apply multiple comparison correction (FDR/Bonferroni)
//! - `neuro_effect_size` - Compute effect size (Cohen's d)
//!
//! ### Service Management
//! - `neuro_status` - Get service status
//! - `neuro_reset` - Clear all loaded data
//!
//! ## System Commands
//!
//! - `get_compute_backend` - Get active compute backend (CUDA/Metal/CPU)
#![warn(missing_docs)]
mod commands;
mod neuro_commands;
mod state;
pub use commands::*;
pub use neuro_commands::{BciState, DatabaseState, LslState, NeuroService, NeuroState};
pub use state::AppState;
/// Runs the Tauri application
///
/// This is the main entry point for the Tauri backend. It:
/// 1. Creates the application state with the hemodynamics service
/// 2. Registers all IPC command handlers
/// 3. Starts the Tauri runtime
///
/// # Panics
///
/// Panics if the application state cannot be created or if Tauri fails to start.
#[cfg_attr(mobile, tauri::mobile_entry_point)]
pub fn run() {
use std::sync::Arc;
use tokio::sync::RwLock;
// Create application state
let app_state = AppState::new();
// Create neuro state
let neuro_state: NeuroState = Arc::new(RwLock::new(NeuroService::new()));
// Create database state
let db_state: neuro_commands::DatabaseState = Arc::new(RwLock::new(None));
// Create LSL state
let lsl_state: neuro_commands::LslState = Arc::new(RwLock::new(rtx_neuro_lsl::LslService::new()));
// Create BCI pipeline state
let bci_state: neuro_commands::BciState = Arc::new(RwLock::new(None));
tauri::Builder::default()
.setup(|app| {
// Add logging plugin in debug builds
if cfg!(debug_assertions) {
app.handle().plugin(
tauri_plugin_log::Builder::default()
.level(log::LevelFilter::Info)
.build(),
)?;
}
// Log startup
log::info!("RustyTorch++ Medical Demos started");
log::info!("Hemodynamics PINN engine initialized");
log::info!("MRE Elastography solver initialized");
log::info!("Thermal Ablation Bioheat solver initialized");
log::info!("SlideScope Pathology engine initialized");
log::info!("Neural Operator demo ready");
log::info!("PIDDM (Physics-Informed Diffusion) demo ready");
log::info!("Medical Digital Twin demo ready");
log::info!("Image Classifier demo ready");
log::info!("Time Series Forecast demo ready");
log::info!("RustyNeuro MEG/EEG engine initialized");
Ok(())
})
.manage(app_state)
.manage(neuro_state)
.manage(db_state)
.manage(lsl_state)
.manage(bci_state)
.invoke_handler(tauri::generate_handler![
// Hemodynamics commands
commands::initialize,
commands::reset,
commands::get_status,
commands::query_fields,
commands::query_grid,
commands::modify_geometry,
commands::get_metrics,
commands::get_simulation_state,
commands::sample_interior,
commands::sample_boundary,
// MRE elastography commands
commands::mre_initialize_phantom,
commands::mre_step,
commands::mre_train,
commands::mre_snapshot,
commands::mre_reset,
commands::mre_status,
// Thermal ablation bioheat commands
commands::bioheat_initialize,
commands::bioheat_initialize_default,
commands::bioheat_step,
commands::bioheat_train,
commands::bioheat_snapshot,
commands::bioheat_get_slice,
commands::bioheat_update_probe,
commands::bioheat_update_power,
commands::bioheat_advance_time,
commands::bioheat_set_time,
commands::bioheat_status,
commands::bioheat_loss_history,
commands::bioheat_reset,
// SlideScope pathology commands
commands::slidescope_initialize,
commands::slidescope_import_slide,
commands::slidescope_list_slides,
commands::slidescope_get_slide,
commands::slidescope_get_tile,
commands::slidescope_queue_processing,
commands::slidescope_job_status,
commands::slidescope_get_result,
commands::slidescope_status,
commands::slidescope_reset,
commands::slidescope_delete_slide,
// Neural Operator demo commands
commands::neural_operator_initialize,
commands::neural_operator_solve,
commands::neural_operator_get_metrics,
commands::neural_operator_get_model_info,
commands::neural_operator_reset,
commands::neural_operator_is_initialized,
// Neural Operator training commands
commands::neural_operator_start_training,
commands::neural_operator_training_progress,
commands::neural_operator_cancel_training,
commands::neural_operator_is_training,
// PIDDM demo commands
commands::piddm_initialize,
commands::piddm_reset,
commands::piddm_start_training,
commands::piddm_training_progress,
commands::piddm_training_result,
commands::piddm_cancel_training,
commands::piddm_start_sampling,
commands::piddm_sampling_progress,
commands::piddm_sampling_result,
// Digital Twin demo commands
commands::digital_twin_initialize,
commands::digital_twin_reset,
commands::digital_twin_start_simulation,
commands::digital_twin_simulation_progress,
commands::digital_twin_simulation_result,
commands::digital_twin_what_if,
commands::digital_twin_get_slice,
// Image Classifier demo commands
commands::image_classifier_initialize,
commands::image_classifier_reset,
commands::image_classifier_classify,
commands::image_classifier_status,
commands::image_classifier_metrics,
commands::image_classifier_is_initialized,
// Time Series Forecast demo commands
commands::timeseries_initialize,
commands::timeseries_reset,
commands::timeseries_fit,
commands::timeseries_forecast,
commands::timeseries_status,
commands::timeseries_is_initialized,
commands::timeseries_generate_sample,
commands::timeseries_get_sample_datasets,
commands::timeseries_get_model_types,
// Portfolio Optimizer demo commands
commands::portfolio_initialize,
commands::portfolio_reset,
commands::portfolio_configure,
commands::portfolio_optimize,
commands::portfolio_efficient_frontier,
commands::portfolio_status,
commands::portfolio_is_initialized,
commands::portfolio_generate_sample,
commands::portfolio_get_presets,
// Risk Analyzer demo commands
commands::risk_analyzer_initialize,
commands::risk_analyzer_reset,
commands::risk_analyzer_analyze,
commands::risk_analyzer_status,
commands::risk_analyzer_is_initialized,
// PINN Benchmark demo commands
commands::pinn_benchmark_initialize,
commands::pinn_benchmark_start_training,
commands::pinn_benchmark_get_status,
commands::pinn_benchmark_compare,
commands::pinn_benchmark_reset,
// FNO Benchmark commands
commands::benchmark_run_classical,
commands::benchmark_run_all,
commands::benchmark_run_with_stats,
commands::benchmark_quick,
// Compute backend detection
commands::get_compute_backend,
// Neuro MEG/EEG commands - File I/O
neuro_commands::neuro_load_edf,
neuro_commands::neuro_load_brainvision,
neuro_commands::neuro_load_fif,
neuro_commands::neuro_load_ctf,
// Neuro MEG/EEG commands - BIDS
neuro_commands::neuro_load_bids,
neuro_commands::neuro_get_bids_subject,
neuro_commands::neuro_get_bids_files,
neuro_commands::neuro_list_bids_datasets,
neuro_commands::neuro_close_bids,
neuro_commands::neuro_get_recording_info,
neuro_commands::neuro_get_data_chunk,
neuro_commands::neuro_get_events,
neuro_commands::neuro_list_recordings,
neuro_commands::neuro_close_recording,
// Neuro MEG/EEG commands - Signal Processing
neuro_commands::neuro_apply_filter,
neuro_commands::neuro_create_epochs,
neuro_commands::neuro_compute_average,
// Neuro MEG/EEG commands - Time-Frequency Analysis
neuro_commands::neuro_compute_tfr,
neuro_commands::neuro_compute_psd,
neuro_commands::neuro_compute_tfr_epochs,
// Neuro MEG/EEG commands - Forward Modeling
neuro_commands::neuro_create_forward_model,
neuro_commands::neuro_get_forward_model,
neuro_commands::neuro_list_forward_models,
// Neuro MEG/EEG commands - Inverse Solutions
neuro_commands::neuro_create_inverse_operator,
neuro_commands::neuro_apply_inverse,
// neuro_commands::neuro_create_beamformer, // Planned for future release
neuro_commands::neuro_list_inverse_operators,
// Neuro MEG/EEG commands - Connectivity
neuro_commands::neuro_compute_connectivity,
neuro_commands::neuro_compute_pac,
// Neuro MEG/EEG commands - SSP/ICA Artifact Removal
neuro_commands::neuro_compute_ssp,
neuro_commands::neuro_apply_ssp,
neuro_commands::neuro_fit_ica,
neuro_commands::neuro_get_ica_sources,
neuro_commands::neuro_apply_ica,
neuro_commands::neuro_list_ica_models,
// Neuro MEG/EEG commands - Statistical Analysis
neuro_commands::neuro_permutation_test,
neuro_commands::neuro_ttest,
neuro_commands::neuro_correct_pvalues,
neuro_commands::neuro_effect_size,
// Neuro MEG/EEG commands - Service Management
neuro_commands::neuro_status,
neuro_commands::neuro_reset,
// Neuro MEG/EEG commands - FreeSurfer Anatomy
neuro_commands::neuro_load_freesurfer_subject,
neuro_commands::neuro_get_surface,
neuro_commands::neuro_get_annotation,
neuro_commands::neuro_get_curvature,
neuro_commands::neuro_list_freesurfer_subjects,
neuro_commands::neuro_close_freesurfer_subject,
// Neuro MEG/EEG commands - Database/Protocol Management
neuro_commands::neuro_open_protocol,
neuro_commands::neuro_create_protocol,
neuro_commands::neuro_get_protocol,
neuro_commands::neuro_list_protocols,
neuro_commands::neuro_delete_protocol,
neuro_commands::neuro_close_database,
// Neuro MEG/EEG commands - Subject Management
neuro_commands::neuro_create_subject,
neuro_commands::neuro_get_subject,
neuro_commands::neuro_list_subjects,
neuro_commands::neuro_delete_subject,
neuro_commands::neuro_set_subject_anatomy,
// Neuro MEG/EEG commands - LSL Streaming
neuro_commands::neuro_lsl_discover,
neuro_commands::neuro_lsl_connect,
neuro_commands::neuro_lsl_disconnect,
neuro_commands::neuro_lsl_get_data,
neuro_commands::neuro_lsl_list_active,
neuro_commands::neuro_lsl_is_connected,
neuro_commands::neuro_lsl_get_sample_count,
neuro_commands::neuro_lsl_clear_buffer,
// Neuro MEG/EEG commands - Real-Time BCI Pipeline
neuro_commands::neuro_bci_create,
neuro_commands::neuro_bci_start,
neuro_commands::neuro_bci_stop,
neuro_commands::neuro_bci_push_sample,
neuro_commands::neuro_bci_get_control_signal,
neuro_commands::neuro_bci_start_calibration,
neuro_commands::neuro_bci_is_calibrated,
neuro_commands::neuro_bci_set_threshold,
neuro_commands::neuro_bci_set_smoothing,
neuro_commands::neuro_bci_latency_stats,
neuro_commands::neuro_bci_status,
neuro_commands::neuro_bci_destroy,
// Neuro MEG/EEG commands - Artifact Detection
neuro_commands::neuro_artifact_types,
neuro_commands::neuro_artifact_detector_create,
neuro_commands::neuro_artifact_detect,
neuro_commands::neuro_artifact_detect_batch,
neuro_commands::neuro_artifact_get_summary,
// Neuro MEG/EEG commands - GNN Brain Graph Analysis
neuro_commands::neuro_build_brain_graph,
neuro_commands::neuro_gnn_create_model,
neuro_commands::neuro_gnn_destroy_model,
neuro_commands::neuro_gnn_predict,
neuro_commands::neuro_gnn_explain,
])
.run(tauri::generate_context!())
.expect("error while running tauri application");
}
#[cfg(test)]
mod tests {
use super::*;
use std::sync::Arc;
#[test]
fn test_app_state_creation() {
let state = AppState::new();
// AppState should have a service with at least one strong reference
assert!(Arc::strong_count(state.service()) >= 1);
}
}