{ "cells": [ { "cell_type": "markdown", "metadata": {}, "source": [ "\n\n# The Raw data structure: continuous data\n\nThis tutorial covers the basics of working with raw EEG/MEG data in Python. It\nintroduces the :class:`~mne.io.Raw` data structure in detail, including how to\nload, query, subselect, export, and plot data from a :class:`~mne.io.Raw`\nobject. For more info on visualization of :class:`~mne.io.Raw` objects, see\n`tut-visualize-raw`. For info on creating a :class:`~mne.io.Raw` object\nfrom simulated data in a :class:`NumPy array `, see\n`tut-creating-data-structures`.\n\nAs usual we'll start by importing the modules we need:\n" ] }, { "cell_type": "code", "execution_count": null, "metadata": { "collapsed": false }, "outputs": [], "source": [ "# Authors: The MNE-Python contributors.\n# License: BSD-3-Clause\n# Copyright the MNE-Python contributors." ] }, { "cell_type": "code", "execution_count": null, "metadata": { "collapsed": false }, "outputs": [], "source": [ "import os\n\nimport matplotlib.pyplot as plt\nimport numpy as np\n\nimport mne" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "## Loading continuous data\n\n.. admonition:: Datasets in MNE-Python\n :class: sidebar note\n\n There are ``data_path`` functions for several example datasets in\n MNE-Python (e.g., :func:`mne.datasets.kiloword.data_path`,\n :func:`mne.datasets.spm_face.data_path`, etc). All of them will check the\n default download location first to see if the dataset is already on your\n computer, and only download it if necessary. The default download\n location is also configurable; see the documentation of any of the\n ``data_path`` functions for more information.\n\nAs mentioned in `the introductory tutorial `,\nMNE-Python data structures are based around\nthe :file:`.fif` file format from Neuromag. This tutorial uses an\n`example dataset ` in :file:`.fif` format, so here we'll\nuse the function :func:`mne.io.read_raw_fif` to load the raw data; there are\nreader functions for `a wide variety of other data formats\n` as well.\n\nThere are also `several other example datasets\n` that can be downloaded with just a few lines\nof code. Functions for downloading example datasets are in the\n:mod:`mne.datasets` submodule; here we'll use\n:func:`mne.datasets.sample.data_path` to download the \"`sample-dataset`\"\ndataset, which contains EEG, MEG, and structural MRI data from one subject\nperforming an audiovisual experiment. When it's done downloading,\n:func:`~mne.datasets.sample.data_path` will return the folder location where\nit put the files; you can navigate there with your file browser if you want\nto examine the files yourself. Once we have the file path, we can load the\ndata with :func:`~mne.io.read_raw_fif`. This will return a\n:class:`~mne.io.Raw` object, which we'll store in a variable called ``raw``.\n\n" ] }, { "cell_type": "code", "execution_count": null, "metadata": { "collapsed": false }, "outputs": [], "source": [ "sample_data_folder = mne.datasets.sample.data_path()\nsample_data_raw_file = os.path.join(\n sample_data_folder, \"MEG\", \"sample\", \"sample_audvis_raw.fif\"\n)\nraw = mne.io.read_raw_fif(sample_data_raw_file)" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "As you can see above, :func:`~mne.io.read_raw_fif` automatically displays\nsome information about the file it's loading. For example, here it tells us\nthat there are three \"projection items\" in the file along with the recorded\ndata; those are :term:`SSP projectors ` calculated to remove\nenvironmental noise from the MEG signals, and are discussed in a the tutorial\n`tut-projectors-background`.\nIn addition to the information displayed during loading, you can\nget a glimpse of the basic details of a :class:`~mne.io.Raw` object by\nprinting it:\n\n" ] }, { "cell_type": "code", "execution_count": null, "metadata": { "collapsed": false }, "outputs": [], "source": [ "print(raw)" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "By default, the :samp:`mne.io.read_raw_{*}` family of functions will *not*\nload the data into memory (instead the data on disk are `memory-mapped`_,\nmeaning the data are only read from disk as-needed). Some operations (such as\nfiltering) require that the data be copied into RAM; to do that we could have\npassed the ``preload=True`` parameter to :func:`~mne.io.read_raw_fif`, but we\ncan also copy the data into RAM at any time using the\n:meth:`~mne.io.Raw.load_data` method. However, since this particular tutorial\ndoesn't do any serious analysis of the data, we'll first\n:meth:`~mne.io.Raw.crop` the :class:`~mne.io.Raw` object to 60 seconds so it\nuses less memory and runs more smoothly on our documentation server.\n\n" ] }, { "cell_type": "code", "execution_count": null, "metadata": { "collapsed": false }, "outputs": [], "source": [ "raw.crop(tmax=60)" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "## Querying the Raw object\n\n.. admonition:: Attributes vs. Methods\n :class: sidebar hint\n\n **Attributes** are usually static properties of Python objects \u2014 things\n that are pre-computed and stored as part of the object's representation\n in memory. Attributes are accessed with the ``.`` operator and do not\n require parentheses after the attribute name (example: ``raw.ch_names``).\n\n **Methods** are like specialized functions attached to an object.\n Usually they require additional user input and/or need some computation\n to yield a result. Methods always have parentheses at the end; additional\n arguments (if any) go inside those parentheses (examples:\n ``raw.estimate_rank()``, ``raw.drop_channels(['EEG 030', 'MEG 2242'])``).\n\nWe saw above that printing the :class:`~mne.io.Raw` object displays some\nbasic information like the total number of channels, the number of time\npoints at which the data were sampled, total duration, and the approximate\nsize in memory. Much more information is available through the various\n*attributes* and *methods* of the :class:`~mne.io.Raw` class. Some useful\nattributes of :class:`~mne.io.Raw` objects include a list of the channel\nnames (:attr:`~mne.io.Raw.ch_names`), an array of the sample times in seconds\n(:attr:`~mne.io.Raw.times`), and the total number of samples\n(:attr:`~mne.io.Raw.n_times`); a list of all attributes and methods is given\nin the documentation of the :class:`~mne.io.Raw` class.\n\n\n### The ``Raw.info`` attribute\n\nThere is also quite a lot of information stored in the ``raw.info``\nattribute, which stores an :class:`~mne.Info` object that is similar to a\n:class:`Python dictionary ` (in that it has fields accessed via named\nkeys). Like Python dictionaries, ``raw.info`` has a ``.keys()`` method that\nshows all the available field names; unlike Python dictionaries, printing\n``raw.info`` will print a nicely-formatted glimpse of each field's data. See\n`tut-info-class` for more on what is stored in :class:`~mne.Info`\nobjects, and how to interact with them.\n\n" ] }, { "cell_type": "code", "execution_count": null, "metadata": { "collapsed": false }, "outputs": [], "source": [ "n_time_samps = raw.n_times\ntime_secs = raw.times\nch_names = raw.ch_names\nn_chan = len(ch_names) # note: there is no raw.n_channels attribute\nprint(\n f\"the (cropped) sample data object has {n_time_samps} time samples and \"\n f\"{n_chan} channels.\"\n)\nprint(f\"The last time sample is at {time_secs[-1]} seconds.\")\nprint(\"The first few channel names are {}.\".format(\", \".join(ch_names[:3])))\nprint() # insert a blank line in the output\n\n# some examples of raw.info:\nprint(\"bad channels:\", raw.info[\"bads\"]) # chs marked \"bad\" during acquisition\nprint(raw.info[\"sfreq\"], \"Hz\") # sampling frequency\nprint(raw.info[\"description\"], \"\\n\") # miscellaneous acquisition info\n\nprint(raw.info)" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "

Note

Most of the fields of ``raw.info`` reflect metadata recorded at\n acquisition time, and should not be changed by the user. There are a few\n exceptions (such as ``raw.info['bads']`` and ``raw.info['projs']``), but\n in most cases there are dedicated MNE-Python functions or methods to\n update the :class:`~mne.Info` object safely (such as\n :meth:`~mne.io.Raw.add_proj` to update ``raw.info['projs']``).

\n\n\n### Time, sample number, and sample index\n\n.. admonition:: Sample numbering in VectorView data\n :class: sidebar warning\n\n For data from VectorView systems, it is important to distinguish *sample\n number* from *sample index*. See :term:`first_samp` for more information.\n\nOne method of :class:`~mne.io.Raw` objects that is frequently useful is\n:meth:`~mne.io.Raw.time_as_index`, which converts a time (in seconds) into\nthe integer index of the sample occurring closest to that time. The method\ncan also take a list or array of times, and will return an array of indices.\n\nIt is important to remember that there may not be a data sample at *exactly*\nthe time requested, so the number of samples between ``time = 1`` second and\n``time = 2`` seconds may be different than the number of samples between\n``time = 2`` and ``time = 3``:\n\n" ] }, { "cell_type": "code", "execution_count": null, "metadata": { "collapsed": false }, "outputs": [], "source": [ "print(raw.time_as_index(20))\nprint(raw.time_as_index([20, 30, 40]), \"\\n\")\n\nprint(np.diff(raw.time_as_index([1, 2, 3])))" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "## Modifying ``Raw`` objects\n\n.. admonition:: ``len(raw)``\n :class: sidebar warning\n\n Although the :class:`~mne.io.Raw` object underlyingly stores data samples\n in a :class:`NumPy array ` of shape (n_channels,\n n_timepoints), the :class:`~mne.io.Raw` object behaves differently from\n :class:`NumPy arrays ` with respect to the :func:`len`\n function. ``len(raw)`` will return the number of timepoints (length along\n data axis 1), not the number of channels (length along data axis 0).\n Hence in this section you'll see ``len(raw.ch_names)`` to get the number\n of channels.\n\n:class:`~mne.io.Raw` objects have a number of methods that modify the\n:class:`~mne.io.Raw` instance in-place and return a reference to the modified\ninstance. This can be useful for `method chaining`_\n(e.g., ``raw.crop(...).pick(...).filter(...).plot()``)\nbut it also poses a problem during interactive analysis: if you modify your\n:class:`~mne.io.Raw` object for an exploratory plot or analysis (say, by\ndropping some channels), you will then need to re-load the data (and repeat\nany earlier processing steps) to undo the channel-dropping and try something\nelse. For that reason, the examples in this section frequently use the\n:meth:`~mne.io.Raw.copy` method before the other methods being demonstrated,\nso that the original :class:`~mne.io.Raw` object is still available in the\nvariable ``raw`` for use in later examples.\n\n\n### Selecting, dropping, and reordering channels\nAltering the channels of a :class:`~mne.io.Raw` object can be done in several\nways. As a first example, we'll use the :meth:`~mne.io.Raw.pick` method\nto restrict the :class:`~mne.io.Raw` object to just the EEG and EOG channels:\n\n" ] }, { "cell_type": "code", "execution_count": null, "metadata": { "collapsed": false }, "outputs": [], "source": [ "eeg_and_eog = raw.copy().pick(picks=[\"eeg\", \"eog\"])\nprint(len(raw.ch_names), \"\u2192\", len(eeg_and_eog.ch_names))" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "In addition, :meth:`~mne.io.Raw.pick` can also be used to pick channels by name, and a\ncorresponding :meth:`~mne.io.Raw.drop_channels` method to remove channels by\nname:\n\n" ] }, { "cell_type": "code", "execution_count": null, "metadata": { "collapsed": false }, "outputs": [], "source": [ "raw_temp = raw.copy()\nprint(\"Number of channels in raw_temp:\")\nprint(len(raw_temp.ch_names), end=\" \u2192 drop two \u2192 \")\nraw_temp.drop_channels([\"EEG 037\", \"EEG 059\"])\nprint(len(raw_temp.ch_names), end=\" \u2192 pick three \u2192 \")\nraw_temp.pick([\"MEG 1811\", \"EEG 017\", \"EOG 061\"])\nprint(len(raw_temp.ch_names))" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "If you want the channels in a specific order (e.g., for plotting),\n:meth:`~mne.io.Raw.reorder_channels` works just like\n:meth:`~mne.io.Raw.pick` but also reorders the channels; for\nexample, here we pick the EOG and frontal EEG channels, putting the EOG\nfirst and the EEG in reverse order:\n\n" ] }, { "cell_type": "code", "execution_count": null, "metadata": { "collapsed": false }, "outputs": [], "source": [ "channel_names = [\"EOG 061\", \"EEG 003\", \"EEG 002\", \"EEG 001\"]\neog_and_frontal_eeg = raw.copy().reorder_channels(channel_names)\nprint(eog_and_frontal_eeg.ch_names)" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "### Changing channel name and type\n\n.. admonition:: Long channel names\n :class: sidebar note\n\n Due to limitations in the :file:`.fif` file format (which MNE-Python uses\n to save :class:`~mne.io.Raw` objects), channel names are limited to a\n maximum of 15 characters.\n\nYou may have noticed that the EEG channel names in the sample data are\nnumbered rather than labelled according to a standard nomenclature such as\nthe [10-20](ten_twenty_) or [10-05](ten_oh_five_) systems, or perhaps it\nbothers you that the channel names contain spaces. It is possible to rename\nchannels using the :meth:`~mne.io.Raw.rename_channels` method, which takes a\nPython dictionary to map old names to new names. You need not rename all\nchannels at once; provide only the dictionary entries for the channels you\nwant to rename. Here's a frivolous example:\n\n" ] }, { "cell_type": "code", "execution_count": null, "metadata": { "collapsed": false }, "outputs": [], "source": [ "raw.rename_channels({\"EOG 061\": \"blink detector\"})" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "This next example replaces spaces in the channel names with underscores,\nusing a Python `dict comprehension`_:\n\n" ] }, { "cell_type": "code", "execution_count": null, "metadata": { "collapsed": false }, "outputs": [], "source": [ "print(raw.ch_names[-3:])\nchannel_renaming_dict = {name: name.replace(\" \", \"_\") for name in raw.ch_names}\nraw.rename_channels(channel_renaming_dict)\nprint(raw.ch_names[-3:])" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "If for some reason the channel types in your :class:`~mne.io.Raw` object are\ninaccurate, you can change the type of any channel with the\n:meth:`~mne.io.Raw.set_channel_types` method. The method takes a\n:class:`dictionary ` mapping channel names to types; allowed types are\n``bio, chpi, csd, dbs, dipole, ecg, ecog, eeg, emg, eog, exci, eyegaze,\nfnirs_cw_amplitude, fnirs_fd_ac_amplitude, fnirs_fd_phase, fnirs_od, gof,\ngsr, hbo, hbr, ias, misc, pupil, ref_meg, resp, seeg, stim, syst,\ntemperature`` (see :term:`sensor types` for more information about them).\nA common use case for changing channel type is when using frontal EEG\nelectrodes as makeshift EOG channels:\n\n" ] }, { "cell_type": "code", "execution_count": null, "metadata": { "collapsed": false }, "outputs": [], "source": [ "raw.set_channel_types({\"EEG_001\": \"eog\"})\nprint(raw.copy().pick(picks=\"eog\").ch_names)" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "### Selection in the time domain\n\nIf you want to limit the time domain of a :class:`~mne.io.Raw` object, you\ncan use the :meth:`~mne.io.Raw.crop` method, which modifies the\n:class:`~mne.io.Raw` object in place (we've seen this already at the start of\nthis tutorial, when we cropped the :class:`~mne.io.Raw` object to 60 seconds\nto reduce memory demands). :meth:`~mne.io.Raw.crop` takes parameters ``tmin``\nand ``tmax``, both in seconds (here we'll again use :meth:`~mne.io.Raw.copy`\nfirst to avoid changing the original :class:`~mne.io.Raw` object):\n\n" ] }, { "cell_type": "code", "execution_count": null, "metadata": { "collapsed": false }, "outputs": [], "source": [ "raw_selection = raw.copy().crop(tmin=10, tmax=12.5)\nprint(raw_selection)" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ ":meth:`~mne.io.Raw.crop` also modifies the :attr:`~mne.io.Raw.first_samp` and\n:attr:`~mne.io.Raw.times` attributes, so that the first sample of the cropped\nobject now corresponds to ``time = 0``. Accordingly, if you wanted to re-crop\n``raw_selection`` from 11 to 12.5 seconds (instead of 10 to 12.5 as above)\nthen the subsequent call to :meth:`~mne.io.Raw.crop` should get ``tmin=1``\n(not ``tmin=11``), and leave ``tmax`` unspecified to keep everything from\n``tmin`` up to the end of the object:\n\n" ] }, { "cell_type": "code", "execution_count": null, "metadata": { "collapsed": false }, "outputs": [], "source": [ "print(raw_selection.times.min(), raw_selection.times.max())\nraw_selection.crop(tmin=1)\nprint(raw_selection.times.min(), raw_selection.times.max())" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "Remember that sample times don't always align exactly with requested ``tmin``\nor ``tmax`` values (due to sampling), which is why the ``max`` values of the\ncropped files don't exactly match the requested ``tmax`` (see\n`time-as-index` for further details).\n\nIf you need to select discontinuous spans of a :class:`~mne.io.Raw` object \u2014\nor combine two or more separate :class:`~mne.io.Raw` objects \u2014 you can use\nthe :meth:`~mne.io.Raw.append` method:\n\n" ] }, { "cell_type": "code", "execution_count": null, "metadata": { "collapsed": false }, "outputs": [], "source": [ "raw_selection1 = raw.copy().crop(tmin=30, tmax=30.1) # 0.1 seconds\nraw_selection2 = raw.copy().crop(tmin=40, tmax=41.1) # 1.1 seconds\nraw_selection3 = raw.copy().crop(tmin=50, tmax=51.3) # 1.3 seconds\nraw_selection1.append([raw_selection2, raw_selection3]) # 2.5 seconds total\nprint(raw_selection1.times.min(), raw_selection1.times.max())" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "

Warning

Be careful when concatenating :class:`~mne.io.Raw` objects from different\n recordings, especially when saving: :meth:`~mne.io.Raw.append` only\n preserves the ``info`` attribute of the initial :class:`~mne.io.Raw`\n object (the one outside the :meth:`~mne.io.Raw.append` method call).

\n\n\n## Extracting data from ``Raw`` objects\n\nSo far we've been looking at ways to modify a :class:`~mne.io.Raw` object.\nThis section shows how to extract the data from a :class:`~mne.io.Raw` object\ninto a :class:`NumPy array `, for analysis or plotting using\nfunctions outside of MNE-Python. To select portions of the data,\n:class:`~mne.io.Raw` objects can be indexed using square brackets. However,\nindexing :class:`~mne.io.Raw` works differently than indexing a :class:`NumPy\narray ` in two ways:\n\n1. Along with the requested sample value(s) MNE-Python also returns an array\n of times (in seconds) corresponding to the requested samples. The data\n array and the times array are returned together as elements of a tuple.\n\n2. The data array will always be 2-dimensional even if you request only a\n single time sample or a single channel.\n\n\n### Extracting data by index\n\nTo illustrate the above two points, let's select a couple seconds of data\nfrom the first channel:\n\n" ] }, { "cell_type": "code", "execution_count": null, "metadata": { "collapsed": false }, "outputs": [], "source": [ "sampling_freq = raw.info[\"sfreq\"]\nstart_stop_seconds = np.array([11, 13])\nstart_sample, stop_sample = (start_stop_seconds * sampling_freq).astype(int)\nchannel_index = 0\nraw_selection = raw[channel_index, start_sample:stop_sample]\nprint(raw_selection)" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "You can see that it contains 2 arrays. This combination of data and times\nmakes it easy to plot selections of raw data (although note that we're\ntransposing the data array so that each channel is a column instead of a row,\nto match what matplotlib expects when plotting 2-dimensional ``y`` against\n1-dimensional ``x``):\n\n" ] }, { "cell_type": "code", "execution_count": null, "metadata": { "collapsed": false }, "outputs": [], "source": [ "x = raw_selection[1]\ny = raw_selection[0].T\nplt.plot(x, y)" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "### Extracting channels by name\n\nThe :class:`~mne.io.Raw` object can also be indexed with the names of\nchannels instead of their index numbers. You can pass a single string to get\njust one channel, or a list of strings to select multiple channels. As with\ninteger indexing, this will return a tuple of ``(data_array, times_array)``\nthat can be easily plotted. Since we're plotting 2 channels this time, we'll\nadd a vertical offset to one channel so it's not plotted right on top\nof the other one:\n\n" ] }, { "cell_type": "code", "execution_count": null, "metadata": { "collapsed": false }, "outputs": [], "source": [ "channel_names = [\"MEG_0712\", \"MEG_1022\"]\ntwo_meg_chans = raw[channel_names, start_sample:stop_sample]\ny_offset = np.array([5e-11, 0]) # just enough to separate the channel traces\nx = two_meg_chans[1]\ny = two_meg_chans[0].T + y_offset\nlines = plt.plot(x, y)\nplt.legend(lines, channel_names)" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "### Extracting channels by type\n\nThere are several ways to select all channels of a given type from a\n:class:`~mne.io.Raw` object. The safest method is to use\n:func:`mne.pick_types` to obtain the integer indices of the channels you\nwant, then use those indices with the square-bracket indexing method shown\nabove. The :func:`~mne.pick_types` function uses the :class:`~mne.Info`\nattribute of the :class:`~mne.io.Raw` object to determine channel types, and\ntakes boolean or string parameters to indicate which type(s) to retain. The\n``meg`` parameter defaults to ``True``, and all others default to ``False``,\nso to get just the EEG channels, we pass ``eeg=True`` and ``meg=False``:\n\n" ] }, { "cell_type": "code", "execution_count": null, "metadata": { "collapsed": false }, "outputs": [], "source": [ "eeg_channel_indices = mne.pick_types(raw.info, meg=False, eeg=True)\neeg_data, times = raw[eeg_channel_indices]\nprint(eeg_data.shape)" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "Some of the parameters of :func:`mne.pick_types` accept string arguments as\nwell as booleans. For example, the ``meg`` parameter can take values\n``'mag'``, ``'grad'``, ``'planar1'``, or ``'planar2'`` to select only\nmagnetometers, all gradiometers, or a specific type of gradiometer. See the\ndocstring of :meth:`mne.pick_types` for full details.\n\n\n### The ``Raw.get_data()`` method\n\nIf you only want the data (not the corresponding array of times),\n:class:`~mne.io.Raw` objects have a :meth:`~mne.io.Raw.get_data` method. Used\nwith no parameters specified, it will extract all data from all channels, in\na (n_channels, n_timepoints) :class:`NumPy array `:\n\n" ] }, { "cell_type": "code", "execution_count": null, "metadata": { "collapsed": false }, "outputs": [], "source": [ "data = raw.get_data()\nprint(data.shape)" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "If you want the array of times, :meth:`~mne.io.Raw.get_data` has an optional\n``return_times`` parameter:\n\n" ] }, { "cell_type": "code", "execution_count": null, "metadata": { "collapsed": false }, "outputs": [], "source": [ "data, times = raw.get_data(return_times=True)\nprint(data.shape)\nprint(times.shape)" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "The :meth:`~mne.io.Raw.get_data` method can also be used to extract specific\nchannel(s) and sample ranges, via its ``picks``, ``start``, and ``stop``\nparameters. The ``picks`` parameter accepts integer channel indices, channel\nnames, or channel types, and preserves the requested channel order given as\nits ``picks`` parameter.\n\n" ] }, { "cell_type": "code", "execution_count": null, "metadata": { "collapsed": false }, "outputs": [], "source": [ "first_channel_data = raw.get_data(picks=0)\neeg_and_eog_data = raw.get_data(picks=[\"eeg\", \"eog\"])\ntwo_meg_chans_data = raw.get_data(picks=[\"MEG_0712\", \"MEG_1022\"], start=1000, stop=2000)\n\nprint(first_channel_data.shape)\nprint(eeg_and_eog_data.shape)\nprint(two_meg_chans_data.shape)" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "### Summary of ways to extract data from ``Raw`` objects\n\nThe following table summarizes the various ways of extracting data from a\n:class:`~mne.io.Raw` object.\n\n.. cssclass:: table-bordered\n.. rst-class:: midvalign\n\n+-------------------------------------+-------------------------+\n| Python code | Result |\n| | |\n| | |\n+=====================================+=========================+\n| ``raw.get_data()`` | :class:`NumPy array |\n| | ` |\n| | (n_chans \u00d7 n_samps) |\n+-------------------------------------+-------------------------+\n| ``raw[:]`` | :class:`tuple` of (data |\n+-------------------------------------+ (n_chans \u00d7 n_samps), |\n| ``raw.get_data(return_times=True)`` | times (1 \u00d7 n_samps)) |\n+-------------------------------------+-------------------------+\n| ``raw[0, 1000:2000]`` | |\n+-------------------------------------+ |\n| ``raw['MEG 0113', 1000:2000]`` | |\n+-------------------------------------+ |\n| ``raw.get_data(picks=0, | :class:`tuple` of |\n| start=1000, stop=2000, | (data (1 \u00d7 1000), |\n| return_times=True)`` | times (1 \u00d7 1000)) |\n+-------------------------------------+ |\n| ``raw.get_data(picks='MEG 0113', | |\n| start=1000, stop=2000, | |\n| return_times=True)`` | |\n+-------------------------------------+-------------------------+\n| ``raw[7:9, 1000:2000]`` | |\n+-------------------------------------+ |\n| ``raw[[2, 5], 1000:2000]`` | :class:`tuple` of |\n+-------------------------------------+ (data (2 \u00d7 1000), |\n| ``raw[['EEG 030', 'EOG 061'], | times (1 \u00d7 1000)) |\n| 1000:2000]`` | |\n+-------------------------------------+-------------------------+\n\n\n## Exporting and saving Raw objects\n\n:class:`~mne.io.Raw` objects have a built-in :meth:`~mne.io.Raw.save` method,\nwhich can be used to write a partially processed :class:`~mne.io.Raw` object\nto disk as a :file:`.fif` file, such that it can be re-loaded later with its\nvarious attributes intact (but see `precision` for an important\nnote about numerical precision when saving).\n\nThere are a few other ways to export just the sensor data from a\n:class:`~mne.io.Raw` object. One is to use indexing or the\n:meth:`~mne.io.Raw.get_data` method to extract the data, and use\n:func:`numpy.save` to save the data array:\n\n" ] }, { "cell_type": "code", "execution_count": null, "metadata": { "collapsed": false }, "outputs": [], "source": [ "data = raw.get_data()\nnp.save(file=\"my_data.npy\", arr=data)" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "It is also possible to export the data to a :class:`Pandas DataFrame\n` object, and use the saving methods that :mod:`Pandas\n` affords. The :class:`~mne.io.Raw` object's\n:meth:`~mne.io.Raw.to_data_frame` method is similar to\n:meth:`~mne.io.Raw.get_data` in that it has a ``picks`` parameter for\nrestricting which channels are exported, and ``start`` and ``stop``\nparameters for restricting the time domain. Note that, by default, times will\nbe converted to milliseconds, rounded to the nearest millisecond, and used as\nthe DataFrame index; see the ``scaling_time`` parameter in the documentation\nof :meth:`~mne.io.Raw.to_data_frame` for more details.\n\n" ] }, { "cell_type": "code", "execution_count": null, "metadata": { "collapsed": false }, "outputs": [], "source": [ "sampling_freq = raw.info[\"sfreq\"]\nstart_end_secs = np.array([10, 13])\nstart_sample, stop_sample = (start_end_secs * sampling_freq).astype(int)\ndf = raw.to_data_frame(picks=[\"eeg\"], start=start_sample, stop=stop_sample)\n# then save using df.to_csv(...), df.to_hdf(...), etc\nprint(df.head())" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "

Note

When exporting data as a :class:`NumPy array ` or\n :class:`Pandas DataFrame `, be sure to properly account\n for the `unit of representation ` in your subsequent\n analyses.

\n\n\n.. LINKS\n\n https://docs.python.org/3/tutorial/datastructures.html#dictionaries\n\n" ] } ], "metadata": { "kernelspec": { "display_name": "Python 3", "language": "python", "name": "python3" }, "language_info": { "codemirror_mode": { "name": "ipython", "version": 3 }, "file_extension": ".py", "mimetype": "text/x-python", "name": "python", "nbconvert_exporter": "python", "pygments_lexer": "ipython3", "version": "3.12.2" } }, "nbformat": 4, "nbformat_minor": 0 }