Skip to content

Commit

Permalink
Merge branch 'dev' into pr/939
Browse files Browse the repository at this point in the history
  • Loading branch information
DominiqueMakowski committed Dec 18, 2023
2 parents a3a6513 + 87c8c60 commit 72e7601
Show file tree
Hide file tree
Showing 7 changed files with 78 additions and 18 deletions.
Binary file modified data/eeg_1min_200hz.pickle
Binary file not shown.
6 changes: 2 additions & 4 deletions neurokit2/data/database.py
Original file line number Diff line number Diff line change
@@ -1,9 +1,7 @@
import pathlib
import urllib.parse
import urllib
import zipfile

import requests


def download_from_url(url, destination_path=None):
"""**Download Files from URLs**
Expand All @@ -26,7 +24,7 @@ def download_from_url(url, destination_path=None):
destination_path = _download_path_sanitize(url, destination_path)

# Download the file
response = requests.get(url)
response = urllib.request.urlopen(url)

if response.status_code == 200:
with destination_path.open("wb") as file:
Expand Down
10 changes: 8 additions & 2 deletions neurokit2/data/read_xdf.py
Original file line number Diff line number Diff line change
Expand Up @@ -79,10 +79,16 @@ def read_xdf(filename, upsample=2, fillmissing=None):

# Special treatment for some devices
if stream["info"]["name"][0] == "Muse":
# Rename GYRO channels and add ACCelerometer
# Rename GYRO channels
if stream["info"]["type"][0] == "GYRO":
dat = dat.rename(columns={"X": "GYRO_X", "Y": "GYRO_Y", "Z": "GYRO_Z"})
dat["ACC"] = np.sqrt(dat["GYRO_X"] ** 2 + dat["GYRO_Y"] ** 2 + dat["GYRO_Z"] ** 2)
# Compute movement
dat["GYRO"] = np.sqrt(dat["GYRO_X"] ** 2 + dat["GYRO_Y"] ** 2 + dat["GYRO_Z"] ** 2)

if stream["info"]["type"][0] == "ACC":
dat = dat.rename(columns={"X": "ACC_X", "Y": "ACC_Y", "Z": "ACC_Z"})
# Compute acceleration
dat["ACC"] = np.sqrt(dat["ACC_X"] ** 2 + dat["ACC_Y"] ** 2 + dat["ACC_Z"] ** 2)

# Muse - PPG data has three channels: ambient, infrared, red
if stream["info"]["type"][0] == "PPG":
Expand Down
20 changes: 11 additions & 9 deletions neurokit2/epochs/epochs_create.py
Original file line number Diff line number Diff line change
Expand Up @@ -113,6 +113,15 @@ def epochs_create(
# Chunk into n blocks of 1 second
epochs = nk.epochs_create(data, sampling_rate=100, epochs_end=1)
* **Example 5**: Epochs with list of starting points
.. ipython:: python
epochs = nk.epochs_create(data, events, sampling_rate=100,
epochs_start=[0, -1, -1, 0],
epochs_end=[1, 0, 0, 1])
[len(epochs[i]) for i in epochs.keys()]
"""

