or run

npx @tessl/cli init
Log in

Version

Tile

Overview

Evals

Files

Files

docs

data-io.mddatasets.mdindex.mdmachine-learning.mdpreprocessing.mdsource-analysis.mdstatistics.mdtime-frequency.mdvisualization.md

preprocessing.mddocs/

0

# Preprocessing

1

2

Comprehensive preprocessing tools for cleaning and preparing neuroimaging data for analysis. Includes filtering, artifact detection and removal, independent component analysis (ICA), Maxwell filtering, and signal space projection (SSP).

3

4

## Capabilities

5

6

### Artifact Detection and Annotation

7

8

Detect and annotate various artifacts in neuroimaging data for subsequent removal or rejection.

9

10

```python { .api }

11

def annotate_amplitude(raw: Raw, peak: Optional[float] = None, flat: Optional[float] = None,

12

bad_percent: float = 5.0, min_duration: float = 0.002,

13

verbose: Optional[Union[bool, str, int]] = None) -> Annotations:

14

"""

15

Detect amplitude-based artifacts and create annotations.

16

17

Parameters:

18

- raw: Raw data instance

19

- peak: Peak amplitude threshold

20

- flat: Flat signal threshold

21

- bad_percent: Percentage of channels required to be bad

22

- min_duration: Minimum duration of detected artifacts

23

- verbose: Verbosity level

24

25

Returns:

26

Annotations object with detected artifacts

27

"""

28

29

def annotate_nan(raw: Raw, verbose: Optional[Union[bool, str, int]] = None) -> Annotations:

30

"""

31

Annotate NaN values in raw data.

32

33

Parameters:

34

- raw: Raw data instance

35

- verbose: Verbosity level

36

37

Returns:

38

Annotations object marking NaN periods

39

"""

40

41

def annotate_muscle_zscore(raw: Raw, threshold: float = 4.0, ch_type: str = 'eeg',

42

filter_freq: Tuple[float, float] = (110, 140),

43

n_jobs: int = 1, verbose: Optional[Union[bool, str, int]] = None) -> Tuple[Annotations, ArrayLike]:

44

"""

45

Annotate muscle artifacts using z-score of filtered data.

46

47

Parameters:

48

- raw: Raw data instance

49

- threshold: Z-score threshold for detection

50

- ch_type: Channel type to analyze

51

- filter_freq: Frequency range for muscle activity

52

- n_jobs: Number of parallel jobs

53

- verbose: Verbosity level

54

55

Returns:

56

Tuple of (annotations, z_scores)

57

"""

58

```

59

60

### Independent Component Analysis (ICA)

61

62

Decompose signals into independent components for artifact identification and removal.

63

64

