def inverseKinematics():
    import os
    import re
    import shutil
    import opensim as osim
    import directories

    # Global Directories
    allDir = list(directories.main(directories))
    parentDir = allDir[0]
    paramsDir = allDir[1]
    subID = allDir[4]
    subResultsDir = allDir[5]
    ikResultsDir = allDir[6]

    # Clear Inverse Kinematics Folder
    if os.path.exists(ikResultsDir):
        shutil.rmtree(ikResultsDir, ignore_errors=True)
    if not os.path.exists(ikResultsDir):
        os.mkdir(ikResultsDir)

    # Input settings File
    genericSettings = paramsDir + "/setupIK.xml"

    # Input trc File
    dataFiles = parentDir + "/data/osDemo"
    ikMarkerFileName = "subject01_walk1.trc"
    ikMarkerFile = dataFiles + "/" + ikMarkerFileName
    shutil.copy(ikMarkerFile, ikResultsDir + "/" + ikMarkerFileName)

    # Load scaled Model
    aModel = osim.Model(subResultsDir + "/" + subID + ".osim")

    # Import Inverse Kinematics Tool
    ikTool = osim.InverseKinematicsTool(genericSettings)

    # Tell IK tool to use loaded model
    ikTool.setModel(aModel)

    # Get scaled marker file + data
    markerData = osim.MarkerData(ikMarkerFile)
    # Get Initial and Final Time
    initial_time = markerData.getStartFrameTime()
    final_time = markerData.getLastFrameTime()
    # set IK tool for this trial
    ikName = re.sub('.trc', '', ikMarkerFileName)

    ikTool.setName(ikName)
    ikTool.setMarkerDataFileName(ikMarkerFile)
    ikTool.setStartTime(initial_time)
    ikTool.setEndTime(final_time)
    ikTool.setOutputMotionFileName(ikResultsDir + "/" + ikName + "_ik.mot")

    # Run IK
    ikTool.run()
    ikTool.printToXML(ikResultsDir + "/" + "setupIK.xml")
    # Clear terminal
    os.system('cls' if os.name == 'nt' else 'clear')
    
    return()
def computedMuscleControl():
    allDir = list(directories.main(directories))
    paramsDir = allDir[1]
    subID = allDir[4]
    subResultsDir = allDir[5]
    ikResultsDir = allDir[6]
    idResultsDir = allDir[7]
    rraResultsDir = allDir[9]
    cmcResultsDir = allDir[10]
    # Input Files
    idData = idResultsDir + "/subject01_walk1_extLoads.xml"
    rraKinematics = rraResultsDir + "/" + "_kinematics_q.sto"
    adjustedModel = rraResultsDir + "/" + subID + "_adjustedModel.osim"
    # Set XML file Variables
    cmcTasks = paramsDir + "/" + "cmcTasks.xml"
    cmcActuators = paramsDir + "/" + "cmcActuators.xml"
    cmcControlConstraints = paramsDir + "/" + "cmcControlConstraints.xml"
    osimGUI = paramsDir + "/" + "osimGUI.xml"
    if os.path.exists(cmcResultsDir):
        shutil.rmtree(cmcResultsDir, ignore_errors=True)
    if not os.path.exists(cmcResultsDir):
        os.mkdir(cmcResultsDir)

    # Load Model
    aModel = osim.Model(adjustedModel)

    # initialize system
    aModel.initSystem()

    cmcTool = osim.CMCTool()
    cmcTool.setModel(aModel)
    cmcTool.setModelFilename(subID + ".osim")
    cmcTool.setDesiredKinematicsFileName(rraKinematics)
    cmcTool.setTaskSetFileName(cmcTasks)
    cmcTool.setExternalLoadsFileName(idData)
    cmcTool.setConstraintsFileName(cmcControlConstraints)
    cmcTool.setStartTime(0.8)
    cmcTool.setFinalTime(1.2)
    cmcTool.setLowpassCutoffFrequency(-1)
    cmcTool.setMaxDT(1)
    cmcTool.setMinDT(0.0000000001)
    cmcTool.setErrorTolerance(0.00001)

    # Force Set
    myForceSet = osim.ForceSet(aModel, cmcActuators)
    cmcTool.setReplaceForceSet(False)
    cmcTool.setResultsDir(cmcResultsDir)

    # Manually append Force Set
    modelForceSet = aModel.updForceSet()
    for i in range(myForceSet.getSize()):
        aModel.updForceSet().append(myForceSet.get(i))

    cmcTool.run()
    cmcTool.printToXML(cmcResultsDir + "/" + "cmcSetup.xml")
    return ()
