Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Added example outputs for CADb, CADc #34

Closed
wants to merge 4 commits into from
Closed
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Binary file not shown.
Binary file not shown.
Binary file not shown.
114 changes: 114 additions & 0 deletions gaitlink/CADB_CADC/CADENCE.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,114 @@
import warnings

import numpy as np

from hklee_algo_improved import hklee_algo_improved
from shin_algo_improved import shin_algo_improved
try:
from cad2sec import cad2sec
except ModuleNotFoundError:
print("The cad2sec module is not found, but the program will continue.")
try:
from GSD_LowbackAcc import GSD_LowBackAcc
except ModuleNotFoundError:
print("The GSD_LowbackAcc module is not found, but the program will continue.")

def CADENCE(DATA, fs, GS, algs):
output_cadence = []
alg_num = 2

# CADENCE ESTIMATION
Accelerometer = DATA[:, 0:3]
print(Accelerometer)
# Gyroscope = DATA[:, 3:6] # Not used by algorithm
BN = len(GS['Start'])
startvec = np.zeros(BN, dtype=int)
stopvec = np.zeros(BN, dtype=int)



#############################################################
finaltemp = np.array([])
for i in range(BN):
#try:
output_cadence_dict = {'Start': [], 'End': [], 'cadSec': [], 'cadMean': [], 'cadSTD': [], 'steps': []}
startvec[i] = int(np.floor(GS['Start'][i] * fs))
if startvec[i] < 1:
startvec[i] = 1

stopvec[i] = int(np.floor(GS['End'][i] * fs))
if stopvec[i] > len(Accelerometer):
stopvec[i] = len(Accelerometer)

chosenacc = Accelerometer[startvec[i]:stopvec[i], :]
warningflag = 0
totalDur = int(np.floor(GS['End'][i] - GS['Start'][i] + (2 / fs)))
cadmat = np.zeros((totalDur, alg_num))
cadinx = np.zeros(alg_num)

if 'HKLee_Imp' in algs: # 1
#IC_HKLee_improved = hklee_algo_improved(chosenacc, fs)
#cadence_HKLee_imp = cad2sec(IC_HKLee_improved, totalDur) / 2
#cadmat[:, 0] = cadence_HKLee_imp[:totalDur]
#cadinx[0] = 1

#test just to run the algo
IC_HKLee_improved = hklee_algo_improved(chosenacc, fs, 'norm')
if len(IC_HKLee_improved) < len(cadmat):
cadmat = cadmat[:len(IC_HKLee_improved)]
cadmat[:, 1] = IC_HKLee_improved[:totalDur]
cadinx[1] = 1

if 'Shin_Imp' in algs: # 2
#IC_Shin_improved = shin_algo_improved(chosenacc, fs)
#cadence_Shin_improved = cad2sec(IC_Shin_improved, totalDur) / 2
#cadmat[:, 1] = cadence_Shin_improved[:totalDur]
#cadinx[1] = 1

#test just to run the algo
try:
IC_Shin_improved = shin_algo_improved(chosenacc, fs, 'norm')
if len(IC_Shin_improved) < len(cadmat):
cadmat = cadmat[:len(IC_Shin_improved)]
cadmat[:, 1] = IC_Shin_improved[:totalDur]
cadinx[1] = 1
except Exception as e:
warnings.warn(str(e))
continue



cadinx = cadinx.astype(bool)
mycad = 120 * cadmat[:, cadinx]

output_cadence_dict['Start'].append(startvec[i] / fs)
output_cadence_dict['End'].append(stopvec[i] / fs)
finaltemp = mycad.flatten()

output_cadence_dict['cadSec'].append(finaltemp)

if len(finaltemp) < totalDur:
finaltemp = np.append(finaltemp, np.full(totalDur - len(finaltemp), finaltemp[-1]))
elif len(finaltemp) > totalDur:
finaltemp = finaltemp[:totalDur]

finaltemp[finaltemp < 30] = 30
finaltemp[finaltemp > 200] = 200
output_cadence_dict['cadMean'].append(np.nanmean(finaltemp))
output_cadence_dict['cadSTD'].append(np.nanstd(finaltemp))
output_cadence_dict['steps'].append(int(np.round(np.nansum(finaltemp) / 60)))

