brainstate.transform.ifelse#
- brainstate.transform.ifelse(conditions, branches, *operands, check_cond=True)#
Represent multi-way
if/elif/elsecontrol flow.- Parameters:
conditions (
Sequence) – Sequence of mutually exclusive boolean predicates. Whencheck_condisTrue, exactly one entry must evaluate toTrue.branches (
Sequence[Callable]) – Sequence of branch callables evaluated lazily. Must have the same length asconditions, contain at least two callables, and each branch receives*operandswhen selected.*operands (Any) – Operands forwarded to the selected branch as positional arguments.
check_cond (
bool) – Whether to verify that exactly one condition evaluates toTrue.
- Returns:
Value produced by the branch corresponding to the active condition.
- Return type:
Notes
Unlike a Python
if/elifchain, conditions are evaluated together rather than first-true-wins, so whencheck_condisTrue(the default) they must be mutually exclusive: exactly one condition may evaluate toTrue, otherwise a runtime error is raised. Withcheck_cond=Falsethe check is skipped and the firstTruecondition wins (falling back to the last branch when none isTrue).Examples
>>> import jax.numpy as jnp >>> import brainstate >>> >>> def grade(a): ... return brainstate.transform.ifelse( ... conditions=[a > 5, jnp.logical_and(a > 0, a <= 5), a <= 0], ... branches=[ ... lambda: 2.0, # greater than five ... lambda: 1.0, # positive ... lambda: 0.0, # non-positive ... ], ... ) >>> >>> grade(jnp.asarray(7.0)) # 2.0 >>> grade(jnp.asarray(-1.0)) # 0.0