```python { .api }

65

class ICA:

66

"""

67

Independent Component Analysis for artifact removal.

68

69

Decomposes multichannel data into independent components to identify

70

and remove artifacts like eye blinks, heartbeat, and muscle activity.

71

"""

72

73

def __init__(self, n_components: Optional[int] = None, algorithm: str = 'fastica',

74

fun: str = 'logcosh', fun_args: Optional[Dict] = None,

75

max_iter: int = 1000, tol: float = 1e-4, w_init: Optional[ArrayLike] = None,

76

whiten: str = 'unit-variance', random_state: Optional[int] = None,

77

method: str = 'fastica', fit_params: Optional[Dict] = None,

78

max_pca_components: Optional[int] = None, n_pca_components: Optional[Union[int, float]] = None,

79

noise_cov: Optional[Covariance] = None, verbose: Optional[Union[bool, str, int]] = None):

80

"""

81

Initialize ICA object.

82

83

Parameters:

84

- n_components: Number of components to extract

85

- algorithm: ICA algorithm ('fastica', 'infomax', 'picard')

86

- fun: Functional form for FastICA

87

- fun_args: Arguments for functional form

88

- max_iter: Maximum iterations

89

- tol: Tolerance for convergence

90

- w_init: Initial unmixing matrix

91

- whiten: Whitening method

92

- random_state: Random state for reproducibility

93

- method: ICA method

94

- fit_params: Additional fit parameters

95

- max_pca_components: Maximum PCA components

96

- n_pca_components: Number of PCA components to keep

97

- noise_cov: Noise covariance matrix

98

- verbose: Verbosity level

99

"""

100

101

def fit(self, inst: Union[Raw, Epochs], picks: Optional[Union[str, List]] = None,

102

start: Optional[float] = None, stop: Optional[float] = None,

103

decim: Optional[int] = None, reject: Optional[Dict] = None,

104

flat: Optional[Dict] = None, tstep: float = 2.0,

105

reject_by_annotation: bool = True, verbose: Optional[Union[bool, str, int]] = None) -> 'ICA':

106

"""

107

Fit ICA on data.

108

109

Parameters:

110

- inst: Raw or Epochs instance to fit

111

- picks: Channel selection

112

- start: Start time for fitting

113

- stop: Stop time for fitting

114

- decim: Decimation factor

115

- reject: Rejection criteria

116

- flat: Flat channel detection criteria

117

- tstep: Time step for data chunks

118

- reject_by_annotation: Reject based on annotations

119

- verbose: Verbosity level

120

121

Returns:

122

Fitted ICA object

123

"""

124

125

def apply(self, inst: Union[Raw, Epochs], include: Optional[List[int]] = None,

126

exclude: Optional[List[int]] = None, n_pca_components: Optional[int] = None,

127

verbose: Optional[Union[bool, str, int]] = None) -> Union[Raw, Epochs]:

128

"""

129

Apply ICA transformation to remove components.

130

131

Parameters:

132

- inst: Instance to transform

133

- include: Components to include (if None, use all except excluded)

134

- exclude: Components to exclude

135

- n_pca_components: Number of PCA components

136

- verbose: Verbosity level

137

138

Returns:

139

Transformed instance with artifacts removed

140

"""

141

142

def find_bads_ecg(self, inst: Union[Raw, Epochs], ch_name: Optional[str] = None,

143

threshold: str = 'auto', start: Optional[float] = None,

144

stop: Optional[float] = None, l_freq: float = 5, h_freq: float = 35,

145

method: str = 'corrcoef', reject_by_annotation: bool = True,

146

measure: str = 'zscore', verbose: Optional[Union[bool, str, int]] = None) -> List[int]:

147

"""

148

Find ECG-related components automatically.

149

150

Parameters:

151

- inst: Raw or Epochs instance

152

- ch_name: ECG channel name

153

- threshold: Threshold for component selection

154

- start: Start time

155

- stop: Stop time

156

- l_freq: Low frequency for ECG filtering

157

- h_freq: High frequency for ECG filtering

158

- method: Method for finding components

159

- reject_by_annotation: Reject based on annotations

160

- measure: Measure for thresholding

161

- verbose: Verbosity level

162

163

Returns:

164

List of ECG component indices

165

"""

166

167

def find_bads_eog(self, inst: Union[Raw, Epochs], ch_name: Optional[Union[str, List[str]]] = None,

168

threshold: float = 3.0, start: Optional[float] = None,

169

stop: Optional[float] = None, l_freq: float = 1, h_freq: float = 10,

170

reject_by_annotation: bool = True, measure: str = 'zscore',

171

verbose: Optional[Union[bool, str, int]] = None) -> List[int]:

172

"""

173

Find EOG-related components automatically.

174

175

Parameters:

176

- inst: Raw or Epochs instance

177

- ch_name: EOG channel name(s)

178

- threshold: Threshold for component selection

179

- start: Start time

180

- stop: Stop time

181

- l_freq: Low frequency for EOG filtering

182

- h_freq: High frequency for EOG filtering

183

- reject_by_annotation: Reject based on annotations

184

- measure: Measure for thresholding

185

- verbose: Verbosity level

186

187

Returns:

188

List of EOG component indices

189

"""

190

191

def plot_components(self, picks: Optional[Union[int, List[int]]] = None,

192

ch_type: Optional[str] = None, res: int = 64,

193

vmin: Optional[float] = None, vmax: Optional[float] = None,

194

colorbar: bool = True, title: Optional[str] = None,

195

show: bool = True, outlines: str = 'head',

196

contours: int = 6, image_interp: str = 'bilinear',

197

inst: Optional[Union[Raw, Epochs]] = None) -> Figure:

198

"""

199

Plot ICA component topographies.

200

201

Parameters:

202

- picks: Components to plot

203

- ch_type: Channel type

204

- res: Resolution of topomaps

205

- vmin: Minimum value for colormap

206

- vmax: Maximum value for colormap

207

- colorbar: Show colorbar

208

- title: Plot title

209

- show: Show plot immediately

210

- outlines: Outline style

211

- contours: Number of contour lines

212

- image_interp: Image interpolation method

213

- inst: Instance for additional channel info

214

215

Returns:

216

Figure object

217

"""

218

219

def plot_sources(self, inst: Union[Raw, Epochs], picks: Optional[Union[int, List[int]]] = None,

220

start: Optional[float] = None, stop: Optional[float] = None,

221

show: bool = True, title: Optional[str] = None, block: bool = False) -> Figure:

222

"""

223

Plot ICA component time series.

224

225

Parameters:

226

- inst: Instance to plot sources from

227

- picks: Components to plot

228

- start: Start time

229

- stop: Stop time

230

- show: Show plot immediately

231

- title: Plot title

232

- block: Block execution until plot is closed

233

234

Returns:

235

Figure object

236

"""

237

```

