Skip to content

Commit 69f2642

Browse files
committed
Make install
1 parent fc09b7b commit 69f2642

File tree

175 files changed

+10507
-9427
lines changed

Some content is hidden

Large Commits have some content hidden by default. Use the searchbox below for content that may be hidden.

175 files changed

+10507
-9427
lines changed
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,122 @@
1+
"""
2+
Interface with MNE-python
3+
-------------------------
4+
This example shows how to use this package with MNE-python.
5+
6+
It relies on the function ``raw_to_mask``, which takes as input a MNE.Raw
7+
instance and an events array, and returns the corresponding input signals
8+
and masks for the ``Comodulogram.fit`` method.
9+
"""
10+
import mne
11+
import numpy as np
12+
import os.path as op
13+
import matplotlib.pyplot as plt
14+
15+
from pactools import simulate_pac, raw_to_mask, Comodulogram, MaskIterator
16+
17+
###############################################################################
18+
# Simulate a dataset and save it out
19+
20+
n_events = 100
21+
mu = 1. # mean onset of PAC in seconds
22+
sigma = 0.25 # standard deviation of onset of PAC in seconds
23+
trial_len = 2. # len of the simulated trial in seconds
24+
first_samp = 5 # seconds before the first sample and after the last
25+
26+
fs = 200. # Hz
27+
high_fq = 50.0 # Hz
28+
low_fq = 3.0 # Hz
29+
low_fq_width = 2.0 # Hz
30+
31+
n_points = int(trial_len * fs)
32+
noise_level = 0.4
33+
34+
35+
def gaussian1d(array, mu, sigma):
36+
return np.exp(-0.5 * ((array - mu) / sigma) ** 2)
37+
38+
39+
# leave one channel for events and make signal as long as events
40+
# with a bit of room on either side so events don't get cut off
41+
signal = np.zeros((2, int(n_points * n_events + 2 * first_samp * fs)))
42+
events = np.zeros((n_events, 3), dtype=int)
43+
events[:, 0] = np.arange((first_samp + mu) * fs,
44+
n_points * n_events + (first_samp + mu) * fs,
45+
trial_len * fs, dtype=int)
46+
events[:, 2] = np.ones((n_events))
47+
mod_fun = gaussian1d(np.arange(n_points), mu * fs, sigma * fs)
48+
for i in range(n_events):
49+
signal_no_pac = simulate_pac(n_points=n_points, fs=fs,
50+
high_fq=high_fq, low_fq=low_fq,
51+
low_fq_width=low_fq_width,
52+
noise_level=1.0, random_state=i)
53+
signal_pac = simulate_pac(n_points=n_points, fs=fs,
54+
high_fq=high_fq, low_fq=low_fq,
55+
low_fq_width=low_fq_width,
56+
noise_level=noise_level, random_state=i)
57+
signal[0, i * n_points:(i + 1) * n_points] = \
58+
signal_pac * mod_fun + signal_no_pac * (1 - mod_fun)
59+
60+
info = mne.create_info(['Ch1', 'STI 014'], fs, ['eeg', 'stim'])
61+
raw = mne.io.RawArray(signal, info)
62+
raw.add_events(events, stim_channel='STI 014')
63+
64+
###############################################################################
65+
# Let's plot the signal and its power spectral density to visualize the data.
66+
# As shown in the plots below, there is a peak for the driver frequency at
67+
# 3 Hz and a peak for the carrier frequency at 50 Hz but phase-amplitude
68+
# coupling cannot be seen in the evoked plot by eye because the signal is
69+
# averaged over different phases for each epoch.
70+
71+
raw.plot_psd(fmax=60)
72+
epochs = mne.Epochs(raw, events, tmin=-3, tmax=3)
73+
epochs.average().plot()
74+
75+
###############################################################################
76+
# Let's save the raw object out for input/output demonstration purposes
77+
78+
root = mne.utils._TempDir()
79+
raw.save(op.join(root, 'pac_example-raw.fif'))
80+
81+
###############################################################################
82+
# Here we define how to build the epochs: which channels will be selected, and
83+
# on which time window around each event.
84+
85+
raw = mne.io.Raw(op.join(root, 'pac_example-raw.fif'))
86+
events = mne.find_events(raw)
87+
88+
# select the time interval around the events
89+
tmin, tmax = mu - 3 * sigma, mu + 3 * sigma
90+
# select the channels (phase_channel, amplitude_channel)
91+
ixs = (0, 0)
92+
93+
###############################################################################
94+
# Then, we create the inputs with the function raw_to_mask, which creates the
95+
# input arrays and the mask arrays. These arrays are then given to a
96+
# comodulogram instance with the `fit` method, and the `plot` method draws the
97+
# results.
98+
99+
# create the input array for Comodulogram.fit
100+
101+
low_sig, high_sig, mask = raw_to_mask(raw, ixs=ixs, events=events, tmin=tmin,
102+
tmax=tmax)
103+
104+
###############################################################################
105+
# The mask is an iterable which goes over the _unique_ events in the event
106+
# array (if it is 3D). PAC is estimated where the `mask` is `False`.
107+
# Alternatively, we could also compute the `MaskIterator` object directly.
108+
# This is useful if you want to compute PAC on other kinds of time series,
109+
# for example source time courses.
110+
111+
low_sig, high_sig = raw[ixs[0], :][0], raw[ixs[1], :][0]
112+
mask = MaskIterator(events, tmin, tmax, raw.n_times, raw.info['sfreq'])
113+
114+
# create the instance of Comodulogram
115+
estimator = Comodulogram(fs=raw.info['sfreq'],
116+
low_fq_range=np.linspace(1, 10, 20), low_fq_width=2.,
117+
method='duprelatour', progress_bar=True)
118+
# compute the comodulogram
119+
estimator.fit(low_sig, high_sig, mask)
120+
# plot the results
121+
estimator.plot(tight_layout=False)
122+
plt.show()

