serrf-testdata 0.2.1

Synthetic metabolomics dataset generator for testing SERRF normalization
Documentation
use ndarray::Array2;
use rand::rngs::StdRng;
use rand::{Rng, SeedableRng};
use serrf::{IntensityMatrix, SampleMeta, SampleType, SerrfInput};

/// Configuration for synthetic dataset generation.
pub struct SyntheticConfig {
    /// Number of compounds (rows) in the intensity matrix.
    pub n_compounds: usize,
    /// Number of QC samples interleaved throughout the run.
    pub n_qc: usize,
    /// Number of held-out validate samples.
    pub n_validate: usize,
    /// Number of biological study samples.
    pub n_samples: usize,
    /// Number of batches. Samples are divided evenly across batches by injection order.
    pub n_batches: usize,
    /// Maximum fractional batch offset applied per compound. A value of `0.3` means
    /// batch effects can shift intensity up or down by up to 30%.
    pub batch_offset_magnitude: f64,
    /// Maximum fractional drift applied linearly across the injection sequence.
    /// A value of `0.2` means intensity can increase by up to 20% from first to last injection.
    pub injection_drift_magnitude: f64,
    /// Standard deviation of multiplicative noise applied to each measurement.
    pub noise_std: f64,
    /// Standard deviation of per-compound biological group effects applied to study samples.
    pub biological_signal_std: f64,
    /// RNG seed for reproducible dataset generation.
    pub seed: u64,
}

impl Default for SyntheticConfig {
    fn default() -> Self {
        SyntheticConfig {
            n_compounds: 50,
            n_qc: 24,
            n_validate: 8,
            n_samples: 88, // total = n_qc + n_validate + n_samples = 120
            n_batches: 2,
            batch_offset_magnitude: 0.3,
            injection_drift_magnitude: 0.2,
            noise_std: 0.05,
            biological_signal_std: 0.5,
            seed: 42,
        }
    }
}

/// Generate a synthetic SerrfInput with known drift structure.
///
/// Each raw value is:
///   base_intensity * biological_effect * batch_effect * injection_drift * noise
///
/// QC samples have biological_effect = 1.0 (no biological variation).
/// Biological samples have compound-specific group effects.
pub fn generate_dataset(cfg: &SyntheticConfig) -> SerrfInput {
    let mut rng = StdRng::seed_from_u64(cfg.seed);
    let total = cfg.n_qc + cfg.n_validate + cfg.n_samples;

    // Interleave QC, validate, and biological samples in injection order
    let mut sample_ids = Vec::with_capacity(total);
    let mut sample_types = Vec::with_capacity(total);
    let mut batches = Vec::with_capacity(total);
    let mut injection_orders = Vec::with_capacity(total);

    let qc_interval = total / cfg.n_qc.max(1);
    // Validate samples are distributed at a fixed offset within each QC interval
    // so they span the full injection range rather than clustering at the end.
    let validate_interval = total.checked_div(cfg.n_validate).unwrap_or(usize::MAX);
    let validate_offset = validate_interval / 2;
    let mut qc_placed = 0usize;
    let mut validate_placed = 0usize;

    for pos in 0..total {
        let is_qc = qc_placed < cfg.n_qc
            && (pos % qc_interval == 0 || pos + (cfg.n_qc - qc_placed) >= total - pos);
        let is_validate = !is_qc
            && validate_placed < cfg.n_validate
            && (pos + validate_interval - validate_offset) % validate_interval == 0;

        let (stype, prefix) = if is_qc {
            qc_placed += 1;
            (SampleType::Qc, "qc")
        } else if is_validate {
            validate_placed += 1;
            (SampleType::Validate, "validate")
        } else {
            (SampleType::Sample, "sample")
        };

        let batch = format!(
            "batch_{}",
            (pos / (total / cfg.n_batches.max(1))).min(cfg.n_batches - 1) + 1
        );
        sample_ids.push(format!("{prefix}_{:04}", pos + 1));
        sample_types.push(stype);
        batches.push(batch);
        injection_orders.push((pos + 1) as u32);
    }

    // Per-compound base intensities (log-normal-ish: sample from exponential)
    let base_intensities: Vec<f64> = (0..cfg.n_compounds)
        .map(|_| 1000.0 * (1.0 + rng.random::<f64>() * 9.0))
        .collect();

    // Per-compound biological group effects for biological samples
    let bio_effects: Vec<f64> = (0..cfg.n_compounds)
        .map(|_| 1.0 + rng.random_range(-cfg.biological_signal_std..cfg.biological_signal_std))
        .collect();

    // Per-batch offsets per compound
    let batch_effects: Vec<Vec<f64>> = (0..cfg.n_compounds)
        .map(|_| {
            (0..cfg.n_batches)
                .map(|_| {
                    1.0 + rng.random_range(-cfg.batch_offset_magnitude..cfg.batch_offset_magnitude)
                })
                .collect()
        })
        .collect();

    // Build intensity matrix
    let mut data = Array2::zeros((cfg.n_compounds, total));
    for j in 0..total {
        let batch_idx: usize = batches[j]
            .trim_start_matches("batch_")
            .parse::<usize>()
            .unwrap_or(1)
            - 1;
        let inj_frac = j as f64 / total.max(1) as f64;
        let drift = 1.0 + cfg.injection_drift_magnitude * inj_frac;

        for i in 0..cfg.n_compounds {
            let bio = match sample_types[j] {
                SampleType::Qc | SampleType::Validate => 1.0,
                SampleType::Sample => bio_effects[i],
                _ => 1.0,
            };
            let batch = batch_effects[i][batch_idx.min(cfg.n_batches - 1)];
            let noise = 1.0 + rng.random_range(-cfg.noise_std..cfg.noise_std);
            data[[i, j]] = base_intensities[i] * bio * batch * drift * noise;
        }
    }

    let compound_ids = (0..cfg.n_compounds)
        .map(|i| format!("compound_{:04}", i + 1))
        .collect();

    let metadata: Vec<SampleMeta> = (0..total)
        .map(|j| SampleMeta {
            sample_id: sample_ids[j].clone(),
            sample_type: sample_types[j].clone(),
            batch: batches[j].clone(),
            injection_order: injection_orders[j],
        })
        .collect();

    SerrfInput {
        intensities: IntensityMatrix {
            compound_ids,
            sample_ids,
            data,
        },
        metadata,
    }
}

