Skip to main content

Exporting standalone Python

The exporter turns a DependencyGraph into a standalone Python package:

from pathlib import Path

from excel_grapher.exporter import CodeGenerator
from excel_grapher.series_bindings import load_series_bindings

workbook_path = Path("model.xlsx")
bindings = load_series_bindings(workbook_path.with_suffix(".bindings.yaml"))

with CodeGenerator(graph) as gen:
    modules = gen.generate_modules(
        series_bindings=bindings,
        bindings_workbook=workbook_path,
    )

generate_modules() returns a dict[str, str] keyed by module filename (__init__.py, api.py, model.py, data.py, internals.py, validation.py, tensor.py, provenance.py, workbook.py, runtime.py, and excel.py). Write all returned files into a package directory of your choice, then import the package as usual. The package has no dependency on excel_grapher.

Package exports use inverted-tree: each compute_* takes the input leaves of its output as ordinary arguments. generate_modules() requires series_bindings and bindings_workbook. There is no bindings-free, address-keyed generate() path; callers who want a named compute_* API provide a sidecar. The paradigm argument and CLI --paradigm option have been removed.

When graph.formula_shapes is set, FormulaEvaluator compiles shared per-shape helpers, and write_workbook may emit Excel shared formulas for contiguous autofill runs. Missing shapes fall back to per-node AST (and per-cell A1 on write). Shapes are opt-in (create_dependency_graph(..., warm_formula_shapes=False) by default); after compression, formula rewrite, or JSON/pickle load the overlay is dropped and callers must rewarm. See Formula-shape overlay.

Inverted-tree packages

CLI equivalent of generate_modules():

uv run excel-grapher bindings validate model.xlsx \
  --smoke-test --emit-dir ./generated

Models with non-literal OFFSET / INDEX / INDIRECT need series domain in the bindings sidecar, or --use-cached-dynamic-refs. See Command-line interface.

--smoke-test with inverted-tree calls each compute_* using the workbook-default input tensors emitted in data.py (SERIES_DEFAULT). Smoke checks call the generated compute functions.

What the package looks like

Module Role
api.py compute_* functions over Model. Each takes a frozen {Output}Inputs bundle (the input leaf closure) and returns one series. Constant leaves are read from data (data.CONSTANT_X, listed on __constants__) rather than passed as fields. Each function also publishes __key__, __domain__, and __cells__. Model is not an api name; Inputs classes are re-exported here.
model.py Model and the per-output {Output}Inputs dataclasses. {Output}Inputs.from_defaults(**overrides) fills that output’s data.*_DEFAULT leaves and validates via validation.CHECKS. {Output}Inputs.describe() lists each field’s axes, keys, bounds, default, and cells. Model.from_defaults(...) binds every input from data.*_DEFAULT with explicit keyword overrides. Model.from_workbook(path, **overrides) reads those input cells from a populated workbook of this vintage through generated provenance. Leaf inputs use the cached cell value. An input.mode: override cell that still holds its formula stays unset so the extracted formula runs; a literal in that cell displaces the formula. Model(**inputs) still validates unbound kwargs and rejects unknown names; Model(bundle) skips checks when the bundle is already validated. Bare Model() still binds nothing. When a series declares axis_labels, CHECKS evaluate that labeller before checking inputs on the runtime axis, and Model.cells(series_id) binds provenance over the evaluated labels. Import with from generated import Model or from generated.model import Model.
data.py Immutable constants and *_DEFAULT inputs, shared axes, reusable authored domains, graph-required domains, value schemas, generated tensor classes, and coordinate-to-cell provenance descriptors. Runtime-labelled axes are AxisTemplate values bound from the labeller; unlabelled packages keep concrete Axis constants. An override input’s default is the UNSET sentinel, so the template formula stays in force until a caller or case workbook supplies a value.
internals.py One named function per formula series, written over semantic coordinates: loops over the required domain, explicit seed and boundary branches, lazy view / span selections over bound series, and scan_* functions returning frozen named results for recurrence groups. Runtime-labelled axes are keyed by the labeller’s evaluated values, not by snapshot header literals.
validation.py Private _check_* helpers and the CHECKS registry used by {Output}Inputs construction (and Model kwargs) to apply input schemas, input.domain, and input.value_map once.
tensor.py Immutable Axis, Domain, Tensor, Series, and schema validation.
provenance.py row_cells, column_cells, block_cells, and grid_cells descriptors that resolve a coordinate to its authored worksheet cell without listing every cell.
workbook.py read_bound_inputs for from_workbook: input-direction cells only, via generated provenance. Override cells are classified from the formula workbook: a remaining formula is unset and a typed literal displaces the template formula.
runtime.py Lazy views over named coordinates, recurrence readers, and the publish metadata decorator.
excel.py Excel value semantics and inverted-tree adapters (xl_add, XlError, as_measure, lookups, aggregates) embedded from the shared core so the package runs standalone.

