示例#1
0
 def __init__(self, residual_actuator_xml=None):
     if residual_actuator_xml:
         res_force_set = osim.ForceSet(residual_actuator_xml, True)
         n_forces = res_force_set.getSize()
         model_force_set = self.model.getForceSet()
         for i in range(n_forces):
             force = res_force_set.get(i)
             model_force_set.cloneAndAppend(force)
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 test_markAdoptedSets():

    # Set's.
    fus = osim.FunctionSet()
    fu1 = osim.Constant()
    fus.adoptAndAppend(fu1)
    del fus
    del fu1

    s = osim.ScaleSet()
    o = osim.Scale()
    s.adoptAndAppend(o)
    del s
    del o

    s = osim.ControlSet()
    o = osim.ControlLinear()
    s.adoptAndAppend(o)
    del s
    del o

    s = osim.BodyScaleSet()
    o = osim.BodyScale()
    s.adoptAndAppend(o)
    del s
    del o

    s = osim.PathPointSet()
    o = osim.PathPoint()
    s.adoptAndAppend(o)
    del s
    del o

    s = osim.IKTaskSet()
    o = osim.IKMarkerTask()
    s.adoptAndAppend(o)
    del s
    del o

    s = osim.MarkerPairSet()
    o = osim.MarkerPair()
    s.adoptAndAppend(o)
    del s
    del o

    s = osim.MeasurementSet()
    o = osim.Measurement()
    s.adoptAndAppend(o)
    del s
    del o

    s = osim.FrameSet()
    o = osim.Body()
    s.adoptAndAppend(o)
    del s
    del o

    s = osim.ForceSet()
    o = osim.CoordinateLimitForce()
    s.adoptAndAppend(o)
    del s
    del o
     
    s = osim.ForceSet()
    o = osim.SpringGeneralizedForce()
    s.append(o)
 
    s = osim.ProbeSet()
    o = osim.Umberger2010MuscleMetabolicsProbe()
    s.adoptAndAppend(o)
    del s
    del o

    a = osim.Model()
    body = osim.Body('body',
            1.0,
            osim.Vec3(0, 0, 0),
            osim.Inertia(0, 0, 0)
            )

    loc_in_parent = osim.Vec3(0, -0, 0)
    orient_in_parent = osim.Vec3(0, 0, 0)
    loc_in_body = osim.Vec3(0, 0, 0)
    orient_in_body = osim.Vec3(0, 0, 0)
    joint = osim.WeldJoint("weld_joint",
            a.getGround(),
            loc_in_parent, orient_in_parent,
            body,
            loc_in_body, orient_in_parent)
    a.addBody(body)


    constr = osim.ConstantDistanceConstraint()
    constr.setBody1ByName("ground")
    constr.setBody1PointLocation(osim.Vec3(0, 0, 0))
    constr.setBody2ByName("body")
    constr.setBody2PointLocation(osim.Vec3(1, 0, 0))
    constr.setConstantDistance(1)
    a.addConstraint(constr)
