serrf-testdata 0.2.0

Synthetic metabolomics dataset generator for testing SERRF normalization
Documentation
# serrf

Rust implementation of **SERRF**: Systematic Error Removal Using Random Forest.

SERRF is a QC-sample-based normalization algorithm for large-scale untargeted metabolomics and lipidomics data. It trains a random forest model per compound on quality-control samples to estimate systematic measurement drift, then applies a multiplicative correction to all samples.

Reference implementations:
- Original R/Shiny: [SERRFweb]https://github.com/slfan2013/Shiny-SERRF - Fan, S. et al. (2019)
- Python: [pySERRF]https://github.com/matteobolner/pyserrf

Original paper:
> Fan, S., Kind, T., Cajka, T., Dolinoy, D. C., Halden, R. U., Barupal, D. K., ... & Fiehn, O. (2019).
> Systematic Error Removal Using Random Forest for Normalizing Large-Scale Untargeted Lipidomics Data.
> *Analytical Chemistry*, 91(5), 3590-3596. https://doi.org/10.1021/acs.analchem.8b05592

The example dataset bundled in `examples/shiny/` is converted from `SERRF example dataset.xlsx`
(not included here; download it from
the [Shiny-SERRF repository](https://github.com/slfan2013/Shiny-SERRF), MIT License) and is used here
for validation purposes.

---

## Quick start: Shiny-SERRF example dataset

The repository includes the example dataset from the original Shiny-SERRF project (268 compounds,
1299 samples across multiple batches). Pre-converted CSVs are in `examples/shiny/`.

```bash
cargo run -p serrf-cli -- normalize \
  --intensities examples/shiny/intensities.csv \
  --metadata    examples/shiny/metadata.csv \
  --output      /tmp/shiny_normalized.csv \
  --report      /tmp/shiny_report.json
```

Expected output:

```
Normalized 268/268 compounds.
Median QC train RSD:    0.2760 -> 0.1086, improvement 2.54x.
Median QC validate RSD: 0.2786 -> 0.1220, improvement 2.28x.
```

To regenerate the CSVs from the raw XLSX (requires Python 3, no extra packages):

```bash
python3 scripts/convert_shiny_serrf_xlsx.py \
  "SERRF example dataset.xlsx" \
  examples/shiny/intensities.csv \
  examples/shiny/metadata.csv
```

---

## Input format

Two CSV files are required.

### intensities.csv

Rows are compounds, columns are samples. First column is compound ID. Empty cells are treated as missing (NaN). Invalid non-numeric cells are errors.

```csv
compound,sample_001,sample_002,qc_001
glucose,123.4,125.0,120.0
lactate,55.1,,54.9
```

### metadata.csv

One row per sample. Supported sample types: `qc`, `sample`, `validate`.

```csv
sample_id,sample_type,batch,injection_order
qc_001,qc,A,1
sample_001,sample,A,2
sample_002,sample,A,3
```

Every sample column in the intensity file must have a metadata row, and vice versa.

---

## CLI usage

```bash
serrf normalize \
  --intensities intensities.csv \
  --metadata metadata.csv \
  --output normalized.csv \
  --report report.json \
  --seed 42 \
  --trees 500
```

All flags:

| Flag | Default | Description |
|------|---------|-------------|
| `--intensities` | required | Intensity matrix CSV |
| `--metadata` | required | Sample metadata CSV |
| `--output` | required | Normalized CSV output path |
| `--report` | required | JSON report output path |
| `--trees` | 500 | Number of RF trees per compound |
| `--max-depth` | unlimited | Maximum tree depth |
| `--min-samples-leaf` | 1 | Minimum samples per leaf |
| `--qc-validation-fraction` | 0.2 | Fraction of QC held out as validation (when no explicit validate samples), 0 to 1 |
| `--seed` | 42 | Random seed |
| `--min-qc-non-missing-fraction` | 0.6 | Minimum fraction of non-missing QC values required per compound, 0 to 1 (at least 2 values are always required) |
| `--epsilon` | 1e-12 | Near-zero threshold |
| `--use-correlated-compounds` | false | Include other compound intensities as predictors |
| `--log-space` | false | Train RF on log-transformed intensities (recommended for log-normal data) |
| `--quiet` | false | Suppress stderr summary |

---

## Algorithm

For each compound:

1. Select QC training samples with at least `min-qc-non-missing-fraction` non-missing values.
2. Build a feature matrix: injection order (normalized to [0,1]), batch index, and optionally other compound intensities.
3. Train a random forest regressor to predict the compound's intensity from those features.
4. Predict for all samples.
5. Apply multiplicative correction: `normalized = raw / prediction * anchor`, where `anchor = mean(predictions at QC training samples)`.

Compounds with too few QC values, invalid predictions, or invalid anchors are skipped and their raw values are copied unchanged to the output.

---

## Metrics

The report includes:

- `median_qc_train_rsd_before` / `after`: median relative standard deviation across QC training samples, before and after normalization.
- `median_qc_validate_rsd_before` / `after`: same for validation QC.
- `qc_train_rsd_improvement_ratio`: before/after ratio. Values above 1.0 indicate improvement.
- Per-compound `qc_train_rsd_before` / `after` and skip reasons.

---

## Warnings and skipped compounds

The report includes a `warnings` array. Compounds are skipped when:

- `insufficient_qc`: too few non-missing QC values.
- `invalid_anchor`: the mean RF prediction at QC training samples is near zero or non-finite.
- `model_training_failed` / `prediction_failed`: the RF model failed. The warning's `detail` field holds the model's error message.

Skipped compounds have their raw values copied unchanged to the output.

In `--log-space` mode, values of zero or below have no logarithm and are copied unchanged.

If no compound is normalized, the CLI exits with an error but still writes the report.

---

## Verification

Property tests (proptest) run with `cargo test`. Kani proofs cover the small numeric helpers
(QC threshold, injection-order scaling, improvement ratio) for every `f64` input:

```bash
cargo kani -p serrf
```

To run both inside a CPU- and memory-capped cgroup (Linux with systemd):

```bash
scripts/verify-bounded.sh            # proptest + kani
scripts/verify-bounded.sh kani       # one of: proptest, kani
MEM_MAX=8G CPU_QUOTA=200% scripts/verify-bounded.sh
```

Defaults: 4 GiB memory (no swap), 4 cores, 4 rayon threads, 20 minutes per step. A job
that goes over the memory cap is killed, not swapped.

---

## Limitations

- Batch encoding is integer-based. One-hot encoding would be more correct for large batch counts.
- `use-correlated-compounds` is off by default; it increases runtime and can remove biological signal if biological variation correlates with injection order.
- Numerically validated on the Shiny-SERRF example dataset (same RSD improvement direction); output values are not bit-for-bit identical to SERRFweb or pySERRF due to different RF implementations.

---

## Future work

- One-hot batch encoding
- Python bindings via pyo3 (`serrf-py`)
- PCA report output
- MTBLS79 / pySERRF metric golden comparison
- Config file support (`--config serrf.toml`)