Skip to main content

Dependency graphs

Key design decisions

  • Node identity: nodes are keyed by sheet-qualified A1 strings like Sheet1!A1 (NodeKey).
  • Edge direction: an edge A -> B means A depends on B (dependency-first evaluation).
  • Leaf definition: a leaf is any node with no cell dependencies (Node.is_leaf=True), including non-formula cells and literal-only formulas (e.g. =1+1).
  • Values are optional: load_values=True loads cached Excel results in the same parse as formulas (keep_formula_cache=True); otherwise formula nodes have value=None.
  • Extensible metadata: each Node exposes metadata as a read-only Mapping[str, Any]. Nodes without metadata share one immutable empty mapping instead of allocating a dict, so hooks write through node.set_metadata(...) / node.update_metadata(...) (or graph.set_node_metadata(key, ...)) rather than node.metadata[key] = value.
  • Range expansion: ranges like A1:A10 are expanded to individual cell dependencies (bounded by max_range_cells, default 50,000). A rectangle larger than the budget raises ValueError rather than silently keeping only the two corner cells.
  • Whole-column/row shorthand: Excel forms like Data!A:A and Data!5:5 parse as syntactic shorthands and resolve to each sheet’s used range (workbook dimensions), not Excel’s full grid (XFD / 1048576). These shorthands expand to every row/column in that extent even when a rectangular range of the same size would exceed max_range_cells. Defined names that use the same shorthand (Macrofw!$5:$134, Macrofw!$A:$C) follow this policy — see Defined-name expansion.
  • Formula AST: each formula node stores formula_ast, the parsed tree extracted from the workbook (the canonical in-memory formula). normalized_formula is a derived view (render_formula(..., style=A1_ABSOLUTE)): sheet-qualified refs, resolved named ranges, and stripped $ markers. It is not stored on the node or in the JSON graph cache. Formula cells are identified by has_formula (formula_ast or unparseable fallback text). Compression and projection rewrite the AST; the string view follows. Identity-transit compression rewrites CellRefNode leaves only: a transit mentioned as a range endpoint or whole-column/row leaf is left in place so the formula cannot name a removed node and range geometry is not rewritten. replace_resolved_cell_ref still retargets those leaves when called directly. formula_shapes is an optional eval/codegen overlay on top of that AST — see Formula-shape overlay.
  • Array formulas: extraction records Node.is_array_formula and the observed spill / CSE ref (Node.array_formula_ref) when fastpyxl surfaces an ArrayFormula. write_workbook emits ArrayFormula rather than a scalar formula string, and refuses a flagged cell whose ref was not observed. fastpyxl does not distinguish legacy CSE from dynamic-array spills; both round-trip as t="array".
  • Defined names: extraction expands name tokens to A1 before parse. write_workbook emits those expanded formulas and, by default, writes the workbook name table from named_ranges / named_range_ranges so Excel still has the aliases. Whole-row and whole-column referents expand as documented in Defined-name expansion.
  • Raw formulas are opt-in: Node.formula (the workbook string, e.g. =A1+$B$2) is stored only with create_dependency_graph(..., store_raw_formula=True). It is an audit/display field — see Raw formula storage.

Quick start: building a graph

from pathlib import Path

from excel_grapher.grapher import create_dependency_graph
from excel_grapher.grapher import to_graphviz, to_mermaid, to_networkx  # optional

wb_path = Path("model.xlsx")
targets = ["Sheet1!A10"]

g = create_dependency_graph(wb_path, targets, load_values=False)
print(len(g))  # number of visited nodes
print(to_graphviz(g))  # GraphViz DOT

Writing a workbook

write_workbook is the inverse of create_dependency_graph: it writes a GraphReadView (DependencyGraph or ProjectionResult) to a new .xlsx. There is no template-patch mode. If destination already exists, pass overwrite=True. The destination is always a new file; the original workbook is never saved in place. Passing series_bindings opens that workbook read-only so bound labels can be copied.

from pathlib import Path

