While#
- class braintools.cogtask.While(condition, body, max_iterations=100, name='While')[source]#
Loop phase while condition is true.
Useful for tasks with variable numbers of repetitions, such as evidence accumulation until a threshold is reached.
Note: The duration computed by get_duration uses max_iterations as an upper bound, but actual execution may be shorter.
- Parameters:
Examples
>>> import brainunit as u >>> import numpy as np >>> from braintools.cogtask import Feature, Response, Stimulus, Task, While >>> # Present a sample until the trial's required count is reached >>> sample = Stimulus(10 * u.ms, inputs={'stimulus': 1.0}, ... on_enter=lambda ctx: ctx.update(seen=ctx.get('seen', 0) + 1)) >>> loop = While(lambda ctx: ctx.get('seen', 0) < ctx['n_samples'], ... body=sample, max_iterations=4) >>> task = Task( ... loop >> Response(10 * u.ms, outputs={'label': 1}), ... Feature(1, 'stimulus'), Feature(2, 'choice'), ... trial_init=lambda ctx: ctx.update(n_samples=2 + ctx['trial_index']), ... dt=10.0 * u.ms, ... ) >>> task.max_trial_duration() # 4 samples + 1 response step 5 >>> X, Y, info = task.sample_trial(0) # two samples, then the response >>> np.asarray(X[:, 0]).tolist(), np.asarray(info['mask']).tolist() ([1.0, 1.0, 0.0, 0.0, 0.0], [True, True, True, False, False])
- children()[source]#
Return the immediate child phases of a compound phase.
Leaf phases return
[]. Subclasses likeSequence,Repeat,Parallel,If,Switch,Whileoverride this so that theTaskcan traverse the whole tree to bind features.
- encode_inputs(ctx)[source]#
Fill ctx.inputs[phase_start:phase_end] with input encoding.
Called once per phase after duration is determined. Must modify ctx.inputs in-place.
- encode_outputs(ctx)[source]#
Fill ctx.outputs[phase_start:phase_end] with target encoding.
Called once per phase after duration is determined. Must modify ctx.outputs in-place.
- execute_packed(ctx)[source]#
Packed-mode loop (eager-only).
The loop is unrolled in Python, so the condition must evaluate to a concrete
bool. This works for eagersample_trialbut NOT underjit/vmap(batch_sample) when the condition depends on a traced value: we detect that case and raise a clearNotImplementedErrorinstead of a crypticTracerBoolConversionError. Full traced support would require ajax.lax.while_loopwith the buffers + trial state threaded as a pytree, which is not yet implemented.- Return type:
- get_duration(ctx)[source]#
Estimate duration using max_iterations.
Note: Actual duration may be less if condition becomes False.
- Return type:
- max_steps(ctx)[source]#
Static upper bound on this phase’s length in timesteps.
Must return a Python int with no dependence on traced values. Used by
Taskin variable-length mode to size shape-stable buffers. The default delegates toget_durationwhich is correct for fixed-duration phases. Variable-duration phases (e.g. those wrappingTruncExp/UniformDuration) override this to return the truncation upper bound divided byctx.dt.
- step_count(ctx)[source]#
Traced actual length of this phase in timesteps.
Returns a
jax.Arrayint32scalar. May depend onctx[...]values populated bytrial_init. Must satisfy0 <= step_count(ctx) <= max_steps(ctx)for every trial.The default returns a static value equal to
get_duration; that is correct for any phase whose actual length matches its upper bound. Variable-duration phases override this to compute the traced length fromctxstate without anyint(...)cast.- Return type:
Array