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 noise_temporal_beta: 1/f^beta temporal coloring of sensor noise noise_rank_deficiency: Number of projected-out sensor dimensions apply_sensor_projector: Apply projector to both signal and noise noise_low_rank_dim: Rank for low-rank spatial noise model return_noise_cov: Include per-sample noise covariance matrices in metadata estimate_noise_cov: Estimate covariance from baseline noise samples noise_cov_n_baseline: Number of baseline samples used for covariance estimate noise_cov_shrinkage: Shrinkage factor for estimated covariance 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_spatial_model: Spatial source model for patch generation source_extent: Number of dipoles per source patch patch_smoothness_sigma: Gaussian smoothness (graph-hop units) within a patch patch_rank: Temporal rank per patch (1=single latent, 2=two latent components)
Source code in invert/simulate/config.py
6 7 8 9 10 11 12 13 14 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 | |
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
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 384 385 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 679 680 681 682 683 684 685 686 687 688 689 690 691 692 693 694 695 696 697 698 699 700 701 702 703 704 705 706 707 708 709 710 711 712 713 714 715 716 717 718 719 720 721 722 723 724 725 726 727 728 | |
__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
empirical_covariance ¶
Estimate covariance from noise samples with optional Ledoit-style shrinkage.
Source code in invert/simulate/noise.py
make_rank_projector ¶
Create an orthogonal projector P = I - U U^T with controlled rank loss.
Source code in invert/simulate/noise.py
make_sensor_noise_covariance ¶
make_sensor_noise_covariance(
n_chans,
mode=None,
noise_color_coeff=0.5,
rng=None,
low_rank_dim=4,
eps=1e-12,
)
Create a PSD spatial covariance matrix for sensor noise.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
n_chans
|
int
|
Number of channels. |
required |
mode
|
None | str
|
One of {None, "cholesky", "banded", "diagonal", "low_rank"}. |
None
|
noise_color_coeff
|
float
|
Strength of spatial correlation/coloring. |
0.5
|
rng
|
Generator | None
|
Random number generator. |
None
|
low_rank_dim
|
int
|
Latent rank used when |
4
|
eps
|
float
|
Diagonal jitter for numerical safety. |
1e-12
|
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
sample_sensor_noise ¶
Sample sensor noise with desired spatial covariance and temporal color.
Source code in invert/simulate/noise.py
scale_noise_to_snr ¶
Scale noise to match target SNR (in dB) for a given signal.
Source code in invert/simulate/noise.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 noise_temporal_beta: 1/f^beta temporal coloring of sensor noise noise_rank_deficiency: Number of projected-out sensor dimensions apply_sensor_projector: Apply projector to both signal and noise noise_low_rank_dim: Rank for low-rank spatial noise model return_noise_cov: Include per-sample noise covariance matrices in metadata estimate_noise_cov: Estimate covariance from baseline noise samples noise_cov_n_baseline: Number of baseline samples used for covariance estimate noise_cov_shrinkage: Shrinkage factor for estimated covariance 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_spatial_model: Spatial source model for patch generation source_extent: Number of dipoles per source patch patch_smoothness_sigma: Gaussian smoothness (graph-hop units) within a patch patch_rank: Temporal rank per patch (1=single latent, 2=two latent components)
Source code in invert/simulate/config.py
6 7 8 9 10 11 12 13 14 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 | |
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
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 384 385 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 679 680 681 682 683 684 685 686 687 688 689 690 691 692 693 694 695 696 697 698 699 700 701 702 703 704 705 706 707 708 709 710 711 712 713 714 715 716 717 718 719 720 721 722 723 724 725 726 727 728 | |
__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. |