def run(initial_time, final_time):
    """
    inputs
    initial time 
    final time
    actuator file = soActuators
    kinematics file = subject01_walk1_ik.mot

    outputs
    

    """

    import os
    import re
    import shutil
    import opensim as osim
    import directories

    allDir = list(directories.main(directories))
    paramsDir = allDir[1]
    subID = allDir[4]
    subResultsDir = allDir[5]
    ikResultsDir = allDir[6]
    idResultsDir = allDir[7]
    soResultsDir = allDir[8]

    actuatorFile = paramsDir + "/soActuators.xml"
    genericSetupSO = paramsDir + "/" + "setupSO.xml"
    ikFileName = "subject01_walk1_ik.mot"
    ikFile = ikResultsDir + "/" + ikFileName

    if os.path.exists(soResultsDir):
        shutil.rmtree(soResultsDir, ignore_errors=True)
    if not os.path.exists(soResultsDir):
        os.mkdir(soResultsDir)

    # Load Model
    aModel = osim.Model(subResultsDir + "/" + subID + ".osim")
    pelvisIndex = aModel.getBodySet().getIndex("pelvis")
    pelvisCOM_Vec3 = osim.Vec3()
    aModel.getBodySet().get(pelvisIndex).getMassCenter(pelvisCOM_Vec3)

    # add reserve actuators
    myForceSet = osim.ForceSet(aModel, actuatorFile)
    # print(aModel.getForceSet().getSize())

    FX = osim.PointActuator.safeDownCast(myForceSet.get(0))
    FX.set_point(pelvisCOM_Vec3)
    FY = osim.PointActuator.safeDownCast(myForceSet.get(1))
    FY.set_point(pelvisCOM_Vec3)
    FZ = osim.PointActuator.safeDownCast(myForceSet.get(2))
    FZ.set_point(pelvisCOM_Vec3)

    for i in range(myForceSet.getSize()):
        aModel.updForceSet().append(myForceSet.get(i))
    print(aModel.getForceSet().getSize())

    # initialize system
    aModel.initSystem()
    # Initialize External Loads File from Generic File
    extLoads = idResultsDir + "/subject01_walk1_extLoads.xml"

    # Get .mot data to determine time range
    # motCoordsData = osim.Storage(ikFile)

    # Get initial and final time
    # initial_time = motCoordsData.getFirstTime()
    # final_time = motCoordsData.getLastTime()

    # Analyze Tool Setup
    analyzeTool = osim.AnalyzeTool(genericSetupSO)
    analyzeTool.setInitialTime(initial_time)
    analyzeTool.setFinalTime(final_time)
    analyzeTool.setResultsDir(soResultsDir)
    analyzeTool.setModelFilename("")
    analyzeTool.setName(re.sub('_ik.mot', '', ikFileName))
    myForceSetArray = analyzeTool.getForceSetFiles()
    myForceSetArray.set(0, "")
    analyzeTool.setReplaceForceSet(False)
    analyzeTool.setForceSetFiles(myForceSetArray)

    # Set coordinates
    coordtype = "mot"
    if coordtype == "mot":
        analyzeTool.setStatesFileName("")
        analyzeTool.setCoordinatesFileName(ikFile)
    elif coordtype == "states":
        analyzeTool.setStatesFileName(ikFile)
        analyzeTool.setCoordinatesFileName("")

    analyzeTool.setExternalLoadsFileName(extLoads)
    analyzeTool.setModel(aModel)
    analyzeTool.run()

    analyzeTool.printToXML(soResultsDir + "/" +
                           re.sub('ik.mot', 'outSetupSO.xml', ikFileName))
    aModel.printToXML(soResultsDir + "/" + subID + "_soActuators.osim")
    os.system('cls' if os.name == 'nt' else 'clear')
    return ()
