Skip to content

Simulator

Simulator(
    *, brain_mask=None, output_dir=None, random_state=None
)

Simulate fMRI data with realistic spatial and temporal characteristics.

This class provides methods for generating synthetic fMRI data with controlled signal patterns, including Gaussian blobs, multi-subject datasets, and various noise structures. Useful for testing analysis pipelines and power analyses.

Parameters:

Name Type Description Default
brain_mask str | Nifti1Image

Path to a NIfTI brain mask file, a nibabel image, or None to use the default template mask.

None
output_dir str

Directory for saving generated data. Defaults to the current working directory.

None
random_state int | RandomState

Seed or RandomState for reproducibility.

None

Attributes:

Name Type Description
brain_mask Nifti1Image

The brain mask image used for simulation.

output_dir str

Output directory path.

random_state RandomState

Random state for reproducible simulations.

data BrainData | Nifti1Image

Most recently simulated data; set by the create_* methods.

y DataFrame | ndarray

Outcome values paired with data; set by the create_* methods.

rep_id DataFrame | list

Repetition/subject id per observation; set by the create_* methods.

Examples:

from nltools.data.simulator import Simulator

sim = Simulator(random_state=42)
# Create a dataset with signal in specific regions
data = sim.create_data(levels=[1, -1, 1, -1], sigma=1, reps=10)

Methods:

Name Description
create_cov_data

Create continuous simulated data with covariance within a single region.

create_data

Create simulated data with discrete intensity levels.

create_ncov_data

Create continuous simulated data with covariance across multiple regions.

gaussian

Create a 3D gaussian signal normalized to a given intensity.

n_spheres

Generate a set of spheres in the brain mask space.

normal_noise

Produce a normal noise distribution for all points in the brain mask.

sphere

Create a sphere of a given radius at a world coordinate in the brain mask.

to_nifti

Convert a numpy array to a NIfTI image with the brain mask's affine.

Methods:

create_cov_data

create_cov_data(
    cor,
    cov,
    sigma,
    *,
    mask=None,
    reps=1,
    n_sub=1,
    output_dir=None,
)

Create continuous simulated data with covariance within a single region.

Results are stored on self.data (a 4-D nibabel.Nifti1Image), self.y, and self.rep_id.

Parameters:

Name Type Description Default
cor float

Covariance between each voxel and the outcome y.

required
cov float

Covariance between voxels.

required
sigma float

Standard deviation of the added noise.

required
mask Nifti1Image

Region where activations are placed. Defaults to a 20 mm sphere at the mask's grid center.

None
reps int

Number of repetitions per subject. Default 1.

1
n_sub int

Number of subjects to simulate. Default 1.

1
output_dir str

Directory to write the image, y.csv, and rep_id.csv into. If None, nothing is written.

None

create_data

create_data(
    levels,
    sigma,
    *,
    radius=10,
    center=None,
    reps=1,
    output_dir=None,
)

Create simulated data with discrete intensity levels.

Parameters:

Name Type Description Default
levels list

Intensities or class labels, one per image in a repetition.

required
sigma float

Standard deviation of the added noise.

required
radius int | float | list

Sphere radius in millimeters, or one radius per sphere. Default 10.0.

10
center list

Sphere center [x, y, z] in world (MNI) millimeters, or one center per sphere [[x1, y1, z1], ...]. None (the default) places every sphere at the world coordinate of the mask's grid center.

None
reps int

Number of repetitions (e.g. trials or subjects). Default 1.

1
output_dir str

Directory to write data.nii.gz, y.csv, and rep_id.csv into. If None, nothing is written.

None

Returns:

Type Description
BrainData

The simulated images with Y set to the levels.

create_ncov_data

create_ncov_data(
    cor,
    cov,
    sigma,
    *,
    masks=None,
    reps=1,
    n_sub=1,
    output_dir=None,
)

Create continuous simulated data with covariance across multiple regions.