#[cfg(test)]
mod tests {
    use super::*;

    #[test]
    fn generate_has_correct_shape() {
        let cfg = SyntheticConfig::default();
        let total = cfg.n_qc + cfg.n_validate + cfg.n_samples;
        let input = generate_dataset(&cfg);
        assert_eq!(input.intensities.compound_ids.len(), cfg.n_compounds);
        assert_eq!(input.intensities.sample_ids.len(), total);
        assert_eq!(input.intensities.data.shape(), &[cfg.n_compounds, total]);
    }

    #[test]
    fn generate_has_correct_sample_type_counts() {
        let cfg = SyntheticConfig::default();
        let input = generate_dataset(&cfg);
        let n_qc = input
            .metadata
            .iter()
            .filter(|m| m.sample_type == SampleType::Qc)
            .count();
        let n_val = input
            .metadata
            .iter()
            .filter(|m| m.sample_type == SampleType::Validate)
            .count();
        let n_bio = input
            .metadata
            .iter()
            .filter(|m| m.sample_type == SampleType::Sample)
            .count();
        assert_eq!(n_qc, cfg.n_qc);
        assert_eq!(n_val, cfg.n_validate);
        assert_eq!(n_bio, cfg.n_samples);
    }

    #[test]
    fn generate_is_deterministic() {
        let cfg = SyntheticConfig::default();
        let a = generate_dataset(&cfg);
        let b = generate_dataset(&cfg);
        for i in 0..a.intensities.data.nrows() {
            for j in 0..a.intensities.data.ncols() {
                assert_eq!(a.intensities.data[[i, j]], b.intensities.data[[i, j]]);
            }
        }
    }

    #[test]
    fn generate_values_are_positive() {
        let cfg = SyntheticConfig::default();
        let input = generate_dataset(&cfg);
        for val in input.intensities.data.iter() {
            assert!(*val > 0.0, "got non-positive value: {val}");
        }
    }
}