Model.from_workbook(path, **overrides) binds every input from a populated workbook of this vintage, then applies keyword overrides through the same validation.CHECKS path as Model(**inputs). Constants stay on data. Leaf inputs are the cached cell values. An input.mode: override series is optional: a cell that still holds the template formula stays unset and the extracted formula runs, including when the cached result is stale, and a literal typed over that cell displaces the formula for the evaluation walk. A literal outside the series domain fails closed. Formulas that are not override inputs stay on the extracted graph; a number typed over one of them is left unread. This is the economist workflow: fill the input sheets in Excel, evaluate in Python. It is not F9 parity — Python still evaluates the extracted graph, so a file whose constants or engine sheets differ from the exported vintage will not match Excel.

from generated import Model

model = Model.from_workbook("ghana-2025.xlsm")
model = Model.from_workbook("ghana-2025.xlsm", discount_rate=0.04)

{Output}Inputs.from_workbook loads only that output’s leaves. Keyword overrides are the same public values compute_* accepts and replace the cells read from the file.

A series with input.value_map is stored in Excel as the workbook needle. from_workbook accepts that needle, checks the public key, and stores the needle formulas compare. Keyword overrides stay public keys. A cell that is not one of the map’s needles fails closed. from_defaults uses the public key of the snapshot needle, so a value-map template still constructs.

These two files are complementary, not duplicates. Generated internals.py imports Excel operators from excel.py and named-axis helpers from runtime.py; runtime.py imports value semantics from excel.py.

Construct inputs from coordinate/value records. The generated schema validates axis names, key types, required coordinates, and value types. Scalar bindings remain plain scalars.

from generated import OutputBaselineInputs, compute_output_baseline, data

# Explicit labels: integer coordinates are years, never storage positions.
growth = data.GROWTH_BASELINE.with_records(
    (((year,), 3.5) for year in (2025, 2026, 2027, 2028, 2029)),
)
result = compute_output_baseline(
    OutputBaselineInputs.from_defaults(
        country_name="Borvelia",
        growth_baseline=growth,
        country_initial_debt=60.0,
    )
)
value = result[2026]

Model is the session object those compute_* functions construct. Bind a subset of input leaves yourself, or bind every snapshot input at once. Unknown names and constants are rejected; constants stay on data (data.overrides to replace them).

from generated import Model, data

model = Model.from_defaults()
model = Model.from_defaults(country_initial_debt=60.0)
model = Model(
    country_name="Borvelia",
    country_initial_debt=60.0,
    growth_baseline=growth,
    interest_baseline=data.INTEREST_BASELINE_DEFAULT,
    primary_balance_baseline=data.PRIMARY_BALANCE_BASELINE_DEFAULT,
)
value = model.output_baseline[2026]

Bindings determine the exact keys in each generated domain. A scenario/year tensor uses values[scenario, year]; four independent axes use four coordinate labels. Sparse domains retain unequal horizons and interior holes. An absent coordinate raises CoordinateError; a present blank (None), zero, and Excel error string remain distinct values.

Use tensor.sel(TIME_PERIOD=2026) for named selection, tensor.items() for canonical coordinate/value records, and tensor.isel(TIME_PERIOD=0) for explicit positional access. No operation implicitly aligns, broadcasts, or fills different input domains.

