Cotton code
353 lines · 14.7 KB · RustRaw
//! The canonical parameters (`kits/health/parameters.json`): one entry per//! real-world analyte, the panel it stands in, its canonical unit and the//! exact conversions into it, and the names labs print for it.//!//! Matching is by name, never by guess: a printed name is folded (case,//! accents, punctuation, a trailing specimen word) and must equal an alias.//! When an alias names more than one parameter (`Neutrophils` is both a//! percentage and an absolute count, `Glucose` is blood and urine) the//! printed unit and the result's own context (a urine panel or specimen)//! choose; when they cannot, nothing is chosen and the result stays under//! Other, listed for review.use std::collections::HashMap;use serde::{Deserialize, Serialize};/// The kit file, as shipped.pub const SHIPPED: &str = include_str!("../../../kits/health/parameters.json");#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]pub struct Panel {    pub id: String,    pub name: String,}#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]pub struct Conversion {    /// The unit as a lab prints it (folded by [`unit_key`] before comparing).    pub unit: String,    /// canonical = printed × factor + offset.    pub factor: f64,    #[serde(default)]    pub offset: f64,}#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]pub struct Parameter {    pub id: String,    pub name: String,    pub panel: String,    #[serde(default, skip_serializing_if = "Option::is_none")]    pub loinc: Option<String>,    /// The unit a trend is drawn in; empty for a ratio or a word.    pub unit: String,    /// `number` or `text` (Negative, Pale yellow).    pub kind: String,    /// One plain line on what it is.    pub line: String,    /// `urine`: matched only in a urine panel or on a urine specimen.    #[serde(default, skip_serializing_if = "Option::is_none")]    pub context: Option<String>,    pub aliases: Vec<String>,    #[serde(default)]    pub convert: Vec<Conversion>,    /// Other units labs print it in that no exact factor turns into the    /// canonical one (an assay's own index): matched, never converted.    #[serde(default, skip_serializing_if = "Vec::is_empty")]    pub units: Vec<String>,}#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]pub struct Catalogue {    pub format_version: u32,    pub id: String,    pub purpose: String,    /// LOINC's attribution line, said wherever a code is shown.    pub attribution: String,    /// In the order the Labs screen reads them.    pub panels: Vec<Panel>,    pub parameters: Vec<Parameter>,    #[serde(skip)]    by_alias: HashMap<String, Vec<usize>>,}/// Why the catalogue's data was refused.#[derive(Debug, Clone, PartialEq, Eq, thiserror::Error)]pub enum CatalogueError {    #[error("the parameters do not read: {0}")]    DoesNotRead(String),    #[error("parameter `{0}` is listed twice")]    Twice(String),    #[error("parameter `{id}` names panel `{panel}`, which is not listed")]    UnknownPanel { id: String, panel: String },    #[error("parameter `{0}` has a conversion that is not a finite number")]    BadFactor(String),    #[error("alias `{alias}` names `{a}` and `{b}`, which neither a unit nor a context tells apart")]    Ambiguous { alias: String, a: String, b: String },}/// What the matcher knows about one printed result.#[derive(Debug, Clone, Default, PartialEq, Eq)]pub struct Seen<'a> {    pub name: &'a str,    pub unit: &'a str,    pub panel: &'a str,    pub specimen: &'a str,}impl Catalogue {    /// The shipped catalogue, read once.    pub fn shipped() -> &'static Catalogue {        static CATALOGUE: std::sync::OnceLock<Catalogue> = std::sync::OnceLock::new();        CATALOGUE.get_or_init(|| Catalogue::parse(SHIPPED).expect("kits/health/parameters.json reads"))    }    pub fn parse(json: &str) -> Result<Catalogue, CatalogueError> {        let mut catalogue: Catalogue = serde_json::from_str(json).map_err(|error| CatalogueError::DoesNotRead(error.to_string()))?;        let mut seen = std::collections::HashSet::new();        for (at, parameter) in catalogue.parameters.iter().enumerate() {            if !seen.insert(parameter.id.clone()) {                return Err(CatalogueError::Twice(parameter.id.clone()));            }            if !catalogue.panels.iter().any(|panel| panel.id == parameter.panel) {                return Err(CatalogueError::UnknownPanel { id: parameter.id.clone(), panel: parameter.panel.clone() });            }            if parameter.convert.iter().any(|c| !c.factor.is_finite() || !c.offset.is_finite() || c.factor == 0.0) {                return Err(CatalogueError::BadFactor(parameter.id.clone()));            }            let mut names: Vec<String> = parameter.aliases.iter().map(|alias| fold_name(alias)).collect();            names.push(fold_name(&parameter.name));            names.sort();            names.dedup();            for name in names {                catalogue.by_alias.entry(name).or_default().push(at);            }        }        catalogue.check_ambiguity()?;        Ok(catalogue)    }    /// Two parameters sharing an alias must differ in context or in every unit    /// each accepts, or a result could match both.    fn check_ambiguity(&self) -> Result<(), CatalogueError> {        for (alias, at) in &self.by_alias {            for (i, &a) in at.iter().enumerate() {                for &b in &at[i + 1..] {                    let (pa, pb) = (&self.parameters[a], &self.parameters[b]);                    if pa.context != pb.context {                        continue;                    }                    let units_a = pa.accepted_units();                    if pb.accepted_units().iter().any(|unit| units_a.contains(unit)) {                        return Err(CatalogueError::Ambiguous { alias: alias.clone(), a: pa.id.clone(), b: pb.id.clone() });                    }                }            }        }        Ok(())    }    /// A urine-only parameter read off a page that does not say urine: taken    /// when it is the only one the name can be and the row itself says so    /// (the name says urine, or albumin as in microalbumin, or the printed    /// unit is one it is measured in).    fn urine_anyway(&self, candidates: &[usize], seen: &Seen<'_>) -> Vec<usize> {        let [only] = candidates else { return Vec::new() };        let parameter = &self.parameters[*only];        if parameter.context.as_deref() != Some("urine") {            return Vec::new();        }        let name = fold_name(seen.name);        let unit = unit_key(seen.unit);        let says = is_urine(seen.name) || name.split(' ').any(|word| word.contains("albumin")) || (!unit.is_empty() && parameter.accepted_units().contains(&unit));        if says { vec![*only] } else { Vec::new() }    }    pub fn parameter(&self, id: &str) -> Option<&Parameter> {        self.parameters.iter().find(|parameter| parameter.id == id)    }    pub fn panel(&self, id: &str) -> Option<&Panel> {        self.panels.iter().find(|panel| panel.id == id)    }    /// Where a panel stands on the Labs screen (unknown panels last).    pub fn panel_rank(&self, id: &str) -> usize {        self.panels.iter().position(|panel| panel.id == id).unwrap_or(self.panels.len())    }    /// The parameter a printed result is, or `None` (kept as printed, under Other).    pub fn match_result(&self, seen: &Seen<'_>) -> Option<&Parameter> {        // The page's own sample type decides; a panel title only when none is printed.        let urine = if seen.specimen.trim().is_empty() { is_urine(seen.panel) } else { is_urine(seen.specimen) };        let name = fold_name(seen.name);        let mut candidates = self.by_alias.get(&name).cloned().unwrap_or_default();        if candidates.is_empty() {            // The same name with its specimen said after it ("Creatinine, Serum").            let bare = strip_specimen(&name);            if bare != name {                candidates = self.by_alias.get(&bare).cloned().unwrap_or_default();            }        }        let in_context: Vec<usize> = candidates            .iter()            .copied()            .filter(|&at| match self.parameters[at].context.as_deref() {                Some("urine") => urine,                _ => !urine,            })            .collect();        let in_context = if in_context.is_empty() { self.urine_anyway(&candidates, seen) } else { in_context };        match in_context.as_slice() {            [] => None,            [only] => {                let parameter = &self.parameters[*only];                // A printed unit the parameter cannot be in says it is not this one.                let unit = unit_key(seen.unit);                if unit.is_empty() || parameter.kind == "text" || parameter.accepted_units().contains(&unit) {                    Some(parameter)                } else {                    None                }            }            several => {                let unit = unit_key(seen.unit);                let fitting: Vec<&usize> = several.iter().filter(|&&at| self.parameters[at].accepted_units().contains(&unit)).collect();                match fitting.as_slice() {                    [only] => Some(&self.parameters[**only]),                    _ => None,                }            }        }    }}impl Parameter {    /// Every unit key this parameter can be printed in: its own, those its    /// conversions name, and the units identical to any of them.    pub fn accepted_units(&self) -> Vec<String> {        let mut out = vec![unit_key(&self.unit)];        out.extend(self.convert.iter().map(|c| unit_key(&c.unit)));        out.extend(self.units.iter().map(|unit| unit_key(unit)));        let mut more = Vec::new();        for unit in &out {            if let Some(group) = SAME_UNITS.iter().find(|group| group.contains(&unit.as_str())) {                more.extend(group.iter().map(|u| u.to_string()));            }        }        out.extend(more);        out.sort();        out.dedup();        out    }    /// `value` printed in `unit`, in the canonical unit; `None` for a unit    /// the parameter has no exact conversion from (never guessed).    pub fn to_canonical(&self, value: f64, unit: &str) -> Option<f64> {        let key = unit_key(unit);        let own = unit_key(&self.unit);        if key == own || same_unit(&key, &own) || (key.is_empty() && own.is_empty()) {            return Some(value);        }        // A ratio or a pH printed with no unit is in its own unit.        if key.is_empty() && self.unit.is_empty() {            return Some(value);        }        self.convert.iter().find(|c| {            let theirs = unit_key(&c.unit);            theirs == key || same_unit(&theirs, &key)        }).map(|c| value * c.factor + c.offset)    }}fn is_urine(text: &str) -> bool {    fold_name(text).split(' ').any(|word| word == "urine" || word == "urinalysis" || word == "routine urine" || word == "urinary")}/// Specimen words a lab may print after a name.const SPECIMEN_WORDS: &[&str] = &["serum", "plasma", "blood", "whole blood", "sr", "s", "edta", "urine"];fn strip_specimen(folded: &str) -> String {    let mut words: Vec<&str> = folded.split(' ').collect();    while words.len() > 1 && words.last().is_some_and(|last| SPECIMEN_WORDS.contains(last)) {        words.pop();    }    while words.len() > 1 && words.first().is_some_and(|first| SPECIMEN_WORDS.contains(first)) {        words.remove(0);    }    words.join(" ")}/// A name folded for matching: lower case, accents dropped, every run of/// punctuation or space one space. `Cholesterol - Total` and/// `cholesterol total` are one name; `HbA1c` keeps its digits.pub fn fold_name(name: &str) -> String {    use unicode_normalization::UnicodeNormalization;    let decomposed: String = name.nfkd().filter(|c| !unicode_normalization::char::is_combining_mark(*c)).collect();    let mut out = String::with_capacity(decomposed.len());    let mut space = false;    for c in decomposed.chars() {        if c.is_alphanumeric() || c == '%' {            if space && !out.is_empty() {                out.push(' ');            }            space = false;            out.extend(c.to_lowercase());        } else {            space = true;        }    }    out}/// Units that are the same unit, whatever the analyte.const SAME_UNITS: &[&[&str]] = &[    &["uiu/ml", "miu/l", "uu/ml", "micro iu/ml", "mu/l"],    &["ng/ml", "ug/l"],    &["pg/ml", "ng/l"],    &["mg/l", "ug/ml"],    &["u/l", "iu/l"],    &["10^3/ul", "10^9/l", "thou/ul", "k/ul", "x10^3/ul", "10^3/cumm", "thousand/ul", "x1000/ul", "1000/ul"],    &["10^6/ul", "10^12/l", "mill/ul", "million/ul", "mill/cumm", "million/cumm", "x10^6/ul", "10^6/cumm", "mili/cumm", "milli/cumm", "millions/cumm", "mil/ul"],    &["mm/hr", "mm/h", "mm/1sthr", "mm/1st hr", "mm in 1st hr", "mm/1st hour", "mm/hour", "mmat1hr", "mmin1hr"],    &["ml/min/1.73m2", "ml/min/1.73 m2", "ml/min/1.73sqm"],    &["/hpf", "hpf", "cells/hpf"],    &["miu/ml", "iu/l"],];fn same_unit(a: &str, b: &str) -> bool {    a == b || SAME_UNITS.iter().any(|group| group.contains(&a) && group.contains(&b))}/// A unit folded for comparing: lower case, no spaces, micro as `u`,/// `cumm`/`mm3`/`µL` as `ul`, `ltr` as `l`, `²` as `2`, powers as `10^n`.pub fn unit_key(unit: &str) -> String {    let mut text: String = unit.trim().to_lowercase().replace(['µ', 'μ'], "u").replace('²', "2").replace('³', "3").replace(['×', '*'], "x");    text.retain(|c| !c.is_whitespace());    for (from, to) in [("mcg", "ug"), ("litre", "l"), ("liter", "l"), ("ltr", "l"), ("cu.mm", "cumm"), ("cmm", "cumm"), ("mm^3", "cumm"), ("mm3", "cumm"), ("10e3", "10^3"), ("10e6", "10^6"), ("10e9", "10^9"), ("103/", "10^3/"), ("106/", "10^6/"), ("109/", "10^9/"), ("1012/", "10^12/"), ("lakh/", "lakhs/")] {        text = text.replace(from, to);    }    if let Some(rest) = text.strip_prefix("x10^") {        text = format!("10^{rest}");    }    // A capital I printed for the l of µl (`10^3/µI`).    if text.starts_with("10^") && text.ends_with("/ui") {        text.replace_range(text.len() - 1.., "l");    }    // `cells/cumm` and `/cumm` stay distinct from `/ul` only in spelling.    match text.as_str() {        "/cumm" | "cells/cumm" | "/ul" | "cells/ul" => "/ul".to_string(),        "10^3/cumm" => "10^3/ul".to_string(),        "10^6/cumm" => "10^6/ul".to_string(),        "lakhs/cumm" | "lakhs/ul" => "lakhs/ul".to_string(),        "mg/dl" | "mg%" => "mg/dl".to_string(),        "gm/dl" | "g/dl" | "gms/dl" | "gm%" => "g/dl".to_string(),        "fl" | "femtolitre" | "cubicmicron" | "cu.micron" | "u3" => "fl".to_string(),        "pg" | "picogram" | "uug" => "pg".to_string(),        "meq/l" | "meq/litre" => "meq/l".to_string(),        "mmol/l" | "mmol/litre" => "mmol/l".to_string(),        "ratio" | "-" | "--" | "na" | "n/a" => String::new(),        _ => text,    }}