Example #1
0
def main(event, force):

    PATHS = utils.config_paths()

    trial_numbers = sorted(settings.keys())

    event_fname = '-'.join(event.lower().split(' '))

    hist_dir = utils.mkdir(
        os.path.join(PATHS['figures_dir'], 'gait-cycle-histograms'))
    grf_dir = utils.mkdir(os.path.join(PATHS['figures_dir'], 'vertical-grfs'))

    for trial_number in trial_numbers:

        msg = 'Cleaning {} event data for trial #{}'.format(
            event, trial_number)

        print('=' * len(msg))
        print(msg)
        print('=' * len(msg))

        trial = utils.Trial(trial_number)

        if force:
            trial.remove_precomputed_data()
        trial._write_event_data_frame_to_disk(event)
        trial._write_inverse_dynamics_to_disk(event)
        trial._section_into_gait_cycles(event)
        cleansed_gait_cycles, _ = trial._remove_bad_gait_cycles(event)

        gait_data = trial.gait_data_objs[event]

        axes = gait_data.gait_cycle_stats.hist()
        fig = plt.gcf()
        fig.savefig(os.path.join(hist_dir,
                                 trial_number + '-' + event_fname + '.png'),
                    dpi=300)
        plt.close(fig)

        axes = plot_gait_cycles(gait_data.gait_cycles, 'FP2.ForY')
        fig = plt.gcf()
        fig.savefig(os.path.join(
            grf_dir, trial_number + '-' + event_fname + '-before.png'),
                    dpi=300)
        plt.close(fig)

        axes = plot_gait_cycles(cleansed_gait_cycles, 'FP2.ForY')
        fig = plt.gcf()
        fig.savefig(os.path.join(
            grf_dir, trial_number + '-' + event_fname + '-after.png'),
                    dpi=300)
        plt.close(fig)

        del trial, fig, axes, cleansed_gait_cycles, gait_data
def main(event, force):

    PATHS = utils.config_paths()

    trial_numbers = sorted(settings.keys())

    event_fname = '-'.join(event.lower().split(' '))

    hist_dir = utils.mkdir(os.path.join(PATHS['figures_dir'],
                                        'gait-cycle-histograms'))
    grf_dir = utils.mkdir(os.path.join(PATHS['figures_dir'], 'vertical-grfs'))

    for trial_number in trial_numbers:

        msg = 'Cleaning {} event data for trial #{}'.format(event, trial_number)

        print('=' * len(msg))
        print(msg)
        print('=' * len(msg))

        trial = utils.Trial(trial_number)

        if force:
            trial.remove_precomputed_data()
        trial._write_event_data_frame_to_disk(event)
        trial._write_inverse_dynamics_to_disk(event)
        trial._section_into_gait_cycles(event)
        cleansed_gait_cycles, _ = trial._remove_bad_gait_cycles(event)

        gait_data = trial.gait_data_objs[event]

        axes = gait_data.gait_cycle_stats.hist()
        fig = plt.gcf()
        fig.savefig(os.path.join(hist_dir, trial_number + '-' + event_fname
                                 + '.png'), dpi=300)
        plt.close(fig)

        axes = plot_gait_cycles(gait_data.gait_cycles, 'FP2.ForY')
        fig = plt.gcf()
        fig.savefig(os.path.join(grf_dir, trial_number + '-' + event_fname +
                                 '-before.png'), dpi=300)
        plt.close(fig)

        axes = plot_gait_cycles(cleansed_gait_cycles, 'FP2.ForY')
        fig = plt.gcf()
        fig.savefig(os.path.join(grf_dir, trial_number + '-' + event_fname +
                                 '-after.png'), dpi=300)
        plt.close(fig)

        del trial, fig, axes, cleansed_gait_cycles, gait_data
import os
from collections import defaultdict

import numpy as np
import pandas as pd

import utils

print('Generating subject table.')

# This just returns absolute paths to the all the necessary files and
# directories.
script_path = os.path.realpath(__file__)
src_dir = os.path.dirname(script_path)
root_dir = os.path.realpath(os.path.join(src_dir, '..'))
raw_dir, processed_dir = utils.config_paths(root_dir)

tables = utils.generate_meta_data_tables(raw_dir)

subject_df = tables['TOP|subject']

for trial in ['001', '002']:
    if trial in subject_df.index:
        subject_df = subject_df.drop(trial)