# Santize data input
Expand All @@ -129,9 +138,7 @@ def epochs_create(
if isinstance(events, int):
events = np.linspace(0, len(data), events + 2)[1:-1]
if isinstance(events, dict) is False:
events = _events_find_label(
{"onset": events}, event_labels=event_labels, event_conditions=event_conditions
)
events = _events_find_label({"onset": events}, event_labels=event_labels, event_conditions=event_conditions)

event_onsets = list(events["onset"])
event_labels = list(events["label"])
Expand Down Expand Up @@ -160,9 +167,7 @@ def epochs_create(
length_buffer = epoch_max_duration

# First createa buffer of the same dtype as data and fill with it 0s
buffer = pd.DataFrame(0, index=range(length_buffer), columns=data.columns).astype(
dtype=data.dtypes
)
buffer = pd.DataFrame(0, index=range(length_buffer), columns=data.columns).astype(dtype=data.dtypes)
# Only then, we convert the non-integers to nans (because regular numpy's ints cannot be nan)
buffer.select_dtypes(exclude="int64").replace({0.0: np.nan}, inplace=True)
# Now we can combine the buffer with the data
Expand All @@ -173,7 +178,6 @@ def epochs_create(

epochs = {}
for i, label in enumerate(parameters["label"]):

# Find indices
start = parameters["onset"][i] + (parameters["start"][i] * sampling_rate)
end = parameters["onset"][i] + (parameters["end"][i] * sampling_rate)
Expand Down Expand Up @@ -201,9 +205,7 @@ def epochs_create(

# Sanitize dtype of individual columns
for i in epochs:

for colname, column in epochs[i].select_dtypes(include=["object"]).items():

# Check whether columns are indices or label/condition
values = column.unique().tolist()
zero_or_one = not (False in [x in [0, 1] for x in values])
Expand Down
4 changes: 3 additions & 1 deletion neurokit2/misc/__init__.py
Original file line number Diff line number Diff line change
Expand Up @@ -5,7 +5,7 @@
"""

from ._warnings import NeuroKitWarning
from .random import check_random_state, check_random_state_children, spawn_random_state
from .check_random_state import check_random_state, check_random_state_children, spawn_random_state
from .check_type import check_type
from .copyfunction import copyfunction
from .expspace import expspace
Expand All @@ -21,6 +21,7 @@
from .replace import replace
from .type_converters import as_vector
from .report import create_report
from .fig2img import fig2img


__all__ = [
Expand All @@ -43,4 +44,5 @@
"check_random_state_children",
"spawn_random_state",
"create_report",
"fig2img",
]
Original file line number Diff line number Diff line change
Expand Up @@ -25,6 +25,7 @@ def check_random_state(seed=None):
rng: numpy.random.Generator or numpy.random.RandomState
Random number generator.
"""

# If seed is an integer, use the legacy RandomState class
if isinstance(seed, numbers.Integral):
return np.random.RandomState(seed)
Expand Down Expand Up @@ -77,7 +78,10 @@ def spawn_random_state(rng, n_children=1):
if rng._bit_generator._seed_seq is not None:
rng_class = type(rng)
bit_generator_class = type(rng._bit_generator)
return [rng_class(bit_generator_class(seed=s)) for s in rng._bit_generator._seed_seq.spawn(n_children)]
return [
rng_class(bit_generator_class(seed=s))
for s in rng._bit_generator._seed_seq.spawn(n_children)
]
except TypeError:
# The rng does not support spawning through SeedSequence, see below
pass
Expand All @@ -94,7 +98,9 @@ def spawn_random_state(rng, n_children=1):
return [np.random.RandomState(seed=s) for s in temp_rng.random_raw(n_children)]


def check_random_state_children(random_state_parent, random_state_children, n_children=1):
def check_random_state_children(
random_state_parent, random_state_children, n_children=1
):
"""**Create new independent children random number generators to be used in sub-functions**
Parameters
Expand Down
46 changes: 46 additions & 0 deletions neurokit2/misc/fig2img.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,46 @@
import io


def fig2img(fig):
"""Matplotlib Figure to PIL Image
Convert a Matplotlib figure to a PIL Image
Parameters
----------
fig : plt.figure
Matplotlib figure.
Returns
----------
list
The rescaled values.
Examples
----------
.. ipython:: python
import neurokit2 as nk
import matplotlib.pyplot as plt
plt.plot([1, 2, 3, 4, 5]) # Make plot
fig = plt.gcf() # Get current figure
nk.fig2img(fig) # Convert to PIL Image
plt.close(fig) # Close figure
"""

try:
import PIL.Image
except ImportError as e:
raise ImportError(
"fig2img(): the 'PIL' (Pillow) module is required for this function to run. ",
"Please install it first (`pip install pillow`).",
) from e

buffer = io.BytesIO()
fig.savefig(buffer)
buffer.seek(0)
img = PIL.Image.open(buffer)
return img

0 comments on commit 72e7601

Please sign in to comment.