Export BOLD observation model output

types

data.types

Classes

Name Description
AlgorithmResult Result of an iterative algorithm (FIC, EIB, etc.).
ExperimentResult Result from a complete experiment run.
ExplorationResult Result of parameter exploration (grid search).
ObservationResult Result from an observation pipeline with named outputs.
OptimizationResult Result of gradient-based optimization.
SimulationResult Output from a single simulation run with its computed observations.
TimeSeries Time-series dataType with JAX pytree support, domain-specific analysis,

AlgorithmResult

data.types.AlgorithmResult(
    name=None,
    state=None,
    history=None,
    pre_tuning=None,
    post_tuning=None,
    post_tuning_observations=None,
    n_iterations=None,
    hyperparameters=None,
    state_names=None,
    **kwargs,
)

Result of an iterative algorithm (FIC, EIB, etc.).

Provides structured access to algorithm outputs with consistent naming regardless of which algorithm was run.

Attributes

name : str Algorithm name state : Bunch Final state with tuned parameters history : Bunch Per-iteration tracking: parameters, observations, metrics pre_tuning : SimulationResult Simulation BEFORE algorithm (for comparison) post_tuning : SimulationResult Simulation AFTER algorithm with attached observations n_iterations : int Number of iterations run hyperparameters : Bunch Algorithm hyperparameters used (eta, window_size, etc.) convergence : Bunch Convergence metrics (final values, deltas, etc.)

Methods

Name Description
get Dict-like get for backward compat with Bunch-based code.
get
data.types.AlgorithmResult.get(key, default=None)

Dict-like get for backward compat with Bunch-based code.

ExperimentResult

data.types.ExperimentResult(
    integration=None,
    explorations=None,
    algorithms=None,
    optimizations=None,
    continuations=None,
    data_sources=None,
    name=None,
    source=None,
    **kwargs,
)

Result from a complete experiment run.

Mirrors the SimulationExperiment schema structure: integration, algorithms, optimizations, explorations, continuations. Accepts both new-style explicit fields and old-style results=Bunch constructor for backward compatibility.

Attributes

integration : SimulationResult or None Primary simulation output with its observations and transient. algorithms : dict Algorithm results keyed by name. optimizations : dict Optimization results keyed by name. explorations : dict Exploration results keyed by name. continuations : dict Bifurcation/continuation results keyed by name. data_sources : dict External/empirical data (not from simulations). name : str or None Experiment name. source : SimulationExperiment or None Back-reference to input specification.

Methods

Name Description
export Export results and metadata to a BIDS-compatible directory.
from_timeseries Create an ExperimentResult from a TVBO TimeSeries.
from_tvb Create an ExperimentResult from a TVB simulator and its run output.
plot Dispatch plot to the most relevant sub-result.
export
data.types.ExperimentResult.export(
    output_dir,
    subject='01',
    session=None,
    description='tvbsim',
)

Export results and metadata to a BIDS-compatible directory.

Writes experiment specification as YAML and simulation data as netCDF/HDF5, following BEP034 directory conventions::

output_dir/
├── dataset_description.json
├── sub-{subject}/
│   ├── sub-{subject}_desc-{desc}_experiment.yaml
│   └── ts/
│       ├── sub-{subject}_desc-{desc}_ts-sim_State.nc
│       ├── sub-{subject}_desc-{desc}_ts-sim_State.json
│       └── sub-{subject}_desc-{desc}_ts-{obs}_BOLD.nc  (per observation)
Parameters

output_dir : str or Path Root output directory (created if it doesn’t exist). subject : str BIDS subject label (default "01"). session : str or None BIDS session label (optional). description : str BIDS desc- entity (default "tvbsim").

Returns

pathlib.Path Path to the output directory.

from_timeseries
data.types.ExperimentResult.from_timeseries(
    ts,
    source=None,
    name=None,
    **extras,
)

Create an ExperimentResult from a TVBO TimeSeries.

Converts a raw TimeSeries (as returned by JAX, PyRates, NetworkDynamics, etc.) into the standard ExperimentResult wrapper.

Parameters

ts : TimeSeries Simulation output with .data, .time, .labels_dimensions. source : SimulationExperiment, optional Back-reference to the experiment that produced this result. name : str, optional Experiment label. **extras Additional attributes to store (e.g. sol, graph).

Returns

ExperimentResult

from_tvb
data.types.ExperimentResult.from_tvb(simulator, result=None)

Create an ExperimentResult from a TVB simulator and its run output.

Wraps TVB simulation output into the standard TVBO result structure:

  • result.integration — primary monitor as SimulationResult (xr.DataArray)
  • result.integration.observations['MonitorName'] — one TimeSeries per additional monitor, keyed by the TVB monitor class name
