def test_benchmark_time_series():
    dataset = bdp.DataSet()
    trial = bdp.Run('700', dataset)

    timeSeries = cbi.benchmark_time_series(trial)

    testing.assert_allclose(trial.taskSignals['RollAngle'], timeSeries['p'])
    testing.assert_allclose(trial.taskSignals['RollRate'], timeSeries['pD'])
    testing.assert_allclose(trial.taskSignals['RollRate'].time_derivative(),
                            timeSeries['pDD'])
    testing.assert_allclose(trial.taskSignals['SteerAngle'], timeSeries['d'])
    testing.assert_allclose(trial.taskSignals['SteerRate'], timeSeries['dD'])
    testing.assert_allclose(trial.taskSignals['SteerRate'].time_derivative(),
                            timeSeries['dDD'])
    testing.assert_allclose(trial.taskSignals['ForwardSpeed'], timeSeries['v'])
    testing.assert_allclose(trial.bicycleRiderParameters['g'], timeSeries['g'])
    testing.assert_allclose(trial.taskSignals['PullForce'], timeSeries['F'])
Example #2
0
def load_trials(runs, H):
    """Returns a dictionary of Run objects which were successfully computed and
    list of runs which had errors.

    Parameters
    ----------
    runs : list
        A list of run numbers to try to load.
    H : dictionary
        The H vector for the lateral force contributions to steer torque and
        roll torque for each rider.

    Returns
    -------
    trials : dictionary
        A dictionary of bicycledataprocess.Run objects. All in `runNums` must
        be present. These trials have an additional attribute `H` which holds
        the value for the bicycle model.
    errors : list
        A list of run numbers that had errors (primarily in the bump finding.


    """
    trials = {}
    errors = []
    dataset = bdp.DataSet()
    for i, r in enumerate(runs):
        try:
            trial = bdp.Run(r, dataset, filterFreq=15.)
        except bdp.bdpexceptions.TimeShiftError:
            errors.append(r)
        except IndexError:
            errors.append(r)
        else:
            trial.H = H[trial.metadata['Rider']]
            trials[r] = trial

    return trials, errors
with open(read('pathToGoodRuns')) as f:
    goodRuns = cPickle.load(f)

with open(read('pathToIdMat')) as f:
    idMat = cPickle.load(f)

dataset = bdp.DataSet()

roll = {k: [] for k in idMat.keys() + ['Whipple', 'Arm']}
steer = {k: [] for k in idMat.keys() + ['Whipple', 'Arm']}

allH = cbi.lateral_force_contribution(['Charlie', 'Jason', 'Luke'])

for runNum in goodRuns:
    trial = bdp.Run(runNum, dataset, filterFreq=15.)
    rider = trial.metadata['Rider']
    timeseries = cbi.benchmark_time_series(trial, subtractMean=True)
    for k, model in idMat.items():
        rollrsq, steerrsq, fig = cbi.input_prediction(timeseries, model)
        roll[k].append(rollrsq)
        steer[k].append(steerrsq)
        fig.savefig('plots/' + str(runNum) + '-' + k + '.png')
        plt.close(fig)
        del fig

    M, C1, K0, K2 = trial.bicycle.canonical(nominal=True)
    rollrsq, steerrsq, fig = cbi.input_prediction(timeseries,
                                                  (M, C1, K0, K2, allH[rider]))
    roll['Whipple'].append(rollrsq)
    steer['Whipple'].append(steerrsq)
        'Coefficient of Determination': [],
        'Maximum Error': []
    }
    max_num_samples = 0

    for run in runs:

        ts = {}
        ts['Steer Tube Torque'] = None
        ts['Compensated Steer Torque'] = None
        ts['Error'] = None

        try:
            trial = bdp.Run(run,
                            data_set,
                            filterFreq=15.,
                            pathToParameterData=PATH_TO_BICYCLE_PARAMETER_DATA,
                            forceRecalc=True)
        except bdp.bdpexceptions.TimeShiftError:

            for k in stats.keys():
                stats[k].append(np.nan)

            for k in ts.keys():
                ts[k] = [np.nan, np.nan]

        except IndexError:

            for k in stats.keys():
                stats[k].append(np.nan)
