Simulation¶
The simulate module provides tools for generating synthetic M/EEG data with known ground truth source activations. This is essential for validating and comparing inverse methods under controlled conditions.
Overview¶
Simulation in invertmeeg supports:
- Configurable source patterns: Single dipoles, extended patches, or multiple simultaneous sources
- Noise models: White noise, colored noise, and realistic sensor noise
- Covariance structures: Correlated sources for testing robustness
- Batch generation: Efficient generation of many samples for training or benchmarking
Quick Start¶
from invert.simulate import SimulationConfig, SimulationGenerator
# Create a simulation configuration
config = SimulationConfig(
n_sources=2,
snr=5.0,
source_extent=10.0, # mm
)
# Generate simulations
generator = SimulationGenerator(forward, config)
evoked, stc_true = generator.generate()
API Reference¶
SimulationConfig ¶
Bases: BaseModel
Configuration for EEG simulation generator.
Attributes: batch_size: Number of simulations per batch batch_repetitions: Number of times to repeat each batch n_sources: Number of active sources (int or tuple for range) n_orders: Smoothness order(s) for spatial patterns amplitude_range: Min/max amplitude for source activity n_timepoints: Number of time samples per simulation snr_range: Signal-to-noise ratio range in dB n_timecourses: Number of pre-generated timecourses beta_range: Power-law exponent range for 1/f noise add_forward_error: Whether to add perturbations to leadfield forward_error: Magnitude of forward model error inter_source_correlation: Correlation between sources (float or range) diffusion_smoothing: Whether to use diffusion-based smoothing diffusion_parameter: Smoothing strength (alpha parameter) correlation_mode: Spatial noise correlation pattern noise_color_coeff: Spatial noise correlation strength random_seed: Random seed for reproducibility normalize_leadfield: Whether to normalize leadfield columns verbose: Verbosity level simulation_mode: Simulation mode ('patches' or 'mixture') background_beta: 1/f^beta exponent for smooth background background_mixture_alpha: Mixing coefficient alpha (higher = more background)
Source code in invert/simulate/config.py
SimulationGenerator ¶
Class-based EEG simulation generator with precomputed components.
This generator creates realistic EEG simulations by: 1. Generating spatially smooth source patterns 2. Assigning colored noise timecourses to sources 3. Projecting through the leadfield matrix 4. Adding spatially/temporally colored sensor noise
The class precomputes spatial smoothing operators and timecourses during initialization for faster batch generation.
Source code in invert/simulate/simulate.py
15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 | |
__init__ ¶
Initialize the simulation generator.
Parameters: fwd: MNE forward solution object config: SimulationConfig instance (optional) **kwargs: Configuration parameters (used if config is None)
Source code in invert/simulate/simulate.py
generate ¶
Generate batches of simulations.
Yields: tuple: (x, y, info) where: - x: EEG data [batch_size, n_channels, n_timepoints] - y: Source activity [batch_size, n_dipoles, n_timepoints] (scaled) - info: DataFrame with simulation metadata
Source code in invert/simulate/simulate.py
compute_covariance ¶
Compute the covariance matrix of the data.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
Y
|
ndarray
|
The data matrix. |
required |
cov_type
|
str
|
The type of covariance matrix to compute. Options are 'basic' and 'SSM'. Default is 'basic'. |
'basic'
|
Return
C : numpy.ndarray The covariance matrix.
Source code in invert/simulate/covariance.py
gen_correlated_sources ¶
Generate Q correlated sources with a specified correlation coefficient. The sources are generated as sinusoids with random frequencies and phases.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
corr_coeff
|
float
|
The correlation coefficient between the sources. |
required |
T
|
int
|
The number of time points in the sources. |
required |
Q
|
int
|
The number of sources to generate. |
required |
Returns:
| Name | Type | Description |
|---|---|---|
Y |
ndarray
|
The generated sources. |
Source code in invert/simulate/covariance.py
get_cov ¶
Generate a covariance matrix that is symmetric along the diagonal that correlates sources to a specified degree.
Source code in invert/simulate/covariance.py
add_white_noise ¶
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
X_clean
|
ndarray
|
The clean EEG data. |
required |
snr
|
float
|
The signal to noise ratio in dB. |
required |
correlation_mode
|
None / str
|
None implies no correlation between the noise in different channels. 'banded' : Colored banded noise, where channels closer to each other will be more correlated. 'diagonal' : Some channels have varying degrees of noise. 'cholesky' : A set correlation coefficient between each pair of channels |
None
|
noise_color_coeff
|
float
|
The magnitude of spatial coloring of the noise (not the magnitude of noise overall!). |
0.5
|
Source code in invert/simulate/noise.py
powerlaw_noise ¶
Generate 1/f^beta colored noise via FFT spectral shaping.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
beta
|
float or array - like
|
Power-law exponent(s). 0=white, 1=pink, 2=brown. If array, must have length n_signals. |
required |
n_timepoints
|
int
|
Number of time samples. |
required |
n_signals
|
int
|
Number of independent signals to generate. |
1
|
rng
|
Generator or None
|
Random number generator. |
None
|
Returns:
| Name | Type | Description |
|---|---|---|
signals |
(ndarray, shape(n_signals, n_timepoints))
|
Colored noise signals. |
Source code in invert/simulate/noise.py
generator ¶
generator(
fwd,
use_cov=True,
cov_type="basic",
batch_size=1284,
batch_repetitions=30,
n_sources=10,
n_orders=2,
amplitude_range=(0.5, 1),
n_timepoints=20,
snr_range=(-5, 5),
n_timecourses=5000,
beta_range=(0, 3),
return_mask=True,
scale_data=True,
return_info=False,
add_forward_error=False,
forward_error=0.1,
remove_channel_dim=False,
inter_source_correlation=(0.25, 0.75),
diffusion_smoothing=True,
diffusion_parameter=0.1,
correlation_mode=None,
noise_color_coeff=0.5,
random_seed=None,
normalize_leadfield=False,
verbose=0,
)
.. deprecated::
Use :class:SimulationGenerator instead.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
fwd
|
object
|
Forward solution object containing the source space and orientation information. |
required |
use_cov
|
bool
|
If True, a covariance matrix is used in the simulation. Default is True. |
True
|
batch_size
|
int
|
Size of each batch of simulations. Default is 1284. |
1284
|
batch_repetitions
|
int
|
Number of repetitions of each batch. Default is 30. |
30
|
n_sources
|
int
|
Number of sources in the brain from which activity is simulated. Default is 10. |
10
|
n_orders
|
int
|
The order of the model used to generate time courses. Default is 2. |
2
|
amplitude_range
|
tuple
|
Range of possible amplitudes for the simulated sources. Default is (0.001,1). |
(0.5, 1)
|
n_timepoints
|
int
|
Number of timepoints in each simulated time course. Default is 20. |
20
|
snr_range
|
tuple
|
Range of signal to noise ratios (in dB) to be used in the simulations. Default is (-5, 5 dB). |
(-5, 5)
|
n_timecourses
|
int
|
Number of unique time courses to simulate. Default is 5000. |
5000
|
beta_range
|
tuple
|
Range of possible power-law exponents for the power spectral density of the simulated sources. Default is (0, 3). |
(0, 3)
|
return_mask
|
bool
|
If True, the function will also return a mask of the sources used. Default is True. |
True
|
scale_data
|
bool
|
If True, the EEG data will be scaled. Default is True. |
True
|
return_info
|
bool
|
If True, the function will return a dictionary with information about the generated data. Default is False. |
False
|
add_forward_error
|
bool
|
If True, the function will add an error to the forward model. Default is False. |
False
|
forward_error
|
float
|
Amount of error to add to the forward model if 'add_forward_error' is True. Default is 0.1. |
0.1
|
remove_channel_dim
|
bool
|
If True, the channel dimension will be removed from the output data. Default is False. |
False
|
inter_source_correlation
|
float | Tuple
|
The level of correlation between different sources. Default is 0.5. |
(0.25, 0.75)
|
diffusion_smoothing
|
bool
|
Whether to use diffusion smoothing. Default is True. |
True
|
diffusion_parameter
|
float
|
The diffusion parameter (alpha). Default is 0.1. |
0.1
|
correlation_mode
|
None / str
|
correlation_mode : None/str None implies no correlation between the noise in different channels. 'banded' : Colored banded noise, where channels closer to each other will be more correlated. 'diagonal' : Channels have varying degrees of noise. |
None
|
noise_color_coeff
|
float
|
The magnitude of spatial coloring of the noise. |
0.5
|
random_seed
|
None / int
|
The random seed for replicable simulations |
None
|
verbose
|
int
|
Level of verbosity for the function. Default is 0. |
0
|
Return
x : numpy.ndarray The EEG data matrix. y : numpy.ndarray The source data matrix.
Source code in invert/simulate/simulate.py
386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594 595 596 597 598 599 600 601 602 603 604 605 606 607 608 609 610 611 612 613 614 615 616 617 618 619 620 621 622 623 624 625 626 627 628 629 630 631 632 633 634 635 636 637 638 639 640 641 642 643 644 645 646 647 648 649 650 651 652 653 654 655 656 657 658 659 660 661 662 663 664 665 666 667 668 669 670 671 672 673 674 675 676 677 678 | |
generator_simple ¶
generator_simple(
fwd,
batch_size,
corrs,
T,
n_sources,
SNR_range,
random_seed=42,
return_info=True,
)
.. deprecated::
Use :class:SimulationGenerator instead.
Source code in invert/simulate/simulate.py
generator_single_simple ¶
.. deprecated::
Use :class:SimulationGenerator instead.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
leadfield
|
ndarray
|
The leadfield matrix. |
required |
corr
|
float
|
The correlation coefficient between the sources. |
required |
T
|
int
|
The number of time points in the sources. |
required |
n_sources
|
int
|
The number of sources to generate. |
required |
indices
|
list
|
The indices of the sources to generate. |
required |
SNR
|
float
|
The signal to noise ratio. |
required |
random_seed
|
int
|
The random seed for replicable simulations. |
42
|
Return
X : numpy.ndarray The simulated EEG data. y: numpy.ndarray The simulated source data.
Source code in invert/simulate/simulate.py
build_adjacency ¶
Build sparse adjacency matrix from an MNE forward solution.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
forward
|
dict
|
MNE forward solution object. |
required |
verbose
|
int
|
Verbosity level. |
0
|
Returns:
| Name | Type | Description |
|---|---|---|
adjacency |
csr_matrix
|
Sparse adjacency matrix. |
Source code in invert/simulate/spatial.py
build_spatial_basis ¶
build_spatial_basis(
adjacency,
n_dipoles,
min_order,
max_order,
diffusion_smoothing=True,
diffusion_parameter=0.1,
)
Build multi-order spatial basis from adjacency matrix.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
adjacency
|
csr_matrix
|
Sparse adjacency matrix. |
required |
n_dipoles
|
int
|
Number of dipoles (source space size). |
required |
min_order
|
int
|
Minimum smoothing order to include. |
required |
max_order
|
int
|
Maximum smoothing order (exclusive). |
required |
diffusion_smoothing
|
bool
|
Whether to use diffusion smoothing (True) or absolute Laplacian (False). |
True
|
diffusion_parameter
|
float
|
Diffusion parameter alpha for smoothing. |
0.1
|
Returns:
| Name | Type | Description |
|---|---|---|
sources |
csr_matrix
|
Stacked spatial basis (sparse). |
sources_dense |
ndarray
|
Dense version for fast indexing. |
gradient |
csr_matrix
|
The gradient/smoothing operator. |
Source code in invert/simulate/spatial.py
SimulationConfig¶
invert.simulate.SimulationConfig ¶
Bases: BaseModel
Configuration for EEG simulation generator.
Attributes: batch_size: Number of simulations per batch batch_repetitions: Number of times to repeat each batch n_sources: Number of active sources (int or tuple for range) n_orders: Smoothness order(s) for spatial patterns amplitude_range: Min/max amplitude for source activity n_timepoints: Number of time samples per simulation snr_range: Signal-to-noise ratio range in dB n_timecourses: Number of pre-generated timecourses beta_range: Power-law exponent range for 1/f noise add_forward_error: Whether to add perturbations to leadfield forward_error: Magnitude of forward model error inter_source_correlation: Correlation between sources (float or range) diffusion_smoothing: Whether to use diffusion-based smoothing diffusion_parameter: Smoothing strength (alpha parameter) correlation_mode: Spatial noise correlation pattern noise_color_coeff: Spatial noise correlation strength random_seed: Random seed for reproducibility normalize_leadfield: Whether to normalize leadfield columns verbose: Verbosity level simulation_mode: Simulation mode ('patches' or 'mixture') background_beta: 1/f^beta exponent for smooth background background_mixture_alpha: Mixing coefficient alpha (higher = more background)
Source code in invert/simulate/config.py
SimulationGenerator¶
invert.simulate.SimulationGenerator ¶
Class-based EEG simulation generator with precomputed components.
This generator creates realistic EEG simulations by: 1. Generating spatially smooth source patterns 2. Assigning colored noise timecourses to sources 3. Projecting through the leadfield matrix 4. Adding spatially/temporally colored sensor noise
The class precomputes spatial smoothing operators and timecourses during initialization for faster batch generation.
Source code in invert/simulate/simulate.py
15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 | |
__init__ ¶
Initialize the simulation generator.
Parameters: fwd: MNE forward solution object config: SimulationConfig instance (optional) **kwargs: Configuration parameters (used if config is None)
Source code in invert/simulate/simulate.py
generate ¶
Generate batches of simulations.
Yields: tuple: (x, y, info) where: - x: EEG data [batch_size, n_channels, n_timepoints] - y: Source activity [batch_size, n_dipoles, n_timepoints] (scaled) - info: DataFrame with simulation metadata
Source code in invert/simulate/simulate.py
Noise Functions¶
invert.simulate.add_white_noise ¶
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
X_clean
|
ndarray
|
The clean EEG data. |
required |
snr
|
float
|
The signal to noise ratio in dB. |
required |
correlation_mode
|
None / str
|
None implies no correlation between the noise in different channels. 'banded' : Colored banded noise, where channels closer to each other will be more correlated. 'diagonal' : Some channels have varying degrees of noise. 'cholesky' : A set correlation coefficient between each pair of channels |
None
|
noise_color_coeff
|
float
|
The magnitude of spatial coloring of the noise (not the magnitude of noise overall!). |
0.5
|
Source code in invert/simulate/noise.py
invert.simulate.powerlaw_noise ¶
Generate 1/f^beta colored noise via FFT spectral shaping.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
beta
|
float or array - like
|
Power-law exponent(s). 0=white, 1=pink, 2=brown. If array, must have length n_signals. |
required |
n_timepoints
|
int
|
Number of time samples. |
required |
n_signals
|
int
|
Number of independent signals to generate. |
1
|
rng
|
Generator or None
|
Random number generator. |
None
|
Returns:
| Name | Type | Description |
|---|---|---|
signals |
(ndarray, shape(n_signals, n_timepoints))
|
Colored noise signals. |
Source code in invert/simulate/noise.py
Covariance Utilities¶
invert.simulate.compute_covariance ¶
Compute the covariance matrix of the data.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
Y
|
ndarray
|
The data matrix. |
required |
cov_type
|
str
|
The type of covariance matrix to compute. Options are 'basic' and 'SSM'. Default is 'basic'. |
'basic'
|
Return
C : numpy.ndarray The covariance matrix.
Source code in invert/simulate/covariance.py
invert.simulate.gen_correlated_sources ¶
Generate Q correlated sources with a specified correlation coefficient. The sources are generated as sinusoids with random frequencies and phases.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
corr_coeff
|
float
|
The correlation coefficient between the sources. |
required |
T
|
int
|
The number of time points in the sources. |
required |
Q
|
int
|
The number of sources to generate. |
required |
Returns:
| Name | Type | Description |
|---|---|---|
Y |
ndarray
|
The generated sources. |