use std::collections::{HashMap, HashSet};
use std::path::Path;
use crate::error::{DatasetError, IoOp, IoResultExt as _, Result, WithinExt as _};
use crate::areas::Area;
use crate::normals::parse_csv;
pub const LGD_ATTRIBUTION: &str = "Source: Local Government Directory, Government of India";
pub const CROSSWALK_HEADER: &str = "overture_id,region_code,overture_name,lgd_state_code,\
lgd_district_code,lgd_name,match_kind,note";
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct Label {
pub lgd_code: Option<String>,
pub approximate: bool,
}
const UNMATCHED: Label = Label {
lgd_code: None,
approximate: true,
};
#[derive(Debug, Clone, Default)]
pub struct Crosswalk {
labels: HashMap<String, Label>,
}
impl Crosswalk {
pub fn read(path: &Path, areas: &[Area]) -> Result<Self> {
let text = std::fs::read_to_string(path).io_at(IoOp::Read, path)?;
Self::parse(&text, areas).within(format!("crosswalk {}", path.display()))
}
pub fn parse(text: &str, areas: &[Area]) -> Result<Self> {
let mut records = Vec::new();
let text = text.strip_prefix('\u{feff}').unwrap_or(text);
for (index, line) in text.lines().enumerate() {
if line.starts_with('#') {
continue;
}
let number = index + 1;
let mut parsed = parse_csv(line).within(format!("line {number}"))?;
if parsed.len() > 1 {
return Err(DatasetError::data(format!(
"line {number}: one line holds several records"
)));
}
records.push((parsed.pop().unwrap_or_default(), number));
}
let mut records = records.into_iter();
let (header, _) = records.next().unwrap_or_default();
if header.join(",") != CROSSWALK_HEADER {
return Err(DatasetError::data(format!(
"header is {:?}, expected {CROSSWALK_HEADER:?}",
header.join(",")
)));
}
let by_id: HashMap<&str, &Area> = areas.iter().map(|a| (a.id.as_str(), a)).collect();
let mut labels = HashMap::with_capacity(areas.len());
let mut code_line: HashMap<String, usize> = HashMap::new();
let mut seen = HashSet::with_capacity(areas.len());
for (record, line) in records {
if record.iter().all(String::is_empty) {
continue;
}
let [id, region, name, _state, code, _lgd_name, kind, _note]: [String; 8] =
record.try_into().map_err(|r: Vec<String>| {
DatasetError::data(format!("line {line}: {} fields, expected 8", r.len()))
})?;
let Some(area) = by_id.get(id.as_str()) else {
return Err(DatasetError::data(format!(
"line {line}: unknown overture_id {id:?}"
)));
};
if region != area.region_code.as_deref().unwrap_or_default() || name != area.name {
return Err(DatasetError::data(format!(
"line {line}: {id} is ({region}, {name}) here but ({}, {}) in the areas",
area.region_code.as_deref().unwrap_or_default(),
area.name
)));
}
if !seen.insert(id.clone()) {
return Err(DatasetError::data(format!(
"line {line}: overture_id {id} appears twice"
)));
}
let numeric = !code.is_empty() && code.bytes().all(|b| b.is_ascii_digit());
let label = match kind.as_str() {
"exact" | "alias" => {
if !numeric {
return Err(DatasetError::data(format!(
"line {line}: {kind} needs a numeric LGD code, got {code:?}"
)));
}
if let Some(earlier) = code_line.insert(code.clone(), line) {
return Err(DatasetError::data(format!(
"lines {earlier} and {line} both give LGD code {code}"
)));
}
Label {
lgd_code: Some(code),
approximate: false,
}
}
"split" | "merged" => {
if !code.is_empty() && !numeric {
return Err(DatasetError::data(format!(
"line {line}: bad LGD code {code:?}"
)));
}
UNMATCHED
}
"none" => {
if !code.is_empty() {
return Err(DatasetError::data(format!(
"line {line}: none carries LGD code {code:?}"
)));
}
UNMATCHED
}
other => {
return Err(DatasetError::data(format!(
"line {line}: unknown match_kind {other:?}"
)));
}
};
labels.insert(id, label);
}
Ok(Self { labels })
}
#[must_use]
pub fn label(&self, id: &str) -> Label {
self.labels.get(id).cloned().unwrap_or(UNMATCHED)
}
#[must_use]
pub fn has_codes(&self) -> bool {
self.labels.values().any(|l| l.lgd_code.is_some())
}
}
#[cfg(test)]
mod tests {
use geo::MultiPolygon;
use super::*;
fn area(id: &str, region: Option<&str>, name: &str) -> Area {
Area {
code: None,
id: id.to_owned(),
name: name.to_owned(),
country: "IN".to_owned(),
level: "county".to_owned(),
parent_id: None,
parent_name: None,
region_code: region.map(str::to_owned),
shape: MultiPolygon::new(vec![]),
}
}
fn areas() -> Vec<Area> {
vec![
area("o1", Some("IN-UK"), "Almora"),
area("o2", Some("IN-UK"), "Pauri Garhwal"),
area("o3", None, "Tawang district"),
area("o4", Some("IN-UK"), "Nowhere"),
area("o5", Some("IN-UK"), "Old"),
]
}
fn csv(rows: &[&str]) -> String {
let mut text = format!("# source line\n# second\n{CROSSWALK_HEADER}\n");
for row in rows {
text.push_str(row);
text.push('\n');
}
text
}
#[test]
fn exact_and_alias_rows_give_a_code_and_drop_approximate() {
let text = csv(&[
"o1,IN-UK,Almora,5,56,ALMORA,exact,",
"o2,IN-UK,Pauri Garhwal,5,61,GARHWAL,alias,\"LGD names it Garhwal, HQ Pauri\"",
"o3,,Tawang district,,,,none,no region code",
"o5,IN-UK,Old,5,70,OLD,split,LGD split it in two",
]);
let cw = Crosswalk::parse(&text, &areas()).expect("valid crosswalk");
let coded = |code: &str| Label {
lgd_code: Some(code.to_owned()),
approximate: false,
};
assert_eq!(cw.label("o1"), coded("56"));
assert_eq!(cw.label("o2"), coded("61"));
assert_eq!(cw.label("o3"), UNMATCHED);
assert_eq!(cw.label("o5"), UNMATCHED, "split keeps approximate");
assert_eq!(cw.label("o4"), UNMATCHED, "no row");
assert!(cw.has_codes());
let none = Crosswalk::parse(&csv(&["o3,,Tawang district,,,,none,x"]), &areas())
.expect("valid crosswalk");
assert!(!none.has_codes());
}
#[test]
fn a_duplicate_code_or_an_unknown_id_fails_loudly() {
let twice = csv(&[
"o1,IN-UK,Almora,5,56,ALMORA,exact,",
"o4,IN-UK,Nowhere,5,56,ALMORA,alias,wrong",
]);
let err = Crosswalk::parse(&twice, &areas()).expect_err("duplicate code");
assert!(
geolith::error::report(&err).contains("lines 4 and 5 both give LGD code 56"),
"{err:#}"
);
let unknown = csv(&["zz,IN-UK,Almora,5,56,ALMORA,exact,"]);
let err = Crosswalk::parse(&unknown, &areas()).expect_err("unknown id");
assert!(
geolith::error::report(&err).contains("unknown overture_id \"zz\""),
"{err:#}"
);
}
#[test]
fn bad_rows_fail_naming_the_line() {
for (row, expected) in [
("o1,IN-UK,Almora,5,56,ALMORA,exact", "7 fields"),
(
"o1,IN-UK,Almora,5,,ALMORA,exact,",
"needs a numeric LGD code",
),
("o1,IN-UK,Almora,5,56,ALMORA,none,", "none carries"),
("o1,IN-UK,Almora,5,56,ALMORA,close,", "unknown match_kind"),
("o1,IN-DL,Almora,5,56,ALMORA,exact,", "in the areas"),
("o1,IN-UK,Almorah,5,56,ALMORA,exact,", "in the areas"),
] {
let err = Crosswalk::parse(&csv(&[row]), &areas()).expect_err(row);
let text = geolith::error::report(&err);
assert!(
text.contains("line 4") && text.contains(expected),
"{row}: {text}"
);
}
let twice = csv(&[
"o3,,Tawang district,,,,none,x",
"o3,,Tawang district,,,,none,y",
]);
let err = Crosswalk::parse(&twice, &areas()).expect_err("id twice");
assert!(
geolith::error::report(&err).contains("appears twice"),
"{err:#}"
);
let header = "overture_id,lgd_code\n";
let err = Crosswalk::parse(header, &areas()).expect_err("header");
assert!(geolith::error::report(&err).contains("header"), "{err:#}");
let split = csv(&["o5,IN-UK,Old,5,7x,OLD,split,typo"]);
let err = Crosswalk::parse(&split, &areas()).expect_err("bad split code");
assert!(
geolith::error::report(&err).contains("line 4: bad LGD code"),
"{err:#}"
);
}
#[test]
fn a_bom_and_crlf_from_a_spreadsheet_are_read() {
let text = format!(
"\u{feff}{}",
csv(&["o1,IN-UK,Almora,5,56,ALMORA,exact,"]).replace('\n', "\r\n")
);
let cw = Crosswalk::parse(&text, &areas()).expect("BOM and CRLF");
assert_eq!(cw.label("o1").lgd_code.as_deref(), Some("56"));
}
#[test]
fn a_missing_file_fails_naming_it() {
let err = Crosswalk::read(Path::new("/nonexistent/crosswalk.csv"), &areas())
.expect_err("missing file");
assert!(
geolith::error::report(&err).contains("/nonexistent/crosswalk.csv"),
"{err:#}"
);
}
}