Exemple #4
0
def run(filename):

    import os
    import pandas as pd
    import matplotlib.pyplot as plt
    import directories

    allDir = list(directories.main(directories))
    idResultsDir = allDir[7]
    soResultsDir = allDir[8]
    cmcResultsDir = allDir[10]

    # Plotting Function
    # Plot Inverse Dynamincs STO file
    if filename == idResultsDir + "/" + "subject01_walk1_id.sto":
        data = idResultsDir + "/" + "idData.csv"
        df = pd.read_csv(data,
                         usecols=[
                             'time', 'pelvis_tilt_moment',
                             'pelvis_list_moment', 'pelvis_rotation_moment'
                         ],
                         index_col='time')

        df.plot(title='Inverse Dynamics')
        fig = plt.gcf()
        plt.savefig(idResultsDir + "/" + "idFigure")

# Static Optimization
    if filename == soResultsDir + "/" + "subject01_walk1_StaticOptimization_force.sto":
        data = soResultsDir + "/" + "soData.csv"
        df = pd.read_csv(
            data,
            usecols=['time', 'glut_med1_r', 'glut_med2_r', 'glut_med3_r'],
            index_col='time')
        df.plot(title='Static Optimization')
        fig = plt.gcf()
        fig.savefig(soResultsDir + "/" + "soFigure")

# Plot so Joint RXN Loading STO file
    if filename == soResultsDir + "/" + "_Gait2354 Joint RXN_ReactionLoads.sto":
        data = soResultsDir + "/" + "soJrData.csv"
        df = pd.read_csv(data,
                         usecols=[
                             'time', 'ground_pelvis_on_pelvis_in_ground_fx',
                             'ground_pelvis_on_pelvis_in_ground_fy',
                             'ground_pelvis_on_pelvis_in_ground_fz'
                         ],
                         index_col='time')
        df.plot(title='Joint RXN Load')
        fig = plt.gcf()
        fig.savefig(soResultsDir + "/" + "soJrFigure")

# Plot so Joint RXN Loading STO file
    if filename == cmcResultsDir + "/" + "_Gait2354 Joint RXN_ReactionLoads.sto":
        data = cmcResultsDir + "/" + "cmcJrData.csv"
        df = pd.read_csv(data,
                         usecols=[
                             'time', 'ground_pelvis_on_pelvis_in_ground_fx',
                             'ground_pelvis_on_pelvis_in_ground_fy',
                             'ground_pelvis_on_pelvis_in_ground_fz'
                         ],
                         index_col='time')
        df.plot(title='Joint RXN Load')
        fig = plt.gcf()
        fig.savefig(cmcResultsDir + "/" + "cmcJrFigure")

    os.system('cls' if os.name == 'nt' else 'clear')
    return ()