def test_benchmark_lstsq_matrices():
    dataset = bdp.DataSet()
    trial = bdp.Run('700', dataset)

    A, B, F = cbi.whipple_state_space(trial.metadata['Rider'], 1.0)
    H = np.dot(np.linalg.inv(B[2:]), F[2:])

    timeSeries = cbi.benchmark_time_series(trial, subtractMean=False)
    M, C1, K0, K2 = trial.bicycle.canonical(nominal=True)
    fixedValues = cbi.benchmark_canon_to_dict(M, C1, K0, K2, H)

    rollParams = [
        'Mpp', 'Mpd', 'C1pp', 'C1pd', 'K0pp', 'K0pd', 'K2pp', 'K2pd', 'HpF'
    ]

    A, B = cbi.benchmark_lstsq_matrices(rollParams, timeSeries, fixedValues)

    testing.assert_allclose(trial.taskSignals['RollRate'].time_derivative(),
                            A[:, 0])
    testing.assert_allclose(trial.taskSignals['SteerRate'].time_derivative(),
                            A[:, 1])
    testing.assert_allclose(
        trial.taskSignals['ForwardSpeed'] * trial.taskSignals['RollRate'],
        A[:, 2])
    testing.assert_allclose(
        trial.taskSignals['ForwardSpeed'] * trial.taskSignals['SteerRate'],
        A[:, 3])
    testing.assert_allclose(9.81 * trial.taskSignals['RollAngle'], A[:, 4])
    testing.assert_allclose(9.81 * trial.taskSignals['SteerAngle'], A[:, 5])
    testing.assert_allclose(
        trial.taskSignals['ForwardSpeed']**2 * trial.taskSignals['RollAngle'],
        A[:, 6])
    testing.assert_allclose(
        trial.taskSignals['ForwardSpeed']**2 * trial.taskSignals['SteerAngle'],
        A[:, 7])
    testing.assert_allclose(-trial.taskSignals['PullForce'], A[:, 8])
    testing.assert_allclose(np.zeros_like(trial.taskSignals['PullForce']), B)

    rollParams = ['Mpp', 'Mpd', 'C1pp', 'C1pd', 'K0pp', 'K0pd', 'K2pp', 'K2pd']

    A, B = cbi.benchmark_lstsq_matrices(rollParams, timeSeries, fixedValues)

    testing.assert_allclose(trial.taskSignals['RollRate'].time_derivative(),
                            A[:, 0])
    testing.assert_allclose(trial.taskSignals['SteerRate'].time_derivative(),
                            A[:, 1])
    testing.assert_allclose(
        trial.taskSignals['ForwardSpeed'] * trial.taskSignals['RollRate'],
        A[:, 2])
    testing.assert_allclose(
        trial.taskSignals['ForwardSpeed'] * trial.taskSignals['SteerRate'],
        A[:, 3])
    testing.assert_allclose(9.81 * trial.taskSignals['RollAngle'], A[:, 4])
    testing.assert_allclose(9.81 * trial.taskSignals['SteerAngle'], A[:, 5])
    testing.assert_allclose(
        trial.taskSignals['ForwardSpeed']**2 * trial.taskSignals['RollAngle'],
        A[:, 6])
    testing.assert_allclose(
        trial.taskSignals['ForwardSpeed']**2 * trial.taskSignals['SteerAngle'],
        A[:, 7])
    testing.assert_allclose(H[0] * trial.taskSignals['PullForce'], B)

    steerParams = [
        'Mdp', 'Mdd', 'C1dp', 'C1dd', 'K0dp', 'K0dd', 'K2dp', 'K2dd', 'HdF'
    ]

    A, B = cbi.benchmark_lstsq_matrices(steerParams, timeSeries, fixedValues)

    testing.assert_allclose(trial.taskSignals['RollRate'].time_derivative(),
                            A[:, 0])
    testing.assert_allclose(trial.taskSignals['SteerRate'].time_derivative(),
                            A[:, 1])

    testing.assert_allclose(
        trial.taskSignals['ForwardSpeed'] * trial.taskSignals['RollRate'],
        A[:, 2])
    testing.assert_allclose(
        trial.taskSignals['ForwardSpeed'] * trial.taskSignals['SteerRate'],
        A[:, 3])

    testing.assert_allclose(9.81 * trial.taskSignals['RollAngle'], A[:, 4])
    testing.assert_allclose(9.81 * trial.taskSignals['SteerAngle'], A[:, 5])

    testing.assert_allclose(
        trial.taskSignals['ForwardSpeed']**2 * trial.taskSignals['RollAngle'],
        A[:, 6])
    testing.assert_allclose(
        trial.taskSignals['ForwardSpeed']**2 * trial.taskSignals['SteerAngle'],
        A[:, 7])

    testing.assert_allclose(-trial.taskSignals['PullForce'], A[:, 8])
    testing.assert_allclose(trial.taskSignals['SteerTorque'], B)

    steerParams = [
        'Mdp', 'Mdd', 'C1dp', 'C1dd', 'K0dp', 'K0dd', 'K2dp', 'K2dd'
    ]

    A, B = cbi.benchmark_lstsq_matrices(steerParams, timeSeries, fixedValues)

    testing.assert_allclose(trial.taskSignals['RollRate'].time_derivative(),
                            A[:, 0])
    testing.assert_allclose(trial.taskSignals['SteerRate'].time_derivative(),
                            A[:, 1])

    testing.assert_allclose(
        trial.taskSignals['ForwardSpeed'] * trial.taskSignals['RollRate'],
        A[:, 2])
    testing.assert_allclose(
        trial.taskSignals['ForwardSpeed'] * trial.taskSignals['SteerRate'],
        A[:, 3])

    testing.assert_allclose(9.81 * trial.taskSignals['RollAngle'], A[:, 4])
    testing.assert_allclose(9.81 * trial.taskSignals['SteerAngle'], A[:, 5])

    testing.assert_allclose(
        trial.taskSignals['ForwardSpeed']**2 * trial.taskSignals['RollAngle'],
        A[:, 6])
    testing.assert_allclose(
        trial.taskSignals['ForwardSpeed']**2 * trial.taskSignals['SteerAngle'],
        A[:, 7])

    testing.assert_allclose(
        trial.taskSignals['SteerTorque'] +
        H[1] * trial.taskSignals['PullForce'], B)

    steerParams = ['Mdp', 'C1dd', 'K0dp', 'K2dp', 'K2dd']

    A, B = cbi.benchmark_lstsq_matrices(steerParams, timeSeries, fixedValues)

    testing.assert_allclose(trial.taskSignals['RollRate'].time_derivative(),
                            A[:, 0])
    testing.assert_allclose(
        trial.taskSignals['ForwardSpeed'] * trial.taskSignals['SteerRate'],
        A[:, 1])
    testing.assert_allclose(9.81 * trial.taskSignals['RollAngle'], A[:, 2])
    testing.assert_allclose(
        trial.taskSignals['ForwardSpeed']**2 * trial.taskSignals['RollAngle'],
        A[:, 3])
    testing.assert_allclose(
        trial.taskSignals['ForwardSpeed']**2 * trial.taskSignals['SteerAngle'],
        A[:, 4])

    testing.assert_allclose(
        H[1] * trial.taskSignals['PullForce'] +
        trial.taskSignals['SteerTorque'] -
        fixedValues['Mdd'] * trial.taskSignals['SteerRate'].time_derivative() -
        fixedValues['C1dp'] * trial.taskSignals['ForwardSpeed'] *
        trial.taskSignals['RollRate'] -
        fixedValues['K0dd'] * 9.81 * trial.taskSignals['SteerAngle'], B)