from excel_grapher.grapher import create_dependency_graph, write_workbook
from excel_grapher.series_bindings import load_series_bindings

graph = create_dependency_graph(Path("model.xlsx"), ["Sheet1!B2"])
graph.set_node_value("Sheet1!A1", 42)
graph.move_node("Sheet1!B2", "Sheet1!C3")
write_workbook(graph, Path("edited.xlsx"))

workbook = Path("model.xlsx")
bindings = load_series_bindings(workbook.with_suffix(".bindings.yaml"))
graph = create_dependency_graph(workbook, ["Sheet1!B2"])
write_workbook(
    graph,
    Path("labelled.xlsx"),
    series_bindings=bindings,
    bindings_workbook=workbook,
)

Default formula spelling is render_formula(..., style=A1_EXCEL) from current formula_ast, so $ vs bare A1 round-trips. The writer never re-parses Node.formula (the opt-in raw audit string, which is stale after compression). Array formulas extracted as fastpyxl ArrayFormula are written back as ArrayFormula with the observed spill / CSE ref. fastpyxl does not distinguish legacy CSE from dynamic-array spills; both round-trip as t="array". A flagged array cell missing that ref is refused rather than written as a scalar formula.

When graph.formula_shapes is warm, write_workbook groups contiguous autofill columns or rows that share an interned relative shape into Excel shared formulas (<f t="shared" ref="B2:B10" si="0">). Group identity is the punched shape plus identical remaining relative axis vectors — the same R1C1 text render_formula(..., style=R1C1) would produce. OOXML stores the master cell in A1 relative to that cell, which is what Excel and fastpyxl persist and re-parse. Pass shared_formulas="off" to keep per-cell A1, or shared_formulas="require" to fail if the overlay is missing. The writer does not auto-rewarm; after compression, rewrite, or load, call warm_formula_shapes and assign the result. project() also drops the overlay on the clone, so a ProjectionResult writes per-cell A1 unless you rewarm projection.projected_graph first (see Exporting standalone Python). Non-contiguous runs, mixed absolute params, array formulas, and INDIRECT stay per-cell.

Defined-name tokens are expanded to A1 at parse (parse_preserving_axes runs expand_defined_names), so a cell that was =A1*TaxRate is written as expanded A1 (for example =A1*Settings!$B$2). That is expected v1 fidelity, not a bug. The workbook defined-name table is still written from graph.named_ranges / named_range_ranges, so aliases such as TaxRate -> Settings!B2 remain in Excel. Pass include_defined_names=False to omit the table. Names the writer cannot express as a cell or rectangle are refused. Graph maps do not record sheet-local vs workbook-global scope, so written names are workbook-global.

Two workflows share the same write API:

Workflow Object What is written
Mutation This DependencyGraph is the workbook (set_node_ast, set_node_value, replace_node_formula, move_node, in-place compress_*) Current formulas and values at current keys. replace_node_formula re-extracts outgoing edges; set_node_formula is the projection primitive and does not rewire. After move_node, new_key is written and old_key is absent (Excel cut semantics: relatives still resolve to the pre-move targets).
Projection Non-mutating export view (IdentityTransitCompression().project) Projected cells only; collapsed addresses are absent

Move then write vs project then write: move_node mutates the canonical graph; write_workbook(graph) persists that geometry. IdentityTransitCompression().project(graph) copies the graph at that moment. A later move_node on the original does not update an existing ProjectionResult — re-run project() after geometry edits if the projected workbook should include them. Writing a pre-move projection is still valid; it exports the pre-move view.

Extraction is a target closure, so styles, charts, VBA, and cells outside the view do not appear in the output. That is accepted v1 lossiness. Pass series_bindings and bindings_workbook to also write row_label, column_header, kind: cell, and attribute source cells that bindings read. Those labels are often outside the formula closure. Formula headers are copied only when every static reference is already in the view or is itself a bound label; missing deps, OFFSET, and INDIRECT fail closed instead of extracting a second closure. The original graph is not mutated; the bindings workbook is opened read-only. Set include_bound_labels=False to keep the strict target-closure file. bindings_workbook is required only when bound labels are included.