_downloads/plot_surrogate_analysis.ipynb _downloads/097c1388cc7c939f7e77c63c1613cf11/plot_surrogate_analysis.ipynb

+2-2
Original file line numberDiff line numberDiff line change
@@ -15,7 +15,7 @@
1515
"cell_type": "markdown",
1616
"metadata": {},
1717
"source": [
18-
"\nSurrogate analysis\n------------------\nThis example shows how to estimate a significance threshold in a comodulogram.\n\nA comodulogram shows the estimated PAC metric on a grid of frequency bands.\nIn absence of PAC, a PAC metric will return values close to zero, but not\nexactly zero. To estimate if a value is significantly far from zero, we use a\nsurrogate analysis.\n\nIn a surrogate analysis, we recompute the comodulogram many times, adding each\ntime a random time shift to remove any possible coupling between the\ncomponents. Nota that these time shifts have to be far from zero to effectively\nremove a potential coupling. These comodulograms give us an estimation of the\nfluctuation of the metric in the absence of PAC.\n\nTo derive a significance level from the list of comodulograms, we discuss here\ntwo different methods:\n- Computing a z-score on each couple of frequency, and thresholding at z = 4.\n- Computing a threshold at a given p-value, over a distribution of comodulogram\nmaxima.\n\n"
18+
"\nSurrogate analysis\n------------------\nThis example shows how to estimate a significance threshold in a comodulogram.\n\nA comodulogram shows the estimated PAC metric on a grid of frequency bands.\nIn absence of PAC, a PAC metric will return values close to zero, but not\nexactly zero. To estimate if a value is significantly far from zero, we use a\nsurrogate analysis.\n\nIn a surrogate analysis, we recompute the comodulogram many times, adding each\ntime a random time shift to remove any possible coupling between the\ncomponents. Nota that these time shifts have to be far from zero to effectively\nremove a potential coupling. These comodulograms give us an estimation of the\nfluctuation of the metric in the absence of PAC.\n\nTo derive a significance level from the list of comodulograms, we discuss here\ntwo different methods:\n- Computing a z-score on each couple of frequency, and thresholding at z = 4.\n- Computing a threshold at a given p-value, over a distribution of comodulogram\nmaxima.\n"
1919
]
2020
},
2121
{
@@ -161,7 +161,7 @@
161161
"name": "python",
162162
"nbconvert_exporter": "python",
163163
"pygments_lexer": "ipython3",
164-
"version": "3.6.2"
164+
"version": "3.8.1"
165165
}
166166
},
167167
"nbformat": 4,