示例#4
0
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 ()
示例#5
0
def test_markAdoptedSets():

    # Set's.
    fus = osim.FunctionSet()
    fu1 = osim.Constant()
    fus.adoptAndAppend(fu1)
    del fus
    del fu1

    gs = osim.GeometrySet()
    dg = osim.DisplayGeometry()
    gs.adoptAndAppend(dg)
    del gs
    del dg

    s = osim.ScaleSet()
    o = osim.Scale()
    s.adoptAndAppend(o)
    del s
    del o

    s = osim.ForceSet()
    o = osim.BushingForce()
    s.adoptAndAppend(o)
    del s
    del o

    cs = osim.ControllerSet()
    csc = osim.PrescribedController()
    cs.adoptAndAppend(csc)
    del cs
    del csc

    s = osim.ContactGeometrySet()
    o = osim.ContactHalfSpace()
    s.adoptAndAppend(o)
    del s
    del o

    s = osim.AnalysisSet()
    o = osim.MuscleAnalysis()
    s.adoptAndAppend(o)
    del s
    del o

    s = osim.ControlSet()
    o = osim.ControlLinear()
    s.adoptAndAppend(o)
    del s
    del o

    s = osim.MarkerSet()
    o = osim.Marker()
    s.adoptAndAppend(o)
    del s
    del o

    s = osim.BodySet()
    o = osim.Body()
    s.adoptAndAppend(o)
    del s
    del o

    s = osim.BodyScaleSet()
    o = osim.BodyScale()
    s.adoptAndAppend(o)
    del s
    del o

    s = osim.CoordinateSet()
    o = osim.Coordinate()
    s.adoptAndAppend(o)
    del s
    del o

    s = osim.JointSet()
    o = osim.BallJoint()
    s.adoptAndAppend(o)
    del s
    del o

    s = osim.PathPointSet()
    o = osim.PathPoint()
    s.adoptAndAppend(o)
    del s
    del o

    s = osim.IKTaskSet()
    o = osim.IKMarkerTask()
    s.adoptAndAppend(o)
    del s
    del o

    s = osim.MarkerPairSet()
    o = osim.MarkerPair()
    s.adoptAndAppend(o)
    del s
    del o

    s = osim.MeasurementSet()
    o = osim.Measurement()
    s.adoptAndAppend(o)
    del s
    del o

    # TODO
    # s = osim.ProbeSet()
    # o = osim.Umberger2010MuscleMetabolicsProbe()
    # s.adoptAndAppend(o)
    # del s
    # del o

    s = osim.ConstraintSet()
    a = osim.Model()
    body = osim.Body('body', 1.0, osim.Vec3(0, 0, 0), osim.Inertia(0, 0, 0))

    loc_in_parent = osim.Vec3(0, -0, 0)
    orient_in_parent = osim.Vec3(0, 0, 0)
    loc_in_body = osim.Vec3(0, 0, 0)
    orient_in_body = osim.Vec3(0, 0, 0)
    joint = osim.WeldJoint("weld_joint", a.getGroundBody(), loc_in_parent,
                           orient_in_parent, body, loc_in_body,
                           orient_in_parent)
    a.addBody(body)

    constr = osim.ConstantDistanceConstraint()
    constr.setBody1ByName("ground")
    constr.setBody1PointLocation(osim.Vec3(0, 0, 0))
    constr.setBody2ByName("body")
    constr.setBody2PointLocation(osim.Vec3(1, 0, 0))
    constr.setConstantDistance(1)

    s.adoptAndAppend(constr)
def perform_so(model_file, ik_file, grf_file, grf_xml, reserve_actuators,
               results_dir):
    """Performs Static Optimization using OpenSim.

    Parameters
    ----------
    model_file: str
        OpenSim model (.osim)
    ik_file: str
        kinematics calculated from Inverse Kinematics
    grf_file: str
        the ground reaction forces
    grf_xml: str
        xml description containing how to apply the GRF forces
    reserve_actuators: str
        path to the reserve actuator .xml file
    results_dir: str
        directory to store the results
    """
    # model
    model = opensim.Model(model_file)

    # prepare external forces xml file
    name = os.path.basename(grf_file)[:-8]
    external_loads = opensim.ExternalLoads(model, grf_xml)
    external_loads.setExternalLoadsModelKinematicsFileName(ik_file)
    external_loads.setDataFileName(grf_file)
    external_loads.setLowpassCutoffFrequencyForLoadKinematics(6)
    external_loads.printToXML(results_dir + name + '.xml')

    # add reserve actuators
    force_set = opensim.ForceSet(model, reserve_actuators)
    force_set.setMemoryOwner(False)  # model will be the owner
    for i in range(0, force_set.getSize()):
        model.updForceSet().append(force_set.get(i))

    # construct static optimization
    motion = opensim.Storage(ik_file)
    static_optimization = opensim.StaticOptimization()
    static_optimization.setStartTime(motion.getFirstTime())
    static_optimization.setEndTime(motion.getLastTime())
    static_optimization.setUseModelForceSet(True)
    static_optimization.setUseMusclePhysiology(True)
    static_optimization.setActivationExponent(2)
    static_optimization.setConvergenceCriterion(0.0001)
    static_optimization.setMaxIterations(100)
    model.addAnalysis(static_optimization)

    # analysis
    analysis = opensim.AnalyzeTool(model)
    analysis.setName(name)
    analysis.setModel(model)
    analysis.setInitialTime(motion.getFirstTime())
    analysis.setFinalTime(motion.getLastTime())
    analysis.setLowpassCutoffFrequency(6)
    analysis.setCoordinatesFileName(ik_file)
    analysis.setExternalLoadsFileName(results_dir + name + '.xml')
    analysis.setLoadModelAndInput(True)
    analysis.setResultsDir(results_dir)
    analysis.run()
    so_force_file = results_dir + name + '_StaticOptimization_force.sto'
    so_activations_file = results_dir + name + \
                          '_StaticOptimization_activation.sto'
    return (so_force_file, so_activations_file)