# except Exception as e:
# print(f"Error on analysis of walking sequence: {str(e)}")
# output_cadence_dict = {
# 'cadSec': np.nan,
# 'cadMean': np.nan,
# 'cadSTD': np.nan,
# 'steps': np.nan
# }
# continue

output_cadence.append(output_cadence_dict)
#print(f"Completed loop iteration {i + 1}")
#print(output_cadence_dict)
return output_cadence
56 changes: 56 additions & 0 deletions gaitlink/CADB_CADC/ICD_CAD.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,56 @@
import os
import numpy as np
import pandas as pd
import csv
import matplotlib.pyplot as plt
from shin_algo_improved import shin_algo_improved
from hklee_algo_improved import hklee_algo_improved
from gaitlink.data import LabExampleDataset
from gaitlink.data import LabExampleDataset
from gaitlink.data._mobilised_matlab_loader import GenericMobilisedDataset


#data=x chooses only the vertical acceleration, data=all chooses all axes
def InitialContactDetection(Accelerometer, fs, GS, algs, data='x'):

# Check if 'data' is provided, if not, set it to the default 'x' (all axes of accelerometry)
if not data or len(data) == 0:
data = 'x'

chosen_data = data # Store the data so no need to call it again

if 'x' in data:
Accelerometer = Accelerometer[:, 0:1]
elif 'norm' in data:
Accelerometer = Accelerometer


if isinstance(GS, pd.DataFrame) and not GS.empty:
SD_Output = {'Start': [], 'End': [], 'IC': []}
BN = len(GS['Start'])
startvec = np.zeros(BN, dtype=int)
stopvec = np.zeros(BN, dtype=int)

for i in range(BN):
startvec[i] = int(np.floor(GS['Start'][i] * fs))
stopvec[i] = int(np.floor(GS['End'][i] * fs))
chosenacc = Accelerometer[startvec[i]:stopvec[i], :]


if 'HKLee_Imp' in algs: # 1
IC_HKLee_improved = hklee_algo_improved(chosenacc, fs, chosen_data)
SD_Output['IC'].append(IC_HKLee_improved)

if 'Shin_Imp' in algs: # 2
IC_Shin_improved = shin_algo_improved(chosenacc, fs, chosen_data)
SD_Output['IC'].append(IC_Shin_improved)

SD_Output['Start'].append(startvec[i])
SD_Output['End'].append(stopvec[i])

else:
print("GS is empty.")
SD_Output = {}

print(SD_Output)
return SD_Output
Empty file added gaitlink/CADB_CADC/__init__.py
Empty file.
103 changes: 103 additions & 0 deletions gaitlink/CADB_CADC/epfl_gait_filter.csv
Original file line number Diff line number Diff line change
@@ -0,0 +1,103 @@
coefficients
-7.32062354912454e-05
3.78508622436883e-05
0.000246348109197937
0.000677903580565397
0.00139121173834152
0.00240120107902306
0.00365134729205267
0.00499791461345996
0.00621524709266542
0.00702710179358570
0.00716251647666459
0.00642763923506909
0.00477644184660929
0.00235955274741389
-0.000467004701949172
-0.00318729268148899
-0.00522215422251725
-0.00606335356628703
-0.00541421442262487
-0.00330024440090518
-0.000113511367820591
0.00343303842402714
0.00644432500038348
0.00805222780827783
0.00764951215205984
0.00508854384693732
0.000785246955265535
-0.00431394654940573
-0.00891383397938441
-0.0116725408042536
-0.0115599416061123
-0.00818324078638784
-0.00198780208134589
0.00573815422238463
0.0130835533924908
0.0179324660414459
0.0184981068429205
0.0138510767938709
0.00430688629153999
-0.00844188778061492
-0.0215122304374164
-0.0313277564810650
-0.0343411216793298
-0.0278350948468902
-0.0106240721245163
0.0165123088037780
0.0507816763239513
0.0877543665066161
0.122104791742143
0.148576643831182
0.162974796835057
0.162974796835057
0.148576643831182
0.122104791742143
0.0877543665066161
0.0507816763239513
0.0165123088037780
-0.0106240721245163
-0.0278350948468902
-0.0343411216793298
-0.0313277564810650
-0.0215122304374164
-0.00844188778061492
0.00430688629153999
0.0138510767938709
0.0184981068429205
0.0179324660414459
0.0130835533924908
0.00573815422238463
-0.00198780208134589
-0.00818324078638784
-0.0115599416061123
-0.0116725408042536
-0.00891383397938441
-0.00431394654940573
0.000785246955265535
0.00508854384693732
0.00764951215205984
0.00805222780827783
0.00644432500038348
0.00343303842402714
-0.000113511367820591
-0.00330024440090518
-0.00541421442262487
-0.00606335356628703
-0.00522215422251725
-0.00318729268148899
-0.000467004701949172
0.00235955274741389
0.00477644184660929
0.00642763923506909
0.00716251647666459
0.00702710179358570
0.00621524709266542
0.00499791461345996
0.00365134729205267
0.00240120107902306
0.00139121173834152
0.000677903580565397
0.000246348109197937
3.78508622436883e-05
-7.32062354912454e-05
91 changes: 91 additions & 0 deletions gaitlink/CADB_CADC/example_GSD_CAD.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,91 @@
#TODO: I had to put all files in this folder to call functions same for _filter