def run(setup, resultsDirectory):
    import os
    import re
    import shutil
    import opensim as osim
    import directories

    allDir = list(directories.main(directories))
    paramsDir = allDir[1]
    subID = allDir[4]
    subResultsDir = allDir[5]
    # ikResultsDir = allDir[6]
    # idResultsDir = allDir[7]
    # soResultsDir = allDir[8]
    # cmcResultsDir = allDir[10]
    # jrResultsDir = allDir[11]

    # # actuatorFile = paramsDir + "/soActuators.xml"
    # # genericSetupSO = paramsDir + "/" + "setupSO.xml"
    # ikFileName = "subject01_walk1_ik.mot"
    # ikFile = ikResultsDir + "/" + ikFileName
    # # soForces = soResultsDir + "/" + "subject01_walk1_StaticOptimization_force.sto"
    # if os.path.exists(jrResultsDir):
    #     shutil.rmtree(jrResultsDir, ignore_errors=True)
    # if not os.path.exists(jrResultsDir):
    #     os.mkdir(jrResultsDir)

    # # Load Model
    aModel = osim.Model(subResultsDir + "/" + subID + ".osim")
    # # initialize system
    aModel.initSystem()
    # # Initialize External Loads File from Generic File
    # extLoads = idResultsDir + "/subject01_walk1_extLoads.xml"
    # # Get .mot data to determine time range
    # motCoordsData = osim.Storage(ikFile)
    # # Get initial and final time
    # initial_time = motCoordsData.getFirstTime()
    # final_time = motCoordsData.getLastTime()

    # Analyze Tool Setup for Static Optimization
    analyzeTool = osim.AnalyzeTool(setup)
    analyzeTool.setModel(aModel)
    analyzeTool.setResultsDir(resultsDirectory)
    analyzeTool.run()

    # analyzeTool = osim.AnalyzeTool(cmcJrSetup)
    # analyzeTool.setExternalLoadsFileName(extLoads)
    # analyzeTool.setInitialTime(initial_time)
    # analyzeTool.setFinalTime(final_time)
    # analyzeTool.setLowpassCutoffFrequency(6)
    # analyzeTool.setOutputPrecision(20)

    # myForceSet = osim.ForceSet(aModel, actuatorFile)
    # for i in range(myForceSet.getSize()):
    #     aModel.updForceSet().append(myForceSet.get(i))
    # print(aModel.getForceSet().getSize())

    # analysisSet = analyzeTool.getAnalysisSet()
    # myForceSetArray = analyzeTool.getForceSetFiles()
    # myForceSetArray.set(0, "")
    # analyzeTool.setReplaceForceSet(False)
    # analyzeTool.setForceSetFiles(myForceSetArray)

    # # Joint Reaction Analysis
    # jrTool = osim.JointReaction(jrSetup)
    # analysisSet.cloneAndAppend(jrTool)

    # # Set coordinates
    # coordtype = "mot"
    # if coordtype == "mot":
    #     analyzeTool.setStatesFileName("")
    #     analyzeTool.setCoordinatesFileName(ikFile)
    # elif coordtype == "states":
    #     analyzeTool.setStatesFileName(ikFile)
    #     analyzeTool.setCoordinatesFileName("")

    # analyzeTool.verifyControlsStates()
    # analyzeTool.setResultsDir(jrResultsDir)
    # # analyzeTool.printToXML(paramsDir +"/setupJR.xml")
    # analyzeTool.run()
    return ()
    os.system('cls' if os.name == 'nt' else 'clear')
