Skip to content

Commit

Permalink
Merge pull request #16 from meyravDayan/master
Browse files Browse the repository at this point in the history
.
  • Loading branch information
sstbrg committed Jun 20, 2019
2 parents eb59d87 + c41027f commit 9b89d31
Show file tree
Hide file tree
Showing 4 changed files with 113 additions and 13 deletions.
3 changes: 3 additions & 0 deletions .vscode/settings.json
Original file line number Diff line number Diff line change
@@ -0,0 +1,3 @@
{
"python.pythonPath": "C:\\ProgramData\\Miniconda3\\envs\\my_env\\python.exe"
}
Empty file added a.csv
Empty file.
108 changes: 95 additions & 13 deletions submovements/DataProcessing.py
Original file line number Diff line number Diff line change
Expand Up @@ -6,6 +6,87 @@
import numpy as np
from scipy.signal import butter, filtfilt
from pathlib import Path
import re
import seaborn as sns;

sns.set()


@attr.s
class Subject(object):
dir_path = attr.ib(default='')
id = attr.ib(init=False)
df_folder = attr.ib(default='')
df_dict = attr.ib({'square_left': [], 'square_right': [], 'tri_left': [], 'tri_right': []})

def __attrs_post_init__(self):
self.id = os.path.split(self.dir_path)[1]

def create_total_df(self):
self.df_total = pd.DataFrame({'Vx': [], 'Vy': [], 'Rep': [], 'Block': [], 'Time': [], 'Condition': [],
'ID': [], 'pos x': [],
'pos y': []}) # creating an empty array for concatination use later
pproc = Preprocessor()
trial_gen = pproc.load_df_from_directory_gen(self.dir_path)
for trial in trial_gen:
trial.preprocess(pproc)
df = trial.create_df()
trial.save_df(df, self.df_folder)
for key in self.df_dict:
if key == trial.stimulus:
self.df_dict[key].append(df)
self.df_total = pd.concat([self.df_total, df])
self.df_total = self.df_total.set_index(['ID', 'Condition', 'Block', 'Rep', 'Time']).sort_values(
['ID', 'Condition', 'Block', 'Rep'], ascending=True)

def stimuli_plot_vx(self, num_of_trials):
fig, axes = plt.subplots(2, 2) # add name to subplots
plt.xlabel('Time (sec)')
plt.ylabel('Vx (cm/sec)')
for n, key in enumerate(self.df_dict):
if n == 0:
axes[0, 0].set_title(key)
if n == 1:
axes[0, 1].set_title(key)
if n == 2:
axes[1, 0].set_title(key)
if n == 3:
axes[1, 1].set_title(key)
for trial in range(num_of_trials):
if n == 0:
sns.lineplot(x="Time", y="Vx", data=self.df_dict[key][trial], ax=axes[0, 0])
if n == 1:
sns.lineplot(x="Time", y="Vx", data=self.df_dict[key][trial], ax=axes[0, 1])
if n == 2:
sns.lineplot(x="Time", y="Vx", data=self.df_dict[key][trial], ax=axes[1, 0])
if n == 3:
sns.lineplot(x="Time", y="Vx", data=self.df_dict[key][trial], ax=axes[1, 1])
plt.show()

def stimuli_plot_vy(self, num_of_trials):
fig, axes = plt.subplots(2, 2) # add name to subplots
plt.xlabel('Time (sec)')
plt.ylabel('Vy (cm/sec)')
for n, key in enumerate(self.df_dict):
if n == 0:
axes[0, 0].set_title(key)
if n == 1:
axes[0, 1].set_title(key)
if n == 2:
axes[1, 0].set_title(key)
if n == 3:
axes[1, 1].set_title(key)
for trial in range(num_of_trials):
if n == 0:
sns.lineplot(x="Time", y="Vy", data=self.df_dict[key][trial], ax=axes[0, 0])
if n == 1:
sns.lineplot(x="Time", y="Vy", data=self.df_dict[key][trial], ax=axes[0, 1])
if n == 2:
sns.lineplot(x="Time", y="Vy", data=self.df_dict[key][trial], ax=axes[1, 0])
if n == 3:
sns.lineplot(x="Time", y="Vy", data=self.df_dict[key][trial], ax=axes[1, 1])
plt.show()