# Create columns for each speed that contain a list of the trial numbers at
# that speed for that subject.
for_group = subject_df.copy()
for_group['Speed'] = tables['TOP|trial']['nominal-speed']
grouped_by_id_speed = for_group.groupby(['id', 'Speed'])
deviation of the planar lower extremity joint angles and joint torques from
perturbed and unperturbed gait cycles. The second is a box plot comparing
basic gait stats for perturbed and unperturbed gait cycles."""

import os

from numpy import rad2deg
from scipy.constants import golden
import matplotlib.pyplot as plt
import pandas
from gaitanalysis.utils import _percent_formatter
import seaborn as sbn

import utils

PATHS = utils.config_paths()

params = {'backend': 'ps',
          'axes.labelsize': 8,
          'axes.titlesize': 10,
          'font.size': 10,
          'legend.fontsize': 8,
          'xtick.labelsize': 8,
          'ytick.labelsize': 8,
          'text.usetex': True,
          'font.family': 'serif',
          'font.serif': ['Computer Modern'],
          'figure.figsize': (6.0, 6.0 / golden),
          }

plt.rcParams.update(params)
identification."""

import os

import numpy as np
from progressbar import ProgressBar
from joblib import Parallel, delayed

from model import QuietStandingModel
from measured_data import DataGenerator
import utils

NUM_GAINS = 8

file_name = 'bias_comparison_input_data.npz'
file_path = os.path.join(utils.config_paths(), file_name)

if os.path.isfile(file_path):

    print('Loading precomputed input data.')

    with np.load(file_path) as data:
        # time = data['time']
        ref_noise_stds = data['ref_noise_stds']
        platform_pos_mags = data['platform_pos_mags']
        platform_acc_stds = data['platform_acc_stds']
        reference_noises = data['reference_noises']
        measured_accel = data['measured_accel']
        measured_states = data['measured_states']
        measured_joint_torques = data['measured_joint_torques']
#!/usr/bin/env python

import os

import sympy as sm
from sympy.physics.vector import vlatex

from model import QuietStandingModel
import utils

paths = utils.config_paths()

m = QuietStandingModel()
m.derive()

# Generate the equations of motion: fr + fr*
fr_plus_frstar = sm.trigsimp(m.fr_plus_frstar)

template = \
r"""\begin{{bmatrix}}
  0 \\
  0 \\
  0 \\
  0
\end{{bmatrix}}
=
\begin{{bmatrix}}
{rows}
\end{{bmatrix}}"""

rows = []
import os
from collections import defaultdict

import numpy as np
import pandas as pd

import utils

print('Generating subject table.')

# This just returns absolute paths to the all the necessary files and
# directories.
script_path = os.path.realpath(__file__)
src_dir = os.path.dirname(script_path)
root_dir = os.path.realpath(os.path.join(src_dir, '..'))
raw_dir, processed_dir = utils.config_paths(root_dir)

tables = utils.generate_meta_data_tables(raw_dir)

subject_df = tables['TOP|subject']

for trial in ['001', '002']:
    if trial in subject_df.index:
        subject_df = subject_df.drop(trial)