import numpy as np
import pandas as pd
import csv
import matplotlib.pyplot as plt
from CADENCE import CADENCE
from shin_algo_improved import shin_algo_improved as Shin_Imp
from hklee_algo_improved import hklee_algo_improved as HKLee_Imp
from gaitlink.data import LabExampleDataset
try:
from gaitlink.data import LabExampleDataset
except ModuleNotFoundError:
print("The example_data module is not found, but the program will continue.")
try:
from gaitlink.data._mobilised_matlab_loader import GenericMobilisedDataset
except ModuleNotFoundError:
print("The _mobilised_matlab_loader module is not found, but the program will continue.")


#for McR
example_data = LabExampleDataset(reference_system = "INDIP")
ha_example_data = example_data.get_subset(cohort="HA")
single_test = ha_example_data.get_subset(participant_id="002", test="Test11", trial="Trial1")
imu_data = single_test.data["LowerBack"]
imu_acc = imu_data.filter(like="acc")
imu_gyr = imu_data.filter(like="gyr")
fs = single_test.sampling_rate_hz

#manual import acc adn gyr ssame aas MATLAB
#fs = 100
#csv_file = "Accelerometer.csv"
#imu_acc = []
#with open(csv_file, 'r', encoding='utf-8-sig') as file:
# reader = csv.reader(file)
# for row in reader:
# # Convert each element in the row to a float and append the entire row
# acc = [float(value) for value in row]
# imu_acc.append(acc)

#csv_file = "Gyroscope.csv"
#imu_gyr = []
#with open(csv_file, 'r', encoding='utf-8-sig') as file:
# reader = csv.reader(file)
# for row in reader:
# gyr = [float(value) for value in row]
# imu_gyr.append(gyr)



DATA = np.concatenate((imu_acc, imu_gyr), axis=1)

# Gait Sequence Detection algorithm with GSD function
# plot_results = True
# GS = GSD_LowBackAcc(imu_acc, fs, plot_results)

# Gait Sequence Detection from example file
# example_data_with_reference = LabExampleDataset(reference_system="INDIP")
# single_trial_with_reference = example_data_with_reference.get_subset(
# cohort="HA", participant_id="001", test="Test11", trial="Trial1"
# )



GS = single_test.reference_parameters_['wb']
GS = [{"Start": r["Start"], "End": r["End"]} for r in GS]
GS = pd.DataFrame.from_records(GS)
#print(GS)



# GS from example file (csv) until I resolve the issue importing the GS from the example file
# file_path = "GS.csv"
# df = pd.read_csv(file_path)
# GS = {
# 'Start': df['Start'].to_numpy(),
# 'End': df['End'].to_numpy(),
# 'fs': df['fs'].to_numpy()
# }

#Cadence detection algorithm
algs = ['Shin_Imp', 'HKLee_Imp']
if len(GS) > 1:
CAD = CADENCE(DATA, fs, GS, 'HKLee_Imp')
GS = CAD

else:
print('Error: the Gait sequence (GS) input is empty')

# Optional: save Gait Sequence
# np.save('GS.npy', GS)
Loading
Loading