Parameters

simulator : tvb.simulator.simulator.Simulator A configured TVB simulator. result : list of (time_array, data_array) tuples, optional Output of simulator.run(). If None, the simulator is run using its simulation_length.

Returns

ExperimentResult

plot
data.types.ExperimentResult.plot(**kwargs)

Dispatch plot to the most relevant sub-result.

ExplorationResult

data.types.ExplorationResult(
    name=None,
    grid=None,
    results=None,
    axes=None,
    observable=None,
    dt=None,
    output_names=None,
    **kwargs,
)

Result of parameter exploration (grid search).

A thin wrapper around tvboptim exploration outputs that provides: - Access to raw results (flat or grid-shaped) - Axis information for parameter values - Utility methods for finding optimal points and slicing - Time series plotting for parameter sweeps (when observable returns time series)

Designed to work with tvboptim’s Space and ParallelResult directly, while also supporting other exploration backends.

Supports two result types: - Scalar results: Each grid point produces a scalar (e.g., loss function). Stored flat, reshaped via as_grid(), with optimal point tracking. - Time series results: Each grid point produces a time series (e.g., model output). Stored as (n_grid, n_time, ...), with plot() support.

Attributes

name : str Exploration name grid : Space Parameter grid specification (tvboptim Space object) results : jnp.ndarray Observable values at each grid point (flat for scalars, multi-dim for time series) axes : list List of axis info (Bunch with name, lo, hi, n, values) observable : str Name of observable computed optimal : Bunch Best point found (parameters, value, index) — only for scalar results shape : tuple Grid shape derived from axes is_timeseries : bool True if results contain time series per grid point dt : float Time step for time series results (optional) output_names : list[str] Names of output variables (e.g., [‘v_pyr’]) for time series results

Methods

Name Description
as_grid Reshape flat results to grid shape.
plot Plot exploration results.
slice Get a slice of results with some parameters fixed.
as_grid
data.types.ExplorationResult.as_grid()

Reshape flat results to grid shape.

Returns

jnp.ndarray Results reshaped to (n_axis1, n_axis2, …) matching axes order. For time series, returns (n_axis1, …, n_time, …) as-is.

plot
data.types.ExplorationResult.plot(figsize=None, sharex=True, **kwargs)

Plot exploration results.

For time series results: subplots for each parameter value. For scalar results: line plot or heatmap over parameter space.

slice
data.types.ExplorationResult.slice(**fixed_params)

Get a slice of results with some parameters fixed.

Example: result.slice(G=0.5) returns 1D slice at G=0.5

ObservationResult

data.types.ObservationResult()

Result from an observation pipeline with named outputs.

Exposes pipeline outputs as attributes (e.g., result.psd, result.frequencies) while maintaining NativeSolution-like interface (.data, .time, .dt).

Attributes

Name Description
data Primary data output (alias for ys).
time Time array (alias for ts).

OptimizationResult

data.types.OptimizationResult(
    name=None,
    state=None,
    history=None,
    simulation=None,
    n_steps=None,
    hyperparameters=None,
    **kwargs,
)

Result of gradient-based optimization.

Provides structured access to optimization outputs including loss trajectory, parameter evolution, and final simulation.

Attributes

name : str Optimization/loss function name state : Bunch Final optimized state (alias: fitted_params) history : Bunch Per-step tracking: loss values, states, gradients simulation : SimulationResult Post-optimization simulation with attached observations loss_trajectory : jnp.ndarray Loss values at each step (convenience accessor) n_steps : int Number of optimization steps final_loss : float Final loss value hyperparameters : Bunch Optimizer settings (learning_rate, algorithm, etc.)

SimulationResult

data.types.SimulationResult(
    data=None,
    observations=None,
    transient=None,
    *,
    result=None,
    state_names=None,
    units=None,
    **kwargs,
)

Output from a single simulation run with its computed observations.

Stores simulation data as an xr.DataArray with named dimensions (time, variable, node[, mode][, trial]). Observations are bound to the simulation that produced them.

Accepts both new-style (data=xr.DataArray) and legacy (result=NativeSolution, state_names=[...]) constructor signatures for backward compatibility with generated template code.

Attributes

data : xr.DataArray or None Simulation data with named dims and coords. observations : dict Computed observations from this simulation (BOLD, FC, etc.). transient : SimulationResult or None Warm-up simulation result that preceded this one.

Attributes

Name Description
coords Coordinates of the data array.
dims Dimension names of the data array.
state_names State variable names from data coordinates.
time Time values as numpy array (backward compatible).
units Unit mapping {variable_name: unit_string} for state/derived variables.

