geolith-dataset-builder 0.5.0

Raster datasets for geolith: district areas, normals, numbers and a map layer per period, and the steps that stage, verify and publish them to any S3-compatible bucket
Documentation
//! The district crosswalk of a build (`geolith dataset build --crosswalk`).
//!
//! A CSV, written by the former `scripts/datasets/crosswalk.ts` and reviewed in the
//! repo, maps each Overture division id to its official LGD district code
//! (Local Government Directory, Government of India). Lines starting with
//! `#` are comments. An area gets its LGD code and `approximate: false` only
//! from an `exact` or `alias` row; `split`, `merged` and `none` rows, and
//! areas without a row, keep `lgd_code: null` and `approximate: true`.

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;

/// The acknowledgement an output carrying LGD codes shows (spec ยง3.1; LGD
/// copyright policy: free reproduction, source prominently acknowledged).
pub const LGD_ATTRIBUTION: &str = "Source: Local Government Directory, Government of India";

/// Header line of the crosswalk CSV.
pub const CROSSWALK_HEADER: &str = "overture_id,region_code,overture_name,lgd_state_code,\
                                    lgd_district_code,lgd_name,match_kind,note";

/// The labels an area gets from the crosswalk.
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct Label {
    /// LGD district code, for an exact or alias match.
    pub lgd_code: Option<String>,
    /// Whether the boundary is not matched to an official code.
    pub approximate: bool,
}

/// The unmatched label: no code, approximate.
const UNMATCHED: Label = Label {
    lgd_code: None,
    approximate: true,
};

/// The crosswalk of one build, by Overture id.
#[derive(Debug, Clone, Default)]
pub struct Crosswalk {
    labels: HashMap<String, Label>,
}

impl Crosswalk {
    /// The crosswalk at `path`, checked against `areas` (see [`Self::parse`]).
    ///
    /// # Errors
    ///
    /// Fails, naming `path`, when it cannot be read or [`Self::parse`] fails.
    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()))
    }

    /// The crosswalk of CSV `text`, checked against `areas`.
    ///
    /// # Errors
    ///
    /// Fails, naming the line, when the header differs, a row has the wrong
    /// number of fields or an unknown `match_kind`, a row names an
    /// `overture_id` that is not an area or whose `region_code` or
    /// `overture_name` differ from the area's (a crosswalk of another
    /// boundary release), an id appears twice, an `exact` or `alias` row has
    /// no numeric LGD code, a `none` row has one, or two `exact`/`alias` rows
    /// share an LGD code.
    pub fn parse(text: &str, areas: &[Area]) -> Result<Self> {
        // One record per line: no field of the crosswalk holds a line break.
        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 })
    }

    /// The labels of area `id`: unmatched when it has no row.
    #[must_use]
    pub fn label(&self, id: &str) -> Label {
        self.labels.get(id).cloned().unwrap_or(UNMATCHED)
    }

    /// Whether any area gets an LGD code.
    #[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:#}"
        );
    }
}