Each generated function publishes __key__, __domain__, and immutable __cells__ coordinate-to-workbook provenance. Data metadata preserves the authored domain separately from the coordinates required by the extracted graph. Supplied tensors may retain additional source coordinates; generated results are eager and complete over their declared result domain.

Inputs have the matching view. {Output}Inputs.describe() returns an InputField per field, in declaration order, with domain (None for a scalar), axes, size, values (the per-value annotation with its Literal choices or Annotated bounds), default, and cells. Each dataclass field also carries metadata["default"] and metadata["cells"], which link it to its data spec without relying on the *_DEFAULT naming rule.

from generated import OutputShockedInputs

for name, field in OutputShockedInputs.describe().items():
    print(name, field.size, [(axis.name, axis.keys) for axis in field.axes])
# interest_baseline 5 [('TIME_PERIOD', (1, 2, 3, 4, 5))]
# shock_year 1 []

A runtime-labelled axis reports its snapshot keys; the keys a model uses come from its labeller.

The representation is versioned as named-axis-v1. Flat arguments are rejected. Use Tensor.from_records with an explicit domain when adapting an ordered buffer.

Records view (as_records)

Convert a tensor or scalar result to a list of coordinate/value dictionaries:

from generated import as_records, compute_output_baseline

result = compute_output_baseline(...)
records = as_records(compute_output_baseline, result)
# [{'TIME_PERIOD': 2008, 'OBS_VALUE': ...}, ...]

as_records reads compute.__key__ / compute.__domain__. For a matrix, each domain point is a key tuple and each record has one column per key field. Do not expect a generated read_* or compute_*(ctx) -> Records wrapper; that is the ctx façade.

Migrating from ctx

ctx inverted-tree
make_context() then set_<series>(ctx, records) Pass a frozen {Output}Inputs bundle to compute_*.
input.mode: override non-leaf inputs The series is an optional input whose default is unset. Omitting it evaluates the template formula. A caller value or a case-workbook literal displaces that formula. from_workbook treats a remaining formula as unset.
Retained graph leaf inside an internal/output series Also bind that cell as a separate input or constant series; otherwise export bakes the workbook literal. See double-binding retained graph leaves.
read_<series>() / input.reader Import data.SERIES (constants) or pass the value you would have read. Extra input.reader keys are rejected.
input.domain Applied to compute_* arguments after setter dtype coercion (enum, between on int, real_between on float/number) (issue 666, issue 825). Out-of-domain values raise ValueError naming the series.
input.value_map on scalar inputs Applied after the domain check, before any expression (issue 677). Callers pass map keys; internals see workbook needles.
compute_*(ctx) -> Records compute_* takes named tensor or scalar inputs and returns a tensor or scalar. Use as_records(compute, result) for coordinate/value records.
output.compute.helper collapsed helpers Every output is already a leaf-closure function; drop the helper name.
CONSTANTS MappingProxyType / sparse leaf store Immutable data.py tensors and scalars. Use data.override_constants for a scoped override (issue 663).
Range-watch invalidation on EvalContext N/A — arguments are immutable for the call. Pass new values.
list_setters() / list_computes() Package __all__, filtered to names starting with compute_.

Bindings features that already apply before codegen — complementary shards / list data_range, sheet_name, value_map, row_index, and column_letter keys, exclude_rows / exclude_columns, layout: matrix, named ranges in data_range — work with inverted-tree because the catalog consumes the merged sidecar.

Shapes that fail closed (export error, not a silent wrong answer): INDIRECT still in the formula AST (issue 668), and any xl_<name> with no inverted-tree runtime helper. SUM / SUMPRODUCT of a covering series, whole-column / whole-row refs, and cross-sheet 3-D ranges lower when every referenced cell is bound (issue 667). Array-style SUM(IF(…)) and SUMPRODUCT(IF(…)) lower as xl_if over positional range tables when interiors are element-aligned (issue 732). Shape mismatch, nested aggregates, AND/OR collapse, whole-column refs, and interiors outside the emit whitelist (unary minus, ABS, &, IFS / CHOOSE / SWITCH) stay fail-closed. Implicit intersection @ does not parse into a formula AST. AVERAGE(IF) and MAX(IF) stay fail-closed (issue 749). Array spill (issue 284) remains unsupported.