import bicycledataprocessor as bdp
import os
import numpy as np
import matplotlib.pyplot as plt

pathToBicycleMechanics = '/media/Data/Documents/School/UC Davis/Bicycle Mechanics'
pathToDatabase = os.path.join(
    pathToBicycleMechanics, 'BicycleDataProcessor/InstrumentedBicycleData.h5')
pathToParameterData = os.path.join(pathToBicycleMechanics,
                                   'BicycleParameters/data')

dataset = bdp.DataSet(fileName=pathToDatabase)
dataset.open()

trial = bdp.Run('00699',
                dataset,
                pathToParameterData=pathToParameterData,
                filterFreq=40.)

dataset.close()

golden_mean = (np.sqrt(5) - 1.0) / 2.0
fig_width = 6.0
fig_height = fig_width * golden_mean
params = {
    'backend': 'ps',
    'axes.labelsize': 8,
    'axes.titlesize': 10,
    'text.fontsize': 8,
    'legend.fontsize': 6,
    'xtick.labelsize': 8,
    'ytick.labelsize': 8,
Example #7
0
import bicycledataprocessor as bdp
import matplotlib.pyplot as plt
from math import sqrt

pathToBicycle = '/media/Data/Documents/School/UC Davis/Bicycle Mechanics'
pathToDatabase = pathToBicycle + '/BicycleDataProcessor/InstrumentedBicycleData.h5'
pathToParameters = pathToBicycle + '/BicycleParameters/data'

dataset = bdp.DataSet(fileName=pathToDatabase)
dataset.open()

trial = bdp.Run('00700', dataset, pathToParameters, forceRecalc=True)

dataset.close()

fig_width = 5.5
fig_height = 7.5
params = {
    'backend': 'ps',
    'axes.labelsize': 10,
    'text.fontsize': 10,
    'legend.fontsize': 6,
    'xtick.labelsize': 8,
    'ytick.labelsize': 8,
    'text.usetex': True,
    'figure.figsize': [fig_width, fig_height],
    'figure.dpi': 200,
    'figure.subplot.left': 0.1,
    'figure.subplot.bottom': 0.1
}
plt.rcParams.update(params)
    'xtick.labelsize': 6,
    'ytick.labelsize': 6,
    'text.usetex': True,
    'figure.figsize': fig_size,
    #'figure.subplot.hspace': 0.3,
    'figure.subplot.wspace': 0.25,
    #'figure.subplot.bottom': 0.1,
    #'figure.subplot.left': 0.1,
    'figure.dpi': 300
}