Constrained inputs are written back as Excel data validations. series_bindings supplies input domains: input enum and value_map needles become dropdown lists (or custom formulas when a member cannot be an inline list), between / real_between become whole or decimal rules, and greater_than / not_equal become custom formulas combined with any numeric bounds. Integer bounds keep an INT(cell)=cell clause when folded into a custom formula so decimals stay rejected. Constants, outputs, and internals are not inputs, so they do not receive rules. Extract-time cell_type_env domains still apply to unbound value leaves when a sidecar is present; a cell covered by both sources must agree or write-back fails closed. Without a sidecar, value cells in cell_type_env are used alone, including when the view is a ProjectionResult. Pass include_cell_validation=False to omit the rules. A formula longer than 255 characters, a relation partner that is not in the written view, or a from_workbook input with no cached value fails closed.

See Exporting standalone Python for projection as the non-mutating helper shared with Python codegen.

Raw formula storage

Extraction always stores formula_ast (when the formula parses). The raw workbook string Node.formula is opt-in, because nothing in evaluation, compression, or export needs it — dropping it is a straight memory saving on large workbooks. normalized_formula is derived on demand via render_formula (A1_ABSOLUTE).

graph = create_dependency_graph(wb_path, targets)  # node.formula is None
graph = create_dependency_graph(wb_path, targets, store_raw_formula=True)

Turn it on when you want:

  • the original text for auditing, debugging, or display (graph exports and the lightweight viewer fall back to the derived normalized_formula view when it is absent); or
  • the TACO range-pattern index below, which infers stride patterns from the relative/absolute ($) markers that normalization strips. build_taco_index raises RawFormulasRequiredError on a graph without them.

Raw formulas are a record of what extraction read. Compression and projection rewrite formula_ast only, so on a compressed graph Node.formula still shows the pre-compression workbook text — display it, but never re-parse it as the node’s current definition. For the same reason the compression audit trail (record.formula_rewrites) reports derived absolute A1 formulas only.

Formula-shape overlay

DependencyGraph.formula_shapes is an optional acceleration overlay for eval, codegen, and Excel write-back. Node.formula_ast is the source of truth; missing or dropped shapes fall back to AST, so correctness does not require the overlay to be warm. write_workbook uses a warm overlay to group autofill columns into Excel shared formulas and otherwise writes per-cell A1.