@attr.s
class Trial():
Expand Down Expand Up @@ -58,20 +139,20 @@ def create_df(self):
# Vx, Vy, Condition, Time, ID, Block, Repetition
# TODO: Generalize to z axis
###


pos_x = self.data['x']
pos_y = self.data['y']
vx = self.data['Vx']
vy = self.data['Vy']
time = np.arange(len(vx)) # change later !!!!
time = self.data.index.values
condition = np.full(shape=len(vx), fill_value=self.stimulus)

# maybe add to main as trial attribute
id = np.full(shape=len(vx),
fill_value=self.id
)
block = np.full(shape=len(vx), fill_value=self.block, dtype=np.int)
rep = np.full(shape=len(vx), fill_value=self.rep, dtype=np.int)
return pd.DataFrame({'Vx': vx, 'Vy': vy, 'Rep': rep, 'Block': block,
'Time': time, 'Condition': condition, 'ID': id})
'Time': time, 'Condition': condition, 'ID': id, 'pos x': pos_x, 'pos y': pos_y})

def save_df(self, df, dest_folder):
###
Expand All @@ -98,7 +179,7 @@ class Preprocessor():
# cut-via-threshold and plot DataFrames
###

raw_paths = attr.ib(default='data') # Path list of all the raw data files
raw_paths = attr.ib(default='data') # Path list of all the raw data files
sample_rate = attr.ib(default=240) # Sample rate the raw data is sampled at

raw_headers = attr.ib(default=['SampleNum', 'x', 'y', 'z',
Expand Down Expand Up @@ -145,7 +226,7 @@ def load_single_file(self, file_path, cols=('x', 'y')):

assert Path(file_path).is_file(), f'File does not exists: {file_path}'
file_path = Path(file_path)
cols=list(cols)
cols = list(cols)
trial_out = Trial()
try:
df = pd.read_csv(file_path, names=self.raw_headers)
Expand Down Expand Up @@ -245,11 +326,12 @@ def remove_baseline(self, data_in: pd.DataFrame, cols=('x', 'y'), threshold=0.05
idx = df.loc[df >= threshold]

# expand data cutting limits
low_cut_index = int(idx.index[0]-0.1*self.sample_rate \
if df.index.min() < idx.index[0]-0.1*self.sample_rate \
else df.index.min())
high_cut_index = int(idx.index[-1]+0.1*self.sample_rate \
if df.index.max() > idx.index[-1]+0.1*self.sample_rate \
else df.index.max())

low_cut_index = int(idx.index[0] - 0.1 * self.sample_rate \
if df.index.min() < idx.index[0] - 0.1 * self.sample_rate \
else df.index.min())
high_cut_index = int(idx.index[-1] + 0.1 * self.sample_rate \
if df.index.max() > idx.index[-1] + 0.1 * self.sample_rate \
else df.index.max())

return data_in.copy()[low_cut_index:high_cut_index].reset_index(drop=True)
15 changes: 15 additions & 0 deletions submovements/meyrav_work.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,15 @@
from DataProcessing import Preprocessor, Trial, Subject
import pandas as pd
import numpy as np
import os
import re
import attr
import matplotlib.pyplot as plt
from scipy.signal import savgol_filter, hilbert
import seaborn as sns; sns.set()

if __name__ == "__main__":
a = Subject('../1', r'C:\Users\meyra\Desktop\s')
a.create_total_df()
a.stimuli_plot_vx(10)
a.stimuli_plot_vy(10)

0 comments on commit 9b89d31

Please sign in to comment.