238

239

### EOG Regression and Advanced Artifact Removal

240

241

Advanced methods for removing eye movement and other artifacts using regression techniques.

242

243

```python { .api }

244

class EOGRegression:

245

"""

246

EOG artifact removal using regression techniques.

247

248

Removes eye movement artifacts by regressing out EOG signals from EEG channels.

249

"""

250

251

def __init__(self, picks_artifact: Optional[Union[str, List]] = None,

252

picks_target: Optional[Union[str, List]] = None) -> None:

253

"""

254

Initialize EOG regression object.

255

256

Parameters:

257

- picks_artifact: Channels containing artifacts (EOG)

258

- picks_target: Target channels to clean (EEG)

259

"""

260

261

def fit(self, epochs: Epochs) -> 'EOGRegression':

262

"""

263

Fit regression model to remove EOG artifacts.

264

265

Parameters:

266

- epochs: Epochs containing both EOG and target channels

267

268

Returns:

269

Fitted EOGRegression object

270

"""

271

272

def apply(self, inst: Union[Raw, Epochs]) -> Union[Raw, Epochs]:

273

"""

274

Apply EOG regression to remove artifacts.

275

276

Parameters:

277

- inst: Data instance to clean

278

279

Returns:

280

Cleaned data instance

281

"""

282

283

class Xdawn:

284

"""

285

Spatial filtering using xDAWN algorithm.

286

287

Enhances event-related responses while suppressing noise and artifacts

288

using spatial filters optimized for signal-to-noise ratio.

289

"""

290

291

def __init__(self, n_components: int = 2, signal_cov: Optional[ArrayLike] = None,

292

correct_overlap: str = 'auto', reg: Optional[Union[str, float]] = None) -> None:

293

"""

294

Initialize xDAWN spatial filter.

295

296

Parameters:

297

- n_components: Number of components to extract

298

- signal_cov: Signal covariance matrix

299

- correct_overlap: Method for correcting overlap

300

- reg: Regularization parameter

301

"""

302

303

def fit(self, epochs: Epochs, y: Optional[ArrayLike] = None) -> 'Xdawn':

304

"""

305

Fit xDAWN spatial filters.

306

307

Parameters:

308

- epochs: Epochs to fit filters on

309

- y: Target variable (not used)

310

311

Returns:

312

Fitted Xdawn object

313

"""

314

315

def apply(self, inst: Union[Raw, Epochs]) -> Union[Raw, Epochs]:

316

"""

317

Apply xDAWN spatial filtering.

318

319

Parameters:

320

- inst: Data instance to filter

321

322

Returns:

323

Spatially filtered data instance

324

"""

325

```

