<commit_before>.. _mne_python_tutorial:

=========================================================
Tutorial: MEG and EEG data processing with MNE and Python
=========================================================

Python offers transparent scripting on top of MNE.
It was designed to be an alternative to the MNE matlab toolbox
but now it can do much more (customize events, compute
contrasts, statistics, time-frequency analysis etc.)
It uses the same files as standard MNE unix commands:
no need to convert your files to a new system or database.

What you're not supposed to do with MNE Python
----------------------------------------------

    - **Forward modeling**: BEM computation and mesh creation (see :ref:`ch_forward`)

What you can do with MNE Python
-------------------------------

    - **Raw data visualization** to visualize recordings, can also use *mne_browse_raw* for extended functionality (see :ref:`ch_browse`)
    - **Epoching**: Define epochs, baseline correction, handle conditions etc.
    - **Averaging** to get Evoked data
    - **Compute SSP pojectors** to remove ECG and EOG artifacts
    - **Compute ICA** to remove artifacts or select latent sources.
    - **Linear inverse solvers** (dSPM, MNE)
    - **Connectivity estimation** in sensor and source space
    - **MNE source estimates visualization**
    - **Time-frequency** analysis with Morlet wavelets (induced power, phase lock value) also in the source space
    - **Spectrum estimation** using multi-taper method
    - **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)

.. note:: Package based on the FIF file format from Neuromag but can work with CTF and 4D after conversion to FIF.


Installation of the required materials
---------------------------------------

See :ref:`getting_started` with Python.

Get the code
^^^^^^^^^^^^

  You can manually get the latest version of the code at:

  https://github.com/mne-tools/mne-python

  Then from the mne-python folder (containing a setup.py file) you can install with::

      python setup.py install

  You can also install the latest release with easy_install::

      easy_install -U mne

  or with pip::

      pip install mne --upgrade

  For the latest development version (the most up to date)::

      pip install -e git+https://github.com/mne-tools/mne-python#egg=mne-dev


Make life easier
~~~~~~~~~~~~~~~~

  For optimal performance we recommend using numpy / scipy with the multi-threaded
  ATLAS, gotoblas2, or intel MKL. The EPD python distribution for example ships with
  tested MKL-compiled numpy / scipy versions. Depending on the use case and your system
  this may speed up operations by a factor greater than 10.

  The expected location for the MNE-sample data is my-path-to/mne-python/examples.
  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.py


From raw data to evoked data
----------------------------

.. _ipython: http://ipython.scipy.org/

Now, launch `ipython`_ (Advanced Python shell)::

  $ ipython -pylab -wthread

First, load the mne package:

    >>> import mne

If you'd like to turn information status messages off:

    >>> mne.set_log_level('WARNING')

But it's generally a good idea to leave them on:

    >>> mne.set_log_level('INFO')

You can set the default level by setting the environment variable
"MNE_LOGGING_LEVEL", or by having mne-python write preferences to a file:

    >>> mne.set_config('MNE_LOGGING_LEVEL','WARNING') # doctest: +SKIP

Note that the location of the mne-python preferences file (for easier manual
editing) can be found using:

    >>> mne.get_config_path() # doctest: +SKIP

By default logging messages print to the console, but look at
mne.set_log_file() to save output to a file.

Access raw data
^^^^^^^^^^^^^^^

    >>> from mne.datasets import sample
    >>> data_path = sample.data_path()
    >>> raw_fname = data_path + '/MEG/sample/sample_audvis_filt-0-40_raw.fif'
    >>> print raw_fname # doctest: +SKIP
    ./MNE-sample-data/MEG/sample/sample_audvis_filt-0-40_raw.fif

.. note:: The MNE sample dataset should be downloaded automatically but be patient (approx. 2GB)

Read data from file:

    >>> raw = mne.fiff.Raw(raw_fname) # doctest:+ELLIPSIS
    Opening raw data ...
    Ready.
    >>> print raw
    <Raw  |  n_channels x n_times : 376 x 41700>

Look at the channels in raw:

    >>> print raw.ch_names # doctest:+ELLIPSIS
    ['MEG 0113', 'MEG 0112', ...]

Read and plot a segment of raw data

    >>> start, stop = raw.time_as_index([100, 115])  # 100 s to 115 s data segment
    >>> data, times = raw[:, start:stop]
    Reading 15015 ... 17266  =     99.998 ...   114.989 secs...<commit_msg>ENH: add repr to tutorial<commit_after>.. _mne_python_tutorial:

=========================================================
Tutorial: MEG and EEG data processing with MNE and Python
=========================================================

Python offers transparent scripting on top of MNE.
It was designed to be an alternative to the MNE matlab toolbox
but now it can do much more (customize events, compute
contrasts, statistics, time-frequency analysis etc.)
It uses the same files as standard MNE unix commands:
no need to convert your files to a new system or database.

