Skip to content
Draft
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
9 changes: 9 additions & 0 deletions changelog.d/1705-shared-firm-mechanics.added.md
Original file line number Diff line number Diff line change
@@ -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.
63 changes: 63 additions & 0 deletions packages/microcosm-build/src/microcosm/build/firms/__init__.py
Original file line number Diff line number Diff line change
@@ -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",
]
16 changes: 16 additions & 0 deletions packages/microcosm-build/src/microcosm/build/firms/_arrays.py
Original file line number Diff line number Diff line change
@@ -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
58 changes: 58 additions & 0 deletions packages/microcosm-build/src/microcosm/build/firms/bands.py
Original file line number Diff line number Diff line change
@@ -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)
Loading
Loading