326

327

### ECG and EOG Event Detection

328

329

Detect heartbeat and eye movement events for artifact analysis and removal.

330

331

```python { .api }

332

def find_ecg_events(raw: Raw, event_id: int = 999, ch_name: Optional[str] = None,

333

tstart: float = 0.0, l_freq: float = 5, h_freq: float = 35,

334

qrs_threshold: Union[float, str] = 'auto', filter_length: str = '10s',

335

return_ecg: bool = False, reject_by_annotation: bool = True,

336

verbose: Optional[Union[bool, str, int]] = None) -> Union[ArrayLike, Tuple[ArrayLike, ArrayLike]]:

337

"""

338

Find ECG events in raw data.

339

340

Parameters:

341

- raw: Raw data instance

342

- event_id: Event ID for ECG events

343

- ch_name: ECG channel name

344

- tstart: Start time for event detection

345

- l_freq: Low frequency for ECG filtering

346

- h_freq: High frequency for ECG filtering

347

- qrs_threshold: QRS detection threshold

348

- filter_length: Filter length

349

- return_ecg: Return filtered ECG signal

350

- reject_by_annotation: Reject based on annotations

351

- verbose: Verbosity level

352

353

Returns:

354

ECG events array, optionally with filtered ECG signal

355

"""

356

357

def find_eog_events(raw: Raw, event_id: int = 998, ch_name: Optional[Union[str, List[str]]] = None,

358

tstart: float = 0.0, l_freq: float = 1, h_freq: float = 10,

359

reject_by_annotation: bool = True, thresh: Optional[float] = None,

360

verbose: Optional[Union[bool, str, int]] = None) -> ArrayLike:

361

"""

362

Find EOG events in raw data.

363

364

Parameters:

365

- raw: Raw data instance

366

- event_id: Event ID for EOG events

367

- ch_name: EOG channel name(s)

368

- tstart: Start time for event detection

369

- l_freq: Low frequency for EOG filtering

370

- h_freq: High frequency for EOG filtering

371

- reject_by_annotation: Reject based on annotations

372

- thresh: Threshold for EOG detection

373

- verbose: Verbosity level

374

375

Returns:

376

EOG events array

377

"""

378

379

def create_ecg_epochs(raw: Raw, ch_name: Optional[str] = None, event_id: int = 999,

380

picks: Optional[Union[str, List]] = None, tmin: float = -0.5, tmax: float = 0.5,

381

l_freq: float = 8, h_freq: float = 16, reject: Optional[Dict] = None,

382

flat: Optional[Dict] = None, baseline: Optional[Tuple[float, float]] = None,

383

preload: bool = True, keep_ecg: bool = False,

384

reject_by_annotation: bool = True, verbose: Optional[Union[bool, str, int]] = None) -> Epochs:

385

"""

386

Create epochs around ECG events.

387

388

Parameters:

389

- raw: Raw data instance

390

- ch_name: ECG channel name

391

- event_id: Event ID for ECG events

392

- picks: Channel selection

393

- tmin: Start time relative to events

394

- tmax: End time relative to events

395

- l_freq: Low frequency for filtering

396

- h_freq: High frequency for filtering

397

- reject: Rejection criteria

398

- flat: Flat channel detection criteria

399

- baseline: Baseline correction period

400

- preload: Load data into memory

401

- keep_ecg: Keep ECG channel in epochs

402

- reject_by_annotation: Reject based on annotations

403

- verbose: Verbosity level

404

405

Returns:

406

Epochs around ECG events

407

"""

408

409

def create_eog_epochs(raw: Raw, ch_name: Optional[Union[str, List[str]]] = None, event_id: int = 998,

410

picks: Optional[Union[str, List]] = None, tmin: float = -0.5, tmax: float = 0.5,

411

l_freq: float = 1, h_freq: float = 10, reject: Optional[Dict] = None,

412

flat: Optional[Dict] = None, baseline: Optional[Tuple[float, float]] = None,

413

preload: bool = True, reject_by_annotation: bool = True,

414

verbose: Optional[Union[bool, str, int]] = None) -> Epochs:

415

"""

416

Create epochs around EOG events.

417

418

Parameters:

419

- raw: Raw data instance

420

- ch_name: EOG channel name(s)

421

- event_id: Event ID for EOG events

422

- picks: Channel selection

423

- tmin: Start time relative to events

424

- tmax: End time relative to events

425

- l_freq: Low frequency for filtering

426

- h_freq: High frequency for filtering

427

- reject: Rejection criteria

428

- flat: Flat channel detection criteria

429

- baseline: Baseline correction period

430

- preload: Load data into memory

431

- reject_by_annotation: Reject based on annotations

432

- verbose: Verbosity level

433

434

Returns:

435

Epochs around EOG events

436

"""

437

```

