Context#

class braintools.cogtask.Context(key=None)[source]#

Mutable trial-level state container shared across phases.

The Context object is the backbone of inter-phase communication. It holds: - Trial-level state that persists across phases (e.g., ground_truth, stimulus_value) - Time tracking (current timestep, phase boundaries) - Input/output buffers for trial data - RNG for reproducible randomness

Parameters:

key (Array | None) – JAX PRNGKey for random number generation. If None, draws fresh randomness from brainstate’s default RNG.

Notes

The time step (dt) is obtained from brainstate.environ.get_dt().

Examples

>>> import jax
>>> import jax.numpy as jnp
>>> from braintools.cogtask import Context
>>> ctx = Context(key=jax.random.PRNGKey(42))
>>> ctx['ground_truth'] = 1
>>> ctx.update(stimulus_direction=0.5 * jnp.pi)
>>> ctx['ground_truth'], 'stimulus_direction' in ctx, ctx.get('missing', 0)
(1, True, 0)
>>>
>>> # Phases write into the buffers with functional updates
>>> # (JAX arrays are immutable; ``.at[...].set(...)`` returns a copy).
>>> ctx.inputs = jnp.zeros((4, 2))
>>> ctx.phase_start, ctx.phase_end = 1, 3
>>> ctx.inputs = ctx.inputs.at[ctx.phase_slice(), 0].set(1.0)
>>> ctx.inputs[:, 0]
Array([0., 1., 1., 0.], dtype=float32)
clear()[source]#

Reset state for a new trial.

property dt: float | Quantity#

Time step in milliseconds (from brainstate.environ.get_dt()).

get(key, default=None)[source]#

Get a value from the trial state with a default.

Return type:

Any

property phase_duration: int#

Duration of current phase in timesteps.

phase_slice()[source]#

Get a slice object for the current phase’s time range.

Return type:

slice

property phase_time: int#

Current timestep relative to phase start.

property state: Dict[str, Any]#

Get a copy of the trial state dictionary.

property total_steps: int#

Total number of timesteps in the trial (based on input buffer).

update(**kwargs)[source]#

Update multiple values in the trial state.