//! A printed result and its printed reference interval, read into numbers //! where they say numbers, and the state a result stands in against its own //! interval. Nothing here is advice: the state is the lab's own interval //! applied to the lab's own value, and a band's word is the lab's. //! //! Values: `5.4`, `< 0.5`, `1,23,000` (Indian grouping), `12.5 H`, `2-3` //! (a range, kept as text), `Negative`, `Pale yellow`. //! //! Intervals: `70 - 100`, `< 200`, `Up to 35`, `> 40`, `Negative`, and bands //! over several lines (`Desirable : < 200`, `Borderline High : 200 - 239`, //! `High : >= 240`), `Male : 13 - 17` / `Female : 12 - 15`. use serde::{Deserialize, Serialize}; /// `<`, `<=`, `>`, `>=` before a number. #[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)] pub enum Comparator { #[serde(rename = "<")] Less, #[serde(rename = "<=")] AtMost, #[serde(rename = ">")] More, #[serde(rename = ">=")] AtLeast, } impl Comparator { pub fn as_str(self) -> &'static str { match self { Comparator::Less => "<", Comparator::AtMost => "<=", Comparator::More => ">", Comparator::AtLeast => ">=", } } pub fn of(text: &str) -> Option { Some(match text { "<" => Comparator::Less, "<=" => Comparator::AtMost, ">" => Comparator::More, ">=" => Comparator::AtLeast, _ => return None, }) } } /// A result as printed, read. #[derive(Debug, Clone, PartialEq, Default)] pub struct ReadValue { /// The number, when the value is one (with its comparator). pub number: Option, pub comparator: Option, /// The value as printed, flag taken off. pub text: String, /// A flag printed in the value cell (`H`, `L`, `*`, `↑`). pub flag: Option, } /// The flags a lab prints after a value. const FLAGS: &[&str] = &["H", "L", "HH", "LL", "High", "Low", "HIGH", "LOW", "*", "**", "↑", "↓", "(H)", "(L)", "Critical", "A"]; fn normalise(text: &str) -> String { text.replace(['–', '—', '‒', '−'], "-").replace('≤', "<=").replace('≥', ">=").replace('\u{a0}', " ").split_whitespace().collect::>().join(" ") } /// A number as printed: `5.4`, `.5`, `1,23,000`, `1,200.5`. pub fn number(text: &str) -> Option { let text = text.trim(); if text.is_empty() || !text.chars().all(|c| c.is_ascii_digit() || c == '.' || c == ',') || !text.chars().any(|c| c.is_ascii_digit()) { return None; } if text.contains(',') { // Grouping commas only: digits after every comma, none before a dot's left. let (whole, fraction) = text.split_once('.').unwrap_or((text, "")); let groups: Vec<&str> = whole.split(',').collect(); if groups.iter().skip(1).any(|group| group.len() != 2 && group.len() != 3) || groups[0].is_empty() || fraction.contains(',') { return None; } let joined = format!("{}{}{}", groups.concat(), if fraction.is_empty() { "" } else { "." }, fraction); return joined.parse().ok().filter(|v: &f64| v.is_finite()); } if text.matches('.').count() > 1 { return None; } text.parse().ok().filter(|v: &f64| v.is_finite()) } /// A comparator and the rest, from the front of `text`. fn comparator_of(text: &str) -> (Option, &str) { let lower = text.to_lowercase(); for (word, comparator) in [ ("<=", Comparator::AtMost), (">=", Comparator::AtLeast), ("<", Comparator::Less), (">", Comparator::More), ("less than or equal to", Comparator::AtMost), ("greater than or equal to", Comparator::AtLeast), ("less than", Comparator::Less), ("lesser than", Comparator::Less), ("below", Comparator::Less), ("more than", Comparator::More), ("greater than", Comparator::More), ("above", Comparator::More), ("up to", Comparator::AtMost), ("upto", Comparator::AtMost), ("till", Comparator::AtMost), ] { if lower.starts_with(word) { if let Some(rest) = text.get(word.len()..) { // A word must end where its letters do (`Belowground` is no comparator). if word.ends_with(char::is_alphabetic) && rest.starts_with(char::is_alphabetic) { continue; } return (Some(comparator), rest.trim_start_matches([' ', ':'])); } } } (None, text) } /// Read a printed result. pub fn read_value(printed: &str) -> ReadValue { let mut text = normalise(printed); let mut flag = None; if let Some((rest, last)) = text.rsplit_once(' ') { if FLAGS.contains(&last) && !rest.is_empty() { flag = Some(last.to_string()); text = rest.to_string(); } } for marker in ["↑", "↓", "*"] { if text.len() > marker.len() && text.ends_with(marker) { flag.get_or_insert_with(|| marker.to_string()); text = text[..text.len() - marker.len()].trim().to_string(); } } let (comparator, rest) = comparator_of(&text); let value = number(rest); ReadValue { number: value, comparator: value.and(comparator), text, flag } } /// One band of an interval: a word and the numbers it spans. #[derive(Debug, Clone, PartialEq, Serialize, Deserialize, Default)] pub struct Band { /// The lab's word for it (`Desirable`, `Borderline high`, `Male`), as printed. pub label: String, #[serde(default, skip_serializing_if = "Option::is_none")] pub low: Option, #[serde(default, skip_serializing_if = "Option::is_none")] pub high: Option, /// `true` when `low` itself is outside (`> 40`). #[serde(default, skip_serializing_if = "std::ops::Not::not")] pub low_open: bool, /// `true` when `high` itself is outside (`< 200`). #[serde(default, skip_serializing_if = "std::ops::Not::not")] pub high_open: bool, /// A word a qualitative result is expected to be (`Negative`). #[serde(default, skip_serializing_if = "Option::is_none")] pub expect: Option, } /// A printed interval, read. #[derive(Debug, Clone, PartialEq, Serialize, Deserialize, Default)] pub struct Interval { pub low: Option, pub high: Option, #[serde(default, skip_serializing_if = "std::ops::Not::not")] pub low_open: bool, #[serde(default, skip_serializing_if = "std::ops::Not::not")] pub high_open: bool, #[serde(default, skip_serializing_if = "Option::is_none")] pub expect: Option, /// Bands, when the interval is several (by category, or by sex). #[serde(default, skip_serializing_if = "Vec::is_empty")] pub bands: Vec, } impl Interval { pub fn is_empty(&self) -> bool { self.low.is_none() && self.high.is_none() && self.expect.is_none() && self.bands.is_empty() } } /// `70 - 100`, `< 200`, `> 40`, `Up to 35`, `Negative`, with a unit after it /// left off; `None` when it says none of these. fn read_span(text: &str) -> Option { let text = text.trim().trim_end_matches(['.', ';', ',']).trim(); if text.is_empty() { return None; } let (comparator, rest) = comparator_of(text); let lead = |rest: &str| -> Option<(f64, String)> { let end = rest.find(|c: char| !(c.is_ascii_digit() || c == '.' || c == ',')).unwrap_or(rest.len()); number(&rest[..end]).map(|value| (value, rest[end..].trim().to_string())) }; if let Some(comparator) = comparator { let (value, _) = lead(rest)?; return Some(match comparator { Comparator::Less => Band { high: Some(value), high_open: true, ..Band::default() }, Comparator::AtMost => Band { high: Some(value), ..Band::default() }, Comparator::More => Band { low: Some(value), low_open: true, ..Band::default() }, Comparator::AtLeast => Band { low: Some(value), ..Band::default() }, }); } if let Some((low, after)) = lead(text) { let after = after.trim_start(); let after = after.strip_prefix('-').or_else(|| after.strip_prefix("to ")).or_else(|| after.strip_prefix("TO "))?.trim_start(); let (high, _) = lead(after)?; if high < low { return None; } return Some(Band { low: Some(low), high: Some(high), ..Band::default() }); } // A word a qualitative result is expected to be: letters and spaces only. if text.chars().all(|c| c.is_alphabetic() || c == ' ' || c == '-') && text.split(' ').count() <= 3 { return Some(Band { expect: Some(text.to_string()), ..Band::default() }); } None } /// `Desirable : < 200`, `< 200 : Desirable`, `Normal 70-100`, `Male: 13 - 17`. fn read_band(line: &str) -> Option { let line = line.trim(); if let Some((left, right)) = line.split_once(':') { let (left, right) = (left.trim(), right.trim()); if let Some(band) = read_span(right).filter(|band| band.expect.is_none()) { if !left.is_empty() { return Some(Band { label: left.to_string(), ..band }); } } if let Some(band) = read_span(left).filter(|band| band.expect.is_none()) { if !right.is_empty() { return Some(Band { label: right.to_string(), ..band }); } } return None; } // A word, then the numbers: `Normal 70-100`, `Prediabetes 5.7 - 6.4`. let start = line.find(|c: char| c.is_ascii_digit() || c == '<' || c == '>')?; let (label, span) = line.split_at(start); let label = label.trim().trim_end_matches(['-', ':']).trim(); let band = read_span(span).filter(|band| band.expect.is_none())?; if label.is_empty() || !label.chars().any(char::is_alphabetic) { return None; } // `Less than 5.7` read its comparator into the span: the word is no label. if comparator_of(line).0.is_some() { return None; } Some(Band { label: label.to_string(), ..band }) } /// Read a printed interval (one line or several). pub fn read_interval(printed: &str) -> Interval { let text = normalise(&printed.replace('\n', " \n ")); let lines: Vec = printed.lines().map(normalise).filter(|line| !line.is_empty()).collect(); if lines.len() <= 1 { if let Some(span) = read_span(&text) { return Interval { low: span.low, high: span.high, low_open: span.low_open, high_open: span.high_open, expect: span.expect, bands: Vec::new() }; } } let bands: Vec = lines.iter().filter_map(|line| read_band(line)).collect(); if bands.is_empty() { if let Some(span) = lines.first().and_then(|line| read_span(line)) { return Interval { low: span.low, high: span.high, low_open: span.low_open, high_open: span.high_open, expect: span.expect, bands: Vec::new() }; } } Interval { bands, ..Interval::default() } } /// Where a result stands against its own interval. #[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)] #[serde(rename_all = "snake_case")] pub enum State { InRange, Borderline, /// Below the interval. Low, /// Above the interval. High, /// Outside, with no side (a qualitative result, a lab's flag alone). OutOfRange, /// Nothing to judge against: no interval that reads, or a word unknown. Unknown, } impl State { pub fn is_out(self) -> bool { matches!(self, State::Low | State::High | State::OutOfRange) } } /// Words a band's label says it is the in-range one. const IN_WORDS: &[&str] = &["normal", "desirable", "optimal", "sufficient", "non diabetic", "non-diabetic", "nondiabetic", "reference", "healthy", "adequate", "low risk", "euthyroid", "negative"]; /// Words a band's label says it is between. const BORDER_WORDS: &[&str] = &["borderline", "near optimal", "near or above optimal", "above optimal", "prediabet", "pre-diabet", "pre diabet", "insufficien", "intermediate", "moderate risk", "average risk", "impaired", "equivocal", "grey zone"]; /// Words a band's label says it is outside. const OUT_WORDS: &[&str] = &["high", "low", "very", "diabet", "deficien", "toxic", "risk", "elevated", "abnormal", "poor", "excess", "hypo", "hyper", "positive", "reactive"]; fn band_state(label: &str) -> State { let label = label.to_lowercase(); if BORDER_WORDS.iter().any(|word| label.contains(word)) { return State::Borderline; } if IN_WORDS.iter().any(|word| label.contains(word)) && !label.contains("non reactive") { return State::InRange; } if label.contains("non reactive") || label.contains("non-reactive") { return State::InRange; } if OUT_WORDS.iter().any(|word| label.contains(word)) { return State::OutOfRange; } State::Unknown } /// Is `label` a sex (`Male`, `Females`, `Men`)? Which. fn sex_of(label: &str) -> Option<&'static str> { let label = label.to_lowercase(); let word = label.split(|c: char| !c.is_alphabetic()).find(|word| !word.is_empty())?; match word { "male" | "males" | "men" | "m" => Some("male"), "female" | "females" | "women" | "f" => Some("female"), _ => None, } } /// Words that say a qualitative result found nothing. const NOTHING: &[&str] = &["negative", "non reactive", "nonreactive", "non-reactive", "nil", "absent", "not detected", "none seen", "not seen", "normal", "neg"]; const SOMETHING: &[&str] = &["positive", "reactive", "present", "detected", "trace", "+", "++", "+++", "1+", "2+", "3+", "4+", "pos"]; fn says_nothing(text: &str) -> bool { let text = text.trim().to_lowercase(); NOTHING.contains(&text.as_str()) } fn says_something(text: &str) -> bool { let text = text.trim().to_lowercase(); SOMETHING.contains(&text.as_str()) || text.starts_with("positive") || (text.starts_with("reactive")) } fn inside(value: f64, comparator: Option, low: Option, low_open: bool, high: Option, high_open: bool) -> Option { // A value printed as a bound (`< 0.5`) is judged only when the whole of it lies one side. let (from, to) = match comparator { None => (value, value), Some(Comparator::Less) | Some(Comparator::AtMost) => (f64::NEG_INFINITY, value), Some(Comparator::More) | Some(Comparator::AtLeast) => (value, f64::INFINITY), }; let below = |x: f64| low.is_some_and(|low| if low_open { x <= low } else { x < low }); let above = |x: f64| high.is_some_and(|high| if high_open { x >= high } else { x > high }); if below(to) { return Some(State::Low); } if above(from) { return Some(State::High); } if !below(from) && !above(to) { return Some(State::InRange); } None } /// The state of `value` against `interval`, for a person of `sex` (`male`, /// `female`, or unknown). `flag` is the lab's own, used only when the /// interval says nothing that reads. pub fn judge(value: &ReadValue, interval: &Interval, sex: Option<&str>, flag: Option<&str>) -> State { let judged = judge_interval(value, interval, sex); if judged != State::Unknown { return judged; } match flag.map(|flag| flag.trim().to_lowercase()) { Some(flag) if matches!(flag.as_str(), "h" | "hh" | "high" | "↑" | "(h)") => State::High, Some(flag) if matches!(flag.as_str(), "l" | "ll" | "low" | "↓" | "(l)") => State::Low, _ => State::Unknown, } } fn judge_interval(value: &ReadValue, interval: &Interval, sex: Option<&str>) -> State { if let Some(expect) = &interval.expect { if says_nothing(expect) { if says_nothing(&value.text) { return State::InRange; } if says_something(&value.text) { return State::OutOfRange; } } return State::Unknown; } let Some(number) = value.number else { return State::Unknown }; if interval.low.is_some() || interval.high.is_some() { return inside(number, value.comparator, interval.low, interval.low_open, interval.high, interval.high_open).unwrap_or(State::Unknown); } if interval.bands.is_empty() { return State::Unknown; } // Bands by sex: the person's own band is the interval. if interval.bands.iter().all(|band| sex_of(&band.label).is_some()) { let Some(sex) = sex else { return State::Unknown }; let Some(band) = interval.bands.iter().find(|band| sex_of(&band.label) == Some(sex)) else { return State::Unknown }; return inside(number, value.comparator, band.low, band.low_open, band.high, band.high_open).unwrap_or(State::Unknown); } // Bands by category: the band the value falls in says the state. let mut found = None; for band in &interval.bands { if inside(number, value.comparator, band.low, band.low_open, band.high, band.high_open) == Some(State::InRange) { if found.is_some() { return State::Unknown; } found = Some(band); } } let Some(band) = found else { return State::Unknown }; match band_state(&band.label) { State::OutOfRange => { // Which side: below the in-range band or above it. let normal = interval.bands.iter().find(|band| band_state(&band.label) == State::InRange); match normal.and_then(|normal| inside(number, value.comparator, normal.low, normal.low_open, normal.high, normal.high_open)) { Some(State::Low) => State::Low, Some(State::High) => State::High, _ => State::OutOfRange, } } other => other, } } /// The in-range band's numbers, for a trend's shaded band: the interval's /// own low and high, the person's sex band, or the in-range category band. pub fn normal_span(interval: &Interval, sex: Option<&str>) -> (Option, Option) { if interval.low.is_some() || interval.high.is_some() { return (interval.low, interval.high); } if interval.bands.iter().all(|band| sex_of(&band.label).is_some()) { return sex .and_then(|sex| interval.bands.iter().find(|band| sex_of(&band.label) == Some(sex))) .map(|band| (band.low, band.high)) .unwrap_or((None, None)); } interval.bands.iter().find(|band| band_state(&band.label) == State::InRange).map(|band| (band.low, band.high)).unwrap_or((None, None)) }