438

439

### Maxwell Filtering (Signal Space Separation)

440

441

Remove external magnetic interference and compensate for head movements in MEG recordings.

442

443

```python { .api }

444

def maxwell_filter(raw: Raw, origin: Union[str, Tuple[float, float, float]] = 'auto',

445

int_order: int = 8, ext_order: int = 3, calibration: Optional[str] = None,

446

cross_talk: Optional[str] = None, st_duration: Optional[float] = None,

447

st_correlation: float = 0.98, coord_frame: str = 'head',

448

destination: Optional[Union[str, ArrayLike]] = None,

449

regularize: str = 'in', ignore_ref: bool = False,

450

bad_condition: str = 'error', head_pos: Optional[ArrayLike] = None,

451

st_fixed: bool = True, st_only: bool = False,

452

mag_scale: Union[float, str] = 100.0, skip_by_annotation: Union[str, List[str]] = 'edge',

453

extended_proj: List = (), verbose: Optional[Union[bool, str, int]] = None) -> Raw:

454

"""

455

Apply Maxwell filtering (Signal Space Separation) to MEG data.

456

457

Parameters:

458

- raw: Raw MEG data

459

- origin: Head origin for coordinate system

460

- int_order: Internal multipole order

461

- ext_order: External multipole order

462

- calibration: Calibration file path

463

- cross_talk: Cross-talk file path

464

- st_duration: Duration for spatiotemporal processing

465

- st_correlation: Correlation threshold for tSSS

466

- coord_frame: Coordinate frame

467

- destination: Destination for head position

468

- regularize: Regularization method

469

- ignore_ref: Ignore reference channels

470

- bad_condition: How to handle bad conditions

471

- head_pos: Head position array

472

- st_fixed: Use fixed correlation window

473

- st_only: Apply only spatiotemporal processing

474

- mag_scale: Magnetometer scaling

475

- skip_by_annotation: Annotations to skip

476

- extended_proj: Extended projections

477

- verbose: Verbosity level

478

479

Returns:

480

Maxwell filtered Raw object

481

"""

482

483

def compute_maxwell_basis(info: Info, origin: Union[str, Tuple[float, float, float]],

484

int_order: int = 8, ext_order: int = 3,

485

regularize: str = 'in', ignore_ref: bool = False,

486

verbose: Optional[Union[bool, str, int]] = None) -> Dict:

487

"""

488

Compute Maxwell filtering basis.

489

490

Parameters:

491

- info: Measurement info

492

- origin: Head origin

493

- int_order: Internal multipole order

494

- ext_order: External multipole order

495

- regularize: Regularization method

496

- ignore_ref: Ignore reference channels

497

- verbose: Verbosity level

498

499

Returns:

500

Dictionary containing Maxwell basis

501

"""

502

503

def find_bad_channels_maxwell(raw: Raw, origin: Union[str, Tuple[float, float, float]] = 'auto',

504

int_order: int = 8, ext_order: int = 3,

505

calibration: Optional[str] = None, cross_talk: Optional[str] = None,

506

coord_frame: str = 'head', regularize: str = 'in',

507

ignore_ref: bool = False, bad_condition: str = 'error',

508

skip_by_annotation: Union[str, List[str]] = 'edge',

509

h_freq: Optional[float] = 40, verbose: Optional[Union[bool, str, int]] = None) -> List[str]:

510

"""

511

Find bad MEG channels using Maxwell filtering.

512

513

Parameters:

514

- raw: Raw MEG data

515

- origin: Head origin

516

- int_order: Internal multipole order

517

- ext_order: External multipole order

518

- calibration: Calibration file path

519

- cross_talk: Cross-talk file path

520

- coord_frame: Coordinate frame

521

- regularize: Regularization method

522

- ignore_ref: Ignore reference channels

523

- bad_condition: How to handle bad conditions

524

- skip_by_annotation: Annotations to skip

525

- h_freq: High-pass filter frequency

526

- verbose: Verbosity level

527

528

Returns:

529

List of bad channel names

530

"""

531

```