What you're not supposed to do with MNE Python
----------------------------------------------

    - **Forward modeling**: BEM computation and mesh creation (see :ref:`ch_forward`)

What you can do with MNE Python
-------------------------------

    - **Raw data visualization** to visualize recordings, can also use *mne_browse_raw* for extended functionality (see :ref:`ch_browse`)
    - **Epoching**: Define epochs, baseline correction, handle conditions etc.
    - **Averaging** to get Evoked data
    - **Compute SSP pojectors** to remove ECG and EOG artifacts
    - **Compute ICA** to remove artifacts or select latent sources.
    - **Linear inverse solvers** (dSPM, MNE)
    - **Connectivity estimation** in sensor and source space
    - **MNE source estimates visualization**
    - **Time-frequency** analysis with Morlet wavelets (induced power, phase lock value) also in the source space
    - **Spectrum estimation** using multi-taper method
    - **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)

.. note:: Package based on the FIF file format from Neuromag but can work with CTF and 4D after conversion to FIF.


Installation of the required materials
---------------------------------------

See :ref:`getting_started` with Python.

Get the code
^^^^^^^^^^^^

  You can manually get the latest version of the code at:

  https://github.com/mne-tools/mne-python

  Then from the mne-python folder (containing a setup.py file) you can install with::

      python setup.py install

  You can also install the latest release with easy_install::

      easy_install -U mne

  or with pip::

      pip install mne --upgrade

  For the latest development version (the most up to date)::

      pip install -e git+https://github.com/mne-tools/mne-python#egg=mne-dev


Make life easier
~~~~~~~~~~~~~~~~

  For optimal performance we recommend using numpy / scipy with the multi-threaded
  ATLAS, gotoblas2, or intel MKL. The EPD python distribution for example ships with
  tested MKL-compiled numpy / scipy versions. Depending on the use case and your system
  this may speed up operations by a factor greater than 10.

  The expected location for the MNE-sample data is my-path-to/mne-python/examples.
  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.py


From raw data to evoked data
----------------------------

.. _ipython: http://ipython.scipy.org/

Now, launch `ipython`_ (Advanced Python shell)::

  $ ipython -pylab -wthread

First, load the mne package:

    >>> import mne

If you'd like to turn information status messages off:

    >>> mne.set_log_level('WARNING')

But it's generally a good idea to leave them on:

    >>> mne.set_log_level('INFO')

You can set the default level by setting the environment variable
"MNE_LOGGING_LEVEL", or by having mne-python write preferences to a file:

    >>> mne.set_config('MNE_LOGGING_LEVEL','WARNING') # doctest: +SKIP

Note that the location of the mne-python preferences file (for easier manual
editing) can be found using:

    >>> mne.get_config_path() # doctest: +SKIP

By default logging messages print to the console, but look at
mne.set_log_file() to save output to a file.

Access raw data
^^^^^^^^^^^^^^^

    >>> from mne.datasets import sample
    >>> data_path = sample.data_path()
    >>> raw_fname = data_path + '/MEG/sample/sample_audvis_filt-0-40_raw.fif'
    >>> print raw_fname # doctest: +SKIP
    ./MNE-sample-data/MEG/sample/sample_audvis_filt-0-40_raw.fif

.. note:: The MNE sample dataset should be downloaded automatically but be patient (approx. 2GB)

Read data from file:

    >>> raw = mne.fiff.Raw(raw_fname) # doctest:+ELLIPSIS
    Opening raw data ...
    Ready.
    >>> print raw
    <Raw  |  n_channels x n_times : 376 x 41700>
    >>> print raw.info # doctest:+ELLIPSIS
    <Info | 19 non-empty ...

Look at the channels in raw:

    >>> print raw.ch_names # doctest:+ELLIPSIS
    ['MEG 0113', 'MEG 0112', ...]

Read and plot a segment of raw data

    >>> start, stop = raw.time_as_index([100, 115])  # 100 s to 115 s data segment
    >>> data, times = raw[:, start:stop]
    Reading 15015 ... 17266  =     99.998 ...   114.989 secs...
{'fraction_non_alphanumeric': 0.1408839779005525, 'fraction_numerical': 0.012036306235201263, 'mean_word_length': 3.2132169576059852, 'pattern_counts': {'":': 0, '<': 6, '<?xml version=': 0, '>': 92, 'https://': 4, 'lorem ipsum': 0, 'www.': 0, 'xml': 0}, 'pii_count': 0, 'substrings_counts': 0, 'word_list_counts': {'cursed_substrings.json': 6, 'profanity_word_list.json': 0, 'sexual_word_list.json': 0, 'zh_pornsignals.json': 0}}
{'dir': 'git-commits-cleaned', 'id': '4867305', 'n_tokens_mistral': 3072, 'n_tokens_neox': 2822, 'n_words': 1195}