def run_pyGait(data, t, sample_rate, duration, threshold, order, cutoff, distance, row, file_path, table_stem, save_rows=False): """ Run pyGait (replication of iGAIT) accelerometer feature extraction code. Steps :: 1. Run pyGait accelerometer feature extraction. 2. Construct a feature row from the original and pyGait rows. 3. Write the feature row to a table or append to a feature table. Parameters ---------- data : numpy array accelerometer data along any (preferably forward walking) axis t : list or numpy array accelerometer time points sample_rate : float sample rate of accelerometer reading (Hz) duration : float duration of accelerometer reading (s) threshold : float ratio to the maximum value of the anterior-posterior acceleration order : integer order of the Butterworth filter cutoff : integer cutoff frequency of the Butterworth filter (Hz) distance : float estimate of distance traversed row : pandas Series row to prepend, unaltered, to feature row file_path : string path to accelerometer file (from row) table_stem : string prepend to output table file save_rows : Boolean save individual rows rather than write to a single feature table? Returns ------- feature_row : pandas Series row combining the original row with a row of pyGait feature values feature_table : string output table file (full path) Examples -------- >>> import pandas as pd >>> from mhealthx.xio import read_accel_json >>> from mhealthx.extract import run_pyGait >>> from mhealthx.extractors.pyGait import project_on_walking_direction >>> input_file = '/Users/arno/DriveWork/mhealthx/mpower_sample_data/accel_walking_outbound.json.items-6dc4a144-55c3-4e6d-982c-19c7a701ca243282023468470322798.tmp' >>> start = 150 >>> device_motion = False >>> t, axyz, gxyz, uxyz, rxyz, sample_rate, duration = read_accel_json(input_file, start, device_motion) >>> ax, ay, az = axyz >>> stride_fraction = 1.0/8.0 >>> threshold0 = 0.5 >>> threshold = 0.2 >>> order = 4 >>> cutoff = max([1, sample_rate/10]) >>> distance = None >>> row = pd.Series({'a':[1], 'b':[2], 'c':[3]}) >>> file_path = '/fake/path' >>> table_stem = './walking' >>> save_rows = True >>> px, py, pz = project_on_walking_direction(ax, ay, az, t, sample_rate, stride_fraction, threshold0, order, cutoff) >>> feature_row, feature_table = run_pyGait(py, t, sample_rate, duration, threshold, order, cutoff, distance, row, file_path, table_stem, save_rows) """ import pandas as pd from mhealthx.extractors.pyGait import heel_strikes, gait from mhealthx.extract import make_row_table # Extract features from data: strikes, strike_indices = heel_strikes(data, sample_rate, threshold, order, cutoff, False, t) number_of_steps, cadence, velocity, avg_step_length, avg_stride_length,\ step_durations, avg_step_duration, sd_step_durations, strides, \ stride_durations, avg_number_of_strides, avg_stride_duration, \ sd_stride_durations, step_regularity, stride_regularity, \ symmetry = gait(strikes, data, duration, distance) # Create row of data: row_data = pd.DataFrame({'number_of_steps': number_of_steps, 'cadence': cadence, 'velocity': velocity, 'avg_step_length': avg_step_length, 'avg_stride_length': avg_stride_length, 'avg_step_duration': avg_step_duration, 'sd_step_durations': sd_step_durations, 'avg_number_of_strides': avg_number_of_strides, 'avg_stride_duration': avg_stride_duration, 'sd_stride_durations': sd_stride_durations, 'step_regularity': step_regularity, 'stride_regularity': stride_regularity, 'symmetry': symmetry}, index=[0]) # Write feature row to a table or append to a feature table: feature_row, feature_table = make_row_table(file_path, table_stem, save_rows, row, row_data, feature_row=None) return feature_row, feature_table
def walk_direction_preheel(ax, ay, az, t, sample_rate, stride_fraction=1.0/8.0, threshold=0.5, order=4, cutoff=5, plot_test=False): """ Estimate local walk (not cardinal) direction with pre-heel strike phase. Inspired by Nirupam Roy's B.E. thesis: "WalkCompass: Finding Walking Direction Leveraging Smartphone's Inertial Sensors," this program derives the local walk direction vector from the end of the primary leg's stride, when it is decelerating in its swing. While the WalkCompass relies on clear heel strike signals across the accelerometer axes, this program just uses the most prominent strikes, and estimates period from the real part of the FFT of the data. NOTE:: This algorithm computes a single walk direction, and could compute multiple walk directions prior to detected heel strikes, but does NOT estimate walking direction for every time point, like walk_direction_attitude(). Parameters ---------- ax : list or numpy array x-axis accelerometer data ay : list or numpy array y-axis accelerometer data az : list or numpy array z-axis accelerometer data t : list or numpy array accelerometer time points sample_rate : float sample rate of accelerometer reading (Hz) stride_fraction : float fraction of stride assumed to be deceleration phase of primary leg threshold : float ratio to the maximum value of the summed acceleration across axes plot_test : Boolean plot most prominent heel strikes? Returns ------- direction : numpy array of three floats unit vector of local walk (not cardinal) direction Examples -------- >>> from mhealthx.xio import read_accel_json >>> from mhealthx.signals import compute_sample_rate >>> input_file = '/Users/arno/DriveWork/mhealthx/mpower_sample_data/deviceMotion_walking_outbound.json.items-a2ab9333-6d63-4676-977a-08591a5d837f5221783798792869048.tmp' >>> device_motion = True >>> start = 150 >>> t, axyz, gxyz, uxyz, rxyz, sample_rate, duration = read_accel_json(input_file, start, device_motion) >>> ax, ay, az = axyz >>> from mhealthx.extractors.pyGait import walk_direction_preheel >>> threshold = 0.5 >>> stride_fraction = 1.0/8.0 >>> order = 4 >>> cutoff = max([1, sample_rate/10]) >>> plot_test = True >>> direction = walk_direction_preheel(ax, ay, az, t, sample_rate, stride_fraction, threshold, order, cutoff, plot_test) """ import numpy as np from mhealthx.extractors.pyGait import heel_strikes from mhealthx.signals import compute_interpeak # Sum of absolute values across accelerometer axes: data = np.abs(ax) + np.abs(ay) + np.abs(az) # Find maximum peaks of smoothed data: plot_test2 = False dummy, ipeaks_smooth = heel_strikes(data, sample_rate, threshold, order, cutoff, plot_test2, t) # Compute number of samples between peaks using the real part of the FFT: interpeak = compute_interpeak(data, sample_rate) decel = np.int(np.round(stride_fraction * interpeak)) # Find maximum peaks close to maximum peaks of smoothed data: ipeaks = [] for ipeak_smooth in ipeaks_smooth: ipeak = np.argmax(data[ipeak_smooth - decel:ipeak_smooth + decel]) ipeak += ipeak_smooth - decel ipeaks.append(ipeak) # Plot peaks and deceleration phase of stride: if plot_test: from pylab import plt if isinstance(t, list): tplot = np.asarray(t) - t[0] else: tplot = np.linspace(0, np.size(ax), np.size(ax)) idecel = [x - decel for x in ipeaks] plt.plot(tplot, data, 'k-', tplot[ipeaks], data[ipeaks], 'rs') for id in idecel: plt.axvline(x=tplot[id]) plt.title('Maximum stride peaks') plt.show() # Compute the average vector for each deceleration phase: vectors = [] for ipeak in ipeaks: decel_vectors = np.asarray([[ax[i], ay[i], az[i]] for i in range(ipeak - decel, ipeak)]) vectors.append(np.mean(decel_vectors, axis=0)) # Compute the average deceleration vector and take the opposite direction: direction = -1 * np.mean(vectors, axis=0) # Return the unit vector in this direction: direction /= np.sqrt(direction.dot(direction)) # Plot vectors: if plot_test: from mhealthx.utilities import plot_vectors dx = [x[0] for x in vectors] dy = [x[1] for x in vectors] dz = [x[2] for x in vectors] hx, hy, hz = direction title = 'Average deceleration vectors + estimated walk direction' plot_vectors(dx, dy, dz, [hx], [hy], [hz], title) return direction