diff --git a/src/a4d/tables/accents.py b/src/a4d/tables/accents.py new file mode 100644 index 00000000..e65d3b50 --- /dev/null +++ b/src/a4d/tables/accents.py @@ -0,0 +1,38 @@ +"""Accent-free copies of name columns. + +The original column keeps the official spelling ("Takéo"); the copy, named +_ascii, holds the same name without accents ("Takeo"). Case and spaces +are kept. The copy is safe for joins, filters and maps that may not handle +accented characters. +""" + +import unicodedata + +import polars as pl + + +def fold_accents(text: str | None) -> str | None: + """Remove accents, keep case and spaces: "Hà Nội" -> "Ha Noi". + + "đ" and "Đ" are letters of their own in Unicode, not "d" with an accent, + so they are mapped by hand. + """ + if text is None: + return None + text = text.replace("đ", "d").replace("Đ", "D") + text = unicodedata.normalize("NFKD", text) + return "".join(c for c in text if not unicodedata.combining(c)) + + +def add_ascii_columns(df: pl.DataFrame, columns: list[str]) -> pl.DataFrame: + """Add _ascii, an accent-free copy, for each of ``columns`` present in df.""" + present = [c for c in columns if c in df.columns] + return df.with_columns( + [ + pl.col(c) + .cast(pl.String) + .map_elements(fold_accents, return_dtype=pl.String) + .alias(f"{c}_ascii") + for c in present + ] + ) diff --git a/src/a4d/tables/clinic.py b/src/a4d/tables/clinic.py index a8af78e1..edb2021c 100644 --- a/src/a4d/tables/clinic.py +++ b/src/a4d/tables/clinic.py @@ -1,6 +1,7 @@ """Create clinic static data table from reference data. -Reads clinic_data.xlsx, fills down hierarchical columns, exports as parquet. +Reads clinic_data.xlsx, fills down hierarchical columns, adds accent-free +copies of name columns, exports as parquet. """ import warnings @@ -10,6 +11,7 @@ from loguru import logger from a4d.reference.loaders import find_reference_data_dir +from a4d.tables.accents import add_ascii_columns # polars' own calamine+pyarrow "eager sheet load" path in read_excel() calls # from_arrow() on an ArrowStreamExportable without disambiguating DataFrame @@ -36,11 +38,16 @@ ] +# Columns that also get an accent-free copy, named _ascii. +_ASCII_COLUMNS = ["clinic_province"] + + def create_table_clinic_static(output_dir: Path) -> Path: """Create clinic static data table from reference data. Reads clinic_data.xlsx from reference_data/, fills hierarchical columns - downward, and writes parquet. + downward, adds clinic_province_ascii (the province without accents), + and writes parquet. Args: output_dir: Directory to write the parquet file @@ -68,6 +75,9 @@ def create_table_clinic_static(output_dir: Path) -> Path: if fill_cols: df = df.with_columns([pl.col(c).forward_fill() for c in fill_cols]) + # Accent-free copies, after the fill so every row has its value + df = add_ascii_columns(df, _ASCII_COLUMNS) + logger.info(f"Clinic static data: {df.shape[0]} rows, {df.shape[1]} columns") output_dir.mkdir(parents=True, exist_ok=True) diff --git a/src/a4d/tables/patient.py b/src/a4d/tables/patient.py index 8ae06629..81ce3297 100644 --- a/src/a4d/tables/patient.py +++ b/src/a4d/tables/patient.py @@ -5,6 +5,8 @@ import polars as pl from loguru import logger +from a4d.tables.accents import add_ascii_columns + def read_cleaned_patient_data(cleaned_files: list[Path]) -> pl.DataFrame: """Read and combine all cleaned patient data files. @@ -29,6 +31,9 @@ def create_table_patient_data_static(patient_data: pl.DataFrame, output_dir: Pat cleaned patient dataframe. Groups by patient_id and takes the latest available data (latest year and month). + Adds province_ascii, the official province name without accents + ("Takéo" -> "Takeo"). + Args: patient_data: Combined cleaned patient dataframe (from read_cleaned_patient_data) output_dir: Directory to save output parquet file @@ -68,6 +73,9 @@ def create_table_patient_data_static(patient_data: pl.DataFrame, output_dir: Pat .sort(["tracker_year", "tracker_month", "patient_id"]) ) + # Accent-free copy of the official province name ("Takéo" -> "Takeo") + static_data = add_ascii_columns(static_data, ["province"]) + logger.info(f"Static patient data dimensions: {static_data.shape}") output_file = output_dir / "patient_data_static.parquet" diff --git a/tests/test_tables/test_accents.py b/tests/test_tables/test_accents.py new file mode 100644 index 00000000..f07c2025 --- /dev/null +++ b/tests/test_tables/test_accents.py @@ -0,0 +1,33 @@ +"""Tests for the accent-free name columns.""" + +import polars as pl + +from a4d.tables.accents import add_ascii_columns, fold_accents + + +def test_fold_accents_removes_accents_and_keeps_case_and_spaces(): + assert fold_accents("Takéo") == "Takeo" + assert fold_accents("Hà Nội") == "Ha Noi" + assert fold_accents("Đà Nẵng") == "Da Nang" + assert fold_accents("Bangkok") == "Bangkok" + assert fold_accents(None) is None + + +def test_add_ascii_columns_keeps_the_official_name(): + df = pl.DataFrame( + { + "clinic_id": ["XX1", "XX2", "XX3"], + "clinic_province": ["Takéo", "Hà Nội", None], + } + ) + + result = add_ascii_columns(df, ["clinic_province"]) + + assert result["clinic_province"].to_list() == ["Takéo", "Hà Nội", None] + assert result["clinic_province_ascii"].to_list() == ["Takeo", "Ha Noi", None] + + +def test_add_ascii_columns_without_the_column_changes_nothing(): + df = pl.DataFrame({"clinic_id": ["XX1"]}) + + assert add_ascii_columns(df, ["clinic_province"]).columns == ["clinic_id"] diff --git a/tests/test_tables/test_patient.py b/tests/test_tables/test_patient.py index bc08475c..ccbb13ba 100644 --- a/tests/test_tables/test_patient.py +++ b/tests/test_tables/test_patient.py @@ -376,3 +376,25 @@ def test_static_table_sorting(cleaned_patient_data_files: list[Path], tmp_path: continue elif tracker_months[i] == tracker_months[i + 1]: assert patient_ids[i] <= patient_ids[i + 1] + + +def test_create_table_patient_data_static_adds_province_ascii(tmp_path): + """The static table keeps the official province and adds it without accents.""" + columns = [ + "clinic_id", "dob", "fbg_baseline_mg", "fbg_baseline_mmol", "file_name", + "hba1c_baseline", "hba1c_baseline_exceeds", "lost_date", "name", + "patient_consent", "patient_id", "province", "recruitment_date", "sex", + "status_out", "t1d_diagnosis_age", "t1d_diagnosis_date", + "t1d_diagnosis_with_dka", "tracker_date", "tracker_month", "tracker_year", + ] # fmt: skip + df = pl.DataFrame({c: [None, None] for c in columns}).with_columns( + pl.Series("patient_id", ["XX_QA001", "XX_QA002"]), + pl.Series("province", ["Takéo", "Hà Nội"]), + pl.Series("tracker_year", [2026, 2026]), + pl.Series("tracker_month", [1, 1]), + ) + + out = pl.read_parquet(create_table_patient_data_static(df, tmp_path)).sort("patient_id") + + assert out["province"].to_list() == ["Takéo", "Hà Nội"] + assert out["province_ascii"].to_list() == ["Takeo", "Ha Noi"]