Skip to main content

grapher.create_dependency_graph()

Build a dependency graph starting from target cells.

Usage

Source

grapher.create_dependency_graph(
    workbook,
    targets,
    *,
    max_depth=50,
    expand_ranges=True,
    max_range_cells=DEFAULT_MAX_RANGE_CELLS,
    hooks=None,
    load_values=True,
    dynamic_refs=None,
    use_cached_dynamic_refs=False,
    capture_dependency_provenance=False,
    store_raw_formula=False,
    blank_ranges=None,
    type_analysis_cache=None,
    warm_ast_cache=False,
    warm_formula_shapes=False,
    formula_overrides=None
)

targets accepts any mix of:

  • sheet-qualified single cells ("Sheet1!A1", "'My Sheet'!B2");
  • sheet-qualified rectangular ranges ("Sheet1!B12:F12", "Sheet1!A1:B2", "'My Sheet'!A1:B2"); and
  • defined names that resolve to a single cell or a rectangular range ("MyInput", "DataRange").

Range and named-range targets are expanded to one BFS root per cell (subject to max_range_cells, default DEFAULT_MAX_RANGE_CELLS); the deduplicated union seeds traversal. Rectangles larger than max_range_cells raise ValueError. Targets that are neither sheet-qualified nor a known defined name raise ValueError.

When load_values is True (default), the workbook is loaded once with keep_formula_cache=True so formula text and Excel’s last-calculated cache are available without a second data_only parse. When False, formula nodes keep value=None and the formula-cache side map is not populated.

Supports basic A1 references, sheet-qualified references, and dynamic references (OFFSET/INDIRECT/INDEX). For OFFSET/INDIRECT/INDEX:

  • use_cached_dynamic_refs=True: Resolve using cached workbook values (existing path). dynamic_refs is ignored.
  • use_cached_dynamic_refs=False (default), dynamic_refs=None: On any formula that contains OFFSET, INDIRECT, or INDEX requiring resolution, raise DynamicRefError. Callers can pass a DynamicRefConfig or set use_cached_dynamic_refs=True to avoid.
  • use_cached_dynamic_refs=False, dynamic_refs set: Resolve OFFSET/INDIRECT/INDEX via the config’s cell_type_env and limits; missing or invalid domains raise DynamicRefError.

To build a config from a dict[str, type] constraints schema, use DynamicRefConfig.from_constraints.

When capture_dependency_provenance is True, each edge stores merged excel_grapher.grapher.dependency_provenance.EdgeProvenance on DependencyGraph._edge_provenance (how the dependency arises: direct reference, static range, dynamic OFFSET/INDIRECT/INDEX). Direct-reference spans are recorded against Node.normalized_formula only.

When store_raw_formula is True, each formula cell also keeps the workbook formula text on Node.formula. It defaults to False because the string is not needed to evaluate, compress, or export a graph: formula_ast is the in-memory source of truth, normalized_formula is a derived render_formula(..., style=A1_ABSOLUTE) view (not stored on the node), and dropping the raw copy is a sizeable memory saving on large workbooks. Enable it when you need the original text – audit / display use, and TACO range compression (excel_grapher.grapher.range_compression), which infers stride patterns from the relative/absolute ($) markers that normalization strips.

Raw formulas are audit records of extraction: compression and projection rewrite formula_ast (the derived normalized_formula view follows), so on a compressed graph Node.formula still shows the pre-compression workbook text and must not be re-parsed as the node’s current definition.

Extraction always parses each formula cell into Node.formula_ast from the raw workbook text, preserving per-axis relative/absolute intent. Distinct ASTs share one interned tree (keyed by the frozen tree itself, not by a JSON encoding or by formula text). normalized_formula is derived absolute A1 via render_formula. Build-time dependency extraction and provenance spans run against that same rendered string, not against regex FormulaNormalizer output. Formulas the AST parser cannot handle leave formula_ast unset and fall back to regex normalization (transitional, non-authoritative) so extraction can still record the cell and its dependencies. CSE and spilled array formulas also store Node.is_array_formula and the observed fastpyxl ref on Node.array_formula_ref so write_workbook can emit ArrayFormula instead of a scalar formula string. fastpyxl does not distinguish legacy CSE from dynamic-array spills.