Shapes are opt-in. create_dependency_graph defaults to warm_formula_shapes=False (parameterized shapes from GitHub #517 did not make this default-on). Pass the flag, or call warm_formula_shapes and assign the result:

from excel_grapher.grapher import create_dependency_graph, warm_formula_shapes
from excel_grapher.evaluator import FormulaEvaluator

graph = create_dependency_graph(wb_path, targets, warm_formula_shapes=True)
# or later:
graph.formula_shapes = warm_formula_shapes(graph)

Compression, formula rewrite, and JSON/pickle load drop the overlay (None, not serialized). The graph does not auto-rewarm. After those events, callers who want shapes again must rewarm:

graph.formula_shapes = warm_formula_shapes(graph)
ev = FormulaEvaluator(graph)  # new evaluator; live ones keep their init snapshot

A FormulaEvaluator holds a shared reference to the graph (no deep copy), but it compiles shape helpers from graph.formula_shapes at construction. Rewarming the overlay on a live graph does not refresh those compiled helpers. Construct a new FormulaEvaluator after rewarming if you want the shape path (GitHub #560).

Optional TACO range-pattern index

After building a cell-level graph, you can optionally attach a TACO-style (arXiv:2302.05482) compressed dependency index. The graph remains canonical for evaluation and export; the index is a parallel structure for range-pattern dependency queries (autofill columns, running totals, fixed lookup tables, and similar).

from pathlib import Path

from excel_grapher.grapher import build_taco_index, create_dependency_graph

wb_path = Path("model.xlsx")

# Build the index as a derived artifact from the canonical graph.
# Pattern inference reads the raw `$` markers, so raw formulas must be stored:
graph = create_dependency_graph(wb_path, ["Sheet1!D3:D100"], store_raw_formula=True)
index = build_taco_index(graph)

# Query compressed ranges, then materialize to cell keys when needed:
dependents = index.find_dependents("Sheet1!B10")
precedents = index.find_precedents("Sheet1!D10")

# Codegen boundaries: keep targets and inputs at cell granularity; compress internals only:
from excel_grapher.grapher import TacoBuildConfig, build_taco_index, input_keys_from_graph

index = build_taco_index(
    graph,
    TacoBuildConfig.for_codegen(graph),  # exclude targets + graph leaf inputs, internal_only=True
)
# Or step-by-step:
index = build_taco_index(
    graph,
    TacoBuildConfig(
        exclude_targets=True,
        exclude_input_keys=input_keys_from_graph(graph),
        internal_only=True,
    ),
)

The index is a derived artifact: create_dependency_graph never builds it and its default output is unchanged. Build the index on demand with build_taco_index(graph) (and rebuild it after mutating the graph). See examples/micro_workbooks/taco_patterns.xlsx for RR, RF, FR, FF, and RR-Chain pattern examples, and examples/micro_workbooks/cross_sheet_taco_patterns.xlsx for cross-sheet precedents (dependent cells on one sheet, input ranges on another).

Target forms

targets accepts any mix of:

  • sheet-qualified single cells: "Sheet1!A1", "'My Sheet'!B2"
  • sheet-qualified ranges: "Sheet1!B12:F12", "Sheet1!A1:B2" (both-end forms like "Sheet1!A1:Sheet1!B2" are also accepted), "'My Sheet'!A1:B2"
  • defined names that resolve to a single cell or rectangular range: "MyInput", "DataRange" (including whole-row / whole-column names expanded against the sheet used range)

Range and named-range targets expand to one root per cell (subject to max_range_cells, default 50,000) and the BFS proceeds from the deduplicated union of roots. Rectangles larger than max_range_cells raise ValueError. Targets that are neither sheet-qualified nor a known defined name raise ValueError.

Defined-name expansion

build_named_range_map (used by create_dependency_graph) records names that resolve to a cell or a single rectangle:

Referent Example Mapped rectangle
Cell Sheet1!$A$1 Sheet1!A1 (cell map)
Rectangle Sheet1!$A$1:$B$10 Sheet1!A1:B10 as written
Whole-row span Macrofw!$5:$134 Macrofw!A5:{last used col}134
Whole-column span Macrofw!$A:$C Macrofw!A1:C{last used row}

Expansion policy. Whole-row and whole-column names fill only the implicit axis from the sheet’s used range (Worksheet.max_row / max_column — the same bounds as formula shorthands A:A / 5:5). The named rows or columns stay as written; they are not clipped to the used extent. This is not Excel’s full grid (XFD / row 1048576): expanding $5:$134 to 16,384 columns would exceed max_range_cells and explode BFS. A name whose sheet is missing from the workbook is omitted (fail closed) rather than defaulting to those Excel limits. Multi-area unions, #REF!, cube refs, and other non-range formulas remain unsupported.

Dynamic OFFSET/INDIRECT configuration

Dynamic references (e.g. OFFSET, INDIRECT) can be handled in three ways via the create_dependency_graph API:

from excel_grapher.grapher import create_dependency_graph, DynamicRefConfig, DynamicRefLimits

## Signature (simplified):
## create_dependency_graph(
##     workbook_path,
##     targets,
##     *,
##     dynamic_refs: DynamicRefConfig | None = None,
##     use_cached_dynamic_refs: bool = False,
##     ...
## )
  • use_cached_dynamic_refs=True
    Use the existing cached-workbook path for OFFSET/INDIRECT. This preserves the legacy behavior and ignores dynamic_refs.

  • use_cached_dynamic_refs=False (default) and dynamic_refs is None
    When the builder encounters dynamic refs that require resolution, it raises DynamicRefError. This is the safe “no silent fallback” default.

  • use_cached_dynamic_refs=False and dynamic_refs is a DynamicRefConfig
    Resolve dynamic refs using static constraints (cell types and limits). Missing or invalid domains still raise DynamicRefError.

You typically author domains on the series binding sidecar and build a DynamicRefConfig with from_bindings. Before that graph exists, list_dynamic_ref_constraint_candidates (CLI: bindings candidates) lists leaves that feed dynamic-ref arguments and have no domain yet. Cells behind an unresolved dynamic ref are omitted until the first domains are in, so the scan is repeated after each selector domain. Exact MATCH that keeps a lookup cell only because its type is missing warns (ExactMatchUndomainedCellWarning) without failing the build. Pass undomained_exact_match to collect those cells separately from the must-bind list. The low-level from_constraints path still accepts a dict[str, type] of sheet-qualified addresses:

from typing import Annotated, Literal

from excel_grapher.grapher import DynamicRefConfig, create_dependency_graph
from excel_grapher.core.cell_types import Between

constraints_schema = {
    "Sheet1!B1": Literal["ROW_INDEX"],
    "Sheet1!C1": Annotated[float, Between(0, 10)],
}

config = DynamicRefConfig.from_constraints(constraints_schema)

graph = create_dependency_graph(
    "model_with_dynamic_refs.xlsx",
    ["Sheet1!D10"],
    load_values=False,
    dynamic_refs=config,
    # use_cached_dynamic_refs=False is the default
)

Key points:

Working with cell data (for transpilation)

The DependencyGraph provides direct O(1) access to cell data via get_node(), plus filter methods for iterating over formula vs. leaf cells.

from pathlib import Path

from excel_grapher.grapher import create_dependency_graph, discover_formula_cells_in_rows
from excel_grapher.grapher import DependencyGraph

## Discover formula cells in specific rows
targets = discover_formula_cells_in_rows(Path("model.xlsx"), "Sheet1", [10, 11, 12])

## Build the dependency graph
graph: DependencyGraph = create_dependency_graph(
    Path("model.xlsx"), targets, load_values=True, store_raw_formula=True
)

## Access cells by normalized address (O(1) lookup)
node = graph.get_node("Sheet1!A10")
print(node.formula)  # Original formula (only with store_raw_formula=True)
print(node.normalized_formula)  # Derived sheet-qualified A1 (`render_formula`)
print(node.value)  # Cached value from Excel
print(node.is_target)  # True if this node came from original targets

## Iterate over formula cells
for key, node in graph.formula_nodes():
    print(key, node.normalized_formula)

## Iterate over leaf (value) cells
for key, node in graph.leaf_node_items():
    print(key, node.value)

## Get sorted keys
formula_keys = graph.formula_keys()
leaf_keys = graph.leaf_keys()
target_keys = graph.target_keys()

DependencyGraph filter methods

Method Returns Description
get_node(key) NodeView \| None O(1) exact-key cell lookup
formula_nodes() Iterator[tuple[NodeKey, Node]] Cells with formulas
leaf_node_items() Iterator[tuple[NodeKey, Node]] Leaf cells (no cell dependencies)
formula_keys() list[NodeKey] Sorted keys for formula cells
leaf_keys() list[NodeKey] Sorted keys for leaf cells
target_keys() list[NodeKey] Sorted keys marked as original targets

Node fields

Field Type Description
formula str \| None Original formula (None for value-only cells)
formula_ast AST | None Parsed formula tree (canonical storage)
normalized_formula str \| None Derived absolute A1 view (render_formula)
value Any Cached or hardcoded value
is_leaf bool True if the node has no cell dependencies
is_target bool True if the node was one of the original graph targets
sheet str Sheet name
column str Column letter
row int Row number

discover_formula_cells_in_rows()

Utility for scanning rows to find formula cells with numeric cached values:

def discover_formula_cells_in_rows(
    wb_path: Path,
    sheet_name: str,
    rows: list[int],
) -> list[str]: ...

Returns sheet-qualified cell addresses (e.g., "'Sheet Name'!A1") for formula cells.