def scale():
    import os
    import opensim as osim
    import shutil
    import directories

    # Global Directories
    allDir = list(directories.main(directories))
    parentDir = allDir[0]
    paramsDir = allDir[1]
    genericDir = allDir[2]
    subID = allDir[4]
    subResultsDir = allDir[5]

    # Get generic Model
    genericModel = "gait2354_LockedJoints.osim"
    genericModelFile = genericDir + "/" + genericModel

    if not os.path.exists(subResultsDir):
        os.mkdir(subResultsDir)

    # generic input XML files
    scaleSetupFull = paramsDir + "/setupScale.xml"
    markerSetFull = paramsDir + "/markerSet.xml"
    # Make scale directory if non-existent
    scaleResultsDir = subResultsDir + "/scale"
    if os.path.exists(scaleResultsDir):
        shutil.rmtree(scaleResultsDir, ignore_errors=True)
    if not os.path.exists(scaleResultsDir):
        os.mkdir(scaleResultsDir)
    # Output XML Files
    outputScaleFile = subID + "_scaleFactors.xml"
    adjustedMarkerSet = subID + "_movedMarkers.xml"
    # Output Model Files
    outputModelFile = subID + ".osim"
    # Input Data Files
    dataFiles = parentDir + "/data/osDemo"
    staticMarkerFile = "subject01_static.trc"
    staticMarkerFull = dataFiles + "/" + staticMarkerFile
    shutil.copy(staticMarkerFull, scaleResultsDir + "/" + staticMarkerFile)

    # Output Data Files
    staticCoordinates = subID + "_staticCoordinates.mot"
    # Subject Measurements
    subjectMass = 72.60000000

    # Load Model
    aModel = osim.Model(genericModelFile)

    aModel.setName(subID)
    # Initialize System
    aModel.initSystem()
    aState = aModel.initSystem()

    # Add Marker Set
    newMarkers = osim.MarkerSet(markerSetFull)
    aModel.replaceMarkerSet(aState, newMarkers)
    # Re-initialize State
    aState = aModel.initSystem()
    # Get Time Array for .trc file
    markerData = osim.MarkerData(staticMarkerFull)
    # Get Initial and Final Time
    initial_time = markerData.getStartFrameTime()
    final_time = markerData.getLastFrameTime()
    # Create an array double and apply the time range
    TimeArray = osim.ArrayDouble()
    TimeArray.set(0, initial_time)
    TimeArray.set(1, final_time)
    # Scale Tool
    scaleTool = osim.ScaleTool(scaleSetupFull)
    scaleTool.setSubjectMass(subjectMass)

    # GenericModelMaker-
    # Tell scale tool to use the loaded model
    scaleTool.getGenericModelMaker().setModelFileName(genericDir + "/" +
                                                      genericModel)
    # # Set the Marker Set file (incase a markerset isnt attached to the model)
    scaleTool.getGenericModelMaker().setMarkerSetFileName(markerSetFull)

    # ModelScaler-
    # Whether or not to use the model scaler during scale
    scaleTool.getModelScaler().setApply(1)
    # Set the marker file (.trc) to be used for scaling
    scaleTool.getModelScaler().setMarkerFileName("/" + staticMarkerFile)
    # set a time range
    scaleTool.getModelScaler().setTimeRange(TimeArray)
    # Indicating whether or not to preserve relative mass between segments
    scaleTool.getModelScaler().setPreserveMassDist(1)
    # Name of OpenSim model file (.osim) to write when done scaling.
    scaleTool.getModelScaler().setOutputModelFileName("")
    # Filename to write scale factors that were applied to the unscaled model (optional)
    scaleTool.getModelScaler().setOutputScaleFileName(outputScaleFile)

    # Run model scaler Tool
    scaleTool.getModelScaler().processModel(aState, aModel, scaleResultsDir,
                                            subjectMass)

    # initialize
    aState = aModel.initSystem()

    # # Marker Placer
    # # Whether or not to use the model scaler during scale
    scaleTool.getMarkerPlacer().setApply(1)
    # # Set the marker placer time range
    scaleTool.getMarkerPlacer().setTimeRange(TimeArray)
    # # Set the marker file (.trc) to be used for scaling
    scaleTool.getMarkerPlacer().setStaticPoseFileName("/" + staticMarkerFile)
    # # Return name to a variable for future use in functions
    scaledAdjustedModel = scaleTool.getMarkerPlacer().setOutputModelFileName(
        "/" + outputModelFile)
    # # Set the output motion filename
    scaleTool.getMarkerPlacer().setOutputMotionFileName("/" +
                                                        staticCoordinates)
    # # Set the output xml of the marker adjustments
    scaleTool.getMarkerPlacer().setOutputMarkerFileName("/" +
                                                        adjustedMarkerSet)
    # # Maximum amount of movement allowed in marker data when averaging
    scaleTool.getMarkerPlacer().setMaxMarkerMovement(-1)
    # # Run Marker Placer
    scaleTool.getMarkerPlacer().processModel(aState, aModel, scaleResultsDir)
    scaleTool.printToXML(scaleResultsDir + "/" + subID + "_setupScale.xml")
    # Clear Terminal
    os.system('cls' if os.name == 'nt' else 'clear')

    shutil.copy(scaleResultsDir + "/" + outputModelFile, subResultsDir)
    return ()
