Example #1
0
import os, sys
import cPickle
import numpy as np
import matplotlib.pyplot as plt
import matplotlib.gridspec as gridspec
import matplotlib.image as image
# import tqdm

### use mpl 1.0 style
import matplotlib as mpl
mpl.style.use('classic')


import seaborn.apionly as sns
colors = sns.color_palette("colorblind")
sns.set_palette(sns.color_palette("colorblind"))

from keplerian import keplerian
from display import DisplayResults
# sys.path.append('/home/joao/Work/OPEN')
# from OPEN.ext.keplerian import keplerian


sys.path.append('.')
from styler import styler

# res = DisplayResults('')
# res.sample = np.atleast_2d(np.loadtxt('sample.txt'))

res = cPickle.load(open('BL2009_joss_figure1.pickle'))
Example #2
0
from __future__ import division
import argparse
import numpy as np
import pandas as pd
import matplotlib.pyplot as plt
import seaborn.apionly as sns

from sklearn.model_selection import learning_curve

from composition.analysis.load_sim import load_sim
from composition.analysis.preprocessing import get_train_test_sets
from composition.analysis.pipelines import get_pipeline

if __name__ == '__main__':

    sns.set_palette('muted')
    sns.set_color_codes()

    p = argparse.ArgumentParser(
        description='Runs extra modules over a given fileList')
    p.add_argument('-c',
                   '--classifier',
                   dest='classifier',
                   default='RF',
                   choices=['RF', 'KN'],
                   help='Option to specify classifier used')
    p.add_argument('--outdir',
                   dest='outdir',
                   default='/home/jbourbeau/public_html/figures/composition',
                   help='Output directory')
    args = p.parse_args()
import numpy as np
import os
import seaborn.apionly as sns
sns.set_palette('muted')
cls = (sns.color_palette())
import matplotlib.pyplot as plt


save_folder = '/Users/Adriaan/GitHubRepos/DiCarloLab_Repositories/Paper_16_RestlessTuning/Figures'
save_format = 'pdf'


def make_figure(fig_name='timing_tech',
                Acquisition_time=np.array([1.6,  0.122, 0.122]),
                AWG_overhead=np.array([0.093,  0.093, 0]),
                Processing_overhead=np.array([.164+.063,  .164+.063, 0]),
                Overhead=np.array([0.04, 0.04, 0.04]),
                methods=('Conventional-', 'Restless-', 'Restless+'),
                ):
    cls = (sns.color_palette('muted'))

    plt.rcParams.update({'font.size': 9, 'legend.labelspacing': 0,
                         'legend.columnspacing': .3,
                         'legend.handletextpad': .2})
    f, ax = plt.subplots(figsize=(3.3, .9))
    y_pos = np.array([.8, 0, -.8])+.1

    lefts = np.array([0, 0, 0])
    ax.barh(y_pos, AWG_overhead, color=cls[2], align='center',
            height=0.6, label='Set pars.')
    lefts = lefts+np.array(AWG_overhead)
Example #4
0
import numpy as np
import pandas as pd
import torch
import pickle

from tqdm import tqdm_notebook as tqdm

import statsmodels.formula.api as smf
import statsmodels.api as sm
import seaborn.apionly as sns

import matplotlib
import matplotlib.pyplot as plt

plt.style.use('clean')
sns.set_palette(['#8F223A', '#505B70', '#A6A29F'])
plt.rcParams['font.sans-serif'] = 'Verdana'
plt.rcParams['figure.figsize'] = (6.5, 4)

%matplotlib inline
%config InlineBackend.figure_format = 'retina'

