<jupyter_start><jupyter_text>Basic MEG and EEG data processing=================================![](http://mne-tools.github.io/stable/_static/mne_logo.png)MNE-Python reimplements most of MNE-C's (the original MNE command line utils)functionality and offers transparent scripting.On top of that it extends MNE-C's functionality considerably(customize events, compute contrasts, group statistics, time-frequencyanalysis, EEG-sensor space analyses, etc.) It uses the same files as standardMNE unix commands: no need to convert your files to a new system or database.What you can do with MNE Python-------------------------------   - **Raw data visualization** to visualize recordings, can also use     *mne_browse_raw* for extended functionality (see `ch_browse`)   - **Epoching**: Define epochs, baseline correction, handle conditions etc.   - **Averaging** to get Evoked data   - **Compute SSP projectors** to remove ECG and EOG artifacts   - **Compute ICA** to remove artifacts or select latent sources.   - **Maxwell filtering** to remove environmental noise.   - **Boundary Element Modeling**: single and three-layer BEM model     creation and solution computation.   - **Forward modeling**: BEM computation and mesh creation     (see `ch_forward`)   - **Linear inverse solvers** (dSPM, sLORETA, MNE, LCMV, DICS)   - **Sparse inverse solvers** (L1/L2 mixed norm MxNE, Gamma Map,     Time-Frequency MxNE)   - **Connectivity estimation** in sensor and source space   - **Visualization of sensor and source space data**   - **Time-frequency** analysis with Morlet wavelets (induced power,     intertrial coherence, phase lock value) also in the source space   - **Spectrum estimation** using multi-taper method   - **Mixed Source Models** combining cortical and subcortical structures   - **Dipole Fitting**   - **Decoding** multivariate pattern analyis of M/EEG topographies   - **Compute contrasts** between conditions, between sensors, across     subjects etc.   - **Non-parametric statistics** in time, space and frequency     (including cluster-level)   - **Scripting** (batch and parallel computing)What you're not supposed to do with MNE Python----------------------------------------------    - **Brain and head surface segmentation** for use with BEM      models -- use Freesurfer.NoteThis package is based on the FIF file format from Neuromag. It          can read and convert CTF, BTI/4D, KIT and various EEG formats to          FIF.Installation of the required materials---------------------------------------See `install_python_and_mne_python`.NoteThe expected location for the MNE-sample data is    ``~/mne_data``. If you downloaded data and an example asks    you whether to download it again, make sure    the data reside in the examples directory and you run the script from its    current directory.    From IPython e.g. say::        cd examples/preprocessing    %run plot_find_ecg_artifacts.pyFrom raw data to evoked data----------------------------Now, launch `ipython`_ (Advanced Python shell) using the QT backend, whichis best supported across systems::  $ ipython --matplotlib=qtFirst, load the mne package:NoteIn IPython, you can press **shift-enter** with a given cell          selected to execute it and advance to the next cell:<jupyter_code>import mne<jupyter_output><empty_output><jupyter_text>If you'd like to turn information status messages off:<jupyter_code>mne.set_log_level('WARNING')<jupyter_output><empty_output><jupyter_text>But it's generally a good idea to leave them on:<jupyter_code>mne.set_log_level('INFO')<jupyter_output><empty_output><jupyter_text>You can set the default level by setting the environment variable"MNE_LOGGING_LEVEL", or by having mne-python write preferences to a file:<jupyter_code>mne.set_config('MNE_LOGGING_LEVEL', 'WARNING', set_env=True)<jupyter_output><empty_output><jupyter_text>Note that the location of the mne-python preferences file (for easier manualediting) can be found using:<jupyter_code>mne.get_config_path()<jupyter_output><empty_output><jupyter_text>By default logging messages print to the console, but look at:func:`mne.set_log_file` to save output to a file.Access raw data^^^^^^^^^^^^^^^<jupyter_code>from mne.datasets import sample  # noqa
data_path = sample.data_path()
raw_fname = data_path + '/MEG/sample/sample_audvis_filt-0-40_raw.fif'
print(raw_fname)<jupyter_output><empty_output><jupyter_text>NoteThe MNE sample dataset should be downloaded automatically but be          patient (approx. 2GB)Read data from file:<jupyter_code>raw = mne.io.read_raw_fif(raw_fname)
print(raw)
print(raw.info)<jupyter_output><empty_output><jupyter_text>Look at the channels in raw:<jupyter_code>print(raw.ch_names)<jupyter_output><empty_output><jupyter_text>Read and plot a segment of raw data<jupyter_code>start, stop = raw.time_as_index([100, 115])  # 100 s to 115 s data segment
data, times = raw[:, start:stop]
print(data.shape)
print(times.shape)
data, times = raw[2:20:3, start:stop]  # access underlying data
raw.plot()<jupyter_output><empty_output><jupyter_text>Save a segment of 150s of raw data (MEG only):<jupyter_code>picks = mne.pick_types(raw.info, meg=True, eeg=False, stim=True,
                       exclude='bads')
raw.save('sample_audvis_meg_raw.fif', tmin=0, tmax=150, picks=picks,
         overwrite=True)<jupyter_output><empty_output><jupyter_text>Define and read epochs^^^^^^^^^^^^^^^^^^^^^^First extract events:<jupyter_code>events = mne.find_events(raw, stim_channel='STI 014')
print(events[:5])<jupyter_output><empty_output><jupyter_text>Note that, by default, we use stim_channel='STI 014'. If you have a differentsystem (e.g., a newer system that uses channel 'STI101' by default), you canuse the following to set the default stim channel to use for finding events:<jupyter_code>mne.set_config('MNE_STIM_CHANNEL', 'STI101', set_env=True)<jupyter_output><empty_output><jupyter_text>Events are stored as a 2D numpy array where the first column is the timeinstant and the last one is the event number. It is therefore easy tomanipulate.Define epochs parameters:<jupyter_code>event_id = dict(aud_l=1, aud_r=2)  # event trigger and conditions
tmin = -0.2  # start of each epoch (200ms before the trigger)
tmax = 0.5  # end of each epoch (500ms after the trigger)<jupyter_output><empty_output><jupyter_text>Exclude some channels (original bads + 2 more):<jupyter_code>raw.info['bads'] += ['MEG 2443', 'EEG 053']<jupyter_output><empty_output><jupyter_text>The variable raw.info['bads'] is just a python list.Pick the good channels, excluding raw.info['bads']:<jupyter_code>picks = mne.pick_types(raw.info, meg=True, eeg=True, eog=True, stim=False,
                       exclude='bads')<jupyter_output><empty_output><jupyter_text>Alternatively one can restrict to magnetometers or gradiometers with:<jupyter_code>mag_picks = mne.pick_types(raw.info, meg='mag', eog=True, exclude='bads')