Methods

Name Description
animate Animate simulation results.
isel Integer-based selection returning a new SimulationResult.
plot Plot simulation results.
sel Label-based selection returning a new SimulationResult.
to_timeseries Convert to a full TimeSeries object for plotting and analysis.
animate
data.types.SimulationResult.animate(type=None, **kwargs)

Animate simulation results.

Parameters

type : str, optional ‘network’ — nodes colored by state on graph layout. ‘phase’ — trailing trajectory in phase space. ‘timeseries’ — evolving time-series traces. A state variable name — selects that variable, then animates. If None, auto-selects ‘network’ when a network is available, otherwise ‘timeseries’. **kwargs Forwarded to the animation function.

Returns

matplotlib.animation.FuncAnimation

isel
data.types.SimulationResult.isel(**kw)

Integer-based selection returning a new SimulationResult.

plot
data.types.SimulationResult.plot(ax=None, type='timeseries', **kwargs)

Plot simulation results.

Parameters

ax : matplotlib.axes.Axes, optional Axes to plot on (single-panel plots only). type : str Plot type: ‘timeseries’ (default), ‘phase’/‘state-space’, ‘vector_field’, ‘eeg’, ‘power_spectrum’, ‘raster’. **kwargs Forwarded to the underlying plot function in tvbo.plot.

sel
data.types.SimulationResult.sel(**kw)

Label-based selection returning a new SimulationResult.

to_timeseries
data.types.SimulationResult.to_timeseries()

Convert to a full TimeSeries object for plotting and analysis.

Returns

TimeSeries 4D time series (Time, State Variable, Space, Mode)

TimeSeries

data.types.TimeSeries(
    time,
    data,
    network=None,
    title='TimeSeries',
    sample_period=None,
    labels_dimensions={},
    units=None,
)

Time-series dataType with JAX pytree support, domain-specific analysis, and visualization methods.

Attributes

Name Description
sample_period_ms :returns sample_period is ms
sample_rate :returns samples per second [Hz]

Methods

Name Description
animate Animate timeseries on a graph layout.
calculate_frequency Calculate the dominant frequency of the time series data using FFT.
compute_normalised_average_power Compute normalized average power spectrum using FFT.
convert_units Convert units for a specific dimension and return a new TimeSeries.
copy Return a deep copy of the current instance.
duplicate Fast shallow-copy-based duplication with attribute update.
plot_eeg Plot each region as a separate channel stacked vertically on a single axes
plot_power_spectrum Plot the power spectrum with normalized average power computed via FFT.
summary_info Gather scientifically interesting summary information from an instance of this datatype.
to_bids Export TimeSeries data to BIDS-compliant format (BEP034).
animate
data.types.TimeSeries.animate(
    state=0,
    format='dots',
    interval=50,
    cmap='viridis',
    node_size=120,
    figsize=(10, 4),
)

Animate timeseries on a graph layout.

Each node is a dot positioned by the graph layout; its color reflects the timeseries value of the selected state variable over time.

Parameters

state : int or str State variable index or name to animate. format : str Animation format. Currently only 'dots' is supported. interval : int Milliseconds between frames. cmap : str Matplotlib colormap name. node_size : int Scatter point size. figsize : tuple Figure size (width, height).

Returns

matplotlib.animation.FuncAnimation The animation object (render with HTML(ani.to_jshtml()) in Jupyter, or ani.save(...)).

calculate_frequency
data.types.TimeSeries.calculate_frequency(state_variable=None, region=0, mode=0)

Calculate the dominant frequency of the time series data using FFT.

Returns
Name Type Description
float Dominant frequency in Hz.
compute_normalised_average_power
data.types.TimeSeries.compute_normalised_average_power(VOI=None)

Compute normalized average power spectrum using FFT.

Parameters

VOI : str, optional Variable of interest to analyze. Required if multiple state variables exist.

Returns

frequency : ndarray Frequency values in Hz power : ndarray Normalized average power values

convert_units
data.types.TimeSeries.convert_units(dimension, target_unit)

Convert units for a specific dimension and return a new TimeSeries.

Parameters:

dimension : str Dimension to convert (‘time’, ‘state’, ‘region’, ‘mode’) target_unit : str Target unit to convert to

Returns:

TimeSeries New TimeSeries with converted values

copy
data.types.TimeSeries.copy()

Return a deep copy of the current instance.

duplicate
data.types.TimeSeries.duplicate(**kwargs)

Fast shallow-copy-based duplication with attribute update.

plot_eeg
data.types.TimeSeries.plot_eeg(
    VOI=None,
    mode=0,
    spacing=None,
    normalize=False,
    channel_labels=True,
    ax=None,
    linewidth=0.5,
    **kwargs,
)

