diff --git a/changelog.d/1705-shared-firm-mechanics.added.md b/changelog.d/1705-shared-firm-mechanics.added.md new file mode 100644 index 0000000000..3eda6eba3e --- /dev/null +++ b/changelog.d/1705-shared-firm-mechanics.added.md @@ -0,0 +1,9 @@ +`microcosm.build.firms`: country-neutral mechanics for synthetic firm populations, taken out of the UK firm port so another country can reuse them (#1705). A country passes its band edges, band roles, registered counts, engine package and receipts as data: +- `draw_in_band` maps caller-drawn uniforms into a band, log-uniform for an open band, and keeps the input's type and dtype; +- `stratified_thin` thins a candidate draw by stratum, with exact base weights; +- a `RegistrationSpec` declares a register's bands as excluded, registrable or selected, which `registration_propensity` and `assign_scope_and_registration` use to reconcile a business register with a tax-registration count; +- `FirmRules`, `FirmRuleOutputs` and `align_rule_outputs` form the seam to a rule engine, with named outputs keyed by firm id, plus `weighted_totals`; +- `read_entity_variables` reads a policyengine-core package's entity variables from source with `ast`, and `input_status_problems` and `export_schema_problems` check a build's input-status record and its export against them; +- `firms.receipts` sets model totals beside sourced official receipts, without inventing a gap for an unset input or a missing figure. + +The UK firm port (#1706) is to be rebuilt on these and will pin that its outputs are unchanged. The firm-only `Frame` is not included: it needs `EntitySchema` root populations. diff --git a/packages/microcosm-build/src/microcosm/build/firms/__init__.py b/packages/microcosm-build/src/microcosm/build/firms/__init__.py new file mode 100644 index 0000000000..59f09aab60 --- /dev/null +++ b/packages/microcosm-build/src/microcosm/build/firms/__init__.py @@ -0,0 +1,63 @@ +"""Country-neutral mechanics for synthetic firm populations. + +A country's firm build draws candidate firms from published band counts, +thins them for speed, calibrates them against a business register and a +tax-registration count, and hands them to a rule engine. The pieces here know +nothing about any country: band edges, band roles, registered counts and rule +engines all arrive as arguments. They come from the UK firm port in +PolicyEngine/microcosm#1706, which is to be rebuilt on them. + +- :mod:`.bands`: values drawn inside a band from uniforms the caller supplies; +- :mod:`.thinning`: stratified thinning with exact base weights; +- :mod:`.registration`: the two-universe treatment of a register and a + tax-registration count, set by a :class:`RegistrationSpec`; +- :mod:`.rules`: the seam to a rule engine, with outputs keyed by firm id; +- :mod:`.engine_inputs`: a rule engine's entity inputs read from source, the + input-status record a build keeps, and checks of an export against both; +- :mod:`.receipts`: model totals beside sourced official receipts, as a + diagnostic table that never invents a gap. + +The firm-only ``Frame`` is not here yet: it needs ``EntitySchema`` to allow a +root population with no person or group entities. +""" + +from __future__ import annotations + +from .bands import draw_in_band +from .engine_inputs import ( + EXPORTED_INPUT_STATUSES, + INPUT_STATUSES, + EntityVariables, + export_schema_problems, + input_status_problems, + read_entity_variables, +) +from .registration import ( + BAND_ROLES, + RegistrationSpec, + assign_scope_and_registration, + registration_propensity, + select_to_weighted_target, +) +from .rules import FirmRuleOutputs, FirmRules, align_rule_outputs, weighted_totals +from .thinning import stratified_thin + +__all__ = [ + "BAND_ROLES", + "EXPORTED_INPUT_STATUSES", + "INPUT_STATUSES", + "EntityVariables", + "FirmRuleOutputs", + "FirmRules", + "RegistrationSpec", + "align_rule_outputs", + "assign_scope_and_registration", + "draw_in_band", + "export_schema_problems", + "input_status_problems", + "read_entity_variables", + "registration_propensity", + "select_to_weighted_target", + "stratified_thin", + "weighted_totals", +] diff --git a/packages/microcosm-build/src/microcosm/build/firms/_arrays.py b/packages/microcosm-build/src/microcosm/build/firms/_arrays.py new file mode 100644 index 0000000000..629333700b --- /dev/null +++ b/packages/microcosm-build/src/microcosm/build/firms/_arrays.py @@ -0,0 +1,16 @@ +"""Array argument checks shared by the firm mechanics.""" + +from __future__ import annotations + +import numpy as np + + +def as_1d(name: str, values: object, length: int | None = None) -> np.ndarray: + """``values`` as a one-dimensional array, optionally of ``length`` entries.""" + + array = np.asarray(values) + if array.ndim != 1: + raise ValueError(f"{name} must be one-dimensional, got shape {array.shape}") + if length is not None and len(array) != length: + raise ValueError(f"{name} has {len(array)} entries; expected {length}") + return array diff --git a/packages/microcosm-build/src/microcosm/build/firms/bands.py b/packages/microcosm-build/src/microcosm/build/firms/bands.py new file mode 100644 index 0000000000..8539703093 --- /dev/null +++ b/packages/microcosm-build/src/microcosm/build/firms/bands.py @@ -0,0 +1,58 @@ +"""Values drawn inside a published band. + +Business statistics publish counts by band (turnover, employment), not +values. A firm in band ``[lower, upper)`` gets a value inside its band: +uniform for closed bands, log-uniform for an open top band whose upper edge is +a declared cap. Both keep every value inside its source band. + +The caller draws the uniforms, so the random stream stays with the caller: +:func:`draw_in_band` is a pure transform. It works on NumPy arrays and on +torch tensors alike and returns the type and dtype it was given, so a caller +that draws float32 uniforms from torch gets the same float32 values it +computed before this module existed. +""" + +from __future__ import annotations + +import math +from typing import Any + +import numpy as np + +__all__ = ["draw_in_band"] + + +def draw_in_band( + unit: Any, + lower: float, + upper: float, + *, + log_uniform: bool = False, + floor: float = 0.0, +) -> Any: + """Map uniforms in ``[0, 1)`` to values in ``[max(lower, floor), upper)``. + + Args: + unit: Uniform draws in ``[0, 1)``, a NumPy array or a torch tensor. + lower: The band's lower edge. + upper: The band's upper edge (an open band's declared cap). + log_uniform: Draw log-uniformly, for an open top band. The low edge + must then be positive. + floor: The smallest value drawn, applied to ``lower``; a band whose + lower edge is zero draws from ``floor`` instead. + + Returns: + Values the same shape, type and dtype as ``unit``. + """ + + low = max(float(lower), float(floor)) + high = float(upper) + if high < low: + raise ValueError(f"band upper edge {high} lies below its low edge {low}") + if log_uniform: + if low <= 0: + raise ValueError(f"a log-uniform band needs a positive low edge, got {low}") + exponent = math.log(low) + unit * (math.log(high) - math.log(low)) + # torch tensors carry .exp(); NumPy arrays and scalars do not. + return exponent.exp() if hasattr(exponent, "exp") else np.exp(exponent) + return low + unit * (high - low) diff --git a/packages/microcosm-build/src/microcosm/build/firms/engine_inputs.py b/packages/microcosm-build/src/microcosm/build/firms/engine_inputs.py new file mode 100644 index 0000000000..94667b9086 --- /dev/null +++ b/packages/microcosm-build/src/microcosm/build/firms/engine_inputs.py @@ -0,0 +1,408 @@ +"""A rule engine's entity inputs, read from source, and checks against them. + +A firm table loads into a country model only if every exported column is one +of the model's formula-less variables on the firm entity, with the right value +type and enum members. This module reads those variables from a +policyengine-core country package's source with ``ast`` (it never imports the +package), so engine-free tests can check an export against a committed +snapshot. It also holds the input-status vocabulary a build uses to record how +it fills each input, and the checks that keep that record complete. + +- :func:`read_entity_variables` reads every ``Variable`` subclass whose + ``entity`` is a given name: value type, unit, default, enum members (the + ``possible_values`` class resolved through the defining module's imports), + definition period, whether it has a formula (a ``formula`` or + ``formula_*`` method or attribute, ``adds`` or ``subtracts``) and its file. + A variable created at runtime is not in the source and so not read. +- :func:`input_status_problems` checks a build's input-status record against + the engine's inputs. +- :func:`export_schema_problems` checks an exported table's columns, dtypes + and enum values against the variables read. +""" + +from __future__ import annotations + +import ast +from collections.abc import Iterable, Mapping +from dataclasses import dataclass, field +from pathlib import Path +from typing import Any, Final + +import pandas as pd + +__all__ = [ + "EXPORTED_INPUT_STATUSES", + "INPUT_STATUSES", + "EntityVariables", + "export_schema_problems", + "input_status_problems", + "read_entity_variables", +] + +#: How a build fills an engine input: +#: +#: - ``set``: mapped directly from a generator column or a source draw; +#: - ``derived``: computed from other columns by a rule; +#: - ``assumed``: carries a data assumption beyond the source; +#: - ``not_set``: not exported; the engine's default applies. +INPUT_STATUSES: Final[tuple[str, ...]] = ("set", "derived", "assumed", "not_set") + +#: The statuses of inputs a build exports. +EXPORTED_INPUT_STATUSES: Final[tuple[str, ...]] = ("set", "derived", "assumed") + +_DTYPE_KINDS: Final[Mapping[str, str]] = {"float": "f", "int": "i", "bool": "b"} + + +@dataclass(frozen=True) +class EntityVariables: + """The variables a country package defines, as read from its source. + + ``variables`` maps each variable on the entity to its record (see + :func:`read_entity_variables`); ``input_names`` lists the formula-less + ones, sorted; ``variable_names`` is every variable the package defines, + on any entity. + """ + + variables: dict[str, dict[str, Any]] + input_names: list[str] + variable_names: list[str] + + +@dataclass +class _Module: + name: str + path: Path + tree: ast.Module + #: Local name -> (module, attribute) for ``from module import attribute``. + imports: dict[str, tuple[str, str]] = field(default_factory=dict) + #: Local alias -> module for ``import module`` and ``import module as m``. + module_aliases: dict[str, str] = field(default_factory=dict) + classes: dict[str, ast.ClassDef] = field(default_factory=dict) + + +def _module_name(package_dir: Path, path: Path) -> str: + parts = list(path.relative_to(package_dir.parent).with_suffix("").parts) + if parts[-1] == "__init__": + parts.pop() + return ".".join(parts) + + +def _resolve_relative(module: _Module, node: ast.ImportFrom) -> str: + if not node.level: + return node.module or "" + package = module.name.split(".") + if module.path.name != "__init__.py": + package = package[:-1] + if node.level > 1: + package = package[: len(package) - (node.level - 1)] + return ".".join([*package, *([node.module] if node.module else [])]) + + +def _read_modules(package_dir: Path) -> dict[str, _Module]: + modules: dict[str, _Module] = {} + tests_dir = package_dir / "tests" + for path in sorted(package_dir.rglob("*.py")): + if tests_dir in path.parents: + continue + tree = ast.parse(path.read_text(encoding="utf-8"), filename=str(path)) + module = _Module(name=_module_name(package_dir, path), path=path, tree=tree) + for node in tree.body: + if isinstance(node, ast.ImportFrom): + source = _resolve_relative(module, node) + for alias in node.names: + if alias.name != "*": + module.imports[alias.asname or alias.name] = ( + source, + alias.name, + ) + elif isinstance(node, ast.Import): + for alias in node.names: + module.module_aliases[alias.asname or alias.name] = alias.name + elif isinstance(node, ast.ClassDef): + module.classes[node.name] = node + modules[module.name] = module + return modules + + +def _base_names(node: ast.ClassDef) -> list[str]: + names = [] + for base in node.bases: + if isinstance(base, ast.Name): + names.append(base.id) + elif isinstance(base, ast.Attribute): + names.append(base.attr) + return names + + +def _assignments(node: ast.ClassDef) -> dict[str, ast.expr]: + values: dict[str, ast.expr] = {} + for statement in node.body: + if isinstance(statement, ast.Assign): + for target in statement.targets: + if isinstance(target, ast.Name): + values[target.id] = statement.value + elif isinstance(statement, ast.AnnAssign) and statement.value is not None: + if isinstance(statement.target, ast.Name): + values[statement.target.id] = statement.value + return values + + +def _is_formula_name(name: str) -> bool: + return name == "formula" or name.startswith("formula_") + + +def _has_formula(node: ast.ClassDef) -> bool: + for statement in node.body: + if isinstance(statement, (ast.FunctionDef, ast.AsyncFunctionDef)): + if _is_formula_name(statement.name): + return True + return any( + _is_formula_name(name) or name in ("adds", "subtracts") + for name in _assignments(node) + ) + + +def _enum_members(node: ast.ClassDef) -> list[str]: + members = [] + for statement in node.body: + if isinstance(statement, ast.Assign): + for target in statement.targets: + if isinstance(target, ast.Name) and not target.id.startswith("_"): + members.append(target.id) + return members + + +def _resolve_class( + modules: dict[str, _Module], + module: _Module, + name: str, + seen: frozenset = frozenset(), +) -> tuple[_Module, ast.ClassDef]: + """The class ``name`` refers to in ``module``, following its imports.""" + + key = (module.name, name) + if key in seen: + raise ValueError(f"Import cycle resolving {name} in {module.name}.") + if name in module.classes: + return module, module.classes[name] + if name in module.imports: + source, attribute = module.imports[name] + if source in modules: + return _resolve_class(modules, modules[source], attribute, seen | {key}) + submodule = f"{source}.{attribute}" + if submodule in modules: + raise ValueError(f"{name} in {module.name} is a module, not a class.") + raise ValueError(f"Cannot resolve class {name} from {module.name}.") + + +def _resolve_enum( + modules: dict[str, _Module], module: _Module, expression: ast.expr +) -> tuple[str, str, list[str]]: + if isinstance(expression, ast.Name): + owner, node = _resolve_class(modules, module, expression.id) + elif isinstance(expression, ast.Attribute) and isinstance( + expression.value, ast.Name + ): + alias = module.module_aliases.get(expression.value.id) + target = modules.get(alias) if alias else None + if target is None: + source = module.imports.get(expression.value.id) + target = modules.get(".".join(source)) if source else None + if target is None: + raise ValueError(f"Cannot resolve {ast.unparse(expression)}.") + owner, node = _resolve_class(modules, target, expression.attr) + else: + raise ValueError(f"Cannot resolve possible_values {ast.unparse(expression)}.") + if "Enum" not in _base_names(node): + raise ValueError(f"{node.name} in {owner.name} is not an Enum.") + return node.name, owner.name, _enum_members(node) + + +def _literal_or_source(expression: ast.expr) -> Any: + try: + return ast.literal_eval(expression) + except ValueError: + return ast.unparse(expression) + + +def _definition_period(expression: ast.expr | None) -> str | None: + if expression is None: + return None + if isinstance(expression, ast.Name): + return expression.id.lower() + return _literal_or_source(expression) + + +def _variable_record( + modules: dict[str, _Module], + module: _Module, + node: ast.ClassDef, + package_dir: Path, +) -> dict[str, Any]: + values = _assignments(node) + enum = None + members: list[str] | None = None + if "possible_values" in values: + enum_name, enum_module, members = _resolve_enum( + modules, module, values["possible_values"] + ) + enum = {"name": enum_name, "module": enum_module} + default = values.get("default_value") + if default is None: + default_value = None + elif ( + members is not None + and isinstance(default, ast.Attribute) + and default.attr in members + ): + default_value = default.attr + else: + default_value = _literal_or_source(default) + unit = values.get("unit") + return { + "default_value": default_value, + "definition_period": _definition_period(values.get("definition_period")), + "enum": enum, + "enum_members": members, + "file": module.path.relative_to(package_dir).as_posix(), + "has_formula": _has_formula(node), + "name": node.name, + "unit": None if unit is None else _literal_or_source(unit), + "value_type": ast.unparse(values["value_type"]) + if "value_type" in values + else None, + } + + +def read_entity_variables(package_dir: Path, *, entity: str) -> EntityVariables: + """Read the variables on ``entity`` from a country package's source. + + ``package_dir`` is the package directory itself (for example + ``policyengine-uk/policyengine_uk``); its ``tests/`` directory is skipped. + ``entity`` is the entity class name the variables assign (for example + ``Firm``). Each record holds ``default_value``, ``definition_period``, + ``enum`` (``name`` and ``module``, or None), ``enum_members``, ``file`` + (relative to the package), ``has_formula``, ``name``, ``unit`` and + ``value_type``. + + Raises ``ValueError`` when the package defines no variable on the entity, + defines one twice, or names an enum it cannot resolve. + """ + + package_dir = Path(package_dir) + if not package_dir.is_dir(): + raise ValueError(f"{package_dir} is not a package directory.") + modules = _read_modules(package_dir) + variable_names: set[str] = set() + variables: dict[str, dict[str, Any]] = {} + for module in modules.values(): + for node in module.classes.values(): + if "Variable" not in _base_names(node): + continue + variable_names.add(node.name) + assigned = _assignments(node).get("entity") + if isinstance(assigned, ast.Name) and assigned.id == entity: + if node.name in variables: + raise ValueError(f"{entity} variable {node.name} is defined twice.") + variables[node.name] = _variable_record( + modules, module, node, package_dir + ) + if not variables: + raise ValueError(f"{package_dir} defines no {entity} variables.") + inputs = sorted( + name for name, variable in variables.items() if not variable["has_formula"] + ) + return EntityVariables( + variables=variables, + input_names=inputs, + variable_names=sorted(variable_names), + ) + + +def input_status_problems( + status: Mapping[str, str], + engine_inputs: Iterable[str], + *, + exported_columns: Iterable[str] | None = None, +) -> list[str]: + """What is wrong with a build's input-status record; empty when nothing. + + ``status`` maps every engine input to one of :data:`INPUT_STATUSES`. It + must cover exactly ``engine_inputs``. With ``exported_columns`` (the + engine inputs the fullest export writes), the inputs whose status is + exported (:data:`EXPORTED_INPUT_STATUSES`) must be exactly those columns. + """ + + problems = [] + unknown = sorted( + {value for value in status.values() if value not in INPUT_STATUSES} + ) + if unknown: + problems.append( + f"unknown input statuses {unknown}; choose from {INPUT_STATUSES}" + ) + inputs = set(engine_inputs) + missing = sorted(inputs - set(status)) + if missing: + problems.append(f"engine inputs without a status: {missing}") + extra = sorted(set(status) - inputs) + if extra: + problems.append(f"statuses for names that are not engine inputs: {extra}") + if exported_columns is not None: + exported = set(exported_columns) + claimed = { + name for name, value in status.items() if value in EXPORTED_INPUT_STATUSES + } + unexported = sorted(claimed - exported) + if unexported: + problems.append( + f"inputs marked exported that no export writes: {unexported}" + ) + unclaimed = sorted(exported - claimed) + if unclaimed: + problems.append(f"exported inputs marked not_set or missing: {unclaimed}") + return problems + + +def export_schema_problems( + table: pd.DataFrame, + variables: EntityVariables, + *, + columns: Iterable[str] | None = None, +) -> list[str]: + """What in ``table`` would not load as engine inputs; empty when nothing. + + Each checked column (``columns``, else every column of ``table``) must be + a formula-less variable in ``variables``. A float, int or bool variable + needs a column of that dtype kind; an enum variable needs string values + that are members of its enum. + """ + + inputs = set(variables.input_names) + problems = [] + for column in table.columns if columns is None else columns: + if column not in table.columns: + problems.append(f"{column}: not in the table") + continue + if column not in inputs: + problems.append(f"{column}: not a formula-less engine input") + continue + variable = variables.variables[column] + value_type = variable["value_type"] + if value_type == "Enum": + values = table[column].to_numpy() + if not all(isinstance(value, str) for value in values): + problems.append(f"{column}: enum values must be member names") + continue + outside = sorted(set(values) - set(variable["enum_members"] or ())) + if outside: + problems.append(f"{column}: values {outside[:5]} are not enum members") + elif value_type in _DTYPE_KINDS: + kind = table[column].dtype.kind + if kind != _DTYPE_KINDS[value_type]: + problems.append( + f"{column}: dtype {table[column].dtype} for value type {value_type}" + ) + else: + problems.append(f"{column}: unchecked value type {value_type!r}") + return problems diff --git a/packages/microcosm-build/src/microcosm/build/firms/receipts.py b/packages/microcosm-build/src/microcosm/build/firms/receipts.py new file mode 100644 index 0000000000..1008ab161b --- /dev/null +++ b/packages/microcosm-build/src/microcosm/build/firms/receipts.py @@ -0,0 +1,242 @@ +"""Model totals beside official receipts, as a sourced diagnostic table. + +A firm build's tax totals are compared with official receipts to see where +the data fall short. The comparison is a diagnostic, never a calibration +target, and it must not invent a gap: + +- a total whose inputs the build leaves unset prints :data:`INPUT_NOT_POPULATED` + rather than a -100% shortfall, so every total needs an explicit + ``populated`` flag; +- a name with no official figure prints :data:`NO_OFFICIAL_FIGURE`; +- every official figure carries its publisher, title, edition, URL and access + date, or the receipts file is refused. + +The country supplies the receipts file, how money is formatted, and the +reasons each model measure differs from the official one. +""" + +from __future__ import annotations + +import csv +from collections.abc import Callable, Mapping, Sequence +from dataclasses import dataclass +from pathlib import Path +from typing import Final + +__all__ = [ + "INPUT_NOT_POPULATED", + "NO_MODEL_TOTAL", + "NO_OFFICIAL_FIGURE", + "RECEIPT_SOURCE_COLUMNS", + "ComparisonRow", + "Receipt", + "build_comparison_rows", + "compare_total", + "read_receipts", + "render_comparison_markdown", +] + +INPUT_NOT_POPULATED: Final = "input not populated" +NO_OFFICIAL_FIGURE: Final = "no official figure fetched" +NO_MODEL_TOTAL: Final = "no model total supplied" + +#: Columns every row with an official figure must fill. +RECEIPT_SOURCE_COLUMNS: Final[tuple[str, ...]] = ( + "measure", + "source_publisher", + "source_title", + "edition", + "url", + "accessed", +) +#: Columns a receipts file carries besides the name and value columns. +_RECEIPT_TEXT_COLUMNS: Final[tuple[str, ...]] = ( + "period", + *RECEIPT_SOURCE_COLUMNS, + "note", +) + + +@dataclass(frozen=True) +class Receipt: + """One official figure and where it comes from.""" + + name: str + official_value: float | None + period: str + measure: str + source_publisher: str + source_title: str + edition: str + url: str + accessed: str + note: str + + +@dataclass(frozen=True) +class ComparisonRow: + """One row of the comparison table, already formatted.""" + + name: str + model: str + official: str + gap: str + ratio: str + reason: str + + +def read_receipts( + path: Path, *, name_column: str, value_column: str +) -> dict[str, Receipt]: + """Read a receipts CSV, refusing missing columns, repeats or unsourced figures. + + The file needs ``name_column``, ``value_column`` (blank when there is no + official figure), ``period``, the :data:`RECEIPT_SOURCE_COLUMNS` and + ``note``. Receipts keep the file's row order. + """ + + required = (name_column, value_column, *_RECEIPT_TEXT_COLUMNS) + with Path(path).open(newline="", encoding="utf-8") as handle: + reader = csv.DictReader(handle) + missing = [c for c in required if c not in (reader.fieldnames or ())] + if missing: + raise ValueError(f"{path}: missing columns {missing}") + receipts: dict[str, Receipt] = {} + for row in reader: + name = row[name_column].strip() + if name in receipts: + raise ValueError(f"{path}: duplicate {name_column} {name!r}") + raw = row[value_column].strip() + value = float(raw) if raw else None + if value is not None: + unsourced = [c for c in RECEIPT_SOURCE_COLUMNS if not row[c].strip()] + if unsourced: + raise ValueError(f"{path}: {name} has a figure but no {unsourced}") + receipts[name] = Receipt( + name=name, + official_value=value, + **{c: row[c].strip() for c in _RECEIPT_TEXT_COLUMNS}, + ) + return receipts + + +def compare_total( + name: str, + *, + model_total: float | None, + populated: bool, + official_value: float | None, + reasons: Sequence[str], + format_value: Callable[[float], str], +) -> ComparisonRow: + """One table row. No gap or ratio unless both sides are real figures. + + ``reasons`` are joined, in order, into the row's reason text. + """ + + official = ( + format_value(official_value) + if official_value is not None + else NO_OFFICIAL_FIGURE + ) + if not populated: + model = gap = ratio = INPUT_NOT_POPULATED + elif model_total is None: + model = gap = ratio = NO_MODEL_TOTAL + else: + model = format_value(model_total) + if official_value is None: + gap = ratio = NO_OFFICIAL_FIGURE + else: + difference = model_total - official_value + gap = format_value(difference) + if official_value: + gap += f" ({difference / official_value:+.1%})" + ratio = f"{model_total / official_value:.3f}" + else: + ratio = "official figure is zero" + return ComparisonRow(name, model, official, gap, ratio, " ".join(reasons)) + + +def build_comparison_rows( + totals: Mapping[str, float | None], + populated: Mapping[str, object], + receipts: Mapping[str, Receipt], + *, + reasons_for: Callable[[str, Receipt | None], Sequence[str]], + format_value: Callable[[float], str], +) -> list[ComparisonRow]: + """Rows in receipts order, then any names only the model has, sorted. + + Every name in ``totals`` needs a true/false ``populated`` flag; without + one an unset input would print as a -100% gap, so it is refused. A name + in the receipts that the model left out entirely reads + :data:`NO_MODEL_TOTAL`. + """ + + unflagged = sorted( + name for name in totals if not isinstance(populated.get(name), bool) + ) + if unflagged: + raise ValueError( + f"totals {unflagged} have no true/false populated flag; without it " + "an unset input would print as a -100% gap" + ) + names = list(receipts) + sorted(set(totals) - set(receipts)) + rows = [] + for name in names: + total = totals.get(name) + receipt = receipts.get(name) + rows.append( + compare_total( + name, + model_total=None if total is None else float(total), + populated=bool(populated.get(name, True)), + official_value=None if receipt is None else receipt.official_value, + reasons=reasons_for(name, receipt), + format_value=format_value, + ) + ) + return rows + + +def _cell(text: str) -> str: + return text.replace("|", "\\|").replace("\n", " ") + + +def render_comparison_markdown( + rows: Sequence[ComparisonRow], + receipts: Mapping[str, Receipt], + *, + title: str, + name_header: str, + note: str | None = None, +) -> str: + """The comparison as markdown: a table, then a source line per receipt.""" + + lines = [ + f"# {title}", + "", + "Gap is model less official (share of official); ratio is model / official.", + ] + if note: + lines += ["", f"Model run note: {note}"] + lines += [ + "", + f"| {name_header} | Model total | Official | Gap | Ratio | Reason / caveat |", + "| --- | --- | --- | --- | --- | --- |", + ] + for row in rows: + cells = (row.name, row.model, row.official, row.gap, row.ratio, row.reason) + lines.append("| " + " | ".join(_cell(v) for v in cells) + " |") + lines += ["", "## Sources", ""] + for receipt in receipts.values(): + if receipt.official_value is None: + lines.append(f"- `{receipt.name}`: {NO_OFFICIAL_FIGURE}. {receipt.note}") + else: + lines.append( + f"- `{receipt.name}`: {receipt.source_publisher}, " + f"{receipt.source_title}; {receipt.edition}; {receipt.url} " + f"(accessed {receipt.accessed}). {receipt.note}" + ) + return "\n".join(lines) + "\n" diff --git a/packages/microcosm-build/src/microcosm/build/firms/registration.py b/packages/microcosm-build/src/microcosm/build/firms/registration.py new file mode 100644 index 0000000000..5ba96dac47 --- /dev/null +++ b/packages/microcosm-build/src/microcosm/build/firms/registration.py @@ -0,0 +1,251 @@ +"""Two universes: a business register and a tax-registration count. + +A firm build often calibrates to two populations that overlap but are not the +same. One is a business register (the frame), counted by band. The other is +a tax administration's count of registered traders by the same bands, which +includes traders outside the register and leaves out registered businesses +that are not registered for the tax. Each frame firm enters the calibration +with its band's registration propensity (registered traders divided by the +band's frame mass). After calibration, a weighted selection per band marks +which firms are in the tax's scope and which are registered. + +What differs by country is data, not code: the band labels and what each band +means for registration. A :class:`RegistrationSpec` declares them. Each band +has a role: + +- ``"excluded"``: frame firms in the band are neither in scope nor + registered, and their propensity is 0. Registered traders outside the frame + sit here (for example, traders with zero or negative turnover). +- ``"registrable"``: every frame firm in the band is in scope (it could + register), and a weighted selection reaching the band's registered count + is registered. This is the band below a registration threshold. +- ``"selected"``: a weighted selection reaching the band's registered count + is both in scope and registered; the rest of the band is out of scope. + These are the bands above a threshold, where an unregistered firm is + outside the tax (exempt, or registered for another tax only). + +Rows outside the frame (``frame_mask`` False) are registered traders by +construction: in scope, registered, with propensity 1. + +Registered counts arrive per call, aligned with the spec's bands. +""" + +from __future__ import annotations + +from dataclasses import dataclass +from typing import Final + +import numpy as np + +from ._arrays import as_1d + +__all__ = [ + "BAND_ROLES", + "RegistrationSpec", + "assign_scope_and_registration", + "registration_propensity", + "select_to_weighted_target", +] + +#: The roles a band can take; see the module docstring. +BAND_ROLES: Final[tuple[str, ...]] = ("excluded", "registrable", "selected") + + +@dataclass(frozen=True) +class RegistrationSpec: + """A country's registration bands and the role each band plays. + + ``band_labels[b]`` names band ``b``; ``band_roles[b]`` is its role, one + of :data:`BAND_ROLES`. Band indices passed to the functions here index + these tuples. + """ + + band_labels: tuple[str, ...] + band_roles: tuple[str, ...] + + def __post_init__(self) -> None: + labels = tuple(str(label) for label in self.band_labels) + roles = tuple(str(role) for role in self.band_roles) + if not labels: + raise ValueError("a registration spec needs at least one band") + if len(labels) != len(roles): + raise ValueError( + f"a registration spec has {len(labels)} band labels " + f"and {len(roles)} band roles" + ) + if len(set(labels)) != len(labels): + raise ValueError("registration band labels must be unique") + unknown = sorted(set(roles) - set(BAND_ROLES)) + if unknown: + raise ValueError( + f"unknown registration band roles {unknown}; choose from {BAND_ROLES}" + ) + object.__setattr__(self, "band_labels", labels) + object.__setattr__(self, "band_roles", roles) + + @property + def n_bands(self) -> int: + return len(self.band_labels) + + def bands_with_role(self, role: str) -> tuple[int, ...]: + """The indices of the bands with ``role``, in index order.""" + + if role not in BAND_ROLES: + raise ValueError(f"unknown registration band role {role!r}") + return tuple(b for b, r in enumerate(self.band_roles) if r == role) + + +def _counts(spec: RegistrationSpec, registered_counts: object) -> np.ndarray: + counts = as_1d("registered_counts", registered_counts, spec.n_bands).astype( + np.float64 + ) + if not np.all(np.isfinite(counts)) or np.any(counts < 0): + raise ValueError("registered_counts must hold finite, non-negative counts") + return counts + + +def _band_indices( + spec: RegistrationSpec, band_idx: object, length: int | None = None +) -> np.ndarray: + bands = as_1d("band_idx", band_idx, length) + if not np.issubdtype(bands.dtype, np.integer): + raise TypeError("band_idx must be an integer array") + if bands.size and (bands.min() < 0 or bands.max() >= spec.n_bands): + raise ValueError(f"band_idx values must lie in [0, {spec.n_bands - 1}]") + return bands.astype(np.int64) + + +def registration_propensity( + spec: RegistrationSpec, + band_idx: np.ndarray, + frame_mask: np.ndarray, + base_weights: np.ndarray, + registered_counts: np.ndarray, +) -> np.ndarray: + """Each row's probability of being a registered trader. + + For each band that is not ``"excluded"``, the propensity of its frame + rows is the band's registered count divided by its base-weighted frame + mass, capped at 1.0 when the frame cannot hold the registered population. + A band with no frame mass leaves its rows at 0.0. Frame rows in an + ``"excluded"`` band get 0.0; rows outside the frame get 1.0. + + Args: + spec: The bands and their roles. + band_idx: Integer array, shape ``(n,)``: each row's band. + frame_mask: Boolean array, shape ``(n,)``: True for frame rows. + base_weights: Float array, shape ``(n,)``: each row's base weight. + registered_counts: Float array, shape ``(spec.n_bands,)``. + + Returns: + Float64 array, shape ``(n,)``, of propensities in ``[0, 1]``. + """ + + bands = _band_indices(spec, band_idx) + n = len(bands) + frame = as_1d("frame_mask", frame_mask, n).astype(bool) + weights = as_1d("base_weights", base_weights, n).astype(np.float64) + counts = _counts(spec, registered_counts) + + frame_mass = np.bincount( + bands[frame], weights=weights[frame], minlength=spec.n_bands + ) + per_band = np.zeros(spec.n_bands, dtype=np.float64) + positive = frame_mass > 0 + per_band[positive] = np.minimum(1.0, counts[positive] / frame_mass[positive]) + per_band[list(spec.bands_with_role("excluded"))] = 0.0 + + propensity = np.where(frame, per_band[bands], 1.0) + return propensity.astype(np.float64) + + +def select_to_weighted_target( + candidates: np.ndarray, + weights: np.ndarray, + target: float, + rng: np.random.Generator, +) -> np.ndarray: + """``candidates`` in a seeded random order until their weight reaches ``target``. + + The first row whose cumulative weight reaches the target is included, so + the selected weight overshoots the target by less than one row's weight. + If the candidates' total weight falls short, every candidate is selected. + With no candidates, or a target of zero or less, nothing is selected and + ``rng`` is not drawn from. + + Args: + candidates: Integer row positions to choose from. + weights: Float array indexed by row position. + target: The weight to reach. + rng: The generator that draws the permutation. + + Returns: + The selected row positions, in selection order. + """ + + if len(candidates) == 0 or target <= 0: + return candidates[:0] + order = candidates[rng.permutation(len(candidates))] + cumulative = np.cumsum(weights[order]) + cutoff = min(int(np.searchsorted(cumulative, target, side="left")), len(order) - 1) + return order[: cutoff + 1] + + +def assign_scope_and_registration( + spec: RegistrationSpec, + band_idx: np.ndarray, + frame_mask: np.ndarray, + weights: np.ndarray, + registered_counts: np.ndarray, + *, + seed: int, +) -> tuple[np.ndarray, np.ndarray]: + """Assign scope and registration flags that match the registered counts. + + Rows outside the frame are in scope and registered. Frame rows follow + their band's role (module docstring). In each band that is not + ``"excluded"``, the registered weight lies in ``[target, target + w)`` + for the weight ``w`` of the last selected row, unless the band's weight + falls short of the target, when every row in the band is selected. + + One ``np.random.default_rng(seed)`` generator draws one permutation per + band that is not ``"excluded"``, in band index order (none for a band + with no candidates or a zero target). + + Args: + spec: The bands and their roles. + band_idx: Integer array, shape ``(n,)``: each row's band. + frame_mask: Boolean array, shape ``(n,)``: True for frame rows. + weights: Float array, shape ``(n,)``: calibration (or base) weights. + registered_counts: Float array, shape ``(spec.n_bands,)``. + seed: Seed of the selection generator. + + Returns: + ``(scope, registered)``: boolean arrays of shape ``(n,)``. + """ + + bands = _band_indices(spec, band_idx) + n = len(bands) + frame = as_1d("frame_mask", frame_mask, n).astype(bool) + row_weights = as_1d("weights", weights, n).astype(np.float64) + counts = _counts(spec, registered_counts) + rng = np.random.default_rng(int(seed)) + + scope = np.zeros(n, dtype=bool) + registered = np.zeros(n, dtype=bool) + scope[~frame] = True + registered[~frame] = True + + for band, role in enumerate(spec.band_roles): + if role == "excluded": + continue + in_band = frame & (bands == band) + if role == "registrable": + scope[in_band] = True + chosen = select_to_weighted_target( + np.flatnonzero(in_band), row_weights, counts[band], rng + ) + scope[chosen] = True + registered[chosen] = True + + return scope, registered diff --git a/packages/microcosm-build/src/microcosm/build/firms/rules.py b/packages/microcosm-build/src/microcosm/build/firms/rules.py new file mode 100644 index 0000000000..97e98a7c52 --- /dev/null +++ b/packages/microcosm-build/src/microcosm/build/firms/rules.py @@ -0,0 +1,134 @@ +"""The seam between a firm build and a rule engine. + +A firm build does not compute taxes itself. It hands a firm table to a rule +engine (a country model, or a cross-check) and reads back named per-firm +outputs, keyed by firm id. The seam is the same for every country: + +- a :class:`FirmRules` implementation's ``evaluate(firms, *, period)`` + returns :class:`FirmRuleOutputs`; +- :func:`align_rule_outputs` puts the outputs back in the build's row order, + refusing a missing, repeated or unrequested firm id; +- :func:`weighted_totals` sums a per-firm output table by firm weight. + +What the table's columns mean, which outputs are read and what ``period`` +stands for are the country's business. +""" + +from __future__ import annotations + +from collections.abc import Mapping +from dataclasses import dataclass +from types import MappingProxyType +from typing import Protocol + +import numpy as np +import pandas as pd + +__all__ = [ + "FirmRuleOutputs", + "FirmRules", + "align_rule_outputs", + "weighted_totals", +] + + +@dataclass(frozen=True) +class FirmRuleOutputs: + """Named per-firm rule results, keyed by ``firm_id``. + + ``values`` maps each output's name to a float64 array aligned with + ``firm_id``; every value must be finite. ``provenance`` names the rules + that produced them. + """ + + firm_id: np.ndarray + values: Mapping[str, np.ndarray] + provenance: Mapping[str, str] + + def __post_init__(self) -> None: + firm_id = np.asarray(self.firm_id) + if firm_id.ndim != 1 or not np.issubdtype(firm_id.dtype, np.integer): + raise ValueError("firm rule outputs need a 1-D integer firm_id") + if not self.values: + raise ValueError("firm rule outputs need at least one named output") + values: dict[str, np.ndarray] = {} + for name, raw in self.values.items(): + name = str(name) + if not name or name == "firm_id": + raise ValueError(f"firm rule output name {name!r} is not allowed") + array = np.asarray(raw, dtype=np.float64) + if array.shape != firm_id.shape: + raise ValueError( + f"firm rule output {name} has shape {array.shape} for " + f"{firm_id.shape[0]} firm ids" + ) + if not np.all(np.isfinite(array)): + raise ValueError(f"firm rule output {name} must be finite") + values[name] = array + object.__setattr__(self, "firm_id", firm_id.astype(np.int64)) + object.__setattr__(self, "values", MappingProxyType(values)) + object.__setattr__( + self, + "provenance", + MappingProxyType({str(k): str(v) for k, v in self.provenance.items()}), + ) + + +class FirmRules(Protocol): + """Evaluate rules for a firm table in ``period``.""" + + def evaluate(self, firms: pd.DataFrame, *, period: int) -> FirmRuleOutputs: + """Return named per-firm outputs keyed by ``firm_id``.""" + + +def align_rule_outputs( + outputs: FirmRuleOutputs, + firm_id: np.ndarray | pd.Series, +) -> dict[str, np.ndarray]: + """Every output of ``outputs``, in the order of ``firm_id``. + + Raises ``ValueError`` when either side repeats a firm id, when a requested + firm has no output, or when the outputs hold a firm not requested. + """ + + requested = pd.Index(np.asarray(firm_id, dtype=np.int64)) + produced = pd.Index(outputs.firm_id) + if not requested.is_unique: + raise ValueError("requested firm ids repeat") + if not produced.is_unique: + raise ValueError("firm rule outputs repeat a firm id") + positions = produced.get_indexer(requested) + missing = requested[positions < 0] + if len(missing): + raise ValueError( + f"firm rule outputs miss {len(missing)} firm ids, " + f"e.g. {missing[:5].tolist()}" + ) + extra = produced[~produced.isin(requested)] + if len(extra): + raise ValueError( + f"firm rule outputs hold {len(extra)} unrequested firm ids, " + f"e.g. {extra[:5].tolist()}" + ) + return {name: values[positions] for name, values in outputs.values.items()} + + +def weighted_totals( + table: pd.DataFrame, + *, + weight_column: str = "firm_weight", + id_column: str = "firm_id", +) -> dict[str, float]: + """``sum(value * weight)`` for every column but the id and weight columns. + + Each total stands alone; the caller decides which ones add up. + """ + + if weight_column not in table.columns: + raise ValueError(f"firm output table misses column {weight_column}") + weight = table[weight_column].to_numpy(np.float64) + return { + str(column): float(np.dot(table[column].to_numpy(np.float64), weight)) + for column in table.columns + if column not in (id_column, weight_column) + } diff --git a/packages/microcosm-build/src/microcosm/build/firms/thinning.py b/packages/microcosm-build/src/microcosm/build/firms/thinning.py new file mode 100644 index 0000000000..7c023748b3 --- /dev/null +++ b/packages/microcosm-build/src/microcosm/build/firms/thinning.py @@ -0,0 +1,108 @@ +"""Stratified thinning of a candidate firm draw, with exact base weights. + +A full firm census (millions of rows) is slow to calibrate. Thinning keeps +rows inside an analysis window (for example around a tax threshold) at one +rate and rows outside it at another, stratum by stratum, and gives each kept +row the base weight that restores its stratum's row count. Strata are the +caller's keys (for example industry and turnover band) crossed with the +window side. +""" + +from __future__ import annotations + +from collections.abc import Sequence + +import numpy as np + +from ._arrays import as_1d + +__all__ = ["stratified_thin"] + + +def stratified_thin( + window_values: np.ndarray, + strata: Sequence[np.ndarray], + *, + window_lo: float, + window_hi: float, + window_fraction: float, + tail_fraction: float, + cell_floor: int, + rng_seed: int, +) -> tuple[np.ndarray, np.ndarray]: + """Thin rows by stratum and return the kept rows and their base weights. + + Rows whose ``window_values`` lie inside ``[window_lo, window_hi]`` + (inclusive) are kept with probability ``window_fraction``; every other row + with probability ``tail_fraction``. A stratum (the ``strata`` keys crossed + with the window side) that keeps fewer than ``min(cell_floor, stratum + size)`` rows is topped up with its unkept rows of lowest uniform draw, so + small strata survive. Each kept row's base weight is its stratum's size + divided by its kept count, so the base-weighted count of every stratum + equals its row count (up to float64 rounding). + + One uniform draw per row comes from ``np.random.default_rng(rng_seed)``. + Draws lie in ``[0, 1)``, so fractions of 1.0 keep every row at weight 1.0. + + Args: + window_values: Float array, shape ``(n,)``: the value the window reads. + strata: Integer arrays, each shape ``(n,)``: the stratum keys. An + empty sequence stratifies by window side alone. + window_lo: Lower window edge (inclusive). + window_hi: Upper window edge (inclusive). + window_fraction: Keep probability inside the window, in ``[0, 1]``. + tail_fraction: Keep probability outside the window, in ``[0, 1]``. + cell_floor: Minimum kept rows per stratum (capped at stratum size). + rng_seed: Seed of the generator that draws the uniforms. + + Returns: + ``(keep_idx, base_weights)``: ascending int64 positions of the kept + rows and their float64 base weights. + """ + + values = as_1d("window_values", window_values).astype(np.float64) + n = len(values) + keys = [] + for position, key in enumerate(strata): + array = as_1d(f"strata[{position}]", key, n) + if not np.issubdtype(array.dtype, np.integer): + raise TypeError(f"strata[{position}] must be an integer array") + keys.append(array.astype(np.int64)) + for name, fraction in ( + ("window_fraction", window_fraction), + ("tail_fraction", tail_fraction), + ): + if not 0.0 <= float(fraction) <= 1.0: + raise ValueError(f"{name} must lie in [0, 1], got {fraction}") + if int(cell_floor) < 0: + raise ValueError(f"cell_floor must be non-negative, got {cell_floor}") + if n == 0: + return np.zeros(0, dtype=np.int64), np.zeros(0, dtype=np.float64) + + in_window = (values >= window_lo) & (values <= window_hi) + fraction = np.where(in_window, float(window_fraction), float(tail_fraction)) + rng = np.random.default_rng(int(rng_seed)) + u = rng.random(n) + keep = u < fraction + + stacked = np.stack([*keys, in_window.astype(np.int64)], axis=1) + _, stratum = np.unique(stacked, axis=0, return_inverse=True) + stratum = stratum.reshape(-1) + n_strata = int(stratum.max()) + 1 + sizes = np.bincount(stratum, minlength=n_strata) + kept = np.bincount(stratum, weights=keep, minlength=n_strata).astype(np.int64) + deficit = np.clip(np.minimum(int(cell_floor), sizes) - kept, 0, None) + + if deficit.any(): + # Top up each deficient stratum with its lowest-u unkept rows. + candidates = np.flatnonzero(~keep & (deficit[stratum] > 0)) + order = candidates[np.lexsort((u[candidates], stratum[candidates]))] + ordered_strata = stratum[order] + first = np.searchsorted(ordered_strata, ordered_strata, side="left") + rank = np.arange(len(order)) - first # 0-based rank within stratum + keep[order[rank < deficit[ordered_strata]]] = True + kept = np.bincount(stratum, weights=keep, minlength=n_strata).astype(np.int64) + + base = sizes / np.maximum(kept, 1) + keep_idx = np.flatnonzero(keep).astype(np.int64) + return keep_idx, base[stratum[keep_idx]].astype(np.float64) diff --git a/packages/microcosm-build/tests/engine_free/shared/test_firm_engine_inputs.py b/packages/microcosm-build/tests/engine_free/shared/test_firm_engine_inputs.py new file mode 100644 index 0000000000..1f02cced98 --- /dev/null +++ b/packages/microcosm-build/tests/engine_free/shared/test_firm_engine_inputs.py @@ -0,0 +1,225 @@ +"""Reading a country package's entity inputs from source, and checks against them. + +The package here is a toy written to ``tmp_path``; no country model is +imported. +""" + +from __future__ import annotations + +import textwrap +from pathlib import Path + +import numpy as np +import pandas as pd +import pytest + +from microcosm.build.firms import ( + EXPORTED_INPUT_STATUSES, + INPUT_STATUSES, + export_schema_problems, + input_status_problems, + read_entity_variables, +) + +_FILES = { + "__init__.py": "", + "enums.py": """ + from enum import Enum + + class Region(Enum): + NORTH = "North" + SOUTH = "South" + _PRIVATE = "hidden" + """, + "variables/__init__.py": "", + "variables/firm/__init__.py": "", + "variables/firm/inputs.py": """ + from toymodel.model_api import * + from toymodel.enums import Region + from toymodel import enums as e + + class firm_turnover(Variable): + entity = Firm + value_type = float + unit = GBP + definition_period = YEAR + default_value = 0 + + class firm_region(Variable): + entity = Firm + value_type = Enum + possible_values = Region + default_value = Region.SOUTH + definition_period = YEAR + + class firm_home_region(Variable): + entity = Firm + value_type = Enum + possible_values = e.Region + definition_period = YEAR + + class firm_is_bank(Variable): + entity = Firm + value_type = bool + definition_period = YEAR + """, + "variables/firm/outputs.py": """ + from toymodel.model_api import * + + class firm_tax(Variable): + entity = Firm + value_type = float + definition_period = YEAR + + def formula(firm, period, parameters): + return firm("firm_turnover", period) * 0.1 + + class firm_total(Variable): + entity = Firm + value_type = float + definition_period = YEAR + adds = ["firm_tax"] + + class person_age(Variable): + entity = Person + value_type = int + definition_period = YEAR + """, + "tests/test_ignored.py": """ + class firm_test_only(Variable): + entity = Firm + value_type = float + """, +} + + +@pytest.fixture +def toy_package(tmp_path: Path) -> Path: + package = tmp_path / "toymodel" + for name, source in _FILES.items(): + path = package / name + path.parent.mkdir(parents=True, exist_ok=True) + path.write_text(textwrap.dedent(source), encoding="utf-8") + return package + + +def test_reader_finds_entity_variables_and_their_inputs(toy_package) -> None: + read = read_entity_variables(toy_package, entity="Firm") + assert sorted(read.variables) == [ + "firm_home_region", + "firm_is_bank", + "firm_region", + "firm_tax", + "firm_total", + "firm_turnover", + ] + assert read.input_names == [ + "firm_home_region", + "firm_is_bank", + "firm_region", + "firm_turnover", + ] + assert "person_age" in read.variable_names + assert "firm_test_only" not in read.variable_names + + +def test_reader_records_types_units_defaults_and_enums(toy_package) -> None: + variables = read_entity_variables(toy_package, entity="Firm").variables + assert variables["firm_turnover"] == { + "default_value": 0, + "definition_period": "year", + "enum": None, + "enum_members": None, + "file": "variables/firm/inputs.py", + "has_formula": False, + "name": "firm_turnover", + "unit": "GBP", + "value_type": "float", + } + region = variables["firm_region"] + assert region["enum"] == {"name": "Region", "module": "toymodel.enums"} + assert region["enum_members"] == ["NORTH", "SOUTH"] + assert region["default_value"] == "SOUTH" + assert variables["firm_home_region"]["enum_members"] == ["NORTH", "SOUTH"] + assert variables["firm_tax"]["has_formula"] + assert variables["firm_total"]["has_formula"] + + +def test_reader_refuses_an_entity_with_no_variables(toy_package) -> None: + with pytest.raises(ValueError, match="defines no Household variables"): + read_entity_variables(toy_package, entity="Household") + + +def test_input_status_must_cover_exactly_the_inputs() -> None: + inputs = ["firm_turnover", "firm_region", "firm_is_bank"] + status = { + "firm_turnover": "set", + "firm_region": "assumed", + "firm_is_bank": "not_set", + } + assert input_status_problems(status, inputs) == [] + assert ( + input_status_problems( + status, inputs, exported_columns=["firm_turnover", "firm_region"] + ) + == [] + ) + problems = input_status_problems( + {**status, "firm_is_bank": "guessed", "firm_other": "set"}, + [*inputs, "firm_new"], + exported_columns=["firm_turnover"], + ) + assert problems == [ + f"unknown input statuses ['guessed']; choose from {INPUT_STATUSES}", + "engine inputs without a status: ['firm_new']", + "statuses for names that are not engine inputs: ['firm_other']", + "inputs marked exported that no export writes: ['firm_other', 'firm_region']", + ] + assert set(EXPORTED_INPUT_STATUSES) == set(INPUT_STATUSES) - {"not_set"} + + +def test_an_exported_column_marked_not_set_is_a_problem() -> None: + problems = input_status_problems( + {"firm_turnover": "not_set"}, + ["firm_turnover"], + exported_columns=["firm_turnover"], + ) + assert problems == ["exported inputs marked not_set or missing: ['firm_turnover']"] + + +def test_export_schema_accepts_a_loadable_table(toy_package) -> None: + read = read_entity_variables(toy_package, entity="Firm") + table = pd.DataFrame( + { + "firm_turnover": np.array([1.0, 2.0]), + "firm_region": ["NORTH", "SOUTH"], + "firm_is_bank": [False, True], + "in_frame": [True, True], + } + ) + columns = [c for c in table.columns if c.startswith("firm_")] + assert export_schema_problems(table, read, columns=columns) == [] + + +def test_export_schema_names_each_unloadable_column(toy_package) -> None: + read = read_entity_variables(toy_package, entity="Firm") + table = pd.DataFrame( + { + "firm_turnover": np.array([1, 2]), + "firm_region": ["NORTH", "EAST"], + "firm_home_region": [1, 2], + "firm_tax": [0.0, 0.0], + "in_frame": [True, True], + } + ) + problems = export_schema_problems( + table, read, columns=[*table.columns, "firm_gone"] + ) + assert problems == [ + "firm_turnover: dtype int64 for value type float", + "firm_region: values ['EAST'] are not enum members", + "firm_home_region: enum values must be member names", + "firm_tax: not a formula-less engine input", + "in_frame: not a formula-less engine input", + "firm_gone: not in the table", + ] diff --git a/packages/microcosm-build/tests/engine_free/shared/test_firm_receipts_comparison.py b/packages/microcosm-build/tests/engine_free/shared/test_firm_receipts_comparison.py new file mode 100644 index 0000000000..7897150b4c --- /dev/null +++ b/packages/microcosm-build/tests/engine_free/shared/test_firm_receipts_comparison.py @@ -0,0 +1,189 @@ +"""The country-neutral comparison of model totals with official receipts.""" + +from __future__ import annotations + +import csv +from pathlib import Path + +import pytest + +from microcosm.build.firms.receipts import ( + INPUT_NOT_POPULATED, + NO_MODEL_TOTAL, + NO_OFFICIAL_FIGURE, + RECEIPT_SOURCE_COLUMNS, + Receipt, + build_comparison_rows, + compare_total, + read_receipts, + render_comparison_markdown, +) + +_COLUMNS = ("levy", "value_eur", "period", *RECEIPT_SOURCE_COLUMNS, "note") +_SOURCE = { + "measure": "cash receipts", + "source_publisher": "Tax Office", + "source_title": "Receipts bulletin", + "edition": "March 2026", + "url": "https://example.org/receipts", + "accessed": "2026-11-20", +} + + +def _write(path: Path, rows: list[dict[str, str]], columns=_COLUMNS) -> Path: + with path.open("w", newline="", encoding="utf-8") as handle: + writer = csv.DictWriter(handle, fieldnames=columns) + writer.writeheader() + for row in rows: + writer.writerow({c: row.get(c, "") for c in columns}) + return path + + +def _row(name: str, value: str, **overrides: str) -> dict[str, str]: + return { + "levy": name, + "value_eur": value, + "period": "2025", + **_SOURCE, + "note": "", + **overrides, + } + + +def _euros(value: float) -> str: + sign = "-" if value < 0 else "" + return f"{sign}€{abs(value) / 1e6:,.1f}m" + + +def _receipts(tmp_path: Path) -> dict[str, Receipt]: + path = _write( + tmp_path / "receipts.csv", + [ + _row("payroll_levy", "200000000"), + _row( + "site_levy", "", note="Not published yet.", **dict.fromkeys(_SOURCE, "") + ), + _row("profit_levy", "50000000"), + ], + ) + return read_receipts(path, name_column="levy", value_column="value_eur") + + +def test_reader_keeps_order_and_blank_figures(tmp_path) -> None: + receipts = _receipts(tmp_path) + assert list(receipts) == ["payroll_levy", "site_levy", "profit_levy"] + assert receipts["payroll_levy"].official_value == 200_000_000.0 + assert receipts["payroll_levy"].edition == "March 2026" + assert receipts["site_levy"].official_value is None + + +def test_reader_refuses_missing_columns_repeats_and_unsourced_figures( + tmp_path, +) -> None: + short = _write(tmp_path / "a.csv", [], columns=_COLUMNS[:-1]) + with pytest.raises(ValueError, match=r"missing columns \['note'\]"): + read_receipts(short, name_column="levy", value_column="value_eur") + repeated = _write(tmp_path / "b.csv", [_row("x", "1"), _row("x", "2")]) + with pytest.raises(ValueError, match="duplicate levy 'x'"): + read_receipts(repeated, name_column="levy", value_column="value_eur") + unsourced = _write(tmp_path / "c.csv", [_row("x", "1", url="")]) + with pytest.raises(ValueError, match=r"x has a figure but no \['url'\]"): + read_receipts(unsourced, name_column="levy", value_column="value_eur") + + +@pytest.mark.parametrize( + ("kwargs", "expected"), + [ + ( + {"model_total": 150e6, "populated": True, "official_value": 200e6}, + ("€150.0m", "€200.0m", "-€50.0m (-25.0%)", "0.750"), + ), + ( + {"model_total": 0.0, "populated": False, "official_value": 200e6}, + (INPUT_NOT_POPULATED, "€200.0m", INPUT_NOT_POPULATED, INPUT_NOT_POPULATED), + ), + ( + {"model_total": None, "populated": True, "official_value": 200e6}, + (NO_MODEL_TOTAL, "€200.0m", NO_MODEL_TOTAL, NO_MODEL_TOTAL), + ), + ( + {"model_total": 5e6, "populated": True, "official_value": None}, + ("€5.0m", NO_OFFICIAL_FIGURE, NO_OFFICIAL_FIGURE, NO_OFFICIAL_FIGURE), + ), + ( + {"model_total": 5e6, "populated": True, "official_value": 0.0}, + ("€5.0m", "€0.0m", "€5.0m", "official figure is zero"), + ), + ], +) +def test_compare_total_never_invents_a_gap(kwargs, expected) -> None: + row = compare_total("levy", reasons=["One.", "Two."], format_value=_euros, **kwargs) + assert (row.model, row.official, row.gap, row.ratio) == expected + assert row.reason == "One. Two." + + +def test_rows_follow_receipts_then_model_only_names(tmp_path) -> None: + receipts = _receipts(tmp_path) + seen = [] + + def reasons_for(name, receipt): + seen.append((name, receipt is not None)) + return [f"Official measure: {receipt.measure}."] if receipt else [] + + rows = build_comparison_rows( + {"payroll_levy": 180e6, "site_levy": 0.0, "extra_credit": 3e6}, + {"payroll_levy": True, "site_levy": False, "extra_credit": True}, + receipts, + reasons_for=reasons_for, + format_value=_euros, + ) + assert [r.name for r in rows] == [ + "payroll_levy", + "site_levy", + "profit_levy", + "extra_credit", + ] + assert rows[1].gap == INPUT_NOT_POPULATED + assert rows[2].model == NO_MODEL_TOTAL + assert rows[3].official == NO_OFFICIAL_FIGURE + assert rows[0].reason == "Official measure: cash receipts." + assert seen[-1] == ("extra_credit", False) + + +def test_rows_refuse_a_total_without_a_populated_flag(tmp_path) -> None: + with pytest.raises(ValueError, match=r"\['payroll_levy'\] have no true/false"): + build_comparison_rows( + {"payroll_levy": 1.0}, + {"payroll_levy": "yes"}, + _receipts(tmp_path), + reasons_for=lambda name, receipt: [], + format_value=_euros, + ) + + +def test_markdown_escapes_cells_and_lists_sources(tmp_path) -> None: + receipts = _receipts(tmp_path) + rows = build_comparison_rows( + {"payroll_levy": 180e6}, + {"payroll_levy": True}, + receipts, + reasons_for=lambda name, receipt: ["a | b"], + format_value=_euros, + ) + report = render_comparison_markdown( + rows, receipts, title="Firm levies, 2025", name_header="Levy", note="run 7" + ) + lines = report.splitlines() + assert lines[0] == "# Firm levies, 2025" + assert "Model run note: run 7" in lines + assert "| Levy | Model total | Official | Gap | Ratio | Reason / caveat |" in lines + assert ( + "| payroll_levy | €180.0m | €200.0m | -€20.0m (-10.0%) | 0.900 | a \\| b |" + in lines + ) + assert "- `site_levy`: no official figure fetched. Not published yet." in lines + assert ( + "- `payroll_levy`: Tax Office, Receipts bulletin; March 2026; " + "https://example.org/receipts (accessed 2026-11-20). " + ) in lines + assert report.endswith("\n") diff --git a/packages/microcosm-build/tests/engine_free/shared/test_firm_rules_seam.py b/packages/microcosm-build/tests/engine_free/shared/test_firm_rules_seam.py new file mode 100644 index 0000000000..9dd836adb0 --- /dev/null +++ b/packages/microcosm-build/tests/engine_free/shared/test_firm_rules_seam.py @@ -0,0 +1,119 @@ +"""The country-neutral firm rules seam: outputs, alignment and totals.""" + +from __future__ import annotations + +import numpy as np +import pandas as pd +import pytest + +from microcosm.build.firms import ( + FirmRuleOutputs, + FirmRules, + align_rule_outputs, + weighted_totals, +) + + +def _outputs(ids, **values) -> FirmRuleOutputs: + return FirmRuleOutputs( + firm_id=np.asarray(ids, dtype=np.int64), + values={name: np.asarray(v, dtype=np.float64) for name, v in values.items()}, + provenance={"rules": "test"}, + ) + + +class _FlatTax: + """A rules double: 10% of turnover, and a count of one per firm.""" + + def evaluate(self, firms: pd.DataFrame, *, period: int) -> FirmRuleOutputs: + return FirmRuleOutputs( + firm_id=firms["firm_id"].to_numpy(), + values={ + "tax": 0.1 * firms["turnover"].to_numpy(np.float64), + "payers": np.ones(len(firms)), + }, + provenance={"rules": "flat", "period": str(period)}, + ) + + +def test_outputs_coerce_and_freeze() -> None: + outputs = FirmRuleOutputs( + firm_id=np.array([1, 2], dtype=np.int32), + values={"tax": [1.5, -2.0]}, + provenance={"rules": "test"}, + ) + assert outputs.firm_id.dtype == np.int64 + assert outputs.values["tax"].dtype == np.float64 + with pytest.raises(TypeError): + outputs.provenance["rules"] = "other" # type: ignore[index] + with pytest.raises(TypeError): + outputs.values["tax"] = np.zeros(2) # type: ignore[index] + + +@pytest.mark.parametrize( + ("ids", "values", "match"), + [ + ([1.0, 2.0], {"tax": [1.0, 2.0]}, "integer"), + ([1, 2], {}, "at least one"), + ([1, 2], {"tax": [1.0]}, "shape"), + ([1, 2], {"tax": [1.0, np.nan]}, "finite"), + ([1, 2], {"firm_id": [1.0, 2.0]}, "not allowed"), + ([1, 2], {"": [1.0, 2.0]}, "not allowed"), + ], +) +def test_outputs_refuse_malformed_arrays(ids, values, match) -> None: + with pytest.raises(ValueError, match=match): + FirmRuleOutputs(firm_id=np.asarray(ids), values=values, provenance={}) + + +def test_align_reorders_every_output_by_firm_id() -> None: + outputs = _outputs([3, 1, 2], tax=[30.0, 10.0, 20.0], payers=[3.0, 1.0, 2.0]) + aligned = align_rule_outputs(outputs, np.array([1, 2, 3])) + assert list(aligned) == ["tax", "payers"] + np.testing.assert_array_equal(aligned["tax"], [10.0, 20.0, 30.0]) + np.testing.assert_array_equal(aligned["payers"], [1.0, 2.0, 3.0]) + by_series = align_rule_outputs(outputs, pd.Series([2, 3, 1])) + np.testing.assert_array_equal(by_series["tax"], [20.0, 30.0, 10.0]) + + +@pytest.mark.parametrize( + ("produced", "requested", "match"), + [ + ([1, 2], [1, 2, 3], "miss 1 firm ids"), + ([1, 2, 3], [1, 2], "unrequested"), + ([1, 1, 2], [1, 2], "outputs repeat"), + ([1, 2], [1, 1, 2], "requested firm ids repeat"), + ], +) +def test_align_refuses_mismatched_ids(produced, requested, match) -> None: + outputs = _outputs(produced, tax=np.zeros(len(produced))) + with pytest.raises(ValueError, match=match): + align_rule_outputs(outputs, np.asarray(requested)) + + +def test_a_rules_double_satisfies_the_protocol_and_aligns() -> None: + rules: FirmRules = _FlatTax() + firms = pd.DataFrame({"firm_id": [7, 5], "turnover": [100.0, 40.0]}) + outputs = rules.evaluate(firms, period=2024) + assert outputs.provenance["period"] == "2024" + aligned = align_rule_outputs(outputs, np.array([5, 7])) + np.testing.assert_allclose(aligned["tax"], [4.0, 10.0]) + + +def test_weighted_totals_sum_each_output_alone() -> None: + table = pd.DataFrame( + { + "firm_id": [1, 2], + "firm_weight": [2.0, 3.0], + "tax": [10.0, -1.0], + "payers": [1.0, 0.0], + } + ) + assert weighted_totals(table) == {"tax": 17.0, "payers": 2.0} + renamed = table.rename(columns={"firm_weight": "w", "firm_id": "id"}) + assert weighted_totals(renamed, weight_column="w", id_column="id") == { + "tax": 17.0, + "payers": 2.0, + } + with pytest.raises(ValueError, match="firm_weight"): + weighted_totals(table.drop(columns="firm_weight")) diff --git a/packages/microcosm-build/tests/engine_free/shared/test_firm_universe_mechanics.py b/packages/microcosm-build/tests/engine_free/shared/test_firm_universe_mechanics.py new file mode 100644 index 0000000000..8048cb1468 --- /dev/null +++ b/packages/microcosm-build/tests/engine_free/shared/test_firm_universe_mechanics.py @@ -0,0 +1,289 @@ +"""The country-neutral firm mechanics: band draws, thinning, registration. + +Two registration specs are used throughout. ``EIGHT_BANDS`` has the shape of +a VAT register with a threshold: an excluded band for traders outside the +frame, one registrable band below the threshold and six selected bands above +it. ``FOUR_BANDS`` has no registrable band and no excluded band, so the +functions are tested on a shape no current country uses. +""" + +from __future__ import annotations + +import numpy as np +import pytest + +from microcosm.build.firms import ( + BAND_ROLES, + RegistrationSpec, + assign_scope_and_registration, + draw_in_band, + registration_propensity, + select_to_weighted_target, + stratified_thin, +) + +EIGHT_BANDS = RegistrationSpec( + tuple(f"band_{b}" for b in range(8)), + ("excluded", "registrable", *("selected",) * 6), +) +FOUR_BANDS = RegistrationSpec(("a", "b", "c", "d"), ("selected",) * 4) + +THIN = { + "window_lo": 15.0, + "window_hi": 150.0, + "window_fraction": 0.3, + "tail_fraction": 0.05, + "cell_floor": 5, + "rng_seed": 43, +} + + +def _draw(n: int = 4000, seed: int = 0) -> tuple[np.ndarray, np.ndarray, np.ndarray]: + rng = np.random.default_rng(seed) + turnover = rng.lognormal(mean=4.0, sigma=1.5, size=n) + sic = rng.choice( + np.array([1, 41, 47, 62, 86]), size=n, p=[0.05, 0.2, 0.4, 0.3, 0.05] + ) + bands = np.digitize( + turnover, [0.0, 90.0, 150.0, 300.0, 500.0, 1000.0, 10000.0], right=True + ) + return turnover, sic, bands.astype(np.int64) + + +def _strata(turnover, sic, bands) -> np.ndarray: + window = (turnover >= THIN["window_lo"]) & (turnover <= THIN["window_hi"]) + keys = np.stack([sic, bands, window.astype(np.int64)], axis=1) + return np.unique(keys, axis=0, return_inverse=True)[1].reshape(-1) + + +# Band draws. + + +def test_closed_band_draw_is_uniform_inside_the_band() -> None: + unit = np.array([0.0, 0.25, 0.5, 0.999]) + values = draw_in_band(unit, 10.0, 50.0) + np.testing.assert_allclose(values, [10.0, 20.0, 30.0, 49.96]) + + +def test_floor_lifts_a_zero_lower_edge() -> None: + values = draw_in_band(np.array([0.0, 0.5]), 0.0, 10.0, floor=2.0) + np.testing.assert_allclose(values, [2.0, 6.0]) + + +def test_open_band_draw_is_log_uniform_and_stays_below_the_cap() -> None: + unit = np.array([0.0, 0.5, 0.999999]) + values = draw_in_band(unit, 100.0, 10000.0, log_uniform=True) + np.testing.assert_allclose(values[:2], [100.0, 1000.0]) + assert values[2] < 10000.0 + + +def test_band_draw_keeps_torch_type_and_dtype() -> None: + torch = pytest.importorskip("torch") + unit = torch.tensor([0.0, 0.5], dtype=torch.float32) + for log_uniform in (False, True): + values = draw_in_band(unit, 1.0, 100.0, log_uniform=log_uniform) + assert isinstance(values, torch.Tensor) + assert values.dtype == torch.float32 + + +def test_band_draw_refuses_inverted_and_non_positive_log_bands() -> None: + with pytest.raises(ValueError, match="below its low edge"): + draw_in_band(np.array([0.5]), 10.0, 5.0) + with pytest.raises(ValueError, match="positive low edge"): + draw_in_band(np.array([0.5]), 0.0, 5.0, log_uniform=True) + + +# Thinning. + + +def test_full_fractions_return_every_row_at_unit_weight() -> None: + turnover, sic, bands = _draw() + params = {**THIN, "window_fraction": 1.0, "tail_fraction": 1.0} + keep, base = stratified_thin(turnover, [sic, bands], **params) + np.testing.assert_array_equal(keep, np.arange(len(turnover))) + np.testing.assert_array_equal(base, np.ones(len(turnover))) + + +def test_base_weighted_stratum_totals_reproduce_the_draw() -> None: + turnover, sic, bands = _draw() + keep, base = stratified_thin(turnover, [sic, bands], **THIN) + assert len(keep) < len(turnover) / 2 + strata = _strata(turnover, sic, bands) + original = np.bincount(strata) + weighted = np.bincount(strata[keep], weights=base, minlength=len(original)) + np.testing.assert_allclose(weighted, original, rtol=1e-12, atol=0.0) + + +def test_cell_floor_keeps_small_strata() -> None: + turnover, sic, bands = _draw() + keep, _ = stratified_thin(turnover, [sic, bands], **THIN) + strata = _strata(turnover, sic, bands) + sizes = np.bincount(strata) + kept = np.bincount(strata[keep], minlength=len(sizes)) + assert np.all(kept >= np.minimum(THIN["cell_floor"], sizes)) + params = {**THIN, "window_fraction": 0.0, "tail_fraction": 0.0} + keep, base = stratified_thin( + np.array([500.0, 600.0, 700.0]), [np.array([1, 1, 1])], **params + ) + np.testing.assert_array_equal(keep, [0, 1, 2]) + np.testing.assert_array_equal(base, [1.0, 1.0, 1.0]) + + +def test_floor_top_up_takes_lowest_draws_and_weights_by_ratio() -> None: + n = 12 + params = {**THIN, "tail_fraction": 0.0, "cell_floor": 4, "rng_seed": 8} + keep, base = stratified_thin( + np.full(n, 500.0), [np.ones(n, dtype=np.int64)], **params + ) + u = np.random.default_rng(8).random(n) + np.testing.assert_array_equal(keep, np.sort(np.argsort(u)[:4])) + np.testing.assert_array_equal(base, np.full(4, 3.0)) + + +def test_thinning_without_keys_stratifies_by_window_side() -> None: + values = np.array([10.0] * 6 + [100.0] * 4) + params = {**THIN, "window_fraction": 0.0, "tail_fraction": 0.0, "cell_floor": 2} + keep, base = stratified_thin(values, [], **params) + assert len(keep) == 4 + assert sorted(base.tolist()) == [2.0, 2.0, 3.0, 3.0] + + +def test_thinning_is_deterministic_by_seed() -> None: + turnover, sic, bands = _draw() + first = stratified_thin(turnover, [sic, bands], **THIN) + second = stratified_thin(turnover, [sic, bands], **THIN) + other = stratified_thin(turnover, [sic, bands], **{**THIN, "rng_seed": 44}) + np.testing.assert_array_equal(first[0], second[0]) + np.testing.assert_array_equal(first[1], second[1]) + assert not np.array_equal(first[0], other[0]) + + +def test_thinning_refuses_misaligned_or_non_integer_keys() -> None: + with pytest.raises(ValueError, match=r"strata\[0\]"): + stratified_thin(np.ones(3), [np.ones(2, dtype=np.int64)], **THIN) + with pytest.raises(TypeError, match="integer"): + stratified_thin(np.ones(3), [np.ones(3)], **THIN) + + +# Registration spec. + + +def test_spec_records_bands_by_role() -> None: + assert EIGHT_BANDS.n_bands == 8 + assert EIGHT_BANDS.bands_with_role("excluded") == (0,) + assert EIGHT_BANDS.bands_with_role("registrable") == (1,) + assert EIGHT_BANDS.bands_with_role("selected") == tuple(range(2, 8)) + assert set(BAND_ROLES) == {"excluded", "registrable", "selected"} + + +@pytest.mark.parametrize( + ("labels", "roles", "message"), + [ + ((), (), "at least one band"), + (("a", "b"), ("selected",), "2 band labels and 1 band roles"), + (("a", "a"), ("selected", "selected"), "unique"), + (("a",), ("threshold",), "unknown registration band roles"), + ], +) +def test_spec_refuses_malformed_declarations(labels, roles, message) -> None: + with pytest.raises(ValueError, match=message): + RegistrationSpec(labels, roles) + + +# Propensity. + + +def test_propensity_is_registered_count_over_frame_mass() -> None: + bands = np.array([0, 1, 1, 1, 2, 2, 3, 0, 7]) + frame = np.array([True, True, True, True, True, True, True, False, True]) + base = np.array([1.0, 10.0, 20.0, 30.0, 4.0, 6.0, 2.0, 1.0, 5.0]) + counts = np.array([99.0, 15.0, 5.0, 8.0, 0.0, 0.0, 0.0, 7.0]) + propensity = registration_propensity(EIGHT_BANDS, bands, frame, base, counts) + expected = [0.0, 0.25, 0.25, 0.25, 0.5, 0.5, 1.0, 1.0, 1.0] + np.testing.assert_allclose(propensity, expected, rtol=0, atol=1e-12) + + +def test_propensity_without_an_excluded_band_covers_every_band() -> None: + bands = np.array([0, 0, 1, 3]) + frame = np.array([True, True, True, False]) + base = np.array([2.0, 2.0, 5.0, 1.0]) + counts = np.array([1.0, 10.0, 0.0, 0.0]) + propensity = registration_propensity(FOUR_BANDS, bands, frame, base, counts) + np.testing.assert_allclose(propensity, [0.25, 0.25, 1.0, 1.0]) + + +def test_propensity_leaves_empty_bands_at_zero() -> None: + propensity = registration_propensity( + EIGHT_BANDS, + np.array([4, 4]), + np.array([True, True]), + np.zeros(2), + np.full(8, 5.0), + ) + np.testing.assert_array_equal(propensity, [0.0, 0.0]) + + +def test_registered_counts_must_align_with_the_spec() -> None: + with pytest.raises(ValueError, match="registered_counts"): + registration_propensity( + EIGHT_BANDS, np.array([1]), np.array([True]), np.ones(1), np.ones(7) + ) + with pytest.raises(ValueError, match="band_idx"): + registration_propensity( + FOUR_BANDS, np.array([4]), np.array([True]), np.ones(1), np.ones(4) + ) + + +# Scope and registration. + + +@pytest.mark.parametrize("spec", [EIGHT_BANDS, FOUR_BANDS]) +def test_registration_totals_match_counts_within_one_weight(spec) -> None: + rng = np.random.default_rng(3) + n = 5000 + bands = rng.integers(0, spec.n_bands, size=n) + frame = rng.random(n) > 0.05 + weights = rng.uniform(1.0, 20.0, size=n) + mass = np.bincount(bands[frame], weights=weights[frame], minlength=spec.n_bands) + counts = np.round(mass * rng.uniform(0.3, 0.95, size=spec.n_bands)) + scope, registered = assign_scope_and_registration( + spec, bands, frame, weights, counts, seed=42 + ) + assert scope[~frame].all() and registered[~frame].all() + assert not (registered & ~scope).any() + for band, role in enumerate(spec.band_roles): + rows = frame & (bands == band) + if role == "excluded": + assert not (scope | registered)[rows].any() + continue + if role == "registrable": + assert scope[rows].all() + else: + assert np.array_equal(scope[rows], registered[rows]) + total = weights[rows & registered].sum() + assert counts[band] <= total < counts[band] + weights[rows].max() + again = assign_scope_and_registration(spec, bands, frame, weights, counts, seed=42) + np.testing.assert_array_equal(again[1], registered) + + +def test_registration_selects_whole_band_when_count_exceeds_mass() -> None: + counts = np.zeros(8) + counts[2] = 100.0 + scope, registered = assign_scope_and_registration( + EIGHT_BANDS, + np.array([2, 2, 2]), + np.ones(3, dtype=bool), + np.ones(3), + counts, + seed=1, + ) + assert scope.all() and registered.all() + + +def test_weighted_selection_draws_nothing_for_an_empty_or_zero_target() -> None: + rng = np.random.default_rng(5) + state = rng.bit_generator.state + empty = select_to_weighted_target(np.zeros(0, dtype=np.int64), np.ones(3), 2.0, rng) + zero = select_to_weighted_target(np.arange(3), np.ones(3), 0.0, rng) + assert len(empty) == len(zero) == 0 + assert rng.bit_generator.state == state