grad_picks = mne.pick_types(raw.info, meg='grad', eog=True, exclude='bads')<jupyter_output><empty_output><jupyter_text>Define the baseline period:<jupyter_code>baseline = (None, 0)  # means from the first instant to t = 0<jupyter_output><empty_output><jupyter_text>Define peak-to-peak rejection parameters for gradiometers, magnetometersand EOG:<jupyter_code>reject = dict(grad=4000e-13, mag=4e-12, eog=150e-6)<jupyter_output><empty_output><jupyter_text>Read epochs:<jupyter_code>epochs = mne.Epochs(raw, events, event_id, tmin, tmax, proj=True, picks=picks,
                    baseline=baseline, preload=False, reject=reject)
print(epochs)<jupyter_output><empty_output><jupyter_text>Get single epochs for one condition:<jupyter_code>epochs_data = epochs['aud_l'].get_data()
print(epochs_data.shape)<jupyter_output><empty_output><jupyter_text>epochs_data is a 3D array of dimension (55 epochs, 365 channels, 106 timeinstants).Scipy supports read and write of matlab files. You can save your singletrials with:<jupyter_code>from scipy import io  # noqa
io.savemat('epochs_data.mat', dict(epochs_data=epochs_data), oned_as='row')<jupyter_output><empty_output><jupyter_text>or if you want to keep all the information about the data you can save yourepochs in a fif file:<jupyter_code>epochs.save('sample-epo.fif')<jupyter_output><empty_output><jupyter_text>and read them later with:<jupyter_code>saved_epochs = mne.read_epochs('sample-epo.fif')<jupyter_output><empty_output><jupyter_text>Compute evoked responses for auditory responses by averaging and plot it:<jupyter_code>evoked = epochs['aud_l'].average()
print(evoked)
evoked.plot()<jupyter_output><empty_output><jupyter_text>.. topic:: Exercise  1. Extract the max value of each epoch<jupyter_code>max_in_each_epoch = [e.max() for e in epochs['aud_l']]  # doctest:+ELLIPSIS
print(max_in_each_epoch[:4])  # doctest:+ELLIPSIS<jupyter_output><empty_output><jupyter_text>It is also possible to read evoked data stored in a fif file:<jupyter_code>evoked_fname = data_path + '/MEG/sample/sample_audvis-ave.fif'
evoked1 = mne.read_evokeds(
    evoked_fname, condition='Left Auditory', baseline=(None, 0), proj=True)<jupyter_output><empty_output><jupyter_text>Or another one stored in the same file:<jupyter_code>evoked2 = mne.read_evokeds(
    evoked_fname, condition='Right Auditory', baseline=(None, 0), proj=True)<jupyter_output><empty_output><jupyter_text>Two evoked objects can be contrasted using :func:`mne.combine_evoked`.This function can use ``weights='equal'``, which provides a simpleelement-by-element subtraction (and sets the``mne.Evoked.nave`` attribute properly based on the underlying numberof trials) using either equivalent call:<jupyter_code>contrast = mne.combine_evoked([evoked1, evoked2], weights=[0.5, -0.5])
