Skip to content

Commit

Permalink
chore: lint errors
Browse files Browse the repository at this point in the history
  • Loading branch information
patmikista committed Apr 5, 2024
1 parent 89883a1 commit 049b3fa
Show file tree
Hide file tree
Showing 10 changed files with 120 additions and 66 deletions.
10 changes: 4 additions & 6 deletions examples/mne_demo.py
Original file line number Diff line number Diff line change
@@ -1,25 +1,23 @@
import os.path as op

import mne
import seaborn as sns

from pyPTE.adapters import mne_adapter

# from mne.datasets.brainstorm import bst_raw

data_path = op.join(mne.datasets.sample.data_path(), 'MEG', 'sample')
raw = mne.io.read_raw_fif(op.join(data_path, 'sample_audvis_raw.fif'),
preload=True)
# raw.plot()

from pyPTE.adapters import mne_adapter

picks = mne.pick_types(raw.info, meg=True, exclude='bads')
t_idx = raw.time_as_index([10., 20.])
data, times = raw[picks, t_idx[0]:t_idx[1]]


dPTE, rPTE = mne_adapter.PTE_from_mne(raw)

import seaborn as sns
from matplotlib import pyplot as plt

sns.heatmap(rPTE)


Expand Down
19 changes: 14 additions & 5 deletions examples/models/kuramoto_global.py
Original file line number Diff line number Diff line change
@@ -1,10 +1,17 @@
import numpy as np
import seaborn as sns
from matplotlib import pyplot as plt
from sdeint import itoint

from pyPTE.core import pyPTE


def kuramoto(omega_vector, K, N, sigma):
def f(theta_vector, t):
#theta_vector = np.atleast_2d(theta_vector)
theta_vector = np.atleast_2d(theta_vector)
d_theta_vector = omega_vector + K/N * np.sum(np.sin(theta_vector - theta_vector.T), 1)
d_theta_vector = omega_vector + K/N * np.sum(
np.sin(theta_vector - theta_vector.T), 1)
p = np.random.normal(0, sigma, N)
return d_theta_vector + p
def G(v, t):
Expand All @@ -19,10 +26,11 @@ def G(v, t):
omega = np.ones_like(theta0)*8

f, G = kuramoto(omega, 1, 10, 0.1)
from sdeint import itoint

tspan = np.linspace(0, 1, 1000)
solution = itoint(f, G, theta0, tspan)
from matplotlib import pyplot as plt


plt.plot(tspan, solution)
plt.show()

Expand All @@ -35,7 +43,8 @@ def G(v, t):
plt.plot(tspan, solution)
plt.show()

from pyPTE.core import pyPTE


# phase = np.swapaxes(solution, 0, 1)
phase = solution
delay = pyPTE.get_delay(phase)
Expand All @@ -46,7 +55,7 @@ def G(v, t):
dPTE, raw_PTE = pyPTE.compute_dPTE_rawPTE(dphase, delay)

print(dPTE)
import seaborn as sns

cmap = sns.diverging_palette(10, 220, sep=80, n=7)
sns.heatmap(dPTE, cmap=cmap, center=0.5)
plt.show()
Expand Down
26 changes: 19 additions & 7 deletions examples/models/kuramoto_local.py
Original file line number Diff line number Diff line change
@@ -1,4 +1,12 @@
import itertools

import numpy as np
import seaborn as sns
from matplotlib import pyplot as plt
from sdeint import itoint

from pyPTE.core import pyPTE


def kuramoto(omega_vector, K, N, sigma):
def f(theta_vector, t):
Expand Down Expand Up @@ -38,10 +46,10 @@ def G(v, t):
steps = t_end / dt
# K[:,3] = 100
f, G = kuramoto(omega, K, N, 0.01)
from sdeint import itoint

tspan = np.linspace(0, t_end, steps)
solution = itoint(f, G, theta0, tspan)
from matplotlib import pyplot as plt

plt.figure(1)
plt.subplot(211)
plt.plot(tspan, solution)
Expand All @@ -52,12 +60,14 @@ def G(v, t):
plt.plot(tspan, solution)
plt.show()

import itertools


dt = 0.1
t_end = 10
steps = t_end / dt
from sdeint import itoint



def repetitive_sims(K, N, theta0, omega, Nsims):
solutions = list()
for _ in itertools.repeat(None, Nsims):
Expand All @@ -72,7 +82,8 @@ def repetitive_sims(K, N, theta0, omega, Nsims):
# Nsim = 10
# solutions = repetitive_sims(K, N, theta0, omega, Nsim)

from matplotlib import pyplot as plt


# for solution in solutions:
# plt.plot(solution)
# plt.show()
Expand All @@ -91,7 +102,7 @@ def repetitive_sims(K, N, theta0, omega, Nsims):
#
# average_dPTE = np.sum(dPTEs) / len(dPTEs)

from pyPTE.core import pyPTE

# phase = np.swapaxes(solution, 0, 1)
phase = solution
delay = pyPTE.get_delay(phase)
Expand All @@ -104,7 +115,8 @@ def repetitive_sims(K, N, theta0, omega, Nsims):



import seaborn as sns