Results are stored on self.data (a 4-D nibabel.Nifti1Image), self.y, and self.rep_id.

Parameters:

Name Type Description Default
cor float | list[float]

Covariance between each region's voxels and the outcome y; one value per region.

required
cov float | list[list[float]]

Covariance between voxels; a scalar for a single region or a region-by-region matrix.

required
sigma float

Standard deviation of the added noise.

required
masks Nifti1Image | list[Nifti1Image]

Region(s) where activations are placed. Defaults to a 20 mm sphere at the mask's grid center.

None
reps int

Number of repetitions per subject. Default 1.

1
n_sub int

Number of subjects to simulate. Default 1.

1
output_dir str

Directory to write the image, y.csv, and rep_id.csv into. If None, nothing is written.

None

gaussian

gaussian(mu, sigma, i_tot)

Create a 3D gaussian signal normalized to a given intensity.

Geometry is millimeters: mu is a world (MNI) coordinate and sigma a physical width, both converted to voxel units through the brain mask's affine, so the same request describes the same blob on any grid.

Parameters:

Name Type Description Default
mu array - like

Center of the gaussian [x, y, z] in world (MNI) millimeters.

required
sigma float | array - like

Standard deviation in millimeters — a scalar for an isotropic blob or one width per axis [sx, sy, sz].

required
i_tot float

Total activation; the gaussian is rescaled so its sum within the brain mask equals this value.

required

Returns:

Type Description
ndarray

3-D array the shape of the brain mask.

Note

sigma is converted per axis with nibabel.affines.voxel_sizes, so the millimeter widths map onto world axes only for an axis-aligned affine. On an oblique affine the blob's principal axes follow the voxel grid.

n_spheres

n_spheres(radius, center=None)

Generate a set of spheres in the brain mask space.

Delegates to nltools.mask.create_sphere, so radii are millimeters and centers are world (MNI) coordinates resolved through the mask's affine.

Parameters:

Name Type Description Default
radius int | float | list

Sphere radius in millimeters, or one radius per sphere.

required
center list

Sphere center [x, y, z] in world (MNI) millimeters, or one center per sphere [[x1, y1, z1], ...]. None places every sphere at the world coordinate of the mask's grid center.

None

Returns:

Type Description
ndarray

3-D binary array the shape of the brain mask holding the union of the requested spheres.

normal_noise

normal_noise(mu, sigma)

Produce a normal noise distribution for all points in the brain mask.

Parameters:

Name Type Description Default
mu float

Mean of the noise (usually 0).

required
sigma float

Standard deviation of the noise.

required

Returns:

Type Description
ndarray

3-D array the shape of the brain mask filled with noise inside the mask.

sphere

sphere(radius, center)

Create a sphere of a given radius at a world coordinate in the brain mask.

Delegates to nltools.mask.create_sphere, so the radius is millimeters and the center is a world (MNI) coordinate resolved through the mask's affine.

Parameters:

Name Type Description Default
radius int | float

Radius of the sphere in millimeters.

required
center array - like

Center of the sphere [x, y, z] in world (MNI) millimeters.

required

Returns:

Type Description
ndarray

3-D array the shape of the brain mask, 1 inside the sphere and 0 elsewhere.

to_nifti

to_nifti(m)

Convert a numpy array to a NIfTI image with the brain mask's affine.

Parameters:

Name Type Description Default
m ndarray

3-D (or 4-D) array to convert.

required

Returns:

Type Description
Nifti1Image

The array as a float32 image.

SimulateGrid

SimulateGrid(
    *,
    grid_width=100,
    signal_width=20,
    n_subjects=20,
    sigma=1,
    signal_amplitude=None,
    random_state=None,
)

Simulate 2D grid data for testing statistical methods.

Creates a 2D grid (e.g., 100x100 pixels) with optional embedded signal regions and Gaussian noise. Useful for testing multiple comparison correction methods, threshold selection, and visualization of statistical maps.

