FrenchCastle's picture
v1.1.0: consolidated panel + panel_dictionary, isora.py loader, World Bank income groups (current + per fiscal year), thousands flag on derived expenditure aggregates
9f0fcd7 verified
Raw History Blame Contribute Delete
9.16 kB
"""Turn the raw SDMX-CSV observation files into one clean, typed, long-format table."""
from __future__ import annotations
import html
import logging
import re
from dataclasses import dataclass
import pandas as pd
from isora_hf import config
from isora_hf.config import Dataflow
log = logging.getLogger(__name__)
NUMERIC_RE = re.compile(r"^[+-]?(\d+\.?\d*|\.\d+)([eE][+-]?\d+)?$")
SPACE_GROUPED_RE = re.compile(r"^-?\d{1,3}( \d{3})+$")
HTML_TAG_RE = re.compile(r"<[^>]+>")
WS_RE = re.compile(r"\s+")
MOJIBAKE_RE = re.compile(r"Ã|â€|Â")
STATUS_VALUE = "value"
STATUS_NOT_AVAILABLE = "not_available"
STATUS_NOT_APPLICABLE = "not_applicable"
STATUS_EMPTY = "empty"
STATUS_UNRECOGNIZED = "unrecognized_code"
UNIT_LCU = "local currency units"
UNIT_LCU_THOUSANDS = "thousands of local currency"
THOUSAND = 1000.0
KIND_NUMERIC = "numeric"
KIND_BINARY = "binary"
KIND_CATEGORICAL = "categorical"
KIND_TEXT = "free_text"
KIND_MIXED = "mixed"
KIND_NO_VALUES = "no_values"
MAX_CATEGORIES = 25
@dataclass(frozen=True)
class ParsedValue:
numeric: float | None
text: str | None
status: str
def repair_mojibake(text: str, max_rounds: int = 3) -> str:
"""Undo UTF-8 text that was decoded as cp1252 one or more times (e.g. '‘' -> '‘')."""
out = text
for _ in range(max_rounds):
if not MOJIBAKE_RE.search(out):
break
try:
candidate = out.encode("cp1252").decode("utf-8")
except (UnicodeEncodeError, UnicodeDecodeError):
break
if candidate == out:
break
out = candidate
return out
def clean_text(raw: str) -> str:
"""Strip HTML tags and entities that leak from the survey UI, repair encoding glitches,
collapse whitespace."""
no_tags = HTML_TAG_RE.sub(" ", html.unescape(raw))
return WS_RE.sub(" ", repair_mojibake(no_tags)).strip()
def parse_value(raw: str | None) -> ParsedValue:
"""Split the mixed-type OBSERVATION string into numeric / text / status."""
stripped = (raw or "").strip()
if not stripped:
return ParsedValue(None, None, STATUS_EMPTY)
if stripped in config.NOT_AVAILABLE_CODES:
return ParsedValue(None, None, STATUS_NOT_AVAILABLE)
if stripped in config.UNRECOGNIZED_CODES:
return ParsedValue(None, stripped, STATUS_UNRECOGNIZED)
if SPACE_GROUPED_RE.match(stripped):
stripped = stripped.replace(" ", "")
if NUMERIC_RE.match(stripped):
return ParsedValue(float(stripped), None, STATUS_VALUE)
text = clean_text(stripped)
if text.lower() in config.NOT_APPLICABLE_STRINGS:
return ParsedValue(None, text, STATUS_NOT_APPLICABLE)
return ParsedValue(None, text, STATUS_VALUE)
def observed_value_kind(numeric: pd.Series, text: pd.Series, status: pd.Series) -> str:
"""Infer what kind of answers an indicator actually holds from its parsed values."""
valued = status == STATUS_VALUE
n_num = int((valued & numeric.notna()).sum())
n_txt = int((valued & text.notna()).sum())
if n_num == 0 and n_txt == 0:
return KIND_NO_VALUES
if n_txt == 0:
return KIND_NUMERIC
if n_num > 0:
return KIND_MIXED
answers = set(text[valued & text.notna()].str.lower())
if answers <= {"yes", "no"}:
return KIND_BINARY
return KIND_CATEGORICAL if len(answers) <= MAX_CATEGORIES else KIND_TEXT
def read_raw(flow_id: str, version: str) -> pd.DataFrame:
path = config.RAW_DATA_DIR / f"{flow_id}__{version}.csv"
frame = pd.read_csv(path, dtype=str, keep_default_na=False, encoding="utf-8")
# Rows without a TIME_PERIOD are dataset/series-level attribute rows, not observations.
return frame[frame["TIME_PERIOD"] != ""].copy()
def _survey_round(year: int) -> str:
try:
return config.FISCAL_YEAR_TO_ROUND[year]
except KeyError as exc:
raise ValueError(f"fiscal year {year} has no known ISORA round") from exc
def monetary_columns(
flow: Dataflow,
indicator_code: pd.Series,
unit_multiplier: pd.Series,
numeric: pd.Series,
monetary_codes: set[str],
) -> tuple[pd.Series, pd.Series]:
"""Harmonize money amounts to base local-currency units.
ISORA 2016/2018 published monetary answers in thousands (as asked on the form) with SCALE=0.
The consolidated FY2018+ dataflow publishes the same questions already multiplied out to base
units and marks them with SCALE=3 (verified against GDP and revenue magnitudes)."""
if flow.generation == "ISORA 2020+":
is_units = unit_multiplier == 3
is_thousands = indicator_code.isin(config.LATEST_THOUSANDS_CODES)
unit = (
pd.Series(pd.NA, index=indicator_code.index, dtype="string")
.mask(is_units, UNIT_LCU)
.mask(is_thousands, UNIT_LCU_THOUSANDS)
)
harmonized = numeric.where(is_units).mask(is_thousands, numeric * THOUSAND)
else:
is_money = indicator_code.isin(monetary_codes)
unit = pd.Series(pd.NA, index=indicator_code.index, dtype="string").mask(
is_money, UNIT_LCU_THOUSANDS
)
harmonized = (numeric * THOUSAND).where(is_money)
return unit, harmonized
def clean_observations(
flow: Dataflow,
indicators: pd.DataFrame,
numeric_to_alpha3: dict[str, str],
jurisdiction_names: dict[str, str],
monetary_codes: set[str],
) -> pd.DataFrame:
raw = read_raw(flow.id, flow.version)
log.info("%s: %d observation rows", flow.id, len(raw))
if not (raw["PUBLIC_DATA"].str.lower() == "true").all():
raise ValueError(f"{flow.id}: found rows not flagged PUBLIC_DATA=true")
geo = raw[flow.geo_dimension]
if geo.str.fullmatch(r"\d+").all():
unmapped = sorted(set(geo) - set(numeric_to_alpha3))
if unmapped:
raise ValueError(f"{flow.id}: numeric jurisdiction codes without alpha-3: {unmapped}")
jurisdiction_code = geo.map(numeric_to_alpha3)
else:
jurisdiction_code = geo
parsed = [parse_value(v) for v in raw["OBSERVATION"]]
labels = indicators.set_index("indicator_code")["label"]
unknown = sorted(set(raw["INDICATOR"]) - set(labels.index))
if unknown:
raise ValueError(f"{flow.id}: indicator codes missing from codelist: {unknown[:10]}")
fiscal_year = raw["TIME_PERIOD"].astype(int)
numeric = pd.Series([p.numeric for p in parsed], index=raw.index, dtype="float64")
text = pd.Series([p.text for p in parsed], index=raw.index, dtype="string")
status = pd.Series([p.status for p in parsed], index=raw.index, dtype="string")
unit_multiplier = raw["SCALE"].replace("", "0").astype(int)
unit, harmonized = monetary_columns(
flow, raw["INDICATOR"], unit_multiplier, numeric, monetary_codes
)
kinds = (
pd.DataFrame({"i": raw["INDICATOR"], "n": numeric, "t": text, "s": status})
.groupby("i")
.apply(lambda g: observed_value_kind(g["n"], g["t"], g["s"]), include_groups=False)
)
out = pd.DataFrame(
{
"jurisdiction_code": jurisdiction_code.values,
"jurisdiction_name": jurisdiction_code.map(jurisdiction_names).values,
"fiscal_year": fiscal_year.astype("int16").values,
"survey_round": [_survey_round(y) for y in fiscal_year],
"questionnaire_generation": flow.generation,
"indicator_code": raw["INDICATOR"].values,
"indicator_label": raw["INDICATOR"].map(labels).values,
"indicator_value_kind": raw["INDICATOR"].map(kinds).values,
"value_raw": raw["OBSERVATION"].values,
"value_numeric": numeric.values,
"value_text": text.values,
"value_status": status.values,
"unit_multiplier": unit_multiplier.astype("int8").values,
"monetary_unit": unit.values,
"value_local_currency_units": harmonized.values,
"form_status": raw[flow.form_status_attr].replace("", None).values,
"footnote": raw["FOOTNOTE"].map(lambda s: clean_text(s) or None).values,
"source_dataflow": flow.id,
"source_dataflow_version": flow.version,
}
)
missing_names = out.loc[out["jurisdiction_name"].isna(), "jurisdiction_code"].unique()
if len(missing_names):
raise ValueError(f"{flow.id}: jurisdictions without a name: {sorted(missing_names)}")
dup = out.duplicated(["jurisdiction_code", "indicator_code", "fiscal_year"]).sum()
if dup:
raise ValueError(f"{flow.id}: {dup} duplicate (jurisdiction, indicator, year) keys")
return out.sort_values(["jurisdiction_code", "indicator_code", "fiscal_year"]).reset_index(
drop=True
)
OBSERVATION_COLUMNS = [
"jurisdiction_code",
"jurisdiction_name",
"fiscal_year",
"survey_round",
"questionnaire_generation",
"indicator_code",
"indicator_label",
"indicator_value_kind",
"value_raw",
"value_numeric",
"value_text",
"value_status",
"unit_multiplier",
"monetary_unit",
"value_local_currency_units",
"form_status",
"footnote",
"source_dataflow",
"source_dataflow_version",
]