Exemple #7
0
def write(filename):

    import opensim as osim
    import csv
    import numpy as np
    import directories

    allDir = list(directories.main(directories))
    idResultsDir = allDir[7]
    soResultsDir = allDir[8]
    cmcResultsDir = allDir[10]

    storage = osim.Storage(filename)
    labels = storage.getColumnLabels()
    labelSize = labels.getSize()
    header = []

    for i in range(labelSize):
        header.append(labels.getitem(i))

    nrows = storage.getSize()

    data = []
    dataArray = []

    if header[0] == 'time':
        st = 1
        dataArray.append(osim.ArrayDouble())
        storage.getTimeColumn(dataArray[0])
        column = []
        for j in range(nrows):
            column.append(dataArray[0].getitem(j))

        data.append(column)
    else:
        st = 0

    for i in range(st, labelSize):
        dataArray.append(osim.ArrayDouble())
        storage.getDataColumn(header[i], dataArray[i])
        column = []
        for j in range(nrows):
            column.append(dataArray[i].getitem(j))

        data.append(column)
    dataFixed = np.transpose(data)
    headerFixed = []
    headerFixed.append(header)

    # Writing excel file for plotting
    if filename == idResultsDir + "/" + "subject01_walk1_id.sto":
        with open((idResultsDir + "/" + "idData.csv"), "wb") as fid:
            csvWriter = csv.writer(fid, dialect='excel')
            csvWriter.writerows(headerFixed)
            csvWriter.writerows(dataFixed)

    if filename == soResultsDir + "/" + "subject01_walk1_StaticOptimization_force.sto":
        with open((soResultsDir + "/" + "soData.csv"), "wb") as fid:
            csvWriter = csv.writer(fid, dialect='excel')
            csvWriter.writerows(headerFixed)
            csvWriter.writerows(dataFixed)

    if filename == soResultsDir + "/" + "_Gait2354 Joint RXN_ReactionLoads.sto":
        with open((soResultsDir + "/" + "soJrData.csv"), "wb") as fid:
            csvWriter = csv.writer(fid, dialect='excel')
            csvWriter.writerows(headerFixed)
            csvWriter.writerows(dataFixed)

    if filename == cmcResultsDir + "/" + "_Gait2354 Joint RXN_ReactionLoads.sto":
        with open((cmcResultsDir + "/" + "cmcJrData.csv"), "wb") as fid:
            csvWriter = csv.writer(fid, dialect='excel')
            csvWriter.writerows(headerFixed)
            csvWriter.writerows(dataFixed)
    return ()
Exemple #8
0
def reduceResidualActuators():
    allDir = list(directories.main(directories))
    paramsDir = allDir[1]
    subID = allDir[4]
    subResultsDir = allDir[5]
    ikResultsDir = allDir[6]
    idResultsDir = allDir[7]
    rraResultsDir = allDir[9]

    # Input Files
    idData = idResultsDir + "/subject01_walk1_extLoads.xml"
    ikFileName = "subject01_walk1_ik.mot"
    ikFile = ikResultsDir + "/" + ikFileName

    # Set XML file Variables
    RRATasks = paramsDir + "/" + "RRATasks.xml"
    RRAActuatorsFile = paramsDir + "/" + "RRAActuators.xml"
    RRAActuators = "RRAActuators.xml"

    if os.path.exists(rraResultsDir):
        shutil.rmtree(rraResultsDir, ignore_errors=True)
    if not os.path.exists(rraResultsDir):
        os.mkdir(rraResultsDir)

    # Load Model
    aModel = osim.Model(subResultsDir + "/" + subID + ".osim")

    # initialize system
    aModel.initSystem()

    rraTool = osim.RRATool()
    rraTool.setModel(aModel)
    rraTool.setModelFilename(subID + ".osim")
    rraTool.setDesiredKinematicsFileName(ikFile)
    rraTool.setTaskSetFileName(RRATasks)
    rraTool.setExternalLoadsFileName(idData)
    rraTool.setStartTime(0.5)
    rraTool.setFinalTime(1.5)
    rraTool.setLowpassCutoffFrequency(6)

    # Force Set
    myForceSet = osim.ForceSet(aModel, RRAActuatorsFile)
    rraTool.setReplaceForceSet(False)
    shutil.copy(RRAActuatorsFile, rraResultsDir + "/" + RRAActuators)

    rraTool.setAdjustCOMToReduceResiduals(True)
    rraTool.setAdjustedCOMBody("torso")
    rraTool.setResultsDir(rraResultsDir)
    rraTool.setOutputModelFileName(rraResultsDir + "/" + subID +
                                   "_adjustedModel.osim")

    # Manually Replace Force Set
    modelForceSet = aModel.updForceSet()
    modelMuscles = osim.ForceSet(aModel.getForceSet())

    modelForceSet.clearAndDestroy()
    for i in range(myForceSet.getSize()):
        aModel.updForceSet().append(myForceSet.get(i))
    rraTool.run()

    rraTool.printToXML(rraResultsDir + "/" + "rraSetup.xml")

    rraModel = osim.Model(rraResultsDir + "/" + subID + "_adjustedModel.osim")
    rraModel.setName(subID + "_adjustedModel")

    rraModel.updForceSet().clearAndDestroy()
    for i in range(modelMuscles.getSize()):
        rraModel.updForceSet().append(modelMuscles.get(i))

    rraModel.printToXML(rraResultsDir + "/" + subID + "_adjustedModel.osim")

    return ()