532

533

### Artifact Detection and Annotation

534

535

Automatically detect and mark various types of artifacts in continuous data.

536

537

```python { .api }

538

def annotate_amplitude(raw: Raw, peak: Optional[float] = None, flat: Optional[float] = None,

539

bad_percent: float = 5.0, min_duration: float = 0.002,

540

verbose: Optional[Union[bool, str, int]] = None) -> Annotations:

541

"""

542

Annotate segments with large amplitude artifacts.

543

544

Parameters:

545

- raw: Raw data instance

546

- peak: Peak amplitude threshold

547

- flat: Flat signal threshold

548

- bad_percent: Percentage of bad channels to trigger annotation

549

- min_duration: Minimum duration of artifacts

550

- verbose: Verbosity level

551

552

Returns:

553

Annotations object with artifact segments

554

"""

555

556

def annotate_break(raw: Raw, min_break_duration: float = 15.0, t_start_after_previous: float = 5.0,

557

t_stop_before_next: float = 5.0, ignore: Union[str, List[str]] = (),

558

verbose: Optional[Union[bool, str, int]] = None) -> Annotations:

559

"""

560

Annotate breaks in data acquisition.

561

562

Parameters:

563

- raw: Raw data instance

564

- min_break_duration: Minimum break duration to annotate

565

- t_start_after_previous: Time after previous segment

566

- t_stop_before_next: Time before next segment

567

- ignore: Existing annotations to ignore

568

- verbose: Verbosity level

569

570

Returns:

571

Annotations object with break segments

572

"""

573

574

def annotate_muscle_zscore(raw: Raw, threshold: float = 4, ch_type: str = 'eeg',

575

l_freq: float = 110, h_freq: float = 140,

576

n_jobs: int = 1, verbose: Optional[Union[bool, str, int]] = None) -> Annotations:

577

"""

578

Annotate muscle artifacts using z-score of high-frequency power.

579

580

Parameters:

581

- raw: Raw data instance

582

- threshold: Z-score threshold for muscle detection

583

- ch_type: Channel type to analyze

584

- l_freq: Low frequency for muscle band

585

- h_freq: High frequency for muscle band

586

- n_jobs: Number of parallel jobs

587

- verbose: Verbosity level

588

589

Returns:

590

Annotations object with muscle artifact segments

591

"""

592

593

def annotate_movement(raw: Raw, pos: ArrayLike, rotation_velocity_limit: Optional[float] = None,

594

translation_velocity_limit: Optional[float] = None,

595

mean_distance_limit: Optional[float] = None,

596

verbose: Optional[Union[bool, str, int]] = None) -> Annotations:

597

"""

598

Annotate movement artifacts from head position data.

599

600

Parameters:

601

- raw: Raw data instance

602

- pos: Head position array

603

- rotation_velocity_limit: Maximum rotation velocity

604

- translation_velocity_limit: Maximum translation velocity

605

- mean_distance_limit: Maximum mean distance from origin

606

- verbose: Verbosity level

607

608

Returns:

609

Annotations object with movement artifact segments

610

"""

611

```

