openreadout_assay/lib.rs
1//! Plate-reader assay analysis: the standard next steps after reading a plate, as
2//! deterministic, documented building blocks.
3//!
4//! - **Layouts**: well roles (blank, standard, sample, positive/negative control, empty),
5//! samples, compounds, concentrations and dilutions from a plate-map grid or long CSV, from
6//! the layout a vendor export embeds (Gen5 `Well ID`, SkanIt `Sample`, BMG `Content`), or from
7//! well flags.
8//! - **Wells**: blank subtraction (mean of the blanks), replicate groups (mean, SD, CV %),
9//! outlier flags (modified z-score or Grubbs).
10//! - **Standard curves**: linear, 4PL, 5PL least squares with weighting, parameter standard
11//! errors and confidence intervals, R², residuals, back-calculated concentrations with range
12//! flags and LLOQ/ULOQ.
13//! - **Dose-response**: IC50/EC50 with confidence interval, Hill slope, top and bottom per
14//! compound, optionally normalised to controls.
15//! - **Kinetics** and **growth curves**: max slope (Vmax), lag, time to max, AUC; growth rate,
16//! doubling time, logistic fit.
17//! - **Assay quality**: Z′, signal/background, signal/noise, SSMD, CVs.
18//!
19//! Methods and conventions: `book/src/guides/plate-analysis.md`. Validation against SciPy, R `drc` and
20//! `growthcurver` (run as black boxes) and against vendor-computed results stored in Gen5 and
21//! SkanIt exports: `docs/provenance/plate-analysis.md`.
22//!
23//! # Example
24//!
25//! ```no_run
26//! use std::path::Path;
27//!
28//! use openreadout_assay::{Analysis, AssayRequest, analyze_file};
29//! use openreadout_core::Registry;
30//!
31//! # fn registry() -> Registry { Registry::new() }
32//! let req = AssayRequest {
33//! analysis: Analysis::Curve,
34//! standards: Some("A1,A2=100;B1,B2=50;C1,C2=25;D1,D2=12.5;E1,E2=6.25".into()),
35//! blank_wells: Some("H1,H2".into()),
36//! ..AssayRequest::default()
37//! };
38//! let out = analyze_file(®istry(), Path::new("elisa.txt"), &req)?;
39//! for w in &out.wells {
40//! println!("{} {:?} {:?}", w.well, w.back_calculated, w.flag);
41//! }
42//! # Ok::<(), openreadout_core::Error>(())
43//! ```
44#![forbid(unsafe_code)]
45#![warn(missing_docs)]
46#![allow(clippy::many_single_char_names)]
47// Exact float equality is intended where it is used: concentration levels, asymptotes and time
48// stamps copied from the same source are compared as written.
49#![allow(clippy::float_cmp)]
50
51mod assay;
52mod data;
53pub mod fit;
54pub mod kinetics;
55pub mod layout;
56mod linalg;
57mod output;
58mod plot;
59mod request;
60mod roles;
61pub mod stats;
62mod tables;
63
64use std::path::Path;
65
66use openreadout_core::{Error, Registry, Result};
67
68pub use assay::{
69 DEFAULT_GRUBBS_ALPHA, DEFAULT_MAD_THRESHOLD, DEFAULT_WINDOW, LOQ_TOLERANCE_PERCENT,
70 MAD_MIN_GROUP, run, user_layout,
71};
72pub use data::{Obs, PlateData, ReadInfo};
73pub use output::{
74 AssayOutput, BlankSummary, CompoundRow, CurvePoint, CurveReport, FitReport, GroupStats,
75 GrowthRow, KineticRow, LayoutSummary, OutlierSummary, ParamRow, QualityReport, ReadSummary,
76 SampleRow, WellRow,
77};
78pub use plot::render as render_plot;
79pub use request::{Analysis, AssayRequest, BlankMode, FitOn, Normalize, OutlierRule, Reduce};
80pub use tables::{render_text, to_csv, write_tables};
81
82/// Largest long-CSV input read (plate data is small).
83const MAX_CSV_BYTES: u64 = 64 << 20;
84
85/// Load the plate of `path`: a long CSV (`well`, `value`, …) is read directly; anything else is
86/// opened with the registry (plate-reader exports).
87pub fn load_plate(reg: &Registry, path: &Path, table: u32) -> Result<PlateData> {
88 let is_text = path.extension().and_then(|e| e.to_str()).is_some_and(|e| {
89 matches!(
90 e.to_ascii_lowercase().as_str(),
91 "csv" | "tsv" | "txt" | "tab"
92 )
93 });
94 if is_text {
95 let meta = std::fs::metadata(path).map_err(|e| Error::io(path, e))?;
96 if meta.len() <= MAX_CSV_BYTES {
97 let bytes = std::fs::read(path).map_err(|e| Error::io(path, e))?;
98 let text = String::from_utf8_lossy(&bytes);
99 if PlateData::is_long_csv(&text) {
100 return PlateData::from_long_csv(&text, &path.display().to_string());
101 }
102 }
103 }
104 let (_, mut ds) = reg.open(path)?;
105 PlateData::from_dataset(ds.as_mut(), table)
106}
107
108/// Run `req` on the plate in `path` (see [`load_plate`]).
109pub fn analyze_file(reg: &Registry, path: &Path, req: &AssayRequest) -> Result<AssayOutput> {
110 let plate = load_plate(reg, path, req.table)?;
111 let user = user_layout(req)?;
112 let mut out = run(&plate, req, user)?;
113 out.path = path.display().to_string();
114 Ok(out)
115}