def ft_ax(ax=None,
          y=1.03,
          yy=1.1,
          title=None,
          subtitle=None,
          source=None,
          add_box=False,
          left_axis=False):
    """
Example #5
0
def plot_joint_moment_breakdown(time,
                                joint_moments,
                                tendon_forces,
                                moment_arms,
                                dof_names,
                                muscle_names,
                                pdf_path,
                                csv_path,
                                ext_moments=None,
                                ext_names=None,
                                ext_colors=None,
                                mass=None):
    """Plots net joint moments, individual muscle moments, and, if included,
    any external moments in the system. Prints a pdf file with plots and a csv
    file containing data.

    N:     # of time points
    Ndof:  # of degrees-of-freedom
    Nmusc: # of muscles 

    Parameters
    ----------
    time (N,): Numpy array
        Vector of time points
    joint_moments (N, Ndof): Numpy array
        Array of experimental net joint moments.
    tendon_forces (N, Nmusc): Numpy array
        Array of computed tendon forces.
    moment_arms (N, Ndof, Nmusc): Numpy array
        Array of muscle moment arms, corresponding to each joint.
    dof_names (Ndof,): list
        List of strings containing degree-of-freedom names.
    muscle_names (Nmusc,): list
        List of strings containing muscle names.
    pdf_path: string
        Path and filename for PDF of final plots.
    csv_path: string
        Path and filename for CSV of moment breakdown data
    mass: kg
        (Optional). Subject mass to normalize moments by.
    ext_moments:
        (Optional). External moments applied to each degree-of-freedom (i.e.
        such as an exoskeleton device torque).

    """

    num_dofs = len(dof_names)
    num_muscles = len(muscle_names)

    # For writing moments to a file.
    dof_array = list()
    actuator_array = list()
    moments_array = list()
    all_moments = list()

    import seaborn.apionly as sns
    palette = sns.color_palette('muted')
    num_colors = 6
    sns.set_palette(palette)

    pgc = 100.0 * (time - time[0]) / (time[-1] - time[0])
    pgc_csv = np.linspace(0, 100, 400)
    fig = pl.figure(figsize=(8.5, 11))
    for idof in range(num_dofs):
        dof_name = dof_names[idof]
        ax = fig.add_subplot(num_dofs, 2, 2 * idof + 1)
        net_integ = np.trapz(np.abs(joint_moments[:, idof]), x=time)
        sum_actuators_shown = np.zeros_like(time)
        icolor = 0
        for imusc in range(num_muscles):
            muscle_name = muscle_names[imusc]
            if np.any(moment_arms[:, idof, imusc]) > 0.00001:
                this_moment = \
                        tendon_forces[:, imusc] * moment_arms[:, idof, imusc]
                mom_integ = np.trapz(np.abs(this_moment), time)
                if mom_integ > 0.05 * net_integ:
                    if np.floor(icolor / num_colors) == 0:
                        ls = '-'
                    elif np.floor(icolor / num_colors) == 1:
                        ls = '--'
                    else:
                        ls = '-.'
                    ax.plot(pgc, this_moment, label=muscle_name, linestyle=ls)
                    dof_array.append(dof_name)
                    actuator_array.append(muscle_name)
                    all_moments.append(np.interp(pgc_csv, pgc, this_moment))

                    sum_actuators_shown += this_moment
                    icolor += 1

        if ext_moments:
            num_ext = len(ext_moments)
            for iext in range(num_ext):

                ext_moment = ext_moments[iext]
                if ext_names:
                    ext_name = ext_names[iext]
                if ext_colors:
                    ext_color = ext_colors[iext]

                pgc_mod = 100.0 * (
                    (ext_moment.index - ext_moment.index[0]) * 1.0 /
                    (ext_moment.index[-1] - ext_moment.index[0]) * 1.0)

                ext_col = -1
                for colname in ext_moment.columns:
                    if colname in dof_name:
                        ext_col = colname
                        break
                if ext_col == -1:
                    raise Exception('Could not find exo torque for DOF %s.' %
                                    dof_name)
                if np.sum(np.abs(ext_moment[ext_col])) != 0:
                    sum_actuators_shown += ext_moment[ext_col]
                    ax.plot(pgc_mod,
                            ext_moment[ext_col],
                            color=ext_color if ext_color else 'blue',
                            label=ext_name if ext_name else 'external',
                            ls='dashed',
                            linewidth=1.5)
                    dof_array.append(dof_name)
                    actuator_array.append(ext_name if ext_name else 'external')
                    all_moments.append(
                        np.interp(pgc_csv, pgc_mod, ext_moment[ext_col]))

        ax.plot(pgc,
                sum_actuators_shown,
                label='sum actuators shown',
                color='gray',
                linewidth=2)

        ax.plot(pgc,
                joint_moments[:, idof],
                label='net',
                color='black',
                linewidth=2)
        dof_array.append(dof_name)
        actuator_array.append('net')
        all_moments.append(np.interp(pgc_csv, pgc, joint_moments[:, idof]))

        ax.set_title(dof_name, fontsize=8)
        ax.set_ylabel('moment (N-m)', fontsize=8)
        ax.legend(frameon=False,
                  bbox_to_anchor=(1, 1),
                  loc='upper left',
                  ncol=2,
                  fontsize=8)
        ax.tick_params(axis='both', labelsize=8)
    ax.set_xlabel('time (% gait cycle)', fontsize=8)

    fig.tight_layout()
    fig.savefig(pdf_path)
    pl.close(fig)

    multiindex_arrays = [dof_array, actuator_array]
    columns = pd.MultiIndex.from_arrays(multiindex_arrays,
                                        names=['DOF', 'actuator'])

    # Normalize by subject mass.
    if mass:
        all_moments_array = (np.array(all_moments).transpose() / mass)
        moments_df = pd.DataFrame(all_moments_array,
                                  columns=columns,
                                  index=pgc_csv)
        with file(csv_path, 'w') as f:
            f.write('# all columns are moments normalized by subject '
                    'mass (N-m/kg).\n')
            moments_df.to_csv(f)