contrast = mne.combine_evoked([evoked1, -evoked2], weights='equal')
print(contrast)<jupyter_output><empty_output><jupyter_text>To do a weighted sum based on the number of averages, which will giveyou what you would have gotten from pooling all trials together in:class:`mne.Epochs` before creating the :class:`mne.Evoked` instance,you can use ``weights='nave'``:<jupyter_code>average = mne.combine_evoked([evoked1, evoked2], weights='nave')
print(contrast)<jupyter_output><empty_output><jupyter_text>Instead of dealing with mismatches in the number of averages, we can usetrial-count equalization before computing a contrast, which can have somebenefits in inverse imaging (note that here ``weights='nave'`` willgive the same result as ``weights='equal'``):<jupyter_code>epochs_eq = epochs.copy().equalize_event_counts(['aud_l', 'aud_r'])[0]
evoked1, evoked2 = epochs_eq['aud_l'].average(), epochs_eq['aud_r'].average()
print(evoked1)
print(evoked2)
contrast = mne.combine_evoked([evoked1, -evoked2], weights='equal')
print(contrast)<jupyter_output><empty_output><jupyter_text>Time-Frequency: Induced power and inter trial coherence^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^Define parameters:<jupyter_code>import numpy as np  # noqa
n_cycles = 2  # number of cycles in Morlet wavelet
freqs = np.arange(7, 30, 3)  # frequencies of interest<jupyter_output><empty_output><jupyter_text>Compute induced power and phase-locking values and plot gradiometers:<jupyter_code>from mne.time_frequency import tfr_morlet  # noqa
power, itc = tfr_morlet(epochs, freqs=freqs, n_cycles=n_cycles,
                        return_itc=True, decim=3, n_jobs=1)
power.plot([power.ch_names.index('MEG 1332')])<jupyter_output><empty_output><jupyter_text>Inverse modeling: MNE and dSPM on evoked and raw data^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^Import the required functions:<jupyter_code>from mne.minimum_norm import apply_inverse, read_inverse_operator  # noqa<jupyter_output><empty_output><jupyter_text>Read the inverse operator:<jupyter_code>fname_inv = data_path + '/MEG/sample/sample_audvis-meg-oct-6-meg-inv.fif'
inverse_operator = read_inverse_operator(fname_inv)<jupyter_output><empty_output><jupyter_text>Define the inverse parameters:<jupyter_code>snr = 3.0
lambda2 = 1.0 / snr ** 2
method = "dSPM"<jupyter_output><empty_output><jupyter_text>Compute the inverse solution:<jupyter_code>stc = apply_inverse(evoked, inverse_operator, lambda2, method)<jupyter_output><empty_output><jupyter_text>Save the source time courses to disk:<jupyter_code>stc.save('mne_dSPM_inverse')<jupyter_output><empty_output><jupyter_text>Now, let's compute dSPM on a raw file within a label:<jupyter_code>fname_label = data_path + '/MEG/sample/labels/Aud-lh.label'
label = mne.read_label(fname_label)<jupyter_output><empty_output><jupyter_text>Compute inverse solution during the first 15s:<jupyter_code>from mne.minimum_norm import apply_inverse_raw  # noqa
start, stop = raw.time_as_index([0, 15])  # read the first 15s of data
stc = apply_inverse_raw(raw, inverse_operator, lambda2, method, label,
                        start, stop)<jupyter_output><empty_output><jupyter_text>Save result in stc files:<jupyter_code>stc.save('mne_dSPM_raw_inverse_Aud')<jupyter_output><empty_output><jupyter_text>What else can you do?^^^^^^^^^^^^^^^^^^^^^    - detect heart beat QRS component    - detect eye blinks and EOG artifacts    - compute SSP projections to remove ECG or EOG artifacts    - compute Independent Component Analysis (ICA) to remove artifacts or      select latent sources    - estimate noise covariance matrix from Raw and Epochs    - visualize cross-trial response dynamics using epochs images    - compute forward solutions    - estimate power in the source space    - estimate connectivity in sensor and source space    - morph stc from one brain to another for group studies    - compute mass univariate statistics base on custom contrasts    - visualize source estimates    - export raw, epochs, and evoked data to other python data analysis      libraries e.g. pandas    - and many more things ...Want to know more ?^^^^^^^^^^^^^^^^^^^Browse `the examples gallery `_.<jupyter_code>print("Done!")<jupyter_output><empty_output>
{'fraction_non_alphanumeric': 0.12342569269521411, 'fraction_numerical': 0.009931630082763584, 'mean_word_length': 5.835218888342351, 'pattern_counts': {'":': 0, '<': 165, '<?xml version=': 0, '>': 165, 'https://': 0, 'lorem ipsum': 0, 'www.': 0, 'xml': 0}, 'pii_count': 0, 'substrings_counts': 0, 'word_list_counts': {'cursed_substrings.json': 3, 'profanity_word_list.json': 0, 'sexual_word_list.json': 0, 'zh_pornsignals.json': 0}}
{'chain_length': '41', 'dir': 'jupyter-structured-clean-dedup', 'id': '172348', 'license': 'BSD-3-Clause', 'n_tokens_mistral': 4636, 'n_tokens_neox': 4397, 'n_words': 1221, 'path': '0.14/_downloads/plot_introduction.ipynb', 'repo_name': 'drammock/mne-tools.github.io', 'size': '13895'}