//! Labs' reading, on synthetic pages: an invented person, invented values. use super::catalogue::{fold_name, unit_key, Catalogue, Seen}; use super::interval::{judge, normal_span, read_interval, read_value, Comparator, State}; use super::layout::Layouts; use super::names::{likeness, whose, Likeness, Whose}; use super::parse::parse; use super::report::{read_age_sex, read_instant, read_report, Status}; use super::rows::{decide, report_key, result_keys, Decision, Held, Version}; use super::text::{assemble, Glyph, TextCell, TextLine, TextPage}; fn line(y: f32, cells: &[(f32, &str)]) -> TextLine { TextLine { y, size: 9.0, cells: cells.iter().map(|(x, text)| TextCell { x0: *x, x1: *x + 5.0 * text.len() as f32, text: text.to_string() }).collect() } } /// A cell whose right edge is said, for a line laid across the columns. fn wide(y: f32, x0: f32, x1: f32, text: &str) -> TextLine { TextLine { y, size: 9.0, cells: vec![TextCell { x0, x1, text: text.into() }] } } const HEAD: [(f32, &str); 5] = [(40.0, "Test Name"), (250.0, "Result"), (320.0, "Unit"), (380.0, "Bio. Ref. Interval"), (500.0, "Method")]; fn header_block(status: &str) -> Vec { vec![ line(40.0, &[(40.0, "Customer Name"), (120.0, ": Asha Verma"), (300.0, "Order Id"), (360.0, ": ORD-1029")]), line(52.0, &[(40.0, "Age/Gender"), (120.0, ": 41 Y / Female"), (300.0, "Sample Type"), (360.0, ": Serum")]), line(64.0, &[(40.0, "Collected Via"), (120.0, ": Home Collection"), (300.0, "Report Status"), (360.0, &format!(": {status}"))]), line(76.0, &[(40.0, "Collected On"), (120.0, ": 12/Mar/2024 08:15 AM"), (300.0, "Reported On"), (360.0, ": 12/Mar/2024 06:40 PM")]), ] } fn page_one(status: &str) -> TextPage { let mut lines = header_block(status); lines.push(line(100.0, &HEAD)); lines.push(line(114.0, &[(40.0, "LIPID PROFILE")])); lines.push(line(126.0, &[(40.0, "Cholesterol - Total"), (250.0, "212"), (320.0, "mg/dL"), (380.0, "Desirable : < 200"), (500.0, "Enzymatic")])); lines.push(line(136.0, &[(380.0, "Borderline High : 200 - 239")])); lines.push(line(146.0, &[(380.0, "High : >= 240")])); lines.push(line(158.0, &[(40.0, "HDL Cholesterol - Direct"), (250.0, "48"), (320.0, "mg/dL"), (380.0, "> 40"), (500.0, "Direct")])); lines.push(line(170.0, &[(40.0, "Triglycerides"), (250.0, "1.9"), (320.0, "mmol/L"), (380.0, "< 1.7"), (500.0, "GPO")])); // An interpretive paragraph: a line laid across every column, then a short last line. lines.push(line(184.0, &[(40.0, "Interpretation :")])); lines.push(wide(194.0, 40.0, 540.0, "Raised cholesterol is one of several factors a doctor reads together with the history and")); lines.push(line(204.0, &[(40.0, "the rest of the profile")])); lines.push(line(220.0, &[(40.0, "Page 1 of 2")])); TextPage { lines } } fn page_two() -> TextPage { let mut lines = header_block("Final"); lines.push(line(100.0, &HEAD)); lines.push(line(114.0, &[(40.0, "COMPLETE BLOOD COUNT")])); lines.push(line(126.0, &[(40.0, "Haemoglobin"), (250.0, "11.8 L"), (320.0, "g/dL"), (380.0, "12.0 - 15.0"), (500.0, "Photometry")])); lines.push(line(138.0, &[(40.0, "Neutrophils"), (250.0, "62"), (320.0, "%"), (380.0, "40 - 80"), (500.0, "Flow")])); lines.push(line(150.0, &[(40.0, "Neutrophils"), (250.0, "4.1"), (320.0, "10^3/µL"), (380.0, "2.0 - 7.0"), (500.0, "Calculated")])); lines.push(line(162.0, &[(40.0, "Platelet Count"), (250.0, "2.1"), (320.0, "lakhs/cumm"), (380.0, "1.5 - 4.1"), (500.0, "Impedance")])); lines.push(line(174.0, &[(40.0, "Zinc Protoporphyrin"), (250.0, "38"), (320.0, "µg/dL"), (380.0, "< 40"), (500.0, "HPLC")])); lines.push(line(188.0, &[(40.0, "URINE ROUTINE")])); lines.push(line(200.0, &[(40.0, "Glucose"), (250.0, "Negative"), (380.0, "Negative"), (500.0, "Strip")])); lines.push(line(212.0, &[(40.0, "Pus Cells"), (250.0, "2-3"), (320.0, "/hpf"), (380.0, "0 - 5"), (500.0, "Microscopy")])); lines.push(line(224.0, &[(320.0, "mg/dL")])); lines.push(line(240.0, &[(40.0, "~~~ End of Report ~~~")])); TextPage { lines } } fn zone() -> chrono_tz::Tz { "Asia/Kolkata".parse().unwrap() } #[test] fn the_catalogue_reads_and_no_alias_names_two_parameters_it_cannot_tell_apart() { let catalogue = Catalogue::shipped(); assert!(catalogue.parameters.len() > 120, "a lifetime of reports needs the common panels"); assert!(catalogue.attribution.contains("LOINC") && catalogue.attribution.contains("Regenstrief")); for parameter in &catalogue.parameters { assert!(!parameter.line.is_empty() && parameter.line.ends_with('.'), "{} says what it is in one line", parameter.id); assert!(matches!(parameter.kind.as_str(), "number" | "text"), "{}", parameter.id); } assert_eq!(catalogue.panels.first().map(|panel| panel.id.as_str()), Some("blood_count")); assert_eq!(catalogue.panels.last().map(|panel| panel.id.as_str()), Some("other")); } #[test] fn names_and_units_fold_to_one_spelling() { assert_eq!(fold_name("Cholesterol - Total"), "cholesterol total"); assert_eq!(fold_name(" HbA1c (Glycosylated)"), "hba1c glycosylated"); assert_eq!(unit_key("mg/dl"), "mg/dl"); assert_eq!(unit_key("µIU/mL"), unit_key("uIU/ml")); assert_eq!(unit_key("cells/cumm"), "/ul"); assert_eq!(unit_key("10³/µL"), "10^3/ul"); assert_eq!(unit_key("Lakhs/cumm"), "lakhs/ul"); } #[test] fn a_parameter_converts_only_by_its_exact_factors() { let catalogue = Catalogue::shipped(); let cholesterol = catalogue.parameter("cholesterol_total").unwrap(); assert!((cholesterol.to_canonical(5.0, "mmol/L").unwrap() - 193.35).abs() < 0.01); assert_eq!(cholesterol.to_canonical(190.0, "mg/dl"), Some(190.0)); assert_eq!(cholesterol.to_canonical(190.0, "g/L"), None, "no conversion is guessed"); let hba1c = catalogue.parameter("hba1c").unwrap(); assert!((hba1c.to_canonical(48.0, "mmol/mol").unwrap() - 6.543).abs() < 0.01); let platelets = catalogue.parameter("platelet_count").unwrap(); assert_eq!(platelets.to_canonical(2.1, "lakhs/cumm").map(|v| (v * 10.0).round() / 10.0), Some(210.0)); assert_eq!(platelets.to_canonical(210000.0, "/cumm"), Some(210.0)); let tsh = catalogue.parameter("tsh").unwrap(); assert_eq!(tsh.to_canonical(2.5, "mIU/L"), Some(2.5)); } #[test] fn a_name_matches_by_its_unit_and_context_or_not_at_all() { let catalogue = Catalogue::shipped(); let id = |name: &str, unit: &str, panel: &str| catalogue.match_result(&Seen { name, unit, panel, specimen: "" }).map(|p| p.id.as_str()); assert_eq!(id("Neutrophils", "%", "Differential count"), Some("neutrophils_pct")); assert_eq!(id("Neutrophils", "10^3/µL", ""), Some("neutrophils_abs")); assert_eq!(id("Neutrophils", "", ""), None, "two parameters and no unit: never guessed"); assert_eq!(id("Glucose", "", "URINE ROUTINE"), Some("urine_glucose")); assert_eq!(id("Glucose", "mg/dL", "BLOOD SUGAR"), Some("glucose_random")); assert_eq!(id("Creatinine, Serum", "mg/dL", ""), Some("creatinine")); assert_eq!(id("SGPT", "U/L", ""), Some("alt")); assert_eq!(id("Cholesterol - Total", "mg/dL", ""), Some("cholesterol_total")); assert_eq!(id("Cholesterol - Total", "kg", ""), None, "a unit it cannot be in says it is not this one"); assert_eq!(id("Zinc Protoporphyrin", "µg/dL", ""), None); } #[test] fn values_read_as_numbers_bounds_flags_or_words() { let value = read_value("1,23,000"); assert_eq!(value.number, Some(123000.0)); let value = read_value("11.8 L"); assert_eq!((value.number, value.flag.as_deref(), value.text.as_str()), (Some(11.8), Some("L"), "11.8")); let value = read_value("< 0.5"); assert_eq!((value.number, value.comparator), (Some(0.5), Some(Comparator::Less))); let value = read_value("2-3"); assert_eq!((value.number, value.text.as_str()), (None, "2-3")); assert_eq!(read_value("Non Reactive").number, None); assert_eq!(read_value("1,2,3").number, None, "not grouping"); } #[test] fn intervals_read_one_line_bounds_words_and_bands() { let simple = read_interval("70 - 100"); assert_eq!((simple.low, simple.high), (Some(70.0), Some(100.0))); let below = read_interval("< 200"); assert_eq!((below.high, below.high_open), (Some(200.0), true)); let upto = read_interval("Up to 35"); assert_eq!((upto.high, upto.high_open), (Some(35.0), false)); assert_eq!(read_interval("> 40").low, Some(40.0)); assert_eq!(read_interval("Negative").expect.as_deref(), Some("Negative")); let bands = read_interval("Desirable : < 200\nBorderline High : 200 - 239\nHigh : >= 240"); assert_eq!(bands.bands.len(), 3); assert_eq!(bands.bands[1].label, "Borderline High"); assert_eq!((bands.bands[1].low, bands.bands[1].high), (Some(200.0), Some(239.0))); let by_sex = read_interval("Male : 13.0 - 17.0\nFemale : 12.0 - 15.0"); assert_eq!(by_sex.bands.len(), 2); assert_eq!(normal_span(&by_sex, Some("female")), (Some(12.0), Some(15.0))); let words = read_interval("Normal 70-99\nPrediabetes 100-125\nDiabetes >= 126"); assert_eq!(words.bands.len(), 3); } #[test] fn a_result_is_judged_by_its_own_interval_only() { let bands = read_interval("Desirable : < 200\nBorderline High : 200 - 239\nHigh : >= 240"); assert_eq!(judge(&read_value("185"), &bands, None, None), State::InRange); assert_eq!(judge(&read_value("212"), &bands, None, None), State::Borderline); assert_eq!(judge(&read_value("251"), &bands, None, None), State::High); let simple = read_interval("12.0 - 15.0"); assert_eq!(judge(&read_value("11.8"), &simple, None, None), State::Low); assert_eq!(judge(&read_value("< 0.5"), &read_interval("< 1"), None, None), State::InRange); let by_sex = read_interval("Male : 13.0 - 17.0\nFemale : 12.0 - 15.0"); assert_eq!(judge(&read_value("12.5"), &by_sex, Some("female"), None), State::InRange); assert_eq!(judge(&read_value("12.5"), &by_sex, Some("male"), None), State::Low); assert_eq!(judge(&read_value("12.5"), &by_sex, None, None), State::Unknown, "a sex band needs the person's sex"); assert_eq!(judge(&read_value("Negative"), &read_interval("Negative"), None, None), State::InRange); assert_eq!(judge(&read_value("Reactive"), &read_interval("Non Reactive"), None, None), State::OutOfRange); assert_eq!(judge(&read_value("7.1"), &read_interval("see note"), None, Some("H")), State::High, "the lab's flag, when its interval does not read"); assert_eq!(judge(&read_value("7.1"), &read_interval(""), None, None), State::Unknown); } #[test] fn a_five_column_report_reads_its_header_rows_panels_and_bands() { let parsed = parse(&[page_one("Partial Report"), page_two()]); assert_eq!(parsed.layout.as_deref(), Some("five_column")); assert_eq!(parsed.fields.get("name").map(String::as_str), Some("Asha Verma")); assert_eq!(parsed.fields.get("order_id").map(String::as_str), Some("ORD-1029")); assert_eq!(parsed.fields.get("status").map(String::as_str), Some("Partial Report")); let names: Vec<&str> = parsed.rows.iter().map(|row| row.name.as_str()).collect(); assert_eq!( names, ["Cholesterol - Total", "HDL Cholesterol - Direct", "Triglycerides", "Haemoglobin", "Neutrophils", "Neutrophils", "Platelet Count", "Zinc Protoporphyrin", "Glucose", "Pus Cells"], "the paragraph and the page furniture are no results" ); assert_eq!(parsed.rows[0].panel, "LIPID PROFILE"); assert_eq!(parsed.rows[0].range, "Desirable : < 200\nBorderline High : 200 - 239\nHigh : >= 240"); assert_eq!(parsed.rows[3].panel, "COMPLETE BLOOD COUNT"); assert_eq!(parsed.rows[8].panel, "URINE ROUTINE"); assert!(parsed.prose >= 2, "the interpretation was read as prose"); // The lone unit far below the last row reads as nothing, by its number only. assert_eq!(parsed.unparsed.len(), 1); } #[test] fn a_report_is_matched_converted_dated_and_its_person_read() { let report = read_report(&parse(&[page_one("Partial Report"), page_two()]), Catalogue::shipped(), zone()); assert_eq!(report.status, Some(Status::Partial)); assert_eq!(report.sex, Some("female")); assert_eq!(report.age_years, Some(41.0)); assert_eq!(report.collected_at.as_deref(), Some("2024-03-12T08:15:00+05:30")); assert_eq!(report.day.as_deref(), Some("2024-03-12")); assert_eq!(report.unmatched(), ["Zinc Protoporphyrin"]); assert_eq!(report.matched(), 9); let triglycerides = report.readings.iter().find(|reading| reading.parameter.as_deref() == Some("triglycerides")).unwrap(); let (value, unit) = triglycerides.canonical.clone().unwrap(); assert!((value - 168.283).abs() < 0.01 && unit == "mg/dL", "kept beside the printed 1.9 mmol/L"); let haemoglobin = report.readings.iter().find(|reading| reading.parameter.as_deref() == Some("haemoglobin")).unwrap(); assert_eq!(haemoglobin.flag.as_deref(), Some("L")); } #[test] fn a_table_no_layout_names_is_read_by_the_generic_one() { let page = TextPage { lines: vec![ line(40.0, &[(40.0, "Patient Name : Ravi K Menon"), (300.0, "Lab No : 55-201")]), line(52.0, &[(40.0, "Age/Sex : 63 Yrs/M"), (300.0, "Report Date : 02-01-2022 10:30")]), line(80.0, &[(40.0, "Investigation"), (260.0, "Observed Value"), (360.0, "Units"), (430.0, "Reference Range")]), line(94.0, &[(40.0, "Glycosylated Hemoglobin (HbA1c)"), (260.0, "6.1"), (360.0, "%"), (430.0, "4.0 - 5.6")]), line(106.0, &[(40.0, "Serum Creatinine"), (260.0, "1.1"), (360.0, "mg/dl"), (430.0, "0.7 - 1.3")]), ], }; let report = read_report(&parse(&[page]), Catalogue::shipped(), zone()); assert_eq!(report.layout.as_deref(), Some("generic")); assert_eq!(report.readings.iter().map(|r| r.parameter.clone().unwrap_or_default()).collect::>(), ["hba1c", "creatinine"]); assert_eq!((report.age_years, report.sex), (Some(63.0), Some("male"))); assert_eq!(report.reported_at.as_deref(), Some("2022-01-02T10:30:00+05:30"), "day first, as Indian labs print"); assert_eq!(report.status, None, "no status printed"); } #[test] fn glyphs_become_lines_and_cells() { let mut glyphs = Vec::new(); let mut put = |x: f32, y: f32, text: &str| { let mut at = x; for ch in text.chars() { glyphs.push(Glyph { x: at, y, width: 5.0, size: 9.0, text: ch.to_string() }); at += 5.0; } }; put(40.0, 100.0, "Test Name"); put(250.0, 100.2, "Result"); put(40.0, 112.0, "Uric Acid"); put(250.0, 112.0, "5.2"); let page = assemble(glyphs); assert_eq!(page.lines.len(), 2); assert_eq!(page.lines[0].cells.iter().map(|c| c.text.as_str()).collect::>(), ["Test Name", "Result"]); assert_eq!(page.lines[1].cells[0].text, "Uric Acid"); } #[test] fn dates_and_ages_read_as_labs_print_them() { let layouts = Layouts::shipped(); assert_eq!(read_instant("12/Mar/2024 | 08:15 AM", zone(), layouts).as_deref(), Some("2024-03-12T08:15:00+05:30")); assert_eq!(read_instant("05-11-2021 19:02", zone(), layouts).as_deref(), Some("2021-11-05T19:02:00+05:30")); assert_eq!(read_instant("2023-07-01", zone(), layouts).as_deref(), Some("2023-07-01T00:00:00+05:30")); assert_eq!(read_age_sex("34 Y / Male"), (Some(34.0), Some("male"))); assert_eq!(read_age_sex("Female/6 Months"), (Some(0.5), Some("female"))); assert_eq!(read_age_sex("34Y/M").1, Some("male")); } #[test] fn a_title_order_or_spacing_is_one_person_and_initials_are_asked() { assert_eq!(likeness("Mrs. Asha Verma", "Asha Verma"), Likeness::Same); assert_eq!(likeness("VERMA ASHA", "Asha Verma"), Likeness::Same); assert_eq!(likeness("Ashaverma", "Asha Verma"), Likeness::Same); assert_eq!(likeness("A Verma", "Asha Verma"), Likeness::Maybe); assert_eq!(likeness("Asha", "Asha Verma"), Likeness::Maybe); assert_eq!(likeness("Arun Verma", "Asha Verma"), Likeness::Other); let known = vec![("p-asha".to_string(), vec!["Asha Verma".to_string()]), ("p-arun".to_string(), vec!["Arun Verma".to_string(), "Arun K Verma".to_string()])]; assert_eq!(whose("Ms Asha Verma", &known), Whose::Person("p-asha".into())); assert_eq!(whose("Verma Arun K", &known), Whose::Person("p-arun".into())); assert_eq!(whose("A Verma", &known), Whose::Ask(vec!["p-arun".into(), "p-asha".into()]), "two of the family fit: asked, never chosen"); assert_eq!(whose("Meena Iyer", &known), Whose::New); } #[test] fn an_order_is_one_report_and_a_final_lands_on_its_partial() { let partial = read_report(&parse(&[page_one("Partial Report")]), Catalogue::shipped(), zone()); let final_ = read_report(&parse(&[page_one("Final"), page_two()]), Catalogue::shipped(), zone()); let key = report_key(&partial, "aaa"); assert_eq!(key, report_key(&final_, "bbb"), "one order, one report"); assert_eq!(key, "report|ord1029|ashaverma"); let mut sibling = final_.clone(); sibling.name = Some("Ravi Verma".into()); assert_ne!(report_key(&sibling, "ccc"), key, "a family booked under one order is one report each"); let partial_keys = result_keys(&key, &partial.readings); let final_keys = result_keys(&key, &final_.readings); assert!(partial_keys.iter().all(|k| final_keys.contains(k)), "the final's rows are the partial's, by key"); assert!(final_keys.contains(&format!("result|{key}|name:zincprotoporphyrin|0")), "an unmatched name keeps its own key"); let held = Held { status: Some(Status::Partial), versions: vec![Version { sha256: "aaa".into(), status: "partial".into(), reported_at: None, mail_message_id: None }] }; assert_eq!(decide(Some(&held), "aaa", Status::Partial), Decision::Seen); assert_eq!(decide(Some(&held), "bbb", Status::Final), Decision::Write); let finished = Held { status: Some(Status::Final), ..held.clone() }; assert_eq!(decide(Some(&finished), "ccc", Status::Partial), Decision::Older, "a partial after the final changes no result"); assert_eq!(decide(None, "aaa", Status::Partial), Decision::Write); } #[cfg(feature = "lab-pdf")] #[test] fn a_synthetic_pdf_reads_back_to_its_rows() { use super::sample_pdf::Sample; let sample = Sample::invented("Asha Verma", "ORD-77", "Final"); let pages = super::pdf::pages_of(&sample.pdf()).expect("the PDF reads"); let report = read_report(&parse(&pages), Catalogue::shipped(), zone()); assert_eq!(report.layout.as_deref(), Some("five_column")); assert_eq!(report.name.as_deref(), Some("Asha Verma")); assert_eq!(report.status, Some(Status::Final)); let ids: Vec = report.readings.iter().map(|r| r.parameter.clone().unwrap_or_else(|| r.row.name.clone())).collect(); assert_eq!(ids, ["cholesterol_total", "hdl", "triglycerides", "hba1c", "estimated_average_glucose"]); assert_eq!(report.readings[0].interval.bands.len(), 3, "the bands over three lines are one interval"); assert!(report.unparsed.is_empty(), "{:?}", report.unparsed); assert!(report.prose >= 2); assert_eq!(super::pdf::pages_of(b"not a pdf"), Err(super::pdf::PdfError::DoesNotRead)); } #[cfg(feature = "lab-pdf")] #[test] fn a_pdf_drawn_in_flipped_forms_with_a_cid_font_reads_as_the_plain_one() { use super::sample_pdf::Sample; let sample = Sample::invented("Asha Verma", "ORD-77", "Final"); let plain = super::pdf::pages_of(&sample.pdf()).expect("the plain PDF reads"); let drawn = super::pdf::pages_of(&sample.pdf_in_forms()).expect("the PDF drawn in forms reads"); let texts = |pages: &[TextPage]| pages.iter().map(|page| page.lines.iter().map(|line| line.cells.iter().map(|cell| cell.text.clone()).collect::>()).collect::>()).collect::>(); assert_eq!(texts(&drawn), texts(&plain), "same lines, same cells, top to bottom; the sideways note left out"); for (a, b) in drawn.iter().flat_map(|page| &page.lines).zip(plain.iter().flat_map(|page| &page.lines)) { assert!((a.y - b.y).abs() < 0.5 && (a.cells[0].x0 - b.cells[0].x0).abs() < 0.5, "where the page draws it"); } assert_eq!(parse(&drawn), parse(&plain)); } fn sized(y: f32, size: f32, cells: &[(f32, &str)]) -> TextLine { TextLine { y, size, cells: cells.iter().map(|(x, text)| TextCell { x0: *x, x1: *x + 0.5 * size * text.chars().count() as f32, text: text.to_string() }).collect() } } /// The lab-at-home family since 2023, as it lays a page out: values printed /// left of their heads, a test's title over a row that says only `Result`, /// its interpretation row, a comment with its own small table of bands, a /// urine page inside a blood report, and a section printed twice. fn home_lab_pages() -> Vec { let header = |sample: &str| { vec![ sized(139.0, 9.0, &[(30.0, "Customer Name"), (131.0, ": Ravi Invented"), (306.0, "Collected Via"), (400.0, ": Home Collection")]), sized(152.0, 9.0, &[(30.0, "Age/Gender"), (131.0, ": 52Y 0M 0D /Male"), (306.0, "Report Status"), (400.0, ": Final Report")]), sized(166.0, 9.0, &[(30.0, "Collection Date"), (131.0, ": 03/Jan/2025 07:40AM"), (306.0, "Report Date"), (400.0, ": 03/Jan/2025 05:10PM")]), sized(192.0, 9.0, &[(30.0, "Sample Type"), (131.0, &format!(": {sample}")), (306.0, "Barcode ID/Order ID"), (400.0, ": B9000123 / 7700123")]), sized(214.0, 10.3, &[(251.0, "BIOCHEMISTRY")]), sized(249.0, 10.3, &[(26.0, "Test Name"), (203.0, "Result"), (287.0, "Unit"), (345.0, "Bio. Ref. Interval"), (448.0, "Method")]), ] }; let mut one = header("Serum"); one.push(sized(260.0, 6.0, &[(27.0, "Tests marked with an asterisk are referred to a partner laboratory and are listed for your records only")])); one.push(sized(283.0, 10.5, &[(22.0, "HIV Antigen and Antibody, Screening by CMIA")])); one.push(sized(300.0, 10.5, &[(28.0, "HIV Combo (Antigen And Antibody) Test")])); one.push(sized(315.0, 11.2, &[(28.0, "Result"), (204.0, "0.11"), (290.0, "S/CO"), (350.0, "<1.0"), (455.0, "CMIA")])); one.push(sized(329.0, 11.2, &[(28.0, "Interpretation"), (204.0, "Non Reactive"), (350.0, "Non Reactive")])); one.push(sized(361.0, 10.5, &[(27.0, "Comment:")])); one.push(sized(375.0, 7.9, &[(29.0, "Result in S/CO"), (112.0, "Remarks")])); one.push(sized(388.0, 7.9, &[(29.0, "< 1"), (112.0, "Non-Reactive")])); one.push(sized(400.0, 7.9, &[(29.0, ">=1"), (112.0, "Reactive")])); one.push(sized(433.0, 10.5, &[(22.0, "LIVER FUNCTION TEST")])); one.push(sized(448.0, 11.2, &[(28.0, "SGOT (Aspartate Aminotransferase)"), (198.0, "31"), (282.0, "U/L"), (340.0, "15-37"), (446.0, "NADH w/o P-5'-P")])); one.push(sized(462.0, 11.2, &[(28.0, "Gamma Glutamyltransferase (GGT)"), (198.0, "24"), (282.0, "U/L"), (340.0, "<55"), (446.0, "L-gamma-glutamyl-3-")])); one.push(sized(475.0, 10.5, &[(446.0, "Carboxy-4-Nitroanilide")])); one.push(sized(490.0, 11.2, &[(28.0, "Thyroid Stimulating Hormone -"), (198.0, "2.104"), (282.0, "µIU/mL"), (340.0, "0.55-4.78"), (446.0, "CMIA")])); one.push(sized(503.0, 10.5, &[(28.0, "Ultrasensitive")])); one.push(sized(520.0, 11.2, &[(28.0, "RBC"), (198.0, "4.91"), (282.0, "10^6/cu.mm 4.5 - 5.5"), (446.0, "Impedance")])); let mut two = header("Urine"); two.push(sized(283.0, 10.5, &[(22.0, "Urine Routine & Microscopy")])); two.push(sized(300.0, 11.2, &[(28.0, "Urine Routine"), (204.0, "Manual")])); two.push(sized(315.0, 10.5, &[(28.0, "Physical & Chemical Examination")])); two.push(sized(329.0, 11.2, &[(28.0, "Glucose"), (204.0, "Negative"), (349.0, "Negative"), (454.0, "GOD-POD")])); two.push(sized(344.0, 11.2, &[(28.0, "Specific gravity"), (204.0, "1.015"), (349.0, "1.003 - 1.035"), (454.0, "pKa change")])); two.push(sized(361.0, 10.5, &[(27.0, "Comment:")])); two.push(sized(374.0, 7.9, &[(63.0, "≤5.6"), (221.0, "Normal")])); // The same liver section printed again on a later page. let mut three = header("Serum"); three.push(sized(283.0, 10.5, &[(22.0, "LIVER FUNCTION TEST")])); three.push(sized(298.0, 11.2, &[(28.0, "SGOT (Aspartate Aminotransferase)"), (198.0, "31"), (282.0, "U/L"), (340.0, "15-37"), (446.0, "NADH w/o P-5'-P")])); vec![TextPage { lines: one }, TextPage { lines: two }, TextPage { lines: three }] } #[test] fn the_home_lab_family_reads_its_titles_small_print_urine_pages_and_repeats() { let parsed = parse(&home_lab_pages()); assert_eq!(parsed.layout.as_deref(), Some("five_column")); let names: Vec<&str> = parsed.rows.iter().map(|row| row.name.as_str()).collect(); assert_eq!( names, ["HIV Combo (Antigen And Antibody) Test", "SGOT (Aspartate Aminotransferase)", "Gamma Glutamyltransferase (GGT)", "Thyroid Stimulating Hormone - Ultrasensitive", "RBC", "Glucose", "Specific gravity"], "a `Result` row is named by its title; its interpretation, the comment's bands, the title-with-a-word and the repeated section are no results" ); assert_eq!(parsed.repeated, 1); let ggt = &parsed.rows[2]; assert_eq!((ggt.result.as_str(), ggt.unit.as_str(), ggt.range.as_str()), ("24", "U/L", "<55"), "values left of their heads land in their columns"); assert_eq!(ggt.method, "L-gamma-glutamyl-3- Carboxy-4-Nitroanilide"); assert_eq!((parsed.rows[4].unit.as_str(), parsed.rows[4].range.as_str()), ("10^6/cu.mm", "4.5 - 5.5")); assert_eq!(parsed.rows[5].specimen, "Urine", "the urine page's own sample type"); let report = read_report(&parsed, Catalogue::shipped(), zone()); assert_eq!(report.order_id.as_deref(), Some("7700123"), "the order of a barcode/order pair"); let ids: Vec> = report.readings.iter().map(|reading| reading.parameter.as_deref()).collect(); assert_eq!(ids, [Some("hiv"), Some("ast"), Some("ggt"), Some("tsh"), Some("rbc_count"), Some("urine_glucose"), Some("urine_specific_gravity")]); } /// Another lab's layout: capital heads, the method on its own line under the /// name, bands over several lines beside it, dates drawn and authenticated. #[test] fn a_lab_with_capital_heads_and_methods_under_names_reads() { let mut lines = vec![ sized(120.0, 9.0, &[(30.0, "Patient Name"), (120.0, ": Mr Ravi Invented")]), sized(132.0, 9.0, &[(30.0, "Age/Sex"), (120.0, ": 52 Year(s) / Male")]), sized(144.0, 9.0, &[(30.0, "Sample Drawn Date"), (120.0, ": 2019-07-14 08:05")]), sized(156.0, 9.0, &[(30.0, "Sample Auth Date"), (120.0, ": 2019-07-14 16:30")]), sized(220.0, 9.9, &[(35.0, "TEST DESCRIPTION"), (267.0, "RESULT"), (342.0, "UNITS"), (410.0, "BIOLOGICAL REFERENCE RANGES")]), sized(236.0, 9.9, &[(35.0, "LIPID PROFILE")]), ]; lines.push(sized(249.0, 9.9, &[(35.0, "Cholesterol - Total"), (267.0, "188"), (342.0, "mg/dL"), (410.0, "<200"), (447.0, ": Desirable")])); lines.push(sized(261.0, 8.9, &[(35.0, "(Method: CHOD/PAP)"), (410.0, "200-239 : Borderline risk")])); lines.push(sized(274.0, 8.9, &[(410.0, ">240"), (447.0, ": High risk")])); lines.push(sized(286.0, 9.9, &[(35.0, "Cholesterol - HDL"), (267.0, "44"), (342.0, "mg/dL"), (410.0, "< 40 : Low")])); lines.push(sized(298.0, 8.9, &[(35.0, "(Method: Direct)"), (410.0, "40 - 60 : Optimal")])); lines.push(sized(320.0, 9.9, &[(35.0, "INFECTIOUS PROFILE")])); lines.push(sized(334.0, 9.9, &[(35.0, "Rapid Plasma Reagin (RPR Test)"), (267.0, "Non-Reactive")])); lines.push(sized(345.0, 6.4, &[(35.0, "(Method: Flocculation)")])); let parsed = parse(&[TextPage { lines }]); assert_eq!(parsed.layout.as_deref(), Some("generic")); assert_eq!(parsed.rows.len(), 3, "a qualitative result alone on its line is a result"); assert_eq!(parsed.rows[0].method, "CHOD/PAP"); assert_eq!(parsed.rows[0].range, "<200 : Desirable\n200-239 : Borderline risk\n>240 : High risk"); assert_eq!(parsed.rows[1].name, "Cholesterol - HDL"); assert!(parsed.unparsed.is_empty(), "{:?}", parsed.unparsed); let report = read_report(&parsed, Catalogue::shipped(), zone()); assert_eq!(report.day.as_deref(), Some("2019-07-14")); assert!(report.reported_at.is_some()); assert_eq!(report.matched(), 3); } /// Wraps and breaks the real reports print: a word result over two lines, a /// value run into its name's cell, a method running on under the next page's /// head past the footer, a lone unit word under a unit, and an age-wise band /// table under its own column heads. #[test] fn wrapped_results_values_in_names_and_methods_over_a_page_break_read() { let head = || sized(249.0, 10.3, &[(26.0, "Test Name"), (203.0, "Result"), (287.0, "Unit"), (345.0, "Bio. Ref. Interval"), (448.0, "Method")]); let one = vec![ head(), sized(273.0, 11.2, &[(28.0, "Appearance"), (204.0, "SLIGHTLY"), (349.0, "Clear"), (454.0, "Manual")]), sized(286.0, 11.2, &[(204.0, "TURBID")]), sized(300.0, 11.2, &[(28.0, "Thyroid Stimulating Hormone - ULTRA 2.15"), (290.0, "µIU/mL"), (349.0, "0.55-4.78"), (454.0, "CMIA")]), sized(314.0, 11.2, &[(28.0, "Microalbumin/Creatinine Ratio"), (204.0, "8.4"), (290.0, "mg/g"), (349.0, "< 30"), (454.0, "Calculated")]), sized(327.0, 10.5, &[(290.0, "creatinine")]), sized(341.0, 11.2, &[(28.0, "Urine Sodium"), (204.0, "96"), (290.0, "mmol/L"), (454.0, "Indirect ISE")]), sized(355.0, 11.2, &[(63.0, "Age Wise"), (205.0, "Biological Ref. Interval")]), sized(369.0, 11.2, &[(160.0, "Male"), (290.0, "Female")]), sized(400.0, 11.2, &[(28.0, "High Sensitive CRP"), (204.0, "1.2"), (289.0, "mg/L"), (349.0, "< 1.0"), (454.0, "Particle")]), sized(740.0, 8.0, &[(130.0, "This test has been performed at")]), sized(751.0, 10.0, &[(130.0, "TATA 1MG HYDERABAD")]), sized(802.0, 8.0, &[(522.0, "Page 3 of 9")]), ]; let two = vec![head(), sized(263.0, 10.5, &[(454.0, "enhanced")]), sized(276.0, 10.5, &[(454.0, "immunoturbidimetry")])]; let parsed = parse(&[TextPage { lines: one }, TextPage { lines: two }]); let rows: Vec<(&str, &str)> = parsed.rows.iter().map(|row| (row.name.as_str(), row.result.as_str())).collect(); assert_eq!(rows, [("Appearance", "SLIGHTLY TURBID"), ("Thyroid Stimulating Hormone - ULTRA", "2.15"), ("Microalbumin/Creatinine Ratio", "8.4"), ("Urine Sodium", "96"), ("High Sensitive CRP", "1.2")]); assert_eq!(parsed.rows[2].unit, "mg/g"); assert_eq!(parsed.rows[4].method, "Particle enhanced immunoturbidimetry"); assert!(parsed.unparsed.is_empty(), "{:?}", parsed.unparsed); } #[test] fn a_test_named_by_figures_is_a_test_and_a_band_is_not() { use super::parse::names_a_band; assert!(names_a_band("99 or below")); assert!(names_a_band("1st trimester")); assert!(names_a_band("<= 5.6")); assert!(names_a_band("G1 >= 90")); assert!(!names_a_band("25-OH Vitamin D (Total)")); assert!(!names_a_band("24 Hrs Urine Protein")); assert!(!names_a_band("17-OH Progesterone")); } /// A lab that heads its name column `Test Report Status` with the status /// beside it, prints each unit a little left of `Units`, each method in small /// print under its row, and the urinalysis title last on a page. #[test] fn a_status_in_the_head_units_left_of_their_head_and_a_title_over_a_page_break_read() { let head = || sized(252.0, 9.0, &[(54.0, "Test Report Status"), (153.0, "Final"), (283.0, "Results"), (387.0, "Biological Reference Interval"), (528.0, "Units")]); let header = || { vec![ sized(169.0, 8.0, &[(54.0, "PATIENT NAME : RAVI INVENTED")]), sized(187.0, 8.0, &[(210.0, "AGE :"), (241.0, "52 Years"), (295.0, "SEX :"), (341.0, "Male")]), sized(208.0, 8.0, &[(54.0, "DRAWN :"), (96.0, "14/07/2019 08:05"), (217.0, "RECEIVED : 14/07/2019 09:10"), (387.0, "REPORTED :"), (444.0, "14/07/2019 16:30")]), ] }; let mut one = header(); one.push(head()); one.push(sized(283.0, 8.0, &[(54.0, "ELECTROLYTES (NA/K/CL), SERUM")])); one.push(sized(297.0, 8.0, &[(54.0, "SODIUM"), (274.0, "139.0"), (387.0, "136 - 145"), (519.0, "mmol/L")])); one.push(sized(309.0, 6.0, &[(61.0, "METHOD : ISE DIRECT")])); one.push(sized(322.0, 8.0, &[(54.0, "LYMPHOCYTES"), (274.0, "31"), (387.0, "20 - 40"), (519.0, "%")])); one.push(sized(348.0, 8.0, &[(54.0, "URINALYSIS")])); one.push(sized(779.0, 8.0, &[(518.0, "Page 1 Of 2")])); let mut two = header(); two.push(head()); two.push(sized(283.0, 8.0, &[(54.0, "PH"), (274.0, "6.0"), (387.0, "4.7 - 7.5")])); two.push(sized(295.0, 6.0, &[(61.0, "METHOD : DOUBLE INDICATOR")])); two.push(sized(308.0, 8.0, &[(54.0, "SPECIFIC GRAVITY"), (274.0, "1.020"), (387.0, "1.003 - 1.035")])); let parsed = parse(&[TextPage { lines: one }, TextPage { lines: two }]); assert_eq!(parsed.layout.as_deref(), Some("status_head")); assert_eq!(parsed.fields.get("status").map(String::as_str), Some("final"), "the status word beside the head"); let rows: Vec<(&str, &str, &str, &str)> = parsed.rows.iter().map(|row| (row.name.as_str(), row.result.as_str(), row.unit.as_str(), row.panel.as_str())).collect(); assert_eq!( rows, [ ("SODIUM", "139.0", "mmol/L", "ELECTROLYTES (NA/K/CL), SERUM"), ("LYMPHOCYTES", "31", "%", "ELECTROLYTES (NA/K/CL), SERUM"), ("PH", "6.0", "", "URINALYSIS"), ("SPECIFIC GRAVITY", "1.020", "", "URINALYSIS"), ], "a unit left of `Units` is the unit, not the interval's tail; the title last on page one names page two's rows" ); assert_eq!(parsed.rows[0].range, "136 - 145"); assert!(parsed.unparsed.is_empty(), "{:?}", parsed.unparsed); let report = read_report(&parsed, Catalogue::shipped(), zone()); assert_eq!(report.day.as_deref(), Some("2019-07-14"), "`DRAWN` is when it was collected"); let ids: Vec> = report.readings.iter().map(|reading| reading.parameter.as_deref()).collect(); assert_eq!(ids, [Some("sodium"), Some("lymphocytes_pct"), Some("urine_ph"), Some("urine_specific_gravity")]); } /// A lab that prints its result under `In Range` or `Out of Range`, its /// interval's head over two lines, a long name over two lines with its bracket /// open, the name under `PATIENT INFORMATION` and each date a little below /// its label. #[test] fn a_split_result_column_a_two_line_head_and_values_below_their_labels_read() { let mut lines = vec![ sized(133.0, 6.8, &[(36.0, "PATIENT INFORMATION"), (194.0, "REFERRED BY"), (377.0, "SPECIMEN INFORMATION")]), sized(142.0, 8.4, &[(36.0, "Mr. Ravi Invented"), (377.0, "SAMPLE TYPE"), (441.0, ":Blood")]), sized(146.0, 8.4, &[(194.0, "Self")]), sized(152.0, 8.4, &[(377.0, "ORDER REQ. NO"), (441.0, ":B-HYD-15-000123")]), sized(160.0, 8.4, &[(36.0, "AGE"), (93.0, ":52 Years")]), sized(170.0, 8.4, &[(36.0, "GENDER"), (93.0, ":Male")]), sized(180.0, 8.4, &[(36.0, "PRIORITY"), (93.0, ":Routine"), (377.0, "COLLECTED ON")]), sized(183.0, 8.4, &[(441.0, ":12-Jul-2015 09:10")]), sized(202.0, 8.4, &[(377.0, "REPORT STATUS :Completed")]), sized(256.0, 8.9, &[(36.0, "Test Name (Methodology)"), (245.0, "In Range"), (308.0, "Out of Range"), (372.0, "Flag"), (404.0, "UOM"), (457.0, "Biological Reference")]), sized(267.0, 8.9, &[(457.0, "Interval")]), sized(291.0, 8.9, &[(34.0, "Complete Blood Count (CBC)")]), ]; lines.push(sized(316.0, 8.9, &[(34.0, "Hemoglobin"), (245.0, "14.2"), (404.0, "g/dL"), (456.0, "13.0 - 17.0")])); lines.push(sized(328.0, 8.9, &[(34.0, "Platelet Count (Electrical impedance/Cell counter or"), (308.0, "120"), (372.0, "L"), (404.0, "10³/µl"), (456.0, "150 - 410")])); lines.push(sized(340.0, 8.9, &[(34.0, "Manual)")])); lines.push(sized(352.0, 8.9, &[(34.0, "Lymphocytes %"), (245.0, "31"), (404.0, "%"), (456.0, "20-40%")])); let parsed = parse(&[TextPage { lines }]); assert_eq!(parsed.layout.as_deref(), Some("methodology_flag")); let rows: Vec<(&str, &str, &str, &str)> = parsed.rows.iter().map(|row| (row.name.as_str(), row.result.as_str(), row.flag.as_str(), row.range.as_str())).collect(); assert_eq!( rows, [ ("Hemoglobin", "14.2", "", "13.0 - 17.0"), ("Platelet Count (Electrical impedance/Cell counter or Manual)", "120", "L", "150 - 410"), ("Lymphocytes %", "31", "", "20-40%"), ], "a result under either head is the result; the head's second line is no interval" ); assert!(parsed.rows.iter().all(|row| row.panel == "Complete Blood Count (CBC)")); assert!(parsed.unparsed.is_empty(), "{:?}", parsed.unparsed); let report = read_report(&parsed, Catalogue::shipped(), zone()); assert_eq!(report.name.as_deref(), Some("Mr. Ravi Invented"), "the name under `PATIENT INFORMATION`"); assert_eq!(report.order_id.as_deref(), Some("B-HYD-15-000123")); assert_eq!(report.day.as_deref(), Some("2015-07-12"), "the date a little below and right of its label"); assert_eq!(report.status, Some(Status::Final)); assert_eq!(report.matched(), 3); } /// A lab that prints `Sample Type` with the order's last sample on every /// page, its units well left of `Units`, and titles centred over the columns. #[test] fn a_sample_type_on_every_page_is_ignored_and_a_centred_title_gives_the_urine_rows_their_context() { let header = || { vec![ sized(119.0, 9.0, &[(40.0, "Patient Name: Mr. Ravi Invented")]), sized(135.0, 9.0, &[(40.0, "Age/Gender : 52 years / Male"), (349.0, "Sample Type"), (421.0, ": URINE1")]), sized(181.0, 9.0, &[(40.0, "Req. No"), (102.0, ": 1800123"), (349.0, "Reported On"), (421.0, ": 03 Feb 2018 06:30 PM")]), sized(200.0, 9.0, &[(103.0, "Test Name"), (229.0, "Observed Values"), (349.0, "Units"), (402.0, "Biological Reference Intervals")]), ] }; let mut one = header(); one.push(TextLine { y: 276.0, size: 11.1, cells: vec![TextCell { x0: 204.0, x1: 391.0, text: "Complete Blood Picture (CBP)".into() }] }); one.push(sized(297.0, 9.0, &[(45.0, "Hemoglobin"), (240.0, "14.1"), (328.0, "g/dL"), (410.0, "13.0 - 17.0")])); one.push(sized(311.0, 7.0, &[(45.0, "(Method : Colorimetry)")])); one.push(sized(484.0, 9.0, &[(45.0, "Lymphocytes"), (240.0, "31.0"), (328.0, "%"), (410.0, "20-40")])); let mut two = header(); two.push(TextLine { y: 276.0, size: 11.1, cells: vec![TextCell { x0: 189.0, x1: 406.0, text: "Complete Urine Examination (CUE)".into() }] }); two.push(sized(299.0, 9.0, &[(45.0, "CHEMICAL EXAMINATION")])); two.push(sized(317.0, 9.0, &[(45.0, "Reaction (pH)"), (240.0, "6.0"), (410.0, "4.6 - 8.0")])); two.push(sized(335.0, 9.0, &[(45.0, "Specific Gravity"), (240.0, "1.020"), (410.0, "1.005 - 1.030")])); let parsed = parse(&[TextPage { lines: one }, TextPage { lines: two }]); assert_eq!(parsed.layout.as_deref(), Some("observed_values")); assert!(!parsed.fields.contains_key("sample_type"), "a sample type this lab prints on every page says nothing"); let rows: Vec<(&str, &str, &str, &str)> = parsed.rows.iter().map(|row| (row.name.as_str(), row.unit.as_str(), row.panel.as_str(), row.specimen.as_str())).collect(); assert_eq!( rows, [ ("Hemoglobin", "g/dL", "Complete Blood Picture (CBP)", ""), ("Lymphocytes", "%", "Complete Blood Picture (CBP)", ""), ("Reaction (pH)", "", "Complete Urine Examination (CUE) · CHEMICAL EXAMINATION", ""), ("Specific Gravity", "", "Complete Urine Examination (CUE) · CHEMICAL EXAMINATION", ""), ] ); assert_eq!(parsed.rows[0].method, "", "small print under a row is left out, as before"); assert!(parsed.unparsed.is_empty(), "{:?}", parsed.unparsed); let report = read_report(&parsed, Catalogue::shipped(), zone()); assert_eq!(report.order_id.as_deref(), Some("1800123")); let ids: Vec> = report.readings.iter().map(|reading| reading.parameter.as_deref()).collect(); assert_eq!(ids, [Some("haemoglobin"), Some("lymphocytes_pct"), Some("urine_ph"), Some("urine_specific_gravity")]); } /// A hospital lab that prints the method second and each interval well left /// of its head, nearer the result's head than its own. #[test] fn a_method_second_and_intervals_left_of_their_head_read() { let lines = vec![ sized(158.0, 10.0, &[(22.0, "Patient Name"), (141.0, "Mrs Asha Invented"), (346.0, "Age/Sex"), (441.0, "61 / F")]), sized(218.0, 10.0, &[(22.0, "Specimen Type"), (141.0, "Whole Blood EDTA"), (346.0, "Collected On"), (441.0, "30/03/2018 08:15")]), sized(229.0, 11.0, &[(83.0, "Test Name"), (237.0, "Method"), (322.0, "Results"), (406.0, "Ref.Range"), (521.0, "Units")]), sized(242.0, 10.0, &[(22.0, "Hemoglobin"), (204.0, "Automated cell Counter"), (314.0, "10.9 L"), (376.0, "12.0 - 15.0"), (496.0, "g/dl")]), sized(258.0, 10.0, &[(22.0, "Fasting Blood Glucose (FBS)"), (204.0, "Hexokinase"), (314.0, "92"), (376.0, "70.0 - 100.0"), (496.0, "mg/dL")]), ]; let parsed = parse(&[TextPage { lines }]); assert_eq!(parsed.layout.as_deref(), Some("method_second")); let rows: Vec<(&str, &str, &str, &str, &str)> = parsed.rows.iter().map(|row| (row.name.as_str(), row.method.as_str(), row.result.as_str(), row.range.as_str(), row.unit.as_str())).collect(); assert_eq!( rows, [ ("Hemoglobin", "Automated cell Counter", "10.9 L", "12.0 - 15.0", "g/dl"), ("Fasting Blood Glucose (FBS)", "Hexokinase", "92", "70.0 - 100.0", "mg/dL"), ], "an interval left of `Ref.Range` is the interval, not the result's tail" ); let report = read_report(&parsed, Catalogue::shipped(), zone()); let ids: Vec> = report.readings.iter().map(|reading| reading.parameter.as_deref()).collect(); assert_eq!(ids, [Some("haemoglobin"), Some("glucose_fasting")]); }