Parameters:

Name Type Description Default
grid_width int

Width/height of the square grid. Default 100.

100
signal_width int

Width of the embedded signal region. Default 20.

20
n_subjects int

Number of simulated subjects. Default 20.

20
sigma float

Standard deviation of the Gaussian noise. Default 1.

1
signal_amplitude float

Amplitude of the embedded signal. If None, no signal is added.

None
random_state int | RandomState

Seed or RandomState for reproducibility.

None

Attributes:

Name Type Description
data ndarray

Simulated data of shape (grid_width, grid_width, n_subjects).

signal_mask ndarray | None

Binary grid marking the signal region, or None when no signal was added.

t_values ndarray | None

T-statistic map after fit().

p_values ndarray | None

P-value map after fit().

thresholded ndarray | None

Thresholded statistical map after threshold_simulation().

isfit bool

Whether fit() has been called.

Examples:

from nltools.data.simulator import SimulateGrid

sim = SimulateGrid(signal_amplitude=0.5, random_state=42)
sim.fit()
sim.plot_grid_simulation(threshold=0.05, threshold_type="q", correction="fdr")

Methods:

Name Description
add_signal

Add a square signal region, centered in the grid, to self.data.

create_mask

Create the binary signal_mask marking a centered square of the grid.

fit

Run a one-sample t-test on self.data.

plot_grid_simulation

Plot the t-map, its thresholded version, and the false positive distribution.

run_multiple_simulations

Run repeated simulations to estimate the false positive rate.

threshold_simulation

Threshold the fitted simulation and store thresholded plus hit rates.

Methods:

add_signal

add_signal(signal_width=20, signal_amplitude=1)

Add a square signal region, centered in the grid, to self.data.

Parameters:

Name Type Description Default
signal_width int

Width of the signal box in pixels. Default 20.

20
signal_amplitude float

Intensity added inside the box. Default 1.

1

create_mask

create_mask(signal_width)

Create the binary signal_mask marking a centered square of the grid.

Parameters:

Name Type Description Default
signal_width int

Width of the signal box in pixels.

required

fit

fit()

Run a one-sample t-test on self.data.

plot_grid_simulation

plot_grid_simulation(
    threshold,
    threshold_type,
    n_simulations=100,
    correction=None,
)

Plot the t-map, its thresholded version, and the false positive distribution.

Fits and thresholds the simulation first if needed, then calls run_multiple_simulations. Adds a signal-recovery histogram when a signal is present.

Parameters:

Name Type Description Default
threshold float

Threshold value to apply.

required
threshold_type str

't', 'p', or 'q' (see threshold_simulation).

required
n_simulations int

Number of simulations to run. Default 100.

100
correction str

Multiple-comparison correction; 'fdr' or None.

None

run_multiple_simulations

run_multiple_simulations(
    threshold,
    threshold_type,
    n_simulations=100,
    correction=None,
)

Run repeated simulations to estimate the false positive rate.

Stores per-simulation results on multiple_thresholded, multiple_fp, and fpr (plus multiple_tp and multiple_fdr when a signal is present).

Parameters:

Name Type Description Default
threshold float

Threshold value to apply to each simulation.

required
threshold_type str

't', 'p', or 'q' (see threshold_simulation).

required
n_simulations int

Number of simulations to run. Default 100.

100
correction str

Multiple-comparison correction; 'fdr' or None.

None

threshold_simulation

threshold_simulation(
    threshold, threshold_type, correction=None
)

Threshold the fitted simulation and store thresholded plus hit rates.

Parameters:

Name Type Description Default
threshold float

Threshold value to apply.

required
threshold_type str

't' (absolute t-value), 'p' (p-value), or 'q' (FDR-corrected q-value; requires correction='fdr').

required
correction str

Multiple-comparison correction; 'fdr' or None.

None