plt.rcParams.update(params)

for r, lims, tag in zip([283, 592], [(8., 24.), (0., 6.)],
                        ['treadmill', 'pavilion']):
    trial = bdp.Run(r, dataset, filterFreq=15.)

    fig = plt.figure()

    sigs = trial.taskSignals

    plotSigs = [['YawRate', 'RollRate', 'PitchRate', 'SteerRate'],
                ['ForwardSpeed'], ['YawAngle', 'RollAngle', 'SteerAngle'],
                ['LateralRearContact', 'LateralFrontContact'], ['SteerTorque'],
                ['PullForce']]

    legends = [[
        r'$\dot{\psi}$', r'$\dot{\phi}$', r'$\dot{\theta}_B$',
        r'$\dot{\delta}$'
    ], [r'$v$'], [r'$\psi$', r'$\phi$', r'$\delta$'], [r'$y_p$', r'$y_q$'],
               [r'$T_\delta$'], [r'$F_{c_l}$']]
Example #9
0
    stats = {
        'Root Mean Square of the Error': [],
        'Coefficient of Determination': [],
        'Maximum Error': []
    }
    max_num_samples = 0

    for run in runs:

        ts = {}
        ts['Steer Tube Torque'] = None
        ts['Compensated Steer Torque'] = None
        ts['Error'] = None

        try:
            trial = bdp.Run(run, data_set, filterFreq=15., forceRecalc=True)
        except bdp.bdpexceptions.TimeShiftError:

            for k in stats.keys():
                stats[k].append(np.nan)

            for k in ts.keys():
                ts[k] = [np.nan, np.nan]

        except IndexError:

            for k in stats.keys():
                stats[k].append(np.nan)

            for k in ts.keys():
                ts[k] = [np.nan, np.nan]