Projection, embed, and visualization exports are not codegen paradigms; they are unchanged.

The deprecated context-based package exporter has been removed. Use the migration table above to replace context calls with explicit compute arguments. Address-keyed CodeGenerator.generate() was removed (issue 764); export is generate_modules() with series bindings.

Series bindings

Optional sidecar manifests (.bindings.yaml) declare structured input/output APIs on exported code. See the dedicated Series bindings guide for the JSON Schema, authoring conventions, validation rules, and Python API. Series I/O is inverted-tree only:

from pathlib import Path

from excel_grapher.exporter import CodeGenerator
from excel_grapher.series_bindings import load_series_bindings

workbook_path = Path("lic_inputs.xlsx")
bindings = load_series_bindings(workbook_path.with_suffix(".bindings.yaml"))

with CodeGenerator(graph) as gen:
    modules = gen.generate_modules(
        series_bindings=bindings,
        bindings_workbook=workbook_path,
    )

generate_modules() requires series_bindings and bindings_workbook. Outputs come from the bindings catalog, not from a cell-address list.

Graph projection for export

Identity transit nodes (pure mirrors such as Outputs!B12 = Engine!C6) can be collapsed in projected export artifacts while the canonical workbook graph stays unchanged. Marked extract targets (is_target) and optional preserve keys are not forwarded, matching OptimalCompression. Pass a ProjectionResult to CodeGenerator or write_workbook so remaining public addresses keep their workbook-facing identity. Projection is the non-mutating export helper for both Python codegen and Excel write-back; in-place compress_* rewrites self and write_workbook would persist that rewrite into a new .xlsx.

A ProjectionResult is a snapshot from project(). Project then write exports that clone. Move then write (write_workbook(graph) after move_node) persists the mutated geometry. A later move_node on the original graph does not update an existing projection; re-run project() after geometry edits if the projected workbook should include them.

from pathlib import Path

from excel_grapher.exporter import CodeGenerator, IdentityTransitCompression
from excel_grapher.grapher import write_workbook

projection = IdentityTransitCompression(
    series_bindings=series_bindings,
    bindings_workbook=workbook_path,
).project(graph)
modules = CodeGenerator(projection).generate_modules(
    series_bindings=series_bindings,
    bindings_workbook=workbook_path,
)
write_workbook(projection, Path("projected.xlsx"))

project() compresses a clone and drops formula_shapes. write_workbook does not rewarm, so default shared_formulas="auto" emits per-cell A1 unless you rewarm the clone first:

from excel_grapher.grapher import warm_formula_shapes

projection.projected_graph.formula_shapes = warm_formula_shapes(projection.projected_graph)
write_workbook(projection, Path("projected.xlsx"))

ProjectionResult behaves like the projected graph for dependency reads, and exposes original_graph plus a serializable manifest. The manifest separates address projection (map_to_projected, used by codegen to keep removed public addresses resolving) from collapse lineage (retained_to_collapsed_sources, removed_node_snapshots with original formulas and metadata, collapsed_groups, formula_rewrites) for audit and refactoring. Visualization can use the same facade:

from excel_grapher.exporter import to_web_viz_payload

payload = to_web_viz_payload(projection)

Projection is an extension point: implement the ProjectionStep protocol to build your own projected graph (see the contributing guide), and compose steps with apply_projection. In-place DependencyGraph.compress_identity_transits() remains available for destructive graph simplification; prefer projections for Python codegen, Excel write-back, and viz workflows.

Tradeoffs for the exported-code approach:

  • Advantages
    • Standalone artifact: output is plain Python; no need to distribute excel_grapher or the evaluator with it.
    • Partial obfuscation: does not expose the extraction engine directly.
    • Minimal runtime surface: embeds only the Excel-equivalent helpers actually needed by the exported graph.
    • Repeatable execution: freezes workbook logic at a point in time; downstream runs are deterministic and Excel-free.
  • Disadvantages
    • Still Excel-shaped: the structure is still series- and cell-centric; interpretability gains are incremental.
    • Regeneration required: changes to the workbook require re-extracting and re-exporting.