formulate

The top-level module: parsing an expression, and the error raised when that fails. Everything you can do with a parsed expression is documented under Abstract Syntax Tree (AST).

Conversions between ROOT, NumExpr and Python expression syntax.

Parse an expression with from_root() or from_numexpr(), then render it with to_root(), to_numexpr() or to_python():

>>> import formulate
>>> formulate.from_root("TMath::Sqrt(x**2 + y**2) > 10").to_numexpr()
'(sqrt(((x ** 2) + (y ** 2))) > 10)'

The parsed expression also reports what it refers to, through variables, named_constants and unnamed_constants.

formulate.from_numexpr(exp: str) AST

Parse a NumExpr expression.

The expression is parsed with Python precedence, so & and | bind tighter than a comparison, ^ is XOR, and ~ is NOT. Chained comparisons such as a < b < c are rejected, as NumExpr does not support them.

Parameters:

exp – the expression to parse.

Returns:

the parsed expression, ready to be rendered to any backend.

Raises:
  • ParseError – if exp is not valid NumExpr syntax. The message points at the offending location and suggests fixes for the mistakes people make most often, such as writing && where NumExpr wants &.

  • SyntaxError – if exp parses but names something that cannot be a symbol, or passes arguments to a constant.

  • ValueError – if exp uses an unknown function or constant.

>>> import formulate
>>> formulate.from_numexpr("abs(x) < 2.5").to_root()
'(TMath::Abs(x) < 2.5)'
formulate.from_root(exp: str) AST

Parse a ROOT TTreeFormula expression.

The expression is parsed with C++ precedence, so && and || bind looser than a comparison, ^ is exponentiation rather than XOR, and ! is logical NOT.

Parameters:

exp – the expression to parse.

Returns:

the parsed expression, ready to be rendered to any backend.

Raises:
  • ParseError – if exp is not valid ROOT syntax. The message points at the offending location and suggests fixes for the mistakes people make most often, such as writing & where ROOT wants &&.

  • SyntaxError – if exp parses but names something that cannot be a symbol, or passes arguments to a constant.

  • ValueError – if exp uses an unknown function, constant, or namespace.

>>> import formulate
>>> formulate.from_root("TMath::Abs(x) < 2.5").to_numexpr()
'(abs(x) < 2.5)'
exception formulate.ParseError(message: str, lark_error: LarkError)

Bases: Exception

Raised when an expression cannot be parsed.

Parameters:
  • message – the human-readable report: where parsing stopped, any suggestions, and the underlying lark message.

  • lark_error – the error raised by lark, kept for programmatic access to details such as the line and column.