> ## Documentation Index
> Fetch the complete documentation index at: https://docs.nimbusbci.com/llms.txt
> Use this file to discover all available pages before exploring further.

# NimbusSTS

> NimbusSTS for Python: the stateful head whose latent state is tracked by an extended Kalman filter — for sessions that drift, with explicit state propagation.

**Python**: `NimbusSTS` | **Julia**: not available\

**Mathematical model**: a softmax emission over the features plus a latent state tracked by an extended Kalman filter (EKF)

`NimbusSTS` is the one head with a memory. Beside the usual "features → class" map it keeps a latent state `z` that evolves from trial to trial, so it can follow a class-prior that shifts with fatigue, electrode impedance, or a new day — without refitting the whole head. That state is the only thing that is filtered; the emission weights are point estimates trained by SGD.

> [!NOTE]
>
> **Python head:** standalone `NimbusSTS`, streamed through `StreamingSession` in STS mode. `Personalizer` does not ship it as a `head=` value; it is the classical path for non-stationary sessions. See [Personalizer](https://docs.nimbusbci.com/personalizer/overview.md).

## Quick start

```python theme={null}
from nimbus_bci import NimbusSTS

clf = NimbusSTS(transition_cov=0.01, num_steps=100)
clf.fit(X_train, y_train)                 # (n_trials, n_features)

labels = clf.predict(X_test)              # state not touched — sklearn semantics
probabilities = clf.predict_proba(X_test)
```

## When to use NimbusSTS

* A long session — thirty minutes or more — with fatigue or impedance drift.
* Cross-day experiments where electrode positions move and you want to carry state over.
* Delayed-feedback loops: predict on the prior, update when the label arrives.

## When not to use it

* **Stationary data.** A state costs trials to track and parameters to tune; `NimbusLDA` is faster and simpler.
* **You need the fastest inference.** The EKF step is not free; `NimbusLDA` is.
* **You need epistemic uncertainty.** Only `z` carries a posterior. BALD, `predict_proba_samples` and Personalizer `mc_samples` **raise `NotImplementedError`** on this head. For active learning use `entropy` / `margin` / `least_confidence`, or switch to LDA, QDA or Softmax.
* **A single-pass learner.** `fit` runs the EKF over the full training sequence, so this is a batch trainer despite the "streaming" framing.

## Model

```
z_t = A @ z_{t-1} + w_t,       w_t ~ N(0, Q)          # latent dynamics (random walk by default)
logits = W @ x_t + H @ z_t + b                        # class logits
p(y = k | x_t, z_t) = softmax(logits)_k
```

`z` captures what persists across samples — a slowly turning class-prior or logit bias. During training the EKF updates `z` from the labels, and emission gradients use the one-step prediction so the current label does not leak into its own regressor. During inference, `propagate_state()` advances the prior without a label.

> [!WARNING]
>
> **Not a fully Bayesian head.** The emission weights `W`, `H` and `b` are SGD point estimates. Only `z` is a Gaussian filter posterior.

> [!WARNING]
>
> **The categorical label is treated as a Gaussian observation** — the EKF linearizes the softmax at the current state (innovation `y_onehot − p`). This is a known heuristic, not a principled filter for a categorical likelihood: for low-dimensional states and slowly-varying priors it is reasonable, for high-dimensional states or sharp posterior changes it can be biased. A particle or point-mass filter over the categorical likelihood is the principled alternative.

## Hyperparameters

| Parameter | Default | Meaning |
| - | - | - |
| `state_dim` | `None` | Dimension of `z`; `None` means `n_classes − 1`. At that default `z` spans only the free logit directions — it behaves as a slowly time-varying **class prior**, not a general trial-level state. Pass a larger value for richer trial-to-trial dynamics |
| `transition_cov` | `None` | Scale of the process noise `Q = transition_cov * I` on `z`; `None` means `0.01`. This is the drift speed. **Do not derive it from feature variance — `Q` lives in latent space** |
| `observation_cov` | `1.0` | Scale of the EKF observation noise `R`, applied isotropically to all classes. A convenience, not a principled default: the softmax Jacobian is strongly class-dependent, so one scalar over-regularizes confident classes and under-regularizes uncertain ones. Tune per problem |
| `transition_matrix` | `None` | The matrix `A`; `None` means identity (a random walk) |
| `w_loc`, `w_scale` | `0.0`, `1.0` | Initialisation mean and scale of the feature weights `W` |
| `learning_rate` | `0.1` | SGD step size for `W`, `H` and `b` |
| `num_steps` | `50` | Number of learning iterations |
| `rng_seed` | `0` | Reproducibility |
| `training_sfreq` | `None` | Sampling rate of the training data; persisted for the cross-session check |

`transition_cov` is the one to tune. Smaller is a slower drift (multi-day stability, short sessions); `0.01` is within-session adaptation; larger is a fast-moving environment such as mobile recording with changing impedance. Start at the default and move an order of magnitude at a time.

## State: the API

| Method | What it does |
| - | - |
| `propagate_state(n_steps=1)` | Advance the latent state by prior dynamics only — the time update. Call it between time-ordered trials |
| `predict` / `predict_proba` | Never mutate the state; each row is scored against the current state (sklearn semantics) |
| `partial_fit(X, y)` | Measurement update — fold in a labelled trial |
| `get_latent_state()` | The current `(z_mean, z_cov)` |
| `set_latent_state(z_mean, z_cov=None)` | Set the state by hand — to carry it into a new session |
| `reset_state()` | Back to the initial values from training |

### A time-ordered loop with delayed feedback

In a real BCI the label is not available at prediction time. Predict on the prior, update when feedback arrives:

```python theme={null}
clf = NimbusSTS(transition_cov=0.01).fit(X_calibration, y_calibration)

for trial in online_session:
    clf.propagate_state()                                   # 1. time update, no label
    prediction = clf.predict(trial.X.reshape(1, -1))[0]    # 2. decide on the prior
    execute_action(prediction)
    label = wait_for_feedback()                             # 3. the label arrives later
    clf.partial_fit(trial.X.reshape(1, -1), [label])        # 4. measurement update
```

Without the `propagate_state()` call a stream is scored as if every trial were independent — `clf.score(X_stream, y_stream)` does exactly that, and is the baseline to beat.

### Carrying state into the next session

Start day 2 from an informed prior, widened so it can adapt:

```python theme={null}
# Day 1 is done: clf holds the end-of-session state.
z_mean, z_cov = clf.get_latent_state()

# Day 2: a head fitted on a short calibration, then seeded with yesterday's state.
clf_day2 = NimbusSTS(transition_cov=0.01).fit(X_day2_cal, y_day2_cal)
clf_day2.set_latent_state(z_mean=z_mean * 0.5, z_cov=z_cov * 2.0)   # decay the mean, widen the covariance
```

The day-2 calibration must contain **every class**: `state_dim` defaults to `n_classes − 1`, so a calibration that is missing a class gives the new head a smaller state and `set_latent_state` refuses the transfer on the shape. If day 2 cannot label every class up front, pass the same explicit `state_dim` to both heads.

## Streaming

`StreamingSession` runs in STS mode when you hand it the **fitted `NimbusSTS` estimator** (not its `.model_`): every `process_chunk` advances the latent state by one step first, and a late label can be fed back through `provide_feedback`.

```python theme={null}
from nimbus_bci import NimbusSTS, StreamingSession
from nimbus_bci.data import BCIMetadata

clf = NimbusSTS(transition_cov=0.01).fit(X_train, y_train)
metadata = BCIMetadata(
    sampling_rate=250.0, paradigm="motor_imagery", feature_type="csp",
    n_features=16, n_classes=4, chunk_size=125, temporal_aggregation="logvar",
)
session = StreamingSession(clf, metadata)            # STS mode

for chunk in eeg_stream:                             # (n_features, chunk_size)
    result = session.process_chunk(chunk)            # advances the state, then scores

session.provide_feedback(label)                      # BEFORE finalize: closes nothing, updates the state
final = session.finalize_trial()                     # aggregates the chunks and ends the trial
```

The order is the one that matters in a real loop: `provide_feedback` goes **between the last `process_chunk` and `finalize_trial`**. `finalize_trial` clears the trial, so a feedback call after it raises; its own `label=` argument only fills the result's calibration readout and does not touch the model. `finalize_trial` resets the trial for you, and neither method resets the latent state — that is `clf.reset_state()`.

Chunk sizes, aggregation and the bridge to `BrainState`: [Python streaming inference](https://docs.nimbusbci.com/python-sdk/streaming-inference.md#streaming-with-nimbussts).

## Model selection context

| Head | Use it for |
| - | - |
| `NimbusSTS` | Non-stationary sessions, latent-state drift, state carried across days |
| [`NimbusLDA`](https://docs.nimbusbci.com/models/nimbuslda) | The default; stationary data; the cheapest online update |
| [`NimbusQDA`](https://docs.nimbusbci.com/models/nimbusqda) | Classes with their own covariance; P300 |
| [`NimbusSoftmax`](https://docs.nimbusbci.com/models/nimbussoftmax) | Non-Gaussian multiclass boundaries |

No preregistered cell has read `NimbusSTS` against the other heads; it is shipped as a capability, not as an accuracy claim. What has been measured head against head: [Evidence](https://docs.nimbusbci.com/personalizer/evidence.md).

## Next read

> [card] [Python streaming inference](https://docs.nimbusbci.com/python-sdk/streaming-inference.md#streaming-with-nimbussts)
>
> `StreamingSession` in STS mode, chunk sizes and aggregation.

> [card] [Online Safety Layer](https://docs.nimbusbci.com/personalizer/safety.md)
>
> Governing `partial_fit` with budgets, drift monitors and rollback.

> [card] [NimbusLDA](https://docs.nimbusbci.com/models/nimbuslda.md)
>
> The default head, when the data does not drift.

> [card] [API Reference](https://docs.nimbusbci.com/python-sdk/api-reference.md)
>
> The full `NimbusSTS` signature.


This documentation is built and hosted on [Mintlify](https://mintlify.com), a developer documentation platform.