Plot each region as a separate channel stacked vertically on a single axes (EEG-like representation).

Parameters

VOI : str | None Variable of interest to plot. If None and multiple variables exist, the first one is used. mode : int Mode index to select. spacing : float | None Vertical spacing between channels. If None, computed from data (median std). normalize : bool If True, z-score each channel before plotting. channel_labels : bool If True, add region labels at the channel offsets on the y-axis. ax : matplotlib.axes.Axes | None Axes to plot on. If None, a new figure and axes are created. color : str Line color for all channels. linewidth : float Line width for plotted channels. **kwargs : dict Additional kwargs forwarded to matplotlib plot.

Returns

matplotlib.figure.Figure | None Returns a figure if it creates one; otherwise None.

plot_power_spectrum
data.types.TimeSeries.plot_power_spectrum(
    VOI=None,
    ROI='mean',
    mode=0,
    bands=None,
    colors=None,
    ax=None,
    label='simulation',
    **kwargs,
)

Plot the power spectrum with normalized average power computed via FFT.

Parameters: - VOI: Variable of Interest, typically selecting subsets of data. - ROI: Region of Interest (“mean” or index). - mode: Mode index for selecting data. - bands: Dictionary of frequency bands to highlight. - colors: Custom colors for frequency bands. - ax: Matplotlib Axes object to plot on. - label: Label for the plot. - kwargs: Additional plotting arguments.

Returns: - Matplotlib figure if ax is None, otherwise None.

summary_info
data.types.TimeSeries.summary_info()

Gather scientifically interesting summary information from an instance of this datatype.

to_bids
data.types.TimeSeries.to_bids(
    output_dir,
    subject='01',
    session=None,
    description=None,
    run=None,
    suffix='State',
    experiment=None,
    include_model=True,
    include_connectivity=True,
    timeseries_format='cifti',
)

Export TimeSeries data to BIDS-compliant format (BEP034).

Creates a BIDS dataset structure following the Computational Model Specification (BEP034 v1.0.0) with: - net/: Network connectivity files (weights, distances) - ts/: Time series data files (CIFTI-2 ptseries or TSV) - eq/: Model equations (tvbo format) - coord/: Region coordinates (if available) - JSON sidecar files with metadata

Uses pydantic models for metadata serialization and pybids patterns for BIDS-compliant filename generation.

Parameters

output_dir : str Root directory for the BIDS dataset. subject : str Subject identifier (without ‘sub-’ prefix). Default: ‘01’. session : str, optional Session identifier (without ‘ses-’ prefix). description : str, optional Description label for the output files. If not provided, uses the model name from experiment (e.g., ‘wilsoncowan’). run : int, optional Run number. suffix : str BIDS suffix indicating the observation/output type: - ‘State’ (default): Raw neural output (no observation model) - ‘BOLD’: fMRI BOLD signal (output convolved with HRF) - ‘EEG’: EEG signal (output with EEG forward model) - ‘MEG’: MEG signal (output with MEG forward model) The ts entity (ts-V, ts-W, ts-Diff) identifies which output variable, which can be a state variable or derived output (e.g., Diff: V-W). The suffix indicates the observation transformation applied. experiment : SimulationExperiment, optional The source simulation experiment for full provenance tracking. If not provided, uses self.source_experiment if available. include_model : bool Whether to export model equations. Default: True. include_connectivity : bool Whether to export connectivity data. Default: True. timeseries_format : str Format for time series output. Options: - ‘cifti’ (default): CIFTI-2 ptseries.nii files with named parcels. Splits data by state variable into separate files. - ‘tsv’: Tab-separated values files. Splits by state variable. - ‘h5’ or ‘hdf5’: HDF5 files preserving full dimensionality. Does NOT split by state variable - keeps all dimensions intact. Ideal for parameter sweeps (e.g., sweep, time, state, region, mode).

Returns

str Path to the created BIDS dataset root directory.

Examples

ts = experiment.run() ts.to_bids(“./derivatives/tvbo”, subject=“01”) ‘./derivatives/tvbo’

bold_ts.to_bids(“./derivatives/tvbo”, suffix=“BOLD”)

Export as TSV instead of CIFTI

ts.to_bids(“./derivatives/tvbo”, timeseries_format=“tsv”)

Export as HDF5 preserving all dimensions (no state variable split)

ts.to_bids(“./derivatives/tvbo”, timeseries_format=“h5”)

Notes

Follows BIDS BEP034 Computational Modeling extension v1.0.0. Uses pydantic for metadata serialization and pybids for filenames.