def inverseDynamics():
    import os
    import re
    import shutil
    import opensim as osim
    import directories

    allDir = list(directories.main(directories))
    parentDir = allDir[0]
    paramsDir = allDir[1]
    subID = allDir[4]
    subResultsDir = allDir[5]
    ikResultsDir = allDir[6]
    idResultsDir = allDir[7]

    # Clear Inverse Dynamics Folder
    if os.path.exists(idResultsDir):
        shutil.rmtree(idResultsDir, ignore_errors=True)
    if not os.path.exists(idResultsDir):
        os.mkdir(idResultsDir)

    # Input data files
    genericExtLoads = paramsDir + "/externalLoads.xml"
    motData = parentDir + "/data/osDemo/subject01_walk1_grf.mot"
    motFileName = "subject01_walk1_grf.mot"
    # saveDir = subResultsDir + "/" + subID + "motionFile.mot"
    ikFileName = "subject01_walk1_ik.mot"
    ikFile = ikResultsDir + "/" + ikFileName

    # Copy GRF File over to Current Directory
    shutil.copy(motData, idResultsDir + "/" + motFileName)

    # Load Inverse Kinematics Model
    aModel = osim.Model(subResultsDir + "/" + subID + ".osim")

    # initialize system
    aModel.initSystem()

    # Initialize External Loads File from Generic File
    extLoads = osim.ExternalLoads(aModel, genericExtLoads)

    # Initialize idTool
    idTool = osim.InverseDynamicsTool()
    idTool.setLowpassCutoffFrequency(6.0)
    idTool.setInputsDir(idResultsDir)
    idTool.setResultsDir(idResultsDir)
    idTool.setModel(aModel)
    idTool.setModelFileName(subResultsDir + "/" + subID + ".osim")
    # Get .mot data to determine time range
    motCoordsData = osim.Storage(ikFile)
    # Get initial and final time
    initial_time = motCoordsData.getFirstTime()
    final_time = motCoordsData.getLastTime()

    # Creat output ID
    idFileName = re.sub('ik.mot', 'id.sto', ikFileName)
    # Customize and save external loads ile
    extLoads.setName(motFileName)
    extLoads.setDataFileName(motData)
    extLoads.setExternalLoadsModelKinematicsFileName(ikFile)
    extLoads.printToXML(idResultsDir + "/" +
                        re.sub('ik.mot', 'extLoads.xml', ikFileName))

    # Setup idTool
    idTool.setName(motFileName)
    idTool.setCoordinatesFileName(ikFile)
    idTool.setStartTime(initial_time)
    idTool.setEndTime(final_time)
    # Must be relative to output directory, not full path!
    idTool.setOutputGenForceFileName(idFileName)
    idTool.setExternalLoadsFileName(
        idResultsDir + "/" + re.sub('ik.mot', 'extLoads.xml', ikFileName))
    # Can comment out if not needed in GUI
    idTool.printToXML(idResultsDir + "/" +
                      re.sub('ik.mot', 'setupID.xml', ikFileName))

    # Run idTool
    idTool.run()
    os.system('cls' if os.name == 'nt' else 'clear')
    return ()
# University of Guelph Masters Graduate
# This script is the main function for all OSIM scripts to date

import scaling
import IK
import ID
import SO
import prePlot
import plot
import readTRC
import RRA
import CMC
import directories
import JR

allDir = list(directories.main(directories))
paramsDir = allDir[1]
idResultsDir = allDir[7]
soResultsDir = allDir[8]
cmcResultsDir = allDir[10]
jrResultsDir = allDir[11]

scaling.scale()
# IK.inverseKinematics()
# ID.inverseDynamics()

# Static Optimization
"""
input parameters 
time - t0 & t1
"""