use std::collections::BTreeMap;
use openreadout_core::model::Finding;
use serde_json::{Value, json};
use crate::sheet::Container;
pub(crate) const MAX_PLATE_DIM: u32 = 1024;
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub(crate) enum Kind {
Gen5,
SoftMaxPro,
BmgMars,
BmgSmartControl,
EnVision,
Kaleido,
TecanIControl,
TecanMagellan,
SkanIt,
Incucyte,
Generic,
}
impl Kind {
pub(crate) fn id(self) -> &'static str {
match self {
Kind::Gen5 => "gen5",
Kind::SoftMaxPro => "softmax-pro",
Kind::BmgMars => "bmg-mars",
Kind::BmgSmartControl => "bmg-smart-control",
Kind::EnVision => "envision",
Kind::Kaleido => "kaleido",
Kind::TecanIControl => "tecan-i-control",
Kind::TecanMagellan => "tecan-magellan",
Kind::SkanIt => "skanit",
Kind::Incucyte => "incucyte",
Kind::Generic => "generic",
}
}
pub(crate) fn manufacturer(self) -> Option<&'static str> {
Some(match self {
Kind::Gen5 => "Agilent BioTek",
Kind::SoftMaxPro => "Molecular Devices",
Kind::BmgMars | Kind::BmgSmartControl => "BMG LABTECH",
Kind::EnVision | Kind::Kaleido => "Revvity (PerkinElmer)",
Kind::TecanIControl | Kind::TecanMagellan => "Tecan",
Kind::SkanIt => "Thermo Fisher Scientific",
Kind::Incucyte => "Sartorius",
Kind::Generic => return None,
})
}
pub(crate) fn software(self) -> Option<&'static str> {
Some(match self {
Kind::Gen5 => "Gen5",
Kind::SoftMaxPro => "SoftMax Pro",
Kind::BmgMars => "MARS",
Kind::BmgSmartControl => "SMART Control",
Kind::EnVision => "EnVision Workstation",
Kind::Kaleido => "Kaleido",
Kind::TecanIControl => "i-control",
Kind::TecanMagellan => "Magellan",
Kind::SkanIt => "SkanIt",
Kind::Incucyte => "Incucyte",
Kind::Generic => return None,
})
}
}
#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord)]
pub(crate) enum Mode {
Absorbance,
Fluorescence,
Luminescence,
Alpha,
Imaging,
Unknown,
}
impl Mode {
pub(crate) fn name(self) -> &'static str {
match self {
Mode::Absorbance => "absorbance",
Mode::Fluorescence => "fluorescence",
Mode::Luminescence => "luminescence",
Mode::Alpha => "alpha",
Mode::Imaging => "imaging",
Mode::Unknown => "unknown",
}
}
pub(crate) fn from_text(s: &str) -> Mode {
let l = s.to_ascii_lowercase();
let od_word = l.split(|c: char| !c.is_ascii_alphanumeric()).any(|w| {
let digits = |x: &str| !x.is_empty() && x.chars().all(|c| c.is_ascii_digit());
w == "od"
|| w.strip_prefix("od").is_some_and(digits)
|| (w.len() == 4 && w.strip_prefix('a').is_some_and(digits))
});
if l.contains("absorb") || l.starts_with("abs") || od_word || l.contains("optical density")
{
Mode::Absorbance
} else if l.contains("alpha") {
Mode::Alpha
} else if l.contains("fluor")
|| l.contains("htrf")
|| l.contains("trf")
|| l == "fi"
|| l.contains("(fi")
|| l.contains("polariz")
{
Mode::Fluorescence
} else if l.contains("lum") {
Mode::Luminescence
} else {
Mode::Unknown
}
}
}
#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord)]
pub(crate) enum ModeBasis {
Stated,
Detector,
Label,
Settings,
Undetermined,
}
impl ModeBasis {
pub(crate) fn name(self) -> &'static str {
match self {
ModeBasis::Stated => "stated",
ModeBasis::Detector => "detector",
ModeBasis::Label => "label",
ModeBasis::Settings => "settings",
ModeBasis::Undetermined => "undetermined",
}
}
pub(crate) fn of(mode: Mode, basis: ModeBasis) -> ModeBasis {
if mode == Mode::Unknown {
ModeBasis::Undetermined
} else {
basis
}
}
}
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub(crate) enum ReadType {
Endpoint,
Kinetic,
Spectrum,
}
impl ReadType {
pub(crate) fn name(self) -> &'static str {
match self {
ReadType::Endpoint => "endpoint",
ReadType::Kinetic => "kinetic",
ReadType::Spectrum => "spectrum",
}
}
}
#[derive(Debug, Clone, PartialEq)]
pub(crate) struct Channel {
pub(crate) label: String,
pub(crate) mode: Mode,
pub(crate) mode_basis: ModeBasis,
pub(crate) wavelength_nm: Option<f64>,
pub(crate) excitation_nm: Option<f64>,
pub(crate) emission_nm: Option<f64>,
pub(crate) unit: Option<String>,
pub(crate) calculated: bool,
pub(crate) formula: Option<String>,
pub(crate) settings: BTreeMap<String, Value>,
}
impl Channel {
pub(crate) fn new(label: impl Into<String>, mode: Mode) -> Self {
Channel {
label: label.into(),
mode,
mode_basis: ModeBasis::of(mode, ModeBasis::Stated),
wavelength_nm: None,
excitation_nm: None,
emission_nm: None,
unit: None,
calculated: false,
formula: None,
settings: BTreeMap::new(),
}
}
pub(crate) fn derived(label: impl Into<String>, mode: Mode, basis: ModeBasis) -> Self {
let mut c = Channel::new(label, mode);
c.mode_basis = ModeBasis::of(mode, basis);
c
}
pub(crate) fn set_mode(&mut self, mode: Mode, basis: ModeBasis) {
self.mode = mode;
self.mode_basis = ModeBasis::of(mode, basis);
}
pub(crate) fn summary(&self, index: usize) -> String {
let label = if self.label.is_empty() {
"unlabelled"
} else {
self.label.as_str()
};
if self.calculated {
format!(
"{} = {label} (CALCULATED by the vendor software, not measured{})",
index + 1,
self.formula
.as_deref()
.map(|f| format!("; formula: {f}"))
.unwrap_or_default()
)
} else {
format!("{} = {label} ({}, measured)", index + 1, self.mode.name())
}
}
pub(crate) fn detection_nm(&self) -> Option<f64> {
self.emission_nm.or(self.wavelength_nm)
}
pub(crate) fn describe(&self, index: usize) -> Value {
let mut m = serde_json::Map::new();
m.insert("read".into(), json!(index + 1));
m.insert("label".into(), json!(self.label));
m.insert("mode".into(), json!(self.mode.name()));
if !self.calculated {
m.insert("mode_basis".into(), json!(self.mode_basis.name()));
}
for (k, v) in [
("wavelength_nm", self.wavelength_nm),
("excitation_nm", self.excitation_nm),
("emission_nm", self.emission_nm),
] {
if let Some(v) = v {
m.insert(k.into(), json!(v));
}
}
if let Some(u) = &self.unit {
m.insert("unit".into(), json!(u));
}
if self.calculated {
m.insert("calculated".into(), json!(true));
}
m.insert(
"origin".into(),
json!(if self.calculated {
"calculated"
} else {
"measured"
}),
);
if let Some(f) = &self.formula {
m.insert("formula".into(), json!(f));
}
if !self.settings.is_empty() {
m.insert("settings".into(), json!(self.settings));
}
Value::Object(m)
}
}
#[derive(Debug, Clone, PartialEq)]
pub(crate) struct Obs {
pub(crate) row: u32,
pub(crate) col: u32,
pub(crate) channel: u32,
pub(crate) time_s: Option<f64>,
pub(crate) wavelength_nm: Option<f64>,
pub(crate) value: f64,
pub(crate) text: Option<String>,
}
#[derive(Debug, Clone, Default)]
pub(crate) struct Block {
pub(crate) name: String,
pub(crate) plate: String,
pub(crate) barcode: Option<String>,
pub(crate) plate_type: Option<String>,
pub(crate) rows: u32,
pub(crate) cols: u32,
pub(crate) declared_wells: Option<u32>,
pub(crate) read_type: Option<ReadType>,
pub(crate) channels: Vec<Channel>,
pub(crate) obs: Vec<Obs>,
pub(crate) temperature_c: Option<f64>,
pub(crate) started_at: Option<String>,
pub(crate) ended_at: Option<String>,
pub(crate) extra: BTreeMap<String, Value>,
pub(crate) findings: Vec<Finding>,
pub(crate) decimal_comma: bool,
pub(crate) sheet: Option<String>,
pub(crate) line: Option<usize>,
}
impl Block {
pub(crate) fn new(name: impl Into<String>, plate: impl Into<String>) -> Self {
Block {
name: name.into(),
plate: plate.into(),
..Default::default()
}
}
pub(crate) fn channel(&mut self, ch: Channel) -> u32 {
if let Some(i) = self.channels.iter().position(|c| *c == ch) {
return i as u32;
}
self.channels.push(ch);
(self.channels.len() - 1) as u32
}
pub(crate) fn push_cell(
&mut self,
row: u32,
col: u32,
channel: u32,
time_s: Option<f64>,
wavelength_nm: Option<f64>,
cell: &crate::sheet::Cell,
) {
if cell.is_blank() {
return;
}
if row >= MAX_PLATE_DIM || col >= MAX_PLATE_DIM {
if !self.findings.iter().any(|f| f.code == "well_out_of_range") {
self.findings.push(Finding::warning(
"well_out_of_range",
format!(
"{}: a value at row {} column {} lies beyond any plate ({MAX_PLATE_DIM} rows or columns); such values are skipped",
self.name,
u64::from(row) + 1,
u64::from(col) + 1
),
));
}
return;
}
let (value, text) = match cell.number() {
Some(v) => (v, None),
None => match self
.decimal_comma
.then(|| decimal_comma(&cell.trimmed()))
.flatten()
{
Some(v) => {
let n = self
.extra
.get("decimal_comma_values")
.and_then(serde_json::Value::as_u64)
.unwrap_or(0);
self.extra
.insert("decimal_comma_values".into(), json!(n + 1));
(v, None)
}
None => (f64::NAN, Some(cell.trimmed())),
},
};
self.obs.push(Obs {
row,
col,
channel,
time_s,
wavelength_nm,
value,
text,
});
}
pub(crate) fn push_value(
&mut self,
row: u32,
col: u32,
channel: u32,
time_s: Option<f64>,
value: f64,
text: Option<String>,
) {
if row >= MAX_PLATE_DIM || col >= MAX_PLATE_DIM {
return;
}
self.obs.push(Obs {
row,
col,
channel,
time_s,
wavelength_nm: None,
value,
text,
});
}
pub(crate) fn settle_geometry(&mut self) {
if let Some((r, c)) = self.declared_wells.and_then(crate::grid::dims_for_wells) {
let fits = self.obs.iter().all(|o| o.row < r && o.col < c);
if fits {
self.rows = r;
self.cols = c;
return;
}
}
let max_r = self.obs.iter().map(|o| o.row).max().unwrap_or(0);
let max_c = self.obs.iter().map(|o| o.col).max().unwrap_or(0);
let (r, c) = crate::grid::smallest_plate(
max_r.max(self.rows.saturating_sub(1)),
max_c.max(self.cols.saturating_sub(1)),
);
self.rows = r;
self.cols = c;
}
pub(crate) fn sort(&mut self) {
let key = |o: &Obs| {
(
o.channel,
o.time_s.unwrap_or(-1.0),
o.wavelength_nm.unwrap_or(-1.0),
o.row,
o.col,
)
};
self.obs.sort_by(|a, b| {
let (ka, kb) = (key(a), key(b));
ka.0.cmp(&kb.0)
.then(ka.1.total_cmp(&kb.1))
.then(ka.2.total_cmp(&kb.2))
.then(ka.3.cmp(&kb.3))
.then(ka.4.cmp(&kb.4))
});
}
pub(crate) fn well_count(&self) -> usize {
let mut w: Vec<(u32, u32)> = self.obs.iter().map(|o| (o.row, o.col)).collect();
w.sort_unstable();
w.dedup();
w.len()
}
pub(crate) fn time_points(&self) -> Vec<f64> {
let mut t: Vec<f64> = self.obs.iter().filter_map(|o| o.time_s).collect();
t.sort_by(f64::total_cmp);
t.dedup();
t
}
}
#[derive(Debug, Clone)]
pub(crate) struct Export {
pub(crate) kind: Kind,
pub(crate) container: Container,
pub(crate) model: Option<String>,
pub(crate) serial: Option<String>,
pub(crate) software_version: Option<String>,
pub(crate) protocol: Option<String>,
pub(crate) experiment: Option<String>,
pub(crate) operator: Option<String>,
pub(crate) acquired_at: Option<String>,
pub(crate) acquired_raw: Option<String>,
pub(crate) saved_raw: Option<String>,
pub(crate) date_order_assumed: bool,
pub(crate) header: Vec<(String, String)>,
pub(crate) sections: BTreeMap<String, Value>,
pub(crate) blocks: Vec<Block>,
pub(crate) findings: Vec<Finding>,
pub(crate) notes: Vec<String>,
pub(crate) sheets_read: Vec<String>,
pub(crate) unread_sheets: Vec<(String, Option<Kind>)>,
}
impl Export {
pub(crate) fn new(kind: Kind, container: Container) -> Self {
Export {
kind,
container,
model: None,
serial: None,
software_version: None,
protocol: None,
experiment: None,
operator: None,
acquired_at: None,
acquired_raw: None,
saved_raw: None,
date_order_assumed: false,
header: Vec::new(),
sections: BTreeMap::new(),
blocks: Vec::new(),
findings: Vec::new(),
notes: Vec::new(),
sheets_read: Vec::new(),
unread_sheets: Vec::new(),
}
}
pub(crate) fn get(&self, key: &str) -> Option<&str> {
let want = key.trim_end_matches(':').trim();
self.header
.iter()
.find(|(k, _)| k.trim_end_matches(':').trim().eq_ignore_ascii_case(want))
.map(|(_, v)| v.as_str())
.filter(|v| !v.trim().is_empty())
}
pub(crate) fn put(&mut self, key: impl Into<String>, value: impl Into<String>) {
self.header.push((key.into(), value.into()));
}
pub(crate) fn set_acquired(&mut self, date: &str, time: Option<&str>) {
let raw = match time {
Some(t) => format!("{} {}", date.trim(), t.trim()),
None => date.trim().to_string(),
};
if let Some((iso, assumed)) = crate::datetime::combine(date, time) {
self.acquired_at = Some(iso);
self.date_order_assumed = assumed;
}
self.acquired_raw = Some(raw);
}
pub(crate) fn finish(&mut self) {
for b in &mut self.blocks {
b.settle_geometry();
b.sort();
}
}
}
pub(crate) fn decimal_comma(s: &str) -> Option<f64> {
let (a, b) = s.split_once(',')?;
let a_ok = !a.is_empty()
&& a.trim_start_matches(['+', '-'])
.chars()
.all(|c| c.is_ascii_digit());
(a_ok && !b.is_empty() && b.chars().all(|c| c.is_ascii_digit()))
.then(|| format!("{a}.{b}").parse().ok())
.flatten()
}
pub(crate) fn nonempty(s: &str) -> Option<String> {
let t = s.trim();
(!t.is_empty()).then(|| t.to_string())
}
pub(crate) fn first_number(s: &str) -> Option<f64> {
let b = s.as_bytes();
let mut i = 0;
while i < b.len() {
if b[i].is_ascii_digit() {
let start = i;
while i < b.len() && (b[i].is_ascii_digit() || b[i] == b'.') {
i += 1;
}
return s[start..i].trim_end_matches('.').parse().ok();
}
i += 1;
}
None
}
pub(crate) fn numbers(s: &str) -> Vec<f64> {
let mut out = Vec::new();
let b = s.as_bytes();
let mut i = 0;
while i < b.len() {
if b[i].is_ascii_digit() {
let start = i;
while i < b.len() && (b[i].is_ascii_digit() || b[i] == b'.') {
i += 1;
}
if let Ok(v) = s[start..i].trim_end_matches('.').parse() {
out.push(v);
}
} else {
i += 1;
}
}
out
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn helpers() {
assert_eq!(first_number("Wavelengths: 450"), Some(450.0));
assert_eq!(first_number("492nm"), Some(492.0));
assert_eq!(numbers("360/40,460/40"), vec![360.0, 40.0, 460.0, 40.0]);
assert_eq!(Mode::from_text("Absorbance Endpoint"), Mode::Absorbance);
assert_eq!(Mode::from_text("Fluorescence (FI)"), Mode::Fluorescence);
assert_eq!(Mode::from_text("Luminescence"), Mode::Luminescence);
assert_eq!(Mode::from_text("AlphaLISA"), Mode::Alpha);
}
}