612

613

### Signal Space Projection (SSP)

614

615

Remove artifacts using signal space projection methods.

616

617

```python { .api }

618

def compute_proj_epochs(epochs: Epochs, n_grad: int = 2, n_mag: int = 2, n_eeg: int = 2,

619

n_jobs: int = 1, desc_prefix: Optional[str] = None,

620

verbose: Optional[Union[bool, str, int]] = None) -> List[Projection]:

621

"""

622

Compute SSP projectors from epochs.

623

624

Parameters:

625

- epochs: Epochs object

626

- n_grad: Number of gradient projectors

627

- n_mag: Number of magnetometer projectors

628

- n_eeg: Number of EEG projectors

629

- n_jobs: Number of parallel jobs

630

- desc_prefix: Description prefix for projectors

631

- verbose: Verbosity level

632

633

Returns:

634

List of Projection objects

635

"""

636

637

def compute_proj_raw(raw: Raw, start: float = 0, stop: Optional[float] = None,

638

duration: float = 1, n_grad: int = 2, n_mag: int = 2, n_eeg: int = 2,

639

reject_by_annotation: bool = True, n_jobs: int = 1,

640

verbose: Optional[Union[bool, str, int]] = None) -> List[Projection]:

641

"""

642

Compute SSP projectors from raw data.

643

644

Parameters:

645

- raw: Raw data instance

646

- start: Start time

647

- stop: Stop time

648

- duration: Duration of data segments

649

- n_grad: Number of gradient projectors

650

- n_mag: Number of magnetometer projectors

651

- n_eeg: Number of EEG projectors

652

- reject_by_annotation: Reject annotated segments

653

- n_jobs: Number of parallel jobs

654

- verbose: Verbosity level

655

656

Returns:

657

List of Projection objects

658

"""

659

660

def compute_proj_evoked(evoked: Evoked, n_grad: int = 2, n_mag: int = 2, n_eeg: int = 2,

661

desc_prefix: Optional[str] = None, verbose: Optional[Union[bool, str, int]] = None) -> List[Projection]:

662

"""

663

Compute SSP projectors from evoked data.

664

665

Parameters:

666

- evoked: Evoked data instance

667

- n_grad: Number of gradient projectors

668

- n_mag: Number of magnetometer projectors

669

- n_eeg: Number of EEG projectors

670

- desc_prefix: Description prefix

671

- verbose: Verbosity level

672

673

Returns:

674

List of Projection objects

675

"""

676

```

677

678

### Referencing and Channel Operations

679

680

Set reference schemes and manipulate channel configurations for optimal signal quality.

681

682

```python { .api }

683

def set_eeg_reference(inst: Union[Raw, Epochs, Evoked], ref_channels: Union[str, List[str]] = 'average',

684

copy: bool = True, projection: bool = False, ch_type: str = 'auto',

685

forward: Optional[Forward] = None, joint: bool = False,

686

verbose: Optional[Union[bool, str, int]] = None) -> Union[Raw, Epochs, Evoked]:

687

"""

688

Set EEG reference for data.

689

690

Parameters:

691

- inst: Instance to re-reference

692

- ref_channels: Reference channel(s) or 'average'

693

- copy: Make copy of instance

694

- projection: Use projection for re-referencing

695

- ch_type: Channel type to re-reference

696

- forward: Forward solution for REST referencing

697

- joint: Use joint reference for MEG and EEG

698

- verbose: Verbosity level

699

700

Returns:

701

Re-referenced instance

702

"""

703

704

def set_bipolar_reference(inst: Union[Raw, Epochs, Evoked], anode: Union[str, List[str]],

705

cathode: Union[str, List[str]], ch_name: Optional[Union[str, List[str]]] = None,

706

ch_info: Optional[Dict] = None, drop_refs: bool = True,

707

copy: bool = True, verbose: Optional[Union[bool, str, int]] = None) -> Union[Raw, Epochs, Evoked]:

708

"""

709

Set bipolar reference.

710

711

Parameters:

712

- inst: Instance to re-reference

713

- anode: Anode channel name(s)

714

- cathode: Cathode channel name(s)

715

- ch_name: New channel name(s)

716

- ch_info: Channel info dict

717

- drop_refs: Drop reference channels

718

- copy: Make copy of instance

719

- verbose: Verbosity level

720

721

Returns:

722

Bipolar referenced instance

723

"""

724

725

def add_reference_channels(inst: Union[Raw, Epochs, Evoked], ref_channels: Union[str, List[str]],

726

copy: bool = True, verbose: Optional[Union[bool, str, int]] = None) -> Union[Raw, Epochs, Evoked]:

727

"""

728

Add reference channels to data.

729

730

Parameters:

731

- inst: Instance to modify

732

- ref_channels: Reference channel name(s) to add

733

- copy: Make copy of instance

734

- verbose: Verbosity level

735

736

Returns:

737

Instance with added reference channels

738

"""

739

```