plt.figure(1)

cmap = sns.diverging_palette(240, 10, as_cmap=True, n=7)
Expand Down
6 changes: 4 additions & 2 deletions examples/models/neural_mass_model.py
Original file line number Diff line number Diff line change
Expand Up @@ -3,7 +3,8 @@

def jansen_rit(g1 = 135, C=None):
"""
Neural mass model which returns a dynamical system F and Wiener process G for a given coupling matrix C
Neural mass model which returns a dynamical system F and Wiener process G
for a given coupling matrix C
This function defines:
all fixed parameters for the Jansen-Rit model
Expand All @@ -18,7 +19,8 @@ def jansen_rit(g1 = 135, C=None):
Model parameter which determines what kind of rhythm will be generated
default : 135 for alpha-waves
C : ndarray
coupling matrix must be quadratic. values of the coupling matrix correspond to the coupling strength between neural mass models
coupling matrix must be quadratic. values of the coupling matrix correspond to
the coupling strength between neural mass models
Returns
-------
Expand Down
9 changes: 6 additions & 3 deletions examples/utils/stats.py
Original file line number Diff line number Diff line change
@@ -1,6 +1,7 @@
from scipy.stats import wilcoxon
import numpy as np
import pandas as pd
from scipy.stats import wilcoxon


def matrix_wilcoxon(x_matrices, y_matrices, alpha = 0.05, bonferroni=True):
x = list()
Expand Down Expand Up @@ -36,7 +37,9 @@ def matrix_wilcoxon(x_matrices, y_matrices, alpha = 0.05, bonferroni=True):
else:
p_mask[i, j] = True

p_values_df = pd.DataFrame(p_values, index=x_matrices[0].index, columns=x_matrices[0].columns)
p_mask_df = pd.DataFrame(p_mask, index=x_matrices[0].index, columns=x_matrices[0].columns)
p_values_df = pd.DataFrame(p_values, index=x_matrices[0].index,
columns=x_matrices[0].columns)
p_mask_df = pd.DataFrame(p_mask, index=x_matrices[0].index,
columns=x_matrices[0].columns)

return p_values_df, p_mask_df
24 changes: 14 additions & 10 deletions pyPTE/adapters/mne_adapter.py
Original file line number Diff line number Diff line change
Expand Up @@ -3,11 +3,13 @@

def interpolate_mne(raw, raw_reference):
"""
This is a utility function which circumvents the issue that MNE allows to interpolate only channels,
which are present and marked as bad channels. Missing channels in a raw file can be interpolated
by passing the mne.io.Raw object subject to interpolation and a reference object which contains all channels.
This is achieved by copying channels, replacing its channel information by the reference channels,
marking it as bad and finally utilizing mne.io.Raw.interpolate_bads()
This is a utility function which circumvents the issue that MNE allows to
interpolate only channels, which are present and marked as bad channels.
Missing channels in a raw file can be interpolated by passing the mne.io.Raw object
subject to interpolation and a reference object which contains all channels.
This is achieved by copying channels, replacing its channel information by
the reference channels, marking it as bad and finally utilizing
mne.io.Raw.interpolate_bads()
Parameters
----------
Expand All @@ -19,7 +21,8 @@ def interpolate_mne(raw, raw_reference):
Returns
-------
d : mne.io.Raw
New object containing all information from the original raw object and interpolated channels
New object containing all information from the original raw object and
interpolated channels
"""
ref_channels = raw_reference.ch_chnames
Expand All @@ -43,8 +46,8 @@ def interpolate_mne(raw, raw_reference):

def PTE_from_mne(mne_raw):
"""
This is a wrapper which allows calculating dPTE,PTE matrices by passing an mne.io.Raw object
and calling pyPTE.pyPTE.PTE_from_dataframe().
This is a wrapper which allows calculating dPTE,PTE matrices by passing an
mne.io.Raw object and calling pyPTE.pyPTE.PTE_from_dataframe().
Parameters
----------
Expand All @@ -54,8 +57,9 @@ def PTE_from_mne(mne_raw):
Returns
-------
result : pandas.DataFrame
The wrapper returns a tuple of (dPTE, PTE) matrices, which are stored as a pandas.DataFrame and indexed by
the channels names of the input file. This allows convenient analysis of the results.
The wrapper returns a tuple of (dPTE, PTE) matrices, which are stored as a
pandas.DataFrame and indexed by the channels names of the input file.
This allows convenient analysis of the results.
"""

Expand Down
12 changes: 7 additions & 5 deletions pyPTE/adapters/pandas_adapter.py
Original file line number Diff line number Diff line change
Expand Up @@ -5,19 +5,21 @@

def PTE_from_dataframe(data_frame):
"""
This is a wrapper which allows calculating dPTE,PTE matrices by passing an pandas.DataFrame
This is a wrapper which allows calculating dPTE,PTE matrices by passing a
pandas.DataFrame
Parameters
----------
data_frame : pandas.DataFrame
This object contains time-series data where pandas.DataFrame.index corresponds to the time samples and
pandas.DataFrame.columns represents the individual channels
This object contains time-series data where pandas.DataFrame.index corresponds
to the time samples and pandas.DataFrame.columns represents the
individual channels
Returns
-------
(dPTE_df, rPTE_df) : tuple of pandas.DataFrame objects
The results from pyPTE.pyPTE.PTE are stored as pandas.DataFrames, while it is indexed in two dimensions by
pandas.DataFrame.columns of the input
The results from pyPTE.pyPTE.PTE are stored as pandas.DataFrames, while it is
indexed in two dimensions by pandas.DataFrame.columns of the input
"""
time_series = data_frame.as_matrix()
Expand Down
1 change: 1 addition & 0 deletions pyPTE/core/handle_multi.py
Original file line number Diff line number Diff line change
@@ -1,4 +1,5 @@
from multiprocessing import Pool, cpu_count

from pyPTE.core import pyPTE


Expand Down
41 changes: 23 additions & 18 deletions pyPTE/core/pyPTE.py
Original file line number Diff line number Diff line change
@@ -1,10 +1,9 @@
from typing import Tuple

import numpy as np
import numpy.typing as npt

from scipy.signal import hilbert

from typing import Tuple


def get_delay(phase: npt.NDArray) -> int:
"""
Expand Down Expand Up @@ -32,7 +31,8 @@ def get_delay(phase: npt.NDArray) -> int:

def get_phase(time_series: npt.ArrayLike) -> npt.NDArray:
"""
Computes phase from time series using a hilbert transform and computing the angles between the real and imaginary part for each sample
Computes phase from time series using a hilbert transform and computing the angles
between the real and imaginary part for each sample
Parameters
----------
Expand Down Expand Up @@ -112,17 +112,20 @@ def get_bincount(binsize: float) -> int:

def compute_PTE(phase: npt.NDArray, delay: int) -> npt.NDArray:
"""
For each channel pair (x, y) containing the individual discretized phase, which is obtained by pyPTE.pyPTE.get_discretized_phase,
this function performs the entropy estimation by counting the occurences of phase values in x, y and y_predicted,
which is achieved by slicing the x, y to consider delay x samples in the past and delay samples in the future.
For each channel pair (x, y) containing the individual discretized phase,
which is obtained by pyPTE.pyPTE.get_discretized_phase,
this function performs the entropy estimation by counting the occurences of
phase values in x, y and y_predicted, which is achieved by slicing the x, y
to consider delay x samples in the past and delay samples in the future.
Parameters
----------
phase : numpy.ndarray
m x n ndarray : m: number of channels, n: number of samples
delay : int
This is the analysis delta, which is the number of samples in the past to be considered for x and y
Momentarily delay is estimated by pyPTE.pyPTE.get_delay(). A custom delay estimation can be used as well.
This is the analysis delta, which is the number of samples in the past
to be considered for x and y. Momentarily delay is estimated by
pyPTE.pyPTE.get_delay(). A custom delay estimation can be used as well.
Returns
-------
Expand Down Expand Up @@ -170,10 +173,10 @@ def compute_dPTE_rawPTE(
phase: npt.NDArray, delay: int
) -> Tuple[npt.NDArray, npt.NDArray]:
"""
This function calls pyPTE.pyPTE.compute_PTE to obtain a PTE matrix and
performs a normalization yielding dPTE to easily investigate directionality information.
Technically it could be a function which computes the normalization for a given PTE matrix, but it appears to be
more convenient to obtain both matrices in one call
This function calls pyPTE.pyPTE.compute_PTE to obtain a PTE matrix and performs a
normalization yielding dPTE to easily investigate directionality information.
Technically it could be a function which computes the normalization for a given
PTE matrix, but it appears to be more convenient to obtain both matrices in one call
Parameters
----------
Expand All @@ -182,8 +185,9 @@ def compute_dPTE_rawPTE(
The discretized phase is computed by pyPTE.pyPTE.get_discretized_phase
delay : int
This is the analysis delta, which is the number of samples in the past to be considered for x and y
Momentarily delay is estimated by pyPTE.pyPTE.get_delay(). A custom delay estimation can be used as well.
This is the analysis delta, which is the number of samples in the past to be
considered for x and y. Momentarily delay is estimated by
pyPTE.pyPTE.get_delay(). A custom delay estimation can be used as well.
Returns
-------
Expand All @@ -202,10 +206,11 @@ def compute_dPTE_rawPTE(
def PTE(time_series: npt.ArrayLike) -> Tuple[npt.NDArray, npt.NDArray]:
"""
This function performs the whole procedure of calculating the PTE:
1. Compute the phase by applying the Hilbert transform on the time-series and calculate the angle between
the real and imaginary part. The phase is defined on the interval [-pi, pi[
1. Compute the phase by applying the Hilbert transform on the time-series and
calculate the angle between the real and imaginary part.
The phase is defined on the interval [-pi, pi[
2. Estimate the analysis delay
3. For ease of binning shift the phase along the ordinate so there are no negative values
3. For binning, shift the phase along the ordinate so there are no negatives values
4. Calculate the binsize in number of samples
5. Bin the phase data
6. Compute the dPTE and raw_PTE
Expand Down
Loading

0 comments on commit 049b3fa

Please sign in to comment.