# Create columns for each speed that contain a list of the trial numbers at
# that speed for that subject.
for_group = subject_df.copy()
for_group['Speed'] = tables['TOP|trial']['nominal-speed']
grouped_by_id_speed = for_group.groupby(['id', 'Speed'])
def load_open_loop_trajectories():
    """Returns an optimal solution of the open loop trajectories of the 7
    link planar walker for a single gait cycle.

    Returns
    -------
    state_trajectories : ndarray, shape(18, 800)
        The trajectories of the system states through half a gait cycle.
    input_trajectories : ndarray, shape(9, 800)
        The open loop control trajectories.
    gait_cycle_duration : float
        The duration of the gait cycle (heel strike to heel strike) in
        seconds.

    Notes
    -----

    System States

    Index Name Description

    0     q1   x hip translation wrt ground
    1     q2   y hip translation wrt ground
    2     q3   trunk z rotation wrt ground
    3     q4   right thigh z rotation wrt trunk
    4     q5   right shank z rotation wrt right thigh
    5     q6   right foot z rotation wrt right shank
    6     q7   left thigh z rotation wrt trunk
    7     q8   left shank z rotation wrt left thigh
    8     q9   left foot z rotation wrt left shank
    9     u1   x hip translation wrt ground
    10    u2   y hip translation wrt ground
    11    u3   trunk z rotation wrt ground
    12    u4   right thigh z rotation wrt trunk
    13    u5   right shank z rotation wrt right thigh
    14    u6   right foot z rotation wrt right shank
    15    u7   left thigh z rotation wrt trunk
    16    u8   left shank z rotation wrt left thigh
    17    u9   left foot z rotation wrt left shank

    Specified Inputs

    0 t1: x force applied to trunk mass center
    1 t2: y force applied to trunk mass center
    2 t3: torque between ground and trunk
    3 t4: torque between right thigh and trunk
    4 t5: torque between right thigh and right shank
    5 t6: torque between right foot and right shank
    6 t7: torque between left thigh and trunk
    7 t8: torque between left thigh and left shank
    8 t9: torque between left foot and left shank

    """

    # this loads a half gait cycle solution
    d = loadmat(os.path.join(utils.config_paths()['processed_data_dir'],
                             'optimal-open-loop-trajectories.mat'))

    # The trunk degrees of freedom stay the same but the left and right need
    # to switch.

    state_trajectories = np.zeros((18, 800))

    # q
    state_trajectories[0] = np.hstack((d['x'][0], d['x'][0] + d['x'][0, -1]))
    state_trajectories[1:3] = np.hstack((d['x'][1:3], d['x'][1:3]))
    state_trajectories[3:6, :] = np.hstack((d['x'][3:6], d['x'][6:9]))
    state_trajectories[6:9, :] = np.hstack((d['x'][6:9], d['x'][3:6]))

    # q'
    state_trajectories[9:12] = np.hstack((d['x'][9:12], d['x'][9:12]))
    state_trajectories[12:15, :] = np.hstack((d['x'][12:15], d['x'][15:18]))
    state_trajectories[15:18, :] = np.hstack((d['x'][15:18], d['x'][12:15]))

    # u
    input_trajectories = np.zeros((9, 800))

    input_trajectories[:3] = np.hstack((d['u'][:3], d['u'][:3]))
    input_trajectories[3:6, :] = np.hstack((d['u'][3:6], d['u'][6:9]))
    input_trajectories[6:9, :] = np.hstack((d['u'][6:9], d['u'][3:6]))

    duration = 2.0 * d['dur']

    return state_trajectories, input_trajectories, duration
"""This script generates the subject table in the paper by parsing the meta
data."""

import os
from collections import defaultdict

import numpy as np
import pandas as pd

import utils
from gait_landmark_settings import settings

print('Generating subject table.')

PATHS = utils.config_paths()

tables = utils.generate_meta_data_tables(PATHS['raw_data_dir'])

subject_df = tables['TOP|subject']

# Only select the trials we use from gait_landmark_settings (skip subject
# #9)
all_trials = set(subject_df.index)
trials_for_this_study = set(settings.keys())
bad_trials = all_trials.difference(trials_for_this_study)

for trial in all_trials:
    if trial in bad_trials or subject_df.ix[trial, 'id'] == 9:
        subject_df = subject_df.drop(trial)
import os

from numpy import rad2deg
from scipy.constants import golden
import matplotlib.pyplot as plt
import pandas
from gaitanalysis.utils import _percent_formatter
import seaborn as sbn

from utils import (trial_file_paths, load_data, remove_bad_gait_cycles,
                   config_paths)

script_path = os.path.realpath(__file__)
src_dir = os.path.dirname(script_path)
root_dir = os.path.realpath(os.path.join(src_dir, '..'))
raw_dir, tmp = config_paths(root_dir)

params = {
    'backend': 'ps',
    'axes.labelsize': 8,
    'axes.titlesize': 10,
    'font.size': 10,
    'legend.fontsize': 8,
    'xtick.labelsize': 8,
    'ytick.labelsize': 8,
    'text.usetex': True,
    'font.family': 'serif',
    'font.serif': ['Computer Modern'],
    'figure.figsize': (6.0, 6.0 / golden),
}
import logbook

from model import QuietStandingModel
import indirect_collocation
import direct_identification
import utils

KNOWN_GAINS = np.array([[950.0, 175.0, 185.0, 50.0],
                        [45.0, 290.0, 60.0, 26.0]])

file_names = {'input_data': 'bias_comparison_input_data.npz',
              'direct_results': 'directly-identified-gains.npy',
              'indirect_results': 'indirectly-indentified-gains.npz',
              'indirect_times': 'indirect-times.npz',
              'indirect_status': 'indirect-status.npz'}
file_paths = {k: os.path.join(utils.config_paths(), v) for k, v in
              file_names.items()}

# TODO : This is a bad hack. Fix.
from generate_bias_comparison_input_data import (ref_noise_stds,
                                                 platform_pos_mags,
                                                 platform_acc_stds,
                                                 reference_noises,
                                                 measured_accel,
                                                 measured_states,
                                                 measured_joint_torques)


