Expression Utilities

A series of utilities are provided to work with expressions in a more convenient way.

Functions

blosc2.evaluate(ex: str, local_dict: dict | None = None, global_dict: dict | None = None, out: Array = None, *, jit: bool | None = None, jit_backend: str | None = None, math_backend: str | None = None, fp_accuracy: FPAccuracy | None = None, **kwargs: Any) → Array[source]

Evaluate a string expression using the Blosc2 compute engine.

This provides a NumExpr-style expression interface using native miniexpr execution and explicit NumPy fallbacks, without importing NumExpr. It allows:

  1. Use additional NumPy/Blosc2 expression functionality.

  2. Follow casting rules of NumPy more closely.

  3. Use both NumPy arrays and Blosc2 NDArrays in the same expression.

As NDArrays can be on-disk, the expression can be evaluated without loading the whole array into memory (i.e. using an out-of-core approach).

Repeated array-only reviewed arithmetic, math and reduction expressions without extra options reuse a bounded, operand-free preparation recipe. Current inputs and any supplied output are rebound on every call; otherwise a fresh NumPy output is allocated. Neither operand/output arrays nor numerical results are retained in the cache.

Aligned C-contiguous native numeric maps with matching operand shapes bind directly to immutable native schedules, avoiding general lazy/storage dispatch. Large partitionable maps retain parallel execution with the current thread count.

Eligible numeric arithmetic and elementwise math calls use the native Menudet kernels, including explicit NumPy or Blosc2 destinations. Compressed destinations retain bounded input tiles; matching floating storage grids use the compression prefilter. Unsupported signatures, aliasing and explicit accuracy policies retain the existing dispatch rules. Explicit compiler options on eligible resident maps use the option-aware Menudet compiler without routing through general chunk execution.

Eligible expressions default to native interpretation through the shared native structural policy (single-return expression versus program), also used by Menudet kernels and graph-generated maps. Explicit JIT settings from blosc2.set_jit_options(), blosc2.jit_options() or ME_DSL_JIT retain their existing precedence. For example, use with blosc2.jit_options(jit=True): to opt into best-effort JIT execution.

Parameters:
  • ex (str) – The expression to evaluate.

  • local_dict (dict, optional) – The local dictionary to use when looking for operands in the expression. If not provided, the local dictionary of the caller will be used.

  • global_dict (dict, optional) – The global dictionary to use when looking for operands in the expression. If not provided, the global dictionary of the caller will be used.

  • out (blosc2.Array, optional) – The output array where the result will be stored. If not provided, a new NumPy array will be created and returned.

  • jit (optional) – Per-call overrides for Compute options. None inherits the current settings. Unsupported expressions can still fall back to NumPy.

  • jit_backend (optional) – Per-call overrides for Compute options. None inherits the current settings. Unsupported expressions can still fall back to NumPy.

  • math_backend (optional) – Per-call overrides for Compute options. None inherits the current settings. Unsupported expressions can still fall back to NumPy.

  • fp_accuracy (optional) – Per-call overrides for Compute options. None inherits the current settings. Unsupported expressions can still fall back to NumPy.

  • kwargs (Any, optional) – Accepted options are order, casting and optimization. optimization defaults to "aggressive", matching NumExpr’s default. Constant real floating-point squares use multiplication. Aggressive optimization allows native multiplication chains for constant integer powers, including negative exponents. These can change rounding and floating-point status, but do not enable global fast-math or alter integer/complex base semantics. Explicit "moderate" or "none" retains general power for other exponents; constant squares still use multiplication. casting defaults to "same_kind" and controls conversion into an explicit destination, not arithmetic precision. order controls newly allocated NumPy output: "C" or "F" requests contiguous row-major or column-major storage, "A" follows Fortran-contiguous operands when possible, and "K" (default) follows operand iteration order. An explicit output retains its layout and identity, including when it is empty. Blosc2 consumes order as an allocation policy; it is not forwarded to NumExpr. Resident strided outputs use native destination descriptors when supported. Unsupported operations use an explicit NumPy fallback. The legacy truediv, sanitize and disable_cache options are no longer accepted. Division follows NumPy semantics, validation follows the expression evaluation policy, and preparation caches are automatic.

Returns:

out – The result of the expression evaluation. If out is provided, the result will be stored in out and returned at the same time.

Return type:

blosc2.Array

Examples

>>> import blosc2
>>> import numpy as np
>>> dtype = np.float64
>>> shape = [3, 3]
>>> size = shape[0] * shape[1]
>>> a = np.linspace(0, 5, num=size, dtype=dtype).reshape(shape)
>>> b = blosc2.linspace(0, 5, num=size, dtype=dtype, shape=shape)
>>> expr = 'a * b + 2'
>>> out = blosc2.evaluate(expr)
>>> out
[[ 2.        2.390625  3.5625  ]
[ 5.515625  8.25     11.765625]
[16.0625   21.140625 27.      ]]
blosc2.re_evaluate(local_dict=None, global_dict=None, _frame_depth=2)[source]

Repeat this thread’s last successful public blosc2.evaluate() call.

Operands are looked up anew in the supplied dictionaries or calling scope. The previous explicit output is reused if it is still alive; otherwise a fresh result is allocated. Output references are weak, and operands are never retained. Failed calls and explicit prepared-evaluator calls do not replace the saved expression. Unlike NumExpr’s unchecked shortcut, shape/dtype/output validation is retained when operands change.

_frame_depth is an internal compatibility argument: the default resolves the direct caller. A wrapper can increase it to resolve its own caller.

blosc2.prepare_evaluate(expression, **options)[source]

Validate an expression once and return an explicit reusable evaluator.

No caller variables are captured. Supply a mapping on every invocation:

>>> import blosc2
>>> import numpy as np
>>> evaluator = blosc2.prepare_evaluate("x + 1")
>>> evaluator({"x": np.arange(3)})
array([1, 2, 3])

The approved expression grammar is used in both safe and full modes. Preparation accepts order, casting and optimization. Pass compute options such as fp_accuracy when calling the prepared evaluator, or set them with blosc2.compute_options(). Per-call overrides do not mutate the recipe.

class blosc2.PreparedEvaluator(expression: str, input_names: tuple[str, ...], options: tuple, evaluation: str)[source]

An immutable expression recipe; execution never retains input/output arrays.

Construct with blosc2.prepare_evaluate(). Dtypes and shapes are inferred on each binding; the existing bounded preparation caches reuse compatible signatures. Compilation is lazy on first execution, not at construction.

Methods

__call__(local_dict, *[, out])

Evaluate with explicit operands and optional per-call option overrides.

evaluate(local_dict, *[, out])

Named equivalent of calling the evaluator.

__call__(local_dict, *, out=None, **options)[source]

Evaluate with explicit operands and optional per-call option overrides.

evaluate(local_dict, *, out=None, **options)[source]

Named equivalent of calling the evaluator.

blosc2.get_expr_operands(expression: str) → set[source]

Given an expression in string form, return its operands.

Parameters:

expression (str) – The expression in string form.

Returns:

A set of operands found in the expression.

Return type:

set

blosc2.validate_expr(expr: str) → None[source]

Validate expression for forbidden syntax and valid method names.

Parameters:

expr (str) – The expression to validate.

Return type:

None

Reusable evaluation

Prepare an operand-free recipe and supply a mapping for each execution:

evaluator = blosc2.prepare_evaluate("x + y * 2")
result = evaluator({"x": x, "y": y}, out=out)
result = evaluator({"x": another_x, "y": another_y}, out=another_out)

The recipe validates the approved expression grammar at construction. Numerical preparation is lazy and reuses the existing bounded signature caches. Shapes and dtypes may change between calls; input and output arrays are never retained by the recipe. Concurrent calls use independent bindings. There is no implicit last-expression state or caller-variable capture. Per-call options override construction options without mutating the recipe.

NumExpr-style repetition

For compatibility-oriented loops, re_evaluate() repeats the last successful public evaluate() call in the current thread:

blosc2.evaluate("x + y * 2", local_dict={"x": x, "y": y}, out=out)
blosc2.re_evaluate(local_dict={"x": another_x, "y": another_y})

The expression and options are remembered, but operands are looked up anew. Without dictionaries, the caller’s locals/globals supply the operands. A live explicit output is reused through a weak reference; if it has been collected, a fresh result is allocated. Implicitly allocated results are never reused.

State is thread-local. Failed evaluations, nested evaluations and explicit PreparedEvaluator calls do not replace it. Calling re_evaluate() before a successful evaluate() in that thread raises RuntimeError. Unlike NumExpr’s unchecked shortcut, Blosc2 retains shape, dtype and destination validation. This API is convenience compatibility, not a guarantee of lower overhead than an explicit prepared evaluator. Use explicit evaluators for interleaved expressions or independent callers sharing a thread.

Evaluation options

Options are validated before choosing a backend, including for Fortran outputs and empty inputs. Unknown keywords and invalid values raise an error before destination writes.

  • order and casting describe destination allocation/conversion.

  • evaluate() defaults to optimization="aggressive", matching NumExpr’s default. Constant real floating squares use multiplication. Aggressive optimization enables native multiplication chains for constant integer powers, including negative exponents. This can change rounding and floating-point status, without enabling global fast-math or changing integer/complex base semantics. Explicit moderate or none retains general power for other exponents, while constant squares still use multiplication. NumPy fallbacks retain NumPy behavior. Prepared evaluators still accept the option as a compatibility hint; their numerical policy is unchanged.

    For example:

    result = blosc2.evaluate("x**3 - 1", local_dict={"x": x})
    strict_result = blosc2.evaluate("x**3 - 1", local_dict={"x": x}, optimization="moderate")
    

truediv, sanitize and disable_cache are no longer accepted, including by prepared evaluators. Division follows NumPy semantics (use // for floor division), validation follows the safe/full expression policy, and preparation caches are managed automatically.

Eligible evaluate() expressions default to native interpretation, as do prepare_evaluate() and re_evaluate(). This follows the shared native automatic policy, not an evaluator-specific override: single-return expressions are interpreted and multi-statement Menudet programs prefer JIT. Explicit global/context JIT settings and the ME_DSL_JIT environment override retain their existing precedence. To opt in for one call:

result = blosc2.evaluate("x + y * 2", local_dict={"x": x, "y": y}, jit=True)

See Compute options for per-call options, defaults and backend selection. The optimization option does not select the math library.

Overlapping NumPy inputs are snapshotted before writing an explicit output; this may require temporary memory proportional to the overlapping operands. Empty sums/products use NumPy identities, and empty extrema raise without an explicit identity. Native output descriptors support validated Fortran, transposed, stepped and reversed destinations with bounded scratch. Unsupported operations retain explicit NumPy fallbacks. NumExpr is not a runtime dependency, and the blosc2.numexpr compatibility placeholder has been removed.

NumExpr migration

Installing NumExpr does not enable another Blosc2 backend, and NUMEXPR_NUM_THREADS / NUMEXPR_MAX_THREADS do not configure Blosc2 workers. Use blosc2.set_nthreads() and Compute options for native execution policy. jit=False requests native interpretation where supported, not NumExpr. Optional benchmark scripts may still use NumExpr as an independent reference.

The backend-neutral evaluate_chunk evaluator neither imports nor invokes NumExpr; ne_evaluate remains a temporary internal compatibility alias. lazyexpr(..., eval_kwargs=...) supplies expression evaluation options; the legacy ne_args= keyword remains a compatibility alias. Do not pass both names. Native preparation can decline an unsupported signature to explicit NumPy semantics. An error after native execution starts propagates instead of replaying the operation through another backend, including for compression prefilters and scalar reductions.

NumPy fallbacks may create expression intermediates. Compressed/mixed inputs remain tile-local where the operation permits it; inherently global operations retain their documented materialization requirements. Interpreter performance is workload-dependent and is not claimed to match NumExpr universally.

Decorators

blosc2.jit(func=None, *, out=None, disable=False, strict=None, **kwargs)[source]

Prepare a function so that it can be used with the Blosc2 compute engine.

The inputs of the function can be any combination of NumPy/NDArray arrays and scalars. By default, the function is traced: it is called once with the NumPy arrays replaced by SimpleProxy objects (NDArray objects are used as is) to record a single expression, which is then what actually gets evaluated. Because tracing only calls the function once, an if/for/ while in the body only ever takes the one path that single call happened to follow — see strict below for when jit instead compiles the function whole, so every branch and loop genuinely runs.

The returned value will be a NDArray if a storage kwarg is provided (e.g. cparams=, chunks=, urlpath= — anything that only makes sense for a compressed/persisted container). Else, the return value will be a NumPy array (if the function returns a NumPy array). Execution-tuning kwargs (jit=, jit_backend=, fp_accuracy=) do not by themselves trigger this — they take effect either way, without changing the return type. If out is provided, the result will be computed and stored in the out array.

Parameters:
  • func (callable) – The function to be prepared for the Blosc2 compute engine.

  • out (np.ndarray, NDArray, optional) – The output array where the result will be stored. On the DSL (control-flow) dispatch route, a NumPy out is filled in place (directly when C-contiguous, else via a copy); an NDArray out is not supported there — use compute(urlpath=..., mode="w") instead.

  • disable (bool, optional) – If True, the decorator is disabled and the original function is returned unchanged. Default is False.

  • strict (bool, optional) –

    Control which evaluation route is used:

    • None (default): if func’s body contains an if/for/while and it compiles as a DSL kernel, dispatch to the DSL route (miniexpr runs the whole function, so branches/loops behave as written); a control-flow function that fails DSL extraction still falls back to tracing, but a subsequent tracing failure is annotated with the DSL extraction error. Functions without control flow always trace, even if they happen to be DSL-valid (tracing is faster for pure elementwise expressions).

    • True: always use the DSL route, raising DSLSyntaxError at decoration time if func’s source cannot be parsed as a DSL kernel. Note the guarantee is exactly that – parsing – and not that the kernel will compile: a function that is DSL-shaped but calls something miniexpr does not implement passes here and fails later, at call time, with a RuntimeError. See the DSL syntax reference for what the grammar accepts. (Unrelated to the retired @dsl_kernel, which built a DSLKernel object rather than an evaluating wrapper.)

      This also works as a pandas engine, which is the only way to reach strict through that entry point: df.apply(f, engine=blosc2.jit(strict=True)).

    • False: always use the tracing route, even if func has control flow (this only works when branches/loops depend on plain Python values, not on traced arrays).

  • **kwargs (dict, optional) – Additional keyword arguments supported by the empty() constructor.

Return type:

wrapper

Notes

  • Although many NumPy functions are supported, some may not be implemented yet. If you find a function that is not supported, please open an issue.

  • out and kwargs parameters are not supported for all expressions (e.g. when using a reduction as the last function). In this case, you can still use the out parameter of the reduction function for some custom control over the output.

  • DSL-route kernels do not support broadcasting: every array argument must share the same shape.

Examples

>>> import numpy as np
>>> import blosc2
>>> @blosc2.jit
... def compute_expression(a, b, c):
...     return np.sum(((a ** 3 + np.sin(a * 2)) > 2 * c) & (b > 0), axis=1)
>>> a = np.arange(20, dtype=np.float32).reshape(4, 5)
>>> b = np.arange(20).reshape(4, 5)
>>> c = np.arange(5)
>>> compute_expression(a, b, c)
array([3, 5, 5, 5])

With strict=True the function is compiled as a DSL kernel, so a real per-element if runs as written – only the matching arm is evaluated:

>>> @blosc2.jit(strict=True)
... def clamp(x):
...     if x < 0.0:
...         out = 0.0
...     else:
...         out = x
...     return out
>>> clamp(np.array([-1.5, 2.0, -0.5]))
array([0., 2., 0.])

The guarantee is that the source parses as DSL, checked at decoration time. A body the grammar does not accept is rejected right away, rather than silently falling back to tracing:

>>> @blosc2.jit(strict=True)
... def not_dsl(x):
...     return np.where(x >= 0, x.mean(), x)
Traceback (most recent call last):
    ...
blosc2.dsl_kernel.DSLSyntaxError: Unsupported call target in DSL ...
blosc2.lazywhere(value1=None, value2=None)[source]

Decorator to apply a where condition to a LazyExpr.