示例#7
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 ()
示例#8
0
 def __init__(self, external_load_xml=None):
     if external_load_xml:
         force_set = osim.ForceSet(external_load_xml)
         n_forces = force_set.getSize()
         for i in range(n_forces):
             self.model.getForceSet().append(force_set.get(i))
示例#9
0
def replace_thelen_muscles_with_millard(model_file, target_folder):
    """Replaces Thelen muscles with Millard muscles so that we can disable
    tendon compliance and perform MuscleAnalysis to compute normalized
    fiber length/velocity without spikes.

    """
    model = opensim.Model(model_file)
    new_force_set = opensim.ForceSet()
    force_set = model.getForceSet()
    for i in range(force_set.getSize()):
        force = force_set.get(i)
        muscle = opensim.Muscle.safeDownCast(force)
        millard_muscle = opensim.Millard2012EquilibriumMuscle.safeDownCast(
            force)
        thelen_muscle = opensim.Thelen2003Muscle.safeDownCast(force)
        if muscle is None:
            new_force_set.adoptAndAppend(force.clone())
        elif millard_muscle is not None:
            millard_muscle = millard_muscle.clone()
            millard_muscle.set_ignore_tendon_compliance(True)
            new_force_set.adoptAndAppend(millard_muscle)
        elif thelen_muscle is not None:
            millard_muscle = opensim.Millard2012EquilibriumMuscle()
            # properties
            millard_muscle.set_default_activation(
                thelen_muscle.getDefaultActivation())
            millard_muscle.set_activation_time_constant(
                thelen_muscle.get_activation_time_constant())
            millard_muscle.set_deactivation_time_constant(
                thelen_muscle.get_deactivation_time_constant())
            # millard_muscle.set_fiber_damping(0)
            # millard_muscle.set_tendon_strain_at_one_norm_force(
            #     thelen_muscle.get_FmaxTendonStrain())
            millard_muscle.setName(thelen_muscle.getName())
            millard_muscle.set_appliesForce(thelen_muscle.get_appliesForce())
            millard_muscle.setMinControl(thelen_muscle.getMinControl())
            millard_muscle.setMaxControl(thelen_muscle.getMaxControl())
            millard_muscle.setMaxIsometricForce(
                thelen_muscle.getMaxIsometricForce())
            millard_muscle.setOptimalFiberLength(
                thelen_muscle.getOptimalFiberLength())
            millard_muscle.setTendonSlackLength(
                thelen_muscle.getTendonSlackLength())
            millard_muscle.setPennationAngleAtOptimalFiberLength(
                thelen_muscle.getPennationAngleAtOptimalFiberLength())
            millard_muscle.setMaxContractionVelocity(
                thelen_muscle.getMaxContractionVelocity())
            # millard_muscle.set_ignore_tendon_compliance(
            #     thelen_muscle.get_ignore_tendon_compliance())
            millard_muscle.set_ignore_tendon_compliance(True)
            millard_muscle.set_ignore_activation_dynamics(
                thelen_muscle.get_ignore_activation_dynamics())
            # muscle path
            pathPointSet = thelen_muscle.getGeometryPath().getPathPointSet()
            geomPath = millard_muscle.updGeometryPath()
            for j in range(pathPointSet.getSize()):
                pathPoint = pathPointSet.get(j).clone()
                geomPath.updPathPointSet().adoptAndAppend(pathPoint)

            # append
            new_force_set.adoptAndAppend(millard_muscle)
        else:
            raise RuntimeError('cannot handle the type of muscle: ' +
                               force.getName())

    new_force_set.printToXML(os.path.join(target_folder, 'muscle_set.xml'))