740

741

## Usage Examples

742

743

### Basic Filtering

744

745

```python

746

import mne

747

748

# Load raw data

749

raw = mne.io.read_raw_fif('sample_audvis_raw.fif', preload=True)

750

751

# Apply band-pass filter (1-40 Hz)

752

raw.filter(l_freq=1.0, h_freq=40.0, fir_design='firwin')

753

754

# Remove 60 Hz line noise

755

raw.notch_filter(freqs=60, fir_design='firwin')

756

757

# Resample to lower sampling rate

758

raw.resample(sfreq=250)

759

```

760

761

### ICA Artifact Removal

762

763

```python

764

import mne

765

from mne.preprocessing import ICA

766

767

# Load and filter data

768

raw = mne.io.read_raw_fif('sample_audvis_raw.fif', preload=True)

769

raw.filter(l_freq=1.0, h_freq=40.0)

770

771

# Setup and fit ICA

772

ica = ICA(n_components=20, random_state=97)

773

ica.fit(raw)

774

775

# Find and exclude ECG artifacts

776

ecg_indices, ecg_scores = ica.find_bads_ecg(raw, method='corrcoef')

777

ica.exclude = ecg_indices

778

779

# Find and exclude EOG artifacts

780

eog_indices, eog_scores = ica.find_bads_eog(raw)

781

ica.exclude.extend(eog_indices)

782

783

# Apply ICA to remove artifacts

784

raw_clean = ica.apply(raw)

785

```

786

787

### Automatic Artifact Detection

788

789

```python

790

import mne

791

792

# Load raw data

793

raw = mne.io.read_raw_fif('sample_audvis_raw.fif', preload=True)

794

795

# Detect amplitude artifacts

796

amp_annot = annotate_amplitude(raw, peak=150e-6, flat=1e-6)

797

798

# Detect muscle artifacts

799

muscle_annot = annotate_muscle_zscore(raw, threshold=4)

800

801

# Combine annotations

802

all_annot = amp_annot + muscle_annot

803

raw.set_annotations(all_annot)

804

```

805

806

## Types

807

808

```python { .api }

809

class Annotations:

810

"""Container for temporal annotations."""

811

onset: ArrayLike # Onset times in seconds

812

duration: ArrayLike # Duration in seconds

813

description: List[str] # Annotation descriptions

814

815

def __add__(self, other: 'Annotations') -> 'Annotations': ...

816

def save(self, fname: str) -> None: ...

817

818

class Projection:

819

"""Signal space projection operator."""

820

data: Dict # Projection data

821

kind: int # Projection type

822

desc: str # Description

823

active: bool # Whether projection is active

824

825

def plot_topomap(self, info: Info, **kwargs) -> Figure: ...

826

827

class Covariance:

828

"""Data covariance matrix."""

829

data: ArrayLike # Covariance matrix

830

ch_names: List[str] # Channel names

831

nfree: int # Degrees of freedom

832

833

def plot(self, info: Info, **kwargs) -> Figure: ...

834

```