Skip to content

feat: evaluate expressions with NumPy or NumExpr - #111

Draft
ariostas wants to merge 3 commits into
mainfrom
feat/evaluate
Draft

ariostas wants to merge 3 commits into
mainfrom
feat/evaluate

Conversation

@ariostas

@ariostas ariostas commented Dec 1, 2026 •

Copy link
Copy Markdown
Member

🤖 AI text below 🤖

Adds expression evaluation to formulate, so NumExpr is no longer needed to compute an expression.

API

formulate.evaluate(expression, variables=None, *, syntax="numexpr", engine="numpy")
AST.evaluate(variables=None, *, engine="numpy")
  • expression is a string, parsed according to syntax ("numexpr" or "root"), or an already parsed expression.
  • variables is anything indexable by name: a dict, a pandas DataFrame or an awkward record array. Lists are converted to arrays.
  • Missing variables raise one NameError listing every missing name.
  • The whole expression is checked against the engine before any array work starts.

Engines

  • "numpy" (default): walks the AST with the existing iterative _traversal.fold and applies a NumPy function at every node, through a new _evaluator method on each node type, analogous to _serializer. It works on any array NumPy dispatches to, jagged awkward arrays included.
  • "numexpr": passes to_numexpr() output to NumExpr, with names like branch.leaf mapped to their encoded form. It supports fewer expressions, and refuses reductions when an input has more than one dimension, since NumExpr would reduce the whole array rather than each entry.

Semantics

These follow ROOT's per-entry model, and were checked against TTreeFormula on a variable-length branch:

  • sum/prod/min/max/length (Sum$, Min$, Length$, …) reduce along the last axis. That is per entry on 2-D or jagged arrays, and the whole array on 1-D arrays, as NumExpr does.
  • Min$/Max$ of an empty entry are 0.
  • arr[i] picks position i within every entry. On awkward arrays, an entry too short to have it gives None. Only non-negative integer literal indices are supported.
  • &&/||/! and &/|/^/~ are logical operations.
  • ** is computed in floating point, so n ** -1 is a fraction.
  • % is floating-point modulo, as before (see the modulo section of issues.rst).
  • ROOT's a:b returns a tuple of arrays.
  • Division by zero and invalid operations give inf/nan silently: the NumPy engine runs under np.errstate(divide="ignore", invalid="ignore"), because where computes both branches and a guarded where(x > 0, 1 / x, 0) would otherwise warn. Overflow and underflow keep the caller's settings. TTreeFormula instead returns 0 for a division by zero; this is documented in issues.rst and pinned by a test, like %.

Other changes

  • New formulate.extras module (uproot-style loaders) and a formulate[numpy] extra. NumPy is still not a required dependency, and is imported only when evaluating.
  • _encode_name moved from AST.py to identifiers.py to avoid an import cycle.
  • awkward added to the test and docs groups.
  • Docs: a new guide page (guide/evaluation.rst), new sections in issues.rst (scalar-branch reductions, how the engines differ), an evaluation subsection in expressions.rst, and updates to the API pages, installation page, README and CHANGELOG.

Deferred

  • A blosc2 engine was considered and deferred for now. Its expression engine is labelled beta, it does not install on 3.15 yet, and on free-threaded builds it re-enables the GIL. It would be about 10 lines to add later.

A bug that was already in main is documented here but not fixed: to_numexpr() turns ROOT's !n into ~n, which NumExpr computes bitwise on integers. The "numexpr" engine inherits this.

Add `formulate.evaluate()` and `AST.evaluate()`, which compute an
expression on arrays without requiring NumExpr. The default "numpy"
engine walks the AST with the existing iterative fold and applies NumPy
functions, so it also works on awkward and pandas inputs; the "numexpr"
engine hands `to_numexpr()` output to NumExpr.

Semantics follow ROOT's per-entry model, checked against TTreeFormula:
reductions act on the last axis, Min$/Max$ of an empty entry are 0,
indexing a short jagged entry gives a missing value, logical operators
are logical, and ** is computed in floating point.

NumPy becomes an optional `formulate[numpy]` extra, loaded through the
new `formulate.extras` module, and `_encode_name` moves to identifiers
to avoid an import cycle.

Assisted-by: Claude Code:claude-opus-5-5
@codecov

codecov Bot commented Dec 1, 2026 •

Copy link
Copy Markdown

Codecov Report

✅ All modified and coverable lines are covered by tests.
✅ Project coverage is 100.00%. Comparing base (e8fbe8d) to head (65e5457).
✅ All tests successful. No failed tests found.

Additional details and impacted files
Files with missing lines Coverage Δ
src/formulate/AST.py 100.00% <100.00%> (ø)
src/formulate/__init__.py 100.00% <100.00%> (ø)
src/formulate/_evaluation.py 100.00% <100.00%> (ø)
src/formulate/extras.py 100.00% <100.00%> (ø)
src/formulate/identifiers.py 100.00% <100.00%> (ø)

- min/max of a 1-D awkward array return a 0-d array, and 0 when empty,
  instead of a 1-element array or a TypeError.
- min/max of empty rectangular entries keep the input dtype.
- Only `variables=None` counts as "nothing passed"; other wrong types
  raise their own TypeError instead of a misleading NameError.
- The NumPy engine evaluates under np.errstate(divide="ignore",
  invalid="ignore"), so guarded expressions such as
  where(x > 0, 1 / x, 0) no longer warn, matching NumExpr and ROOT.
- Document and pin against ROOT that TTreeFormula gives 0 for a
  division by zero, where NumExpr, NumPy and evaluate give inf.
- Quote the extras in the install hint and list `~` in the docstring.

Assisted-by: Claude Code:claude-opus-5-5

This branch has not been deployed

No deployments
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant