braintools.tree.idx

Contents

braintools.tree.idx#

braintools.tree.idx(tree, idx, is_leaf=<function is_quantity>)[source]#

Index every leaf of a PyTree.

Parameters:
  • tree (Quantity]) – Input PyTree.

  • idx (int | slice | Array | ndarray | bool | number | bool | float | complex | Quantity) – Indices used to index each leaf x as x[idx].

  • is_leaf (Callable[[Any], bool] | None) – Predicate to treat a node as a leaf during traversal. Defaults to u.math.is_quantity.

Returns:

PyTree with leaves indexed by idx.

Return type:

PyTree

Examples

>>> import jax.numpy as jnp
>>> import braintools
>>> tree = {'x': jnp.array([0.0, 1.0, 2.0, 3.0]), 'y': jnp.array([0.0, 10.0, 20.0, 30.0])}
>>> out = braintools.tree.idx(tree, 1)
>>> {k: v.tolist() for k, v in out.items()}
{'x': 1.0, 'y': 10.0}
>>>
>>> out = braintools.tree.idx(tree, [0, 2])
>>> {k: v.tolist() for k, v in out.items()}
{'x': [0.0, 2.0], 'y': [0.0, 20.0]}