_downloads/plot_phase_delay.ipynb _downloads/1698a7a11bdf113a93ec5f687e455c77/plot_phase_delay.ipynb

+2-2
Original file line numberDiff line numberDiff line change
@@ -15,7 +15,7 @@
1515
"cell_type": "markdown",
1616
"metadata": {},
1717
"source": [
18-
"\nPhase shift and temporal delay in PAC\n-------------------------------------\n\nThis example disantangles the two distinct notions of phase shift and temporal\ndelay in phase-amplitude coupling. The phase shift ($\\phi$) is the phase of the\nslow oscillation which corresponds to the maximum amplitude of the fast\noscillation. The temporal delay ($\\tau$) is the delay between the two coupled\ncomponents. The two notions would be identical should the driver be a perfect\nstationary sinusoid.\n\n(1st line) When both are equal to zero, the high frequency bursts happen in\nthe driver's peaks.\n\n(2nd line) When $\\tau = 0$ and $\\phi != 0$, the bursts are shifted in time with\nrespect to the driver's peaks, and this shift varies depending on the\ninstantaneous frequency of the driver.\n\n(3rd line) When $\\tau != 0$ and $\\phi = 0$, the bursts are shifted in time with\nrespect to the driver's peaks, and this shift is constant over the signal. In\nthis case, note how the driver's phase corresponding to the bursts varies\ndepending on the instantaneous frequency of the driver.\n\n(4th line) Both $\\tau$ and $\\phi$ can also be both non-zero.\n\nThe temporal delay is estimated maximizing the likelihood on DAR models.\nThe phase shift is extracted from a DAR model fitted with the optimal\ntemporal delay.\n\nReferences\n==========\nDupre la Tour et al. (2017). Non-linear Auto-Regressive Models for\nCross-Frequency Coupling in Neural Time Series. bioRxiv, 159731.\n\n"
18+
"\nPhase shift and temporal delay in PAC\n-------------------------------------\n\nThis example disantangles the two distinct notions of phase shift and temporal\ndelay in phase-amplitude coupling. The phase shift ($\\phi$) is the phase of the\nslow oscillation which corresponds to the maximum amplitude of the fast\noscillation. The temporal delay ($\\tau$) is the delay between the two coupled\ncomponents. The two notions would be identical should the driver be a perfect\nstationary sinusoid.\n\n(1st line) When both are equal to zero, the high frequency bursts happen in\nthe driver's peaks.\n\n(2nd line) When $\\tau = 0$ and $\\phi != 0$, the bursts are shifted in time with\nrespect to the driver's peaks, and this shift varies depending on the\ninstantaneous frequency of the driver.\n\n(3rd line) When $\\tau != 0$ and $\\phi = 0$, the bursts are shifted in time with\nrespect to the driver's peaks, and this shift is constant over the signal. In\nthis case, note how the driver's phase corresponding to the bursts varies\ndepending on the instantaneous frequency of the driver.\n\n(4th line) Both $\\tau$ and $\\phi$ can also be both non-zero.\n\nThe temporal delay is estimated maximizing the likelihood on DAR models.\nThe phase shift is extracted from a DAR model fitted with the optimal\ntemporal delay.\n\nReferences\n==========\nDupre la Tour et al. (2017). Non-linear Auto-Regressive Models for\nCross-Frequency Coupling in Neural Time Series. bioRxiv, 159731.\n"
1919
]
2020
},
2121
{
@@ -46,7 +46,7 @@
4646
"name": "python",
4747
"nbconvert_exporter": "python",
4848
"pygments_lexer": "ipython3",
49-
"version": "3.6.2"
49+
"version": "3.8.1"
5050
}
5151
},
5252
"nbformat": 4,
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,162 @@
1+
{
2+
"cells": [
3+
{
4+
"cell_type": "code",
5+
"execution_count": null,
6+
"metadata": {
7+
"collapsed": false
8+
},
9+
"outputs": [],
10+
"source": [
11+
"%matplotlib inline"
12+
]
13+
},
14+
{
15+
"cell_type": "markdown",
16+
"metadata": {},
17+
"source": [
18+
"\nInterface with MNE-python\n-------------------------\nThis example shows how to use this package with MNE-python.\n\nIt relies on the function ``raw_to_mask``, which takes as input a MNE.Raw\ninstance and an events array, and returns the corresponding input signals\nand masks for the ``Comodulogram.fit`` method.\n"
19+
]
20+
},
21+
{
22+
"cell_type": "code",
23+
"execution_count": null,
24+
"metadata": {
25+
"collapsed": false
26+
},
27+
"outputs": [],
28+
"source": [
29+
"import mne\nimport numpy as np\nimport os.path as op\nimport matplotlib.pyplot as plt\n\nfrom pactools import simulate_pac, raw_to_mask, Comodulogram, MaskIterator"
30+
]
31+
},
32+
{
33+
"cell_type": "markdown",
34+
"metadata": {},
35+
"source": [
36+
"Simulate a dataset and save it out\n\n"
37+
]
38+
},
39+
{
40+
"cell_type": "code",
41+
"execution_count": null,
42+
"metadata": {
43+
"collapsed": false
44+
},
45+
"outputs": [],
46+
"source": [
47+
"n_events = 100\nmu = 1. # mean onset of PAC in seconds\nsigma = 0.25 # standard deviation of onset of PAC in seconds\ntrial_len = 2. # len of the simulated trial in seconds\nfirst_samp = 5 # seconds before the first sample and after the last\n\nfs = 200. # Hz\nhigh_fq = 50.0 # Hz\nlow_fq = 3.0 # Hz\nlow_fq_width = 2.0 # Hz\n\nn_points = int(trial_len * fs)\nnoise_level = 0.4\n\n\ndef gaussian1d(array, mu, sigma):\n return np.exp(-0.5 * ((array - mu) / sigma) ** 2)\n\n\n# leave one channel for events and make signal as long as events\n# with a bit of room on either side so events don't get cut off\nsignal = np.zeros((2, int(n_points * n_events + 2 * first_samp * fs)))\nevents = np.zeros((n_events, 3), dtype=int)\nevents[:, 0] = np.arange((first_samp + mu) * fs,\n n_points * n_events + (first_samp + mu) * fs,\n trial_len * fs, dtype=int)\nevents[:, 2] = np.ones((n_events))\nmod_fun = gaussian1d(np.arange(n_points), mu * fs, sigma * fs)\nfor i in range(n_events):\n signal_no_pac = simulate_pac(n_points=n_points, fs=fs,\n high_fq=high_fq, low_fq=low_fq,\n low_fq_width=low_fq_width,\n noise_level=1.0, random_state=i)\n signal_pac = simulate_pac(n_points=n_points, fs=fs,\n high_fq=high_fq, low_fq=low_fq,\n low_fq_width=low_fq_width,\n noise_level=noise_level, random_state=i)\n signal[0, i * n_points:(i + 1) * n_points] = \\\n signal_pac * mod_fun + signal_no_pac * (1 - mod_fun)\n\ninfo = mne.create_info(['Ch1', 'STI 014'], fs, ['eeg', 'stim'])\nraw = mne.io.RawArray(signal, info)\nraw.add_events(events, stim_channel='STI 014')"
48+
]
49+
},
50+
{
51+
"cell_type": "markdown",
52+
"metadata": {},
53+
"source": [
54+
"Let's plot the signal and its power spectral density to visualize the data.\nAs shown in the plots below, there is a peak for the driver frequency at\n3 Hz and a peak for the carrier frequency at 50 Hz but phase-amplitude\ncoupling cannot be seen in the evoked plot by eye because the signal is\naveraged over different phases for each epoch.\n\n"
55+
]
56+
},
57+
{
58+
"cell_type": "code",
59+
"execution_count": null,
60+
"metadata": {
61+
"collapsed": false
62+
},
63+
"outputs": [],
64+
"source": [
65+
"raw.plot_psd(fmax=60)\nepochs = mne.Epochs(raw, events, tmin=-3, tmax=3)\nepochs.average().plot()"
66+
]
67+
},
68+
{
69+
"cell_type": "markdown",
70+
"metadata": {},
71+
"source": [
72+
"Let's save the raw object out for input/output demonstration purposes\n\n"
73+
]
74+
},
75+
{
76+
"cell_type": "code",
77+
"execution_count": null,
78+
"metadata": {
79+
"collapsed": false
80+
},
81+
"outputs": [],
82+
"source": [
83+
"root = mne.utils._TempDir()\nraw.save(op.join(root, 'pac_example-raw.fif'))"
84+
]
85+
},
86+
{
87+
"cell_type": "markdown",
88+
"metadata": {},
89+
"source": [
90+
"Here we define how to build the epochs: which channels will be selected, and\non which time window around each event.\n\n"
91+
]
92+
},
93+
{
94+
"cell_type": "code",
95+
"execution_count": null,
96+
"metadata": {
97+
"collapsed": false
98+
},
99+
"outputs": [],
100+
"source": [
101+
"raw = mne.io.Raw(op.join(root, 'pac_example-raw.fif'))\nevents = mne.find_events(raw)\n\n# select the time interval around the events\ntmin, tmax = mu - 3 * sigma, mu + 3 * sigma\n# select the channels (phase_channel, amplitude_channel)\nixs = (0, 0)"
102+
]
103+
},
104+
{
105+
"cell_type": "markdown",
106+
"metadata": {},
107+
"source": [
108+
"Then, we create the inputs with the function raw_to_mask, which creates the\ninput arrays and the mask arrays. These arrays are then given to a\ncomodulogram instance with the `fit` method, and the `plot` method draws the\nresults.\n\n"
109+
]
110+
},
111+
{
112+
"cell_type": "code",
113+
"execution_count": null,
114+
"metadata": {
115+
"collapsed": false
116+
},
117+
"outputs": [],
118+
"source": [
119+
"# create the input array for Comodulogram.fit\n\nlow_sig, high_sig, mask = raw_to_mask(raw, ixs=ixs, events=events, tmin=tmin,\n tmax=tmax)"
120+
]
121+
},
122+
{
123+
"cell_type": "markdown",
124+
"metadata": {},
125+
"source": [
126+
"The mask is an iterable which goes over the _unique_ events in the event\narray (if it is 3D). PAC is estimated where the `mask` is `False`.\nAlternatively, we could also compute the `MaskIterator` object directly.\nThis is useful if you want to compute PAC on other kinds of time series,\nfor example source time courses.\n\n"
127+
]
128+
},
129+
{
130+
"cell_type": "code",
131+
"execution_count": null,
132+
"metadata": {
133+
"collapsed": false
134+
},
135+
"outputs": [],
136+
"source": [
137+
"low_sig, high_sig = raw[ixs[0], :][0], raw[ixs[1], :][0]\nmask = MaskIterator(events, tmin, tmax, raw.n_times, raw.info['sfreq'])\n\n# create the instance of Comodulogram\nestimator = Comodulogram(fs=raw.info['sfreq'],\n low_fq_range=np.linspace(1, 10, 20), low_fq_width=2.,\n method='duprelatour', progress_bar=True)\n# compute the comodulogram\nestimator.fit(low_sig, high_sig, mask)\n# plot the results\nestimator.plot(tight_layout=False)\nplt.show()"
138+
]
139+
}
140+
],
141+
"metadata": {
142+
"kernelspec": {
143+
"display_name": "Python 3",
144+
"language": "python",
145+
"name": "python3"
146+
},
147+
"language_info": {
148+
"codemirror_mode": {
149+
"name": "ipython",
150+
"version": 3
151+
},
152+
"file_extension": ".py",
153+
"mimetype": "text/x-python",
154+
"name": "python",
155+
"nbconvert_exporter": "python",
156+
"pygments_lexer": "ipython3",
157+
"version": "3.8.1"
158+
}
159+
},
160+
"nbformat": 4,
161+
"nbformat_minor": 0
162+
}

_downloads/plot_grid_search.py _downloads/21e1e70318607f4598cfde637f3c81b3/plot_grid_search.py

+1-1
Original file line numberDiff line numberDiff line change
@@ -79,7 +79,7 @@
7979
# Plug the model and the parameter grid into a GridSearchCV estimator
8080
# (GridSearchCVProgressBar is identical to GridSearchCV, but it adds a nice
8181
# progress bar to monitor progress.)
82-
gscv = GridSearchCVProgressBar(model, param_grid=param_grid,
82+
gscv = GridSearchCVProgressBar(model, param_grid=param_grid, cv=3,
8383
return_train_score=False, verbose=1)
8484

8585
# Fit the grid-search. We use `MultipleArray` to put together low_sig and

0 commit comments

Comments
 (0)