Example #10
0
import bicycledataprocessor as bdp
import os
import numpy as np
import matplotlib.pyplot as plt

pathToBicycleMechanics = '/media/Data/Documents/School/UC Davis/Bicycle Mechanics'
pathToDatabase = os.path.join(
    pathToBicycleMechanics, 'BicycleDataProcessor/InstrumentedBicycleData.h5')
pathToParameterData = os.path.join(pathToBicycleMechanics,
                                   'BicycleParameters/data')

dataset = bdp.DataSet(fileName=pathToDatabase)
dataset.open()

trial = bdp.Run('00690',
                dataset,
                pathToParameterData=pathToParameterData,
                forceRecalc=True)

dataset.close()

golden_mean = (np.sqrt(5) - 1.0) / 2.0
fig_width = 4.0
fig_height = fig_width * golden_mean
params = {
    'backend': 'ps',
    'axes.labelsize': 8,
    'axes.titlesize': 10,
    'text.fontsize': 8,
    'legend.fontsize': 6,
    'xtick.labelsize': 8,
    'ytick.labelsize': 8,
#!/usr/bin/env python
# -*- coding: utf-8 -*-
"""This script generates a plot showing the contributions to torque due to
friction and inertial effects."""

# standard library
import os
from ConfigParser import SafeConfigParser

import bicycledataprocessor as bdp
import matplotlib.pyplot as plt

dataset = bdp.DataSet()
dataset.open()

trial = bdp.Run('00700', dataset, forceRecalc=True)

dataset.close()

column_width_in_pt = 424.58624
inches_per_pt = 1.0 / 72.27
column_width_in_inches = column_width_in_pt * inches_per_pt
fig_width = column_width_in_inches
fig_height = 4.5
params = {
    'backend': 'ps',
    'axes.labelsize': 10,
    'text.fontsize': 10,
    'legend.fontsize': 6,
    'xtick.labelsize': 8,
    'ytick.labelsize': 8,
import bicycledataprocessor as bdp
import matplotlib.pyplot as plt

# get the paths to the data files
path_to_config = os.path.join(os.getcwd(), 'bicycle-data.cfg')
config = SafeConfigParser()
config.read(path_to_config)
PATH_TO_BICYCLE_PARAMETER_DATA = \
    config.get('data', 'PATH_TO_BICYCLE_PARAMETER_DATA')
PATH_TO_INSTRUMENTED_BICYCLE_DATA = \
    config.get('data', 'PATH_TO_INSTRUMENTED_BICYCLE_DATA')

dataset = bdp.DataSet(pathToDatabase=PATH_TO_INSTRUMENTED_BICYCLE_DATA)
dataset.open()

trial = bdp.Run('00700', dataset, PATH_TO_BICYCLE_PARAMETER_DATA,
                forceRecalc=True)

dataset.close()

column_width_in_pt = 424.58624
inches_per_pt = 1.0 / 72.27
column_width_in_inches = column_width_in_pt * inches_per_pt
fig_width = column_width_in_inches
fig_height = 4.5
params = {'backend': 'ps',
          'axes.labelsize': 10,
          'text.fontsize': 10,
          'legend.fontsize': 6,
          'xtick.labelsize': 8,
          'ytick.labelsize': 8,
          'text.usetex': True,