blank_ranges is an optional iterable of sheet-qualified A1 rectangles (e.g. \"Sheet1!B2:D10\") treated as structurally empty: no nodes are created for those cells (edges into them are kept), and dynamic-ref leaf constraints are not required for addresses inside these ranges. Pair with the same declarations on excel_grapher.FormulaEvaluator and excel_grapher.exporter.codegen.CodeGenerator.generate_modules for evaluator <-> export parity (consistent behavior between evaluation and generated packages).

When warm_ast_cache is True, each distinct derived normalized_formula in the built graph is stored on DependencyGraph.preparsed_formulas as an absolute-bound AST (bind_axes of Node.formula_ast). The mapping is keyed by absolute A1 text, not NodeKey. FormulaEvaluator evaluates per-node trees directly and seeds its string-keyed fallback cache from those bound ASTs, so first evaluation does not re-parse unless formulas change after extraction. Seeding is best-effort when distinct formulas exceed FormulaEvaluator.ast_cache_maxsize (oldest warmed entries may be evicted). preparsed_formulas is not stored in JSON graph caches; call warm_preparsed_formulas after cache load or formula mutation if you need the string-keyed overlay.

Formula-shape overlay (DependencyGraph.formula_shapes) is opt-in acceleration for eval and codegen. Default remains warm_formula_shapes=False; parameterized shapes from GitHub #517 stay opt-in. Node.formula_ast is authoritative. Missing or dropped shapes fall back to AST, so correctness does not require the overlay to be warm.

When warm_formula_shapes is True, the same parse pass interns punched AST skeletons on DependencyGraph.formula_shapes, keyed by NodeKey. FormulaEvaluator compiles each shape once at construction. write_workbook may emit Excel shared formulas for contiguous autofill runs. Package export (CodeGenerator.generate_modules) compiles per-node formula ASTs. The table is not JSON/pickle serialized. Compression and formula rewrite drop it (None). After those events, call warm_formula_shapes(graph) and assign the result; the graph does not auto-rewarm. Rewarming does not refresh _shape_fns on a live FormulaEvaluator – construct a new one (GitHub #560).

Cost model: constraint-based dynamic-ref expansion (dynamic_refs set, use_cached_dynamic_refs=False) skips argument_subgraph_refs and expand_leaf_env_to_argument_env when every INDEX/OFFSET selector can be bounded from static range geometry (MATCH over a rectangular lookup, ROWS/COLUMNS, literals) without cell types (issue #757). Otherwise it expands only when some argument-subgraph ref is not yet in the shared cell-type cache. The first formula that needs a given set of argument cells pays for expansion; later formulas whose argument refs are already typed skip the expand call and reuse the env (issue #528). INDEX / OFFSET target inference is keyed by FormulaShape.shape_key, lookup bases, and the domains of that shape’s cell parameters so row-wise copies over a fixed array share the inferred set when those domains match (issue #716). Distinct selector domains (different exact-MATCH pins) do not share a collapsed target set. Shifted arrays (distinct INDEX/OFFSET first-arg text, or a shifted lookup range) miss that cache and keep per-cell deps. INDIRECT and any ROW( / COLUMN( call stay per-cell.

Provenance collection (capture_dependency_provenance=True) reads the per-cell _dyn_cache of inferred targets filled during extraction. That cache uses the same shape, lookup-base, and selector-domain key, so row-wise copies share inference only when those domains match (issue #716). Host A1 stays in the key for INDIRECT and any ROW( / COLUMN( call, where the shifted array, host position, or referenced address actually changes the target set.

Top-level IF/IFS/CHOOSE/SWITCH provenance is accumulated during extract_deps_with_guards (the same walk that builds guards). Other formulas still use collect_provenance_for_formula for span-accurate direct-ref sites. Extraction and provenance share one DynamicRefWalkContext for argument-subgraph BFS and static ref parsing (issue #539). Callers doing iterative constraint-tuning workflows can leave capture_dependency_provenance=False (the default) to skip remaining provenance overhead.

formula_overrides is an optional map of canonical node keys to formula text used instead of the workbook cell when that address is visited. The rest of the BFS still reads the workbook. Used by DependencyGraph.replace_node_formula to re-extract a cell whose in-memory formula has changed.