def identify_gains_indirectly():
    # create a Problem for each of the platform eaccelerations because that
    # is although it seems like you may be able to change out the
#!/usr/bin/env python
"""This script generates two plots from an example identification. The first
shows the identified controller gains and the second shows how well the
predicted torques fit the measured torques."""

# standard library
import os

# external
from scipy.constants import golden
import matplotlib.pyplot as plt

# local
import utils

paths = utils.config_paths()

params = {
    'backend': 'ps',
    'axes.labelsize': 8,
    'axes.titlesize': 8,
    'font.size': 10,
    'legend.fontsize': 6,
    'xtick.labelsize': 6,
    'ytick.labelsize': 6,
    'text.usetex': True,
    'font.family': 'serif',
    'font.serif': ['Computer Modern'],
    'figure.figsize': (6.0, 6.0 / golden),
}
import os

from numpy import rad2deg
from scipy.constants import golden
import matplotlib.pyplot as plt
import pandas
from gaitanalysis.utils import _percent_formatter
import seaborn as sbn

from utils import (trial_file_paths, load_data, remove_bad_gait_cycles,
                   config_paths)

script_path = os.path.realpath(__file__)
src_dir = os.path.dirname(script_path)
root_dir = os.path.realpath(os.path.join(src_dir, '..'))
raw_dir, tmp = config_paths(root_dir)

params = {'backend': 'ps',
          'axes.labelsize': 8,
          'axes.titlesize': 10,
          'font.size': 10,
          'legend.fontsize': 8,
          'xtick.labelsize': 8,
          'ytick.labelsize': 8,
          'text.usetex': True,
          'font.family': 'serif',
          'font.serif': ['Computer Modern'],
          'figure.figsize': (6.0, 6.0 / golden),
          }

plt.rcParams.update(params)
Example #14
0
# Identify $\mathbf{m}^*(t)$ and $\mathbf{K}(\varphi)$ (joint isolated
# structure)
for i, row in enumerate(gain_inclusion_matrix):
    row[2 * i:2 * i + 2] = True
result = solver.solve(gain_inclusion_matrix=gain_inclusion_matrix)
joint_isolated_control_vafs = utils.variance_accounted_for(
    result[-1], solver.validation_data, trial.controls)

# Identify $\mathbf{m}^*(t)$ and $\mathbf{K}(\varphi)$ (full gain matrix)

# Note that this solution will take 30 minutes to and hour if the
# `ignore_cov` flag is False. This is due to a speed bottleneck in
# `dtk.process.least_squares_variance`.

result = solver.solve(ignore_cov=True)
full_control_vafs = utils.variance_accounted_for(result[-1],
                                                 solver.validation_data,
                                                 trial.controls)

# Compare VAF for each identification
vafs = no_control_vafs.copy()
for k, v in vafs.items():
    vafs[k] = [v, joint_isolated_control_vafs[k], full_control_vafs[k]]

vaf_df = pandas.DataFrame(
    vafs, index=['No Control', 'Joint Isolated Control', 'Full Control'])

fname = os.path.join(utils.config_paths()['tables_dir'],
                     'no-control-vaf-table.tex')
vaf_df.T.to_latex(fname)
for i, row in enumerate(gain_inclusion_matrix):
    row[2 * i:2 * i + 2] = True
result = solver.solve(gain_inclusion_matrix=gain_inclusion_matrix)
joint_isolated_control_vafs = utils.variance_accounted_for(
    result[-1], solver.validation_data, trial.controls)

# Identify $\mathbf{m}^*(t)$ and $\mathbf{K}(\varphi)$ (full gain matrix)

# Note that this solution will take 30 minutes to and hour if the
# `ignore_cov` flag is False. This is due to a speed bottleneck in
# `dtk.process.least_squares_variance`.

result = solver.solve(ignore_cov=True)
full_control_vafs = utils.variance_accounted_for(result[-1],
                                                 solver.validation_data,
                                                 trial.controls)

# Compare VAF for each identification
vafs = no_control_vafs.copy()
for k, v in vafs.items():
    vafs[k] = [v, joint_isolated_control_vafs[k], full_control_vafs[k]]


vaf_df = pandas.DataFrame(vafs, index=['No Control',
                                       'Joint Isolated Control',
                                       'Full Control'])

fname = os.path.join(utils.config_paths()['tables_dir'],
                     'no-control-vaf-table.tex')
vaf_df.T.to_latex(fname)