Skip to main content

serrf_testdata/
synthetic.rs

1use ndarray::Array2;
2use rand::rngs::StdRng;
3use rand::{Rng, SeedableRng};
4use serrf::{IntensityMatrix, SampleMeta, SampleType, SerrfInput};
5
6/// Configuration for synthetic dataset generation.
7pub struct SyntheticConfig {
8    /// Number of compounds (rows) in the intensity matrix.
9    pub n_compounds: usize,
10    /// Number of QC samples interleaved throughout the run.
11    pub n_qc: usize,
12    /// Number of held-out validate samples.
13    pub n_validate: usize,
14    /// Number of biological study samples.
15    pub n_samples: usize,
16    /// Number of batches. Samples are divided evenly across batches by injection order.
17    pub n_batches: usize,
18    /// Maximum fractional batch offset applied per compound. A value of `0.3` means
19    /// batch effects can shift intensity up or down by up to 30%.
20    pub batch_offset_magnitude: f64,
21    /// Maximum fractional drift applied linearly across the injection sequence.
22    /// A value of `0.2` means intensity can increase by up to 20% from first to last injection.
23    pub injection_drift_magnitude: f64,
24    /// Standard deviation of multiplicative noise applied to each measurement.
25    pub noise_std: f64,
26    /// Standard deviation of per-compound biological group effects applied to study samples.
27    pub biological_signal_std: f64,
28    /// RNG seed for reproducible dataset generation.
29    pub seed: u64,
30}
31
32impl Default for SyntheticConfig {
33    fn default() -> Self {
34        SyntheticConfig {
35            n_compounds: 50,
36            n_qc: 24,
37            n_validate: 8,
38            n_samples: 88, // total = n_qc + n_validate + n_samples = 120
39            n_batches: 2,
40            batch_offset_magnitude: 0.3,
41            injection_drift_magnitude: 0.2,
42            noise_std: 0.05,
43            biological_signal_std: 0.5,
44            seed: 42,
45        }
46    }
47}
48
49/// Generate a synthetic SerrfInput with known drift structure.
50///
51/// Each raw value is:
52///   base_intensity * biological_effect * batch_effect * injection_drift * noise
53///
54/// QC samples have biological_effect = 1.0 (no biological variation).
55/// Biological samples have compound-specific group effects.
56pub fn generate_dataset(cfg: &SyntheticConfig) -> SerrfInput {
57    let mut rng = StdRng::seed_from_u64(cfg.seed);
58    let total = cfg.n_qc + cfg.n_validate + cfg.n_samples;
59
60    // Interleave QC, validate, and biological samples in injection order
61    let mut sample_ids = Vec::with_capacity(total);
62    let mut sample_types = Vec::with_capacity(total);
63    let mut batches = Vec::with_capacity(total);
64    let mut injection_orders = Vec::with_capacity(total);
65
66    let qc_interval = total / cfg.n_qc.max(1);
67    // Validate samples are distributed at a fixed offset within each QC interval
68    // so they span the full injection range rather than clustering at the end.
69    let validate_interval = total.checked_div(cfg.n_validate).unwrap_or(usize::MAX);
70    let validate_offset = validate_interval / 2;
71    let mut qc_placed = 0usize;
72    let mut validate_placed = 0usize;
73
74    for pos in 0..total {
75        let is_qc = qc_placed < cfg.n_qc
76            && (pos % qc_interval == 0 || pos + (cfg.n_qc - qc_placed) >= total - pos);
77        let is_validate = !is_qc
78            && validate_placed < cfg.n_validate
79            && (pos + validate_interval - validate_offset) % validate_interval == 0;
80
81        let (stype, prefix) = if is_qc {
82            qc_placed += 1;
83            (SampleType::Qc, "qc")
84        } else if is_validate {
85            validate_placed += 1;
86            (SampleType::Validate, "validate")
87        } else {
88            (SampleType::Sample, "sample")
89        };
90
91        let batch = format!(
92            "batch_{}",
93            (pos / (total / cfg.n_batches.max(1))).min(cfg.n_batches - 1) + 1
94        );
95        sample_ids.push(format!("{prefix}_{:04}", pos + 1));
96        sample_types.push(stype);
97        batches.push(batch);
98        injection_orders.push((pos + 1) as u32);
99    }
100
101    // Per-compound base intensities (log-normal-ish: sample from exponential)
102    let base_intensities: Vec<f64> = (0..cfg.n_compounds)
103        .map(|_| 1000.0 * (1.0 + rng.random::<f64>() * 9.0))
104        .collect();
105
106    // Per-compound biological group effects for biological samples
107    let bio_effects: Vec<f64> = (0..cfg.n_compounds)
108        .map(|_| 1.0 + rng.random_range(-cfg.biological_signal_std..cfg.biological_signal_std))
109        .collect();
110
111    // Per-batch offsets per compound
112    let batch_effects: Vec<Vec<f64>> = (0..cfg.n_compounds)
113        .map(|_| {
114            (0..cfg.n_batches)
115                .map(|_| {
116                    1.0 + rng.random_range(-cfg.batch_offset_magnitude..cfg.batch_offset_magnitude)
117                })
118                .collect()
119        })
120        .collect();
121
122    // Build intensity matrix
123    let mut data = Array2::zeros((cfg.n_compounds, total));
124    for j in 0..total {
125        let batch_idx: usize = batches[j]
126            .trim_start_matches("batch_")
127            .parse::<usize>()
128            .unwrap_or(1)
129            - 1;
130        let inj_frac = j as f64 / total.max(1) as f64;
131        let drift = 1.0 + cfg.injection_drift_magnitude * inj_frac;
132
133        for i in 0..cfg.n_compounds {
134            let bio = match sample_types[j] {
135                SampleType::Qc | SampleType::Validate => 1.0,
136                SampleType::Sample => bio_effects[i],
137                _ => 1.0,
138            };
139            let batch = batch_effects[i][batch_idx.min(cfg.n_batches - 1)];
140            let noise = 1.0 + rng.random_range(-cfg.noise_std..cfg.noise_std);
141            data[[i, j]] = base_intensities[i] * bio * batch * drift * noise;
142        }
143    }
144
145    let compound_ids = (0..cfg.n_compounds)
146        .map(|i| format!("compound_{:04}", i + 1))
147        .collect();
148
149    let metadata: Vec<SampleMeta> = (0..total)
150        .map(|j| SampleMeta {
151            sample_id: sample_ids[j].clone(),
152            sample_type: sample_types[j].clone(),
153            batch: batches[j].clone(),
154            injection_order: injection_orders[j],
155        })
156        .collect();
157
158    SerrfInput {
159        intensities: IntensityMatrix {
160            compound_ids,
161            sample_ids,
162            data,
163        },
164        metadata,
165    }
166}
167
168#[cfg(test)]
169mod tests {
170    use super::*;
171
172    #[test]
173    fn generate_has_correct_shape() {
174        let cfg = SyntheticConfig::default();
175        let total = cfg.n_qc + cfg.n_validate + cfg.n_samples;
176        let input = generate_dataset(&cfg);
177        assert_eq!(input.intensities.compound_ids.len(), cfg.n_compounds);
178        assert_eq!(input.intensities.sample_ids.len(), total);
179        assert_eq!(input.intensities.data.shape(), &[cfg.n_compounds, total]);
180    }
181
182    #[test]
183    fn generate_has_correct_sample_type_counts() {
184        let cfg = SyntheticConfig::default();
185        let input = generate_dataset(&cfg);
186        let n_qc = input
187            .metadata
188            .iter()
189            .filter(|m| m.sample_type == SampleType::Qc)
190            .count();
191        let n_val = input
192            .metadata
193            .iter()
194            .filter(|m| m.sample_type == SampleType::Validate)
195            .count();
196        let n_bio = input
197            .metadata
198            .iter()
199            .filter(|m| m.sample_type == SampleType::Sample)
200            .count();
201        assert_eq!(n_qc, cfg.n_qc);
202        assert_eq!(n_val, cfg.n_validate);
203        assert_eq!(n_bio, cfg.n_samples);
204    }
205
206    #[test]
207    fn generate_is_deterministic() {
208        let cfg = SyntheticConfig::default();
209        let a = generate_dataset(&cfg);
210        let b = generate_dataset(&cfg);
211        for i in 0..a.intensities.data.nrows() {
212            for j in 0..a.intensities.data.ncols() {
213                assert_eq!(a.intensities.data[[i, j]], b.intensities.data[[i, j]]);
214            }
215        }
216    }
217
218    #[test]
219    fn generate_values_are_positive() {
220        let cfg = SyntheticConfig::default();
221        let input = generate_dataset(&cfg);
222        for val in input.intensities.data.iter() {
223            assert!(*val > 0.0, "got non-positive value: {val}");
224        }
225    }
226}