Files
rustytorch/demos/tumorboard-shared/src/lib.rs
T
osobhandClaude Opus 4.6 02d382d5f6 style: apply rustfmt across all crates and demos
Consistent formatting pass: line wrapping, import sorting, trailing
whitespace removal, let-chain indentation, merged derive attributes,
and unsafe block reformatting.

Co-Authored-By: Claude Opus 4.6 (1M context) <[email protected]>
2026-04-12 07:01:58 -07:00

803 lines
21 KiB
Rust

//! Shared IPC types for `TumorBoard` AI multi-modal medical imaging demo.
//!
//! This crate provides data structures for communication between
//! the Tauri frontend and Rust backend for multi-modal tumor analysis.
#![allow(missing_docs)] // Demo crate - documentation not required for all items
use serde::{Deserialize, Serialize};
// ============================================================================
// Imaging Types
// ============================================================================
/// Medical imaging modality.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
#[serde(rename_all = "snake_case")]
pub enum ImagingModality {
/// Computed Tomography
CT,
/// Magnetic Resonance Imaging
MRI,
/// Positron Emission Tomography
PET,
/// Digital pathology (whole slide imaging)
Pathology,
/// Ultrasound
Ultrasound,
/// X-ray
XRay,
/// Mammography
Mammography,
}
impl ImagingModality {
/// Get display name.
#[must_use]
pub fn display_name(&self) -> &'static str {
match self {
ImagingModality::CT => "CT Scan",
ImagingModality::MRI => "MRI",
ImagingModality::PET => "PET Scan",
ImagingModality::Pathology => "Pathology Slide",
ImagingModality::Ultrasound => "Ultrasound",
ImagingModality::XRay => "X-Ray",
ImagingModality::Mammography => "Mammography",
}
}
}
/// Medical image metadata.
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct ImageMetadata {
/// Image ID
pub id: String,
/// Modality
pub modality: ImagingModality,
/// Acquisition date
pub acquisition_date: String,
/// Image dimensions
pub dimensions: ImageDimensions,
/// Pixel/voxel spacing (mm)
pub spacing: [f32; 3],
/// Body region
pub body_region: BodyRegion,
/// Series description
pub series_description: Option<String>,
}
/// Image dimensions.
#[derive(Debug, Clone, Copy, Serialize, Deserialize)]
pub struct ImageDimensions {
/// Width (pixels)
pub width: usize,
/// Height (pixels)
pub height: usize,
/// Depth (slices for 3D)
pub depth: usize,
}
/// Body region.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
#[serde(rename_all = "snake_case")]
pub enum BodyRegion {
Head,
Neck,
Chest,
Abdomen,
Pelvis,
Extremity,
WholeBody,
}
// ============================================================================
// Analysis Types
// ============================================================================
/// Case analysis request.
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct CaseAnalysisRequest {
/// Case ID
pub case_id: String,
/// Patient info (anonymized)
pub patient_info: PatientInfo,
/// Available imaging studies
pub studies: Vec<ImagingStudy>,
/// Clinical context
pub clinical_context: ClinicalContext,
/// Analysis configuration
pub config: AnalysisConfig,
}
/// Patient information (anonymized).
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct PatientInfo {
/// Age (years)
pub age: Option<u8>,
/// Sex
pub sex: Option<Sex>,
/// Relevant medical history
pub medical_history: Vec<String>,
}
/// Patient sex.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
pub enum Sex {
Male,
Female,
Other,
}
/// Imaging study.
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct ImagingStudy {
/// Study ID
pub study_id: String,
/// Modality
pub modality: ImagingModality,
/// Images in study
pub images: Vec<ImageMetadata>,
/// Study description
pub description: Option<String>,
}
/// Clinical context for analysis.
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct ClinicalContext {
/// Primary clinical question
pub clinical_question: String,
/// Known diagnosis
pub known_diagnosis: Option<String>,
/// Relevant lab values
pub lab_values: Vec<LabValue>,
/// Prior treatments
pub prior_treatments: Vec<String>,
}
/// Laboratory value.
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct LabValue {
/// Test name
pub name: String,
/// Value
pub value: f32,
/// Unit
pub unit: String,
/// Reference range
pub reference_range: Option<(f32, f32)>,
}
/// Analysis configuration.
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct AnalysisConfig {
/// Run CT analysis
pub analyze_ct: bool,
/// Run MRI analysis
pub analyze_mri: bool,
/// Run pathology analysis
pub analyze_pathology: bool,
/// Generate report
pub generate_report: bool,
/// Include explainability
pub include_explanations: bool,
}
impl Default for AnalysisConfig {
fn default() -> Self {
Self {
analyze_ct: true,
analyze_mri: true,
analyze_pathology: true,
generate_report: true,
include_explanations: true,
}
}
}
// ============================================================================
// Finding Types
// ============================================================================
/// Analysis result.
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct CaseAnalysisResult {
/// Case ID
pub case_id: String,
/// CT findings
pub ct_findings: Option<CTFindings>,
/// MRI findings
pub mri_findings: Option<MRIFindings>,
/// Pathology findings
pub pathology_findings: Option<PathologyFindings>,
/// Fused analysis
pub fused_analysis: FusedAnalysis,
/// Generated report
pub report: Option<MedicalReport>,
/// Recommendations
pub recommendations: Vec<Recommendation>,
/// Analysis metadata
pub metadata: AnalysisMetadata,
}
/// CT scan findings.
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct CTFindings {
/// Detected lesions
pub lesions: Vec<Lesion>,
/// Organ measurements
pub organ_measurements: Vec<OrganMeasurement>,
/// Hounsfield unit analysis
pub hu_analysis: Vec<RegionHU>,
/// Overall assessment
pub assessment: String,
/// Confidence score
pub confidence: f32,
}
/// MRI findings.
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct MRIFindings {
/// Detected lesions
pub lesions: Vec<Lesion>,
/// Sequence-specific findings
pub sequence_findings: Vec<SequenceFinding>,
/// Enhancement pattern
pub enhancement_pattern: Option<EnhancementPattern>,
/// Overall assessment
pub assessment: String,
/// Confidence score
pub confidence: f32,
}
/// Pathology findings.
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct PathologyFindings {
/// Cell classifications
pub cell_classifications: Vec<CellClassification>,
/// Tissue architecture
pub tissue_architecture: TissueArchitecture,
/// Biomarker status
pub biomarkers: Vec<Biomarker>,
/// Grade/stage if applicable
pub grading: Option<TumorGrade>,
/// Overall assessment
pub assessment: String,
/// Confidence score
pub confidence: f32,
}
/// Detected lesion.
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct Lesion {
/// Lesion ID
pub id: String,
/// Location
pub location: LesionLocation,
/// Size (mm)
pub size: [f32; 3],
/// Volume (mm³)
pub volume: f32,
/// Lesion type
pub lesion_type: LesionType,
/// Malignancy probability
pub malignancy_probability: f32,
/// Confidence
pub confidence: f32,
}
/// Lesion location.
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct LesionLocation {
/// Organ
pub organ: String,
/// Anatomical region
pub region: String,
/// Center coordinates (mm)
pub center: [f32; 3],
}
/// Lesion type.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
#[serde(rename_all = "snake_case")]
pub enum LesionType {
Mass,
Nodule,
Cyst,
Infiltrative,
Calcification,
Enhancement,
Other,
}
/// Organ measurement.
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct OrganMeasurement {
/// Organ name
pub organ: String,
/// Measurement type
pub measurement_type: String,
/// Value
pub value: f32,
/// Unit
pub unit: String,
/// Normal range
pub normal_range: Option<(f32, f32)>,
/// Is abnormal
pub is_abnormal: bool,
}
/// Hounsfield unit analysis for a region.
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct RegionHU {
/// Region name
pub region: String,
/// Mean HU
pub mean: f32,
/// Standard deviation
pub std_dev: f32,
/// Interpretation
pub interpretation: String,
}
/// MRI sequence-specific finding.
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct SequenceFinding {
/// Sequence name (T1, T2, DWI, etc.)
pub sequence: String,
/// Finding description
pub finding: String,
/// Signal characteristics
pub signal: SignalCharacteristic,
}
/// MRI signal characteristic.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
#[serde(rename_all = "snake_case")]
pub enum SignalCharacteristic {
Hyperintense,
Isointense,
Hypointense,
Heterogeneous,
}
/// Enhancement pattern.
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct EnhancementPattern {
/// Pattern type
pub pattern: String,
/// Enhancement degree
pub degree: EnhancementDegree,
/// Description
pub description: String,
}
/// Enhancement degree.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
#[serde(rename_all = "snake_case")]
pub enum EnhancementDegree {
None,
Mild,
Moderate,
Avid,
}
/// Cell classification result.
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct CellClassification {
/// Cell type
pub cell_type: String,
/// Count
pub count: usize,
/// Percentage
pub percentage: f32,
/// Abnormality score
pub abnormality: f32,
}
/// Tissue architecture analysis.
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct TissueArchitecture {
/// Pattern
pub pattern: String,
/// Is preserved
pub is_preserved: bool,
/// Notable features
pub features: Vec<String>,
}
/// Biomarker status.
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct Biomarker {
/// Marker name
pub name: String,
/// Status
pub status: BiomarkerStatus,
/// Expression level
pub expression: Option<f32>,
}
/// Biomarker status.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
#[serde(rename_all = "snake_case")]
pub enum BiomarkerStatus {
Positive,
Negative,
Equivocal,
NotTested,
}
/// Tumor grade.
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct TumorGrade {
/// Grading system
pub system: String,
/// Grade
pub grade: String,
/// Description
pub description: String,
}
// ============================================================================
// Fused Analysis Types
// ============================================================================
/// Fused multi-modal analysis.
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct FusedAnalysis {
/// Primary diagnosis
pub primary_diagnosis: Diagnosis,
/// Differential diagnoses
pub differential_diagnoses: Vec<Diagnosis>,
/// Cross-modal correlations
pub correlations: Vec<ModalityCorrelation>,
/// Integrated tumor assessment
pub tumor_assessment: Option<TumorAssessment>,
/// Overall confidence
pub confidence: f32,
}
/// Diagnosis with probability.
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct Diagnosis {
/// ICD-10 code
pub icd_code: Option<String>,
/// Diagnosis name
pub name: String,
/// Probability
pub probability: f32,
/// Supporting evidence
pub evidence: Vec<Evidence>,
}
/// Evidence for diagnosis.
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct Evidence {
/// Source modality
pub modality: ImagingModality,
/// Finding description
pub finding: String,
/// Contribution weight
pub weight: f32,
}
/// Cross-modality correlation.
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct ModalityCorrelation {
/// First modality
pub modality_a: ImagingModality,
/// Second modality
pub modality_b: ImagingModality,
/// Correlation type
pub correlation_type: CorrelationType,
/// Description
pub description: String,
}
/// Correlation type.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
#[serde(rename_all = "snake_case")]
pub enum CorrelationType {
Concordant,
Complementary,
Discordant,
}
/// Integrated tumor assessment.
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct TumorAssessment {
/// TNM staging
pub tnm_stage: Option<TNMStage>,
/// Response assessment
pub response: Option<TreatmentResponse>,
/// Prognostic factors
pub prognostic_factors: Vec<PrognosticFactor>,
}
/// TNM staging.
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct TNMStage {
/// T (tumor)
pub t: String,
/// N (nodes)
pub n: String,
/// M (metastasis)
pub m: String,
/// Overall stage
pub overall_stage: String,
}
/// Treatment response assessment.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
#[serde(rename_all = "snake_case")]
pub enum TreatmentResponse {
CompleteResponse,
PartialResponse,
StableDisease,
ProgressiveDisease,
}
/// Prognostic factor.
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct PrognosticFactor {
/// Factor name
pub name: String,
/// Value/status
pub value: String,
/// Impact
pub impact: PrognosticImpact,
}
/// Prognostic impact.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
#[serde(rename_all = "snake_case")]
pub enum PrognosticImpact {
Favorable,
Neutral,
Unfavorable,
}
// ============================================================================
// Report Types
// ============================================================================
/// Medical report.
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct MedicalReport {
/// Report sections
pub sections: Vec<ReportSection>,
/// Key findings summary
pub summary: String,
/// Impression
pub impression: String,
/// Report metadata
pub metadata: ReportMetadata,
}
/// Report section.
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct ReportSection {
/// Section title
pub title: String,
/// Content
pub content: String,
/// References to images
pub image_references: Vec<String>,
}
/// Report metadata.
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct ReportMetadata {
/// Generation timestamp
pub generated_at: String,
/// AI model version
pub model_version: String,
/// Disclaimer
pub disclaimer: String,
}
/// Clinical recommendation.
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct Recommendation {
/// Recommendation type
pub recommendation_type: RecommendationType,
/// Description
pub description: String,
/// Priority
pub priority: Priority,
/// Rationale
pub rationale: String,
}
/// Recommendation type.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
#[serde(rename_all = "snake_case")]
pub enum RecommendationType {
ImagingFollowUp,
Biopsy,
LabTest,
Referral,
Treatment,
Surveillance,
}
/// Priority level.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
#[serde(rename_all = "snake_case")]
pub enum Priority {
Urgent,
High,
Moderate,
Routine,
}
/// Analysis metadata.
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct AnalysisMetadata {
/// Processing time (seconds)
pub processing_time: f32,
/// Models used
pub models_used: Vec<String>,
/// Timestamp
pub timestamp: String,
}
// ============================================================================
// Sample Data
// ============================================================================
/// Get sample case for demo.
#[must_use]
pub fn get_sample_case() -> CaseAnalysisRequest {
CaseAnalysisRequest {
case_id: "CASE-001".to_string(),
patient_info: PatientInfo {
age: Some(62),
sex: Some(Sex::Male),
medical_history: vec![
"Former smoker (30 pack-years)".to_string(),
"Hypertension".to_string(),
],
},
studies: vec![
ImagingStudy {
study_id: "CT-001".to_string(),
modality: ImagingModality::CT,
images: vec![ImageMetadata {
id: "CT-001-001".to_string(),
modality: ImagingModality::CT,
acquisition_date: "2024-01-15".to_string(),
dimensions: ImageDimensions {
width: 512,
height: 512,
depth: 200,
},
spacing: [0.7, 0.7, 1.5],
body_region: BodyRegion::Chest,
series_description: Some("Chest CT with contrast".to_string()),
}],
description: Some("Chest CT with IV contrast".to_string()),
},
ImagingStudy {
study_id: "MRI-001".to_string(),
modality: ImagingModality::MRI,
images: vec![ImageMetadata {
id: "MRI-001-001".to_string(),
modality: ImagingModality::MRI,
acquisition_date: "2024-01-16".to_string(),
dimensions: ImageDimensions {
width: 256,
height: 256,
depth: 60,
},
spacing: [1.0, 1.0, 3.0],
body_region: BodyRegion::Chest,
series_description: Some("T2 FLAIR".to_string()),
}],
description: Some("Brain MRI".to_string()),
},
],
clinical_context: ClinicalContext {
clinical_question: "Evaluate for primary lung malignancy".to_string(),
known_diagnosis: None,
lab_values: vec![LabValue {
name: "CEA".to_string(),
value: 8.5,
unit: "ng/mL".to_string(),
reference_range: Some((0.0, 3.0)),
}],
prior_treatments: vec![],
},
config: AnalysisConfig::default(),
}
}
// ============================================================================
// Tests
// ============================================================================
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn test_imaging_modality() {
assert_eq!(ImagingModality::CT.display_name(), "CT Scan");
assert_eq!(ImagingModality::MRI.display_name(), "MRI");
}
#[test]
fn test_analysis_config_default() {
let config = AnalysisConfig::default();
assert!(config.analyze_ct);
assert!(config.generate_report);
}
#[test]
fn test_sample_case() {
let case = get_sample_case();
assert!(!case.case_id.is_empty());
assert!(!case.studies.is_empty());
}
#[test]
fn test_serialization() {
let case = get_sample_case();
let json = serde_json::to_string(&case).unwrap();
assert!(json.contains("CASE-001"));
}
#[test]
fn test_lesion_type() {
let lesion = Lesion {
id: "L001".to_string(),
location: LesionLocation {
organ: "Lung".to_string(),
region: "Right upper lobe".to_string(),
center: [100.0, 150.0, 80.0],
},
size: [25.0, 20.0, 18.0],
volume: 4712.0,
lesion_type: LesionType::Nodule,
malignancy_probability: 0.75,
confidence: 0.92,
};
assert_eq!(lesion.lesion_type, LesionType::Nodule);
}
#[test]
fn test_biomarker_status() {
let marker = Biomarker {
name: "PD-L1".to_string(),
status: BiomarkerStatus::Positive,
expression: Some(80.0),
};
assert_eq!(marker.status, BiomarkerStatus::Positive);
}
#[test]
fn test_tnm_staging() {
let stage = TNMStage {
t: "T2a".to_string(),
n: "N0".to_string(),
m: "M0".to_string(),
overall_stage: "IB".to_string(),
};
assert_eq!(stage.overall_stage, "IB");
}
#[test]
fn test_recommendation() {
let rec = Recommendation {
recommendation_type: RecommendationType::Biopsy,
description: "CT-guided biopsy of lung nodule".to_string(),
priority: Priority::High,
rationale: "Required for tissue diagnosis".to_string(),
};
assert_eq!(rec.priority, Priority::High);
}
}