Exemple #1
0
    def test_markAdopted2(self):
        a = osim.Model()

        # We just need the following not to cause a segfault.

        # Model add*
        pa = osim.PathActuator()
        pa.setName('pa')
        a.addForce(pa)

        probe = osim.Umberger2010MuscleMetabolicsProbe()
        probe.setName('probe')
        a.addProbe(probe)

        ma = osim.MuscleAnalysis()
        ma.setName('ma')
        a.addAnalysis(ma)

        pc = osim.PrescribedController()
        pc.setName('pc')
        a.addController(pc)

        body = osim.Body('body1', 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)
        print "creating Weld Joint.."
        joint = osim.WeldJoint("weld_joint", a.getGround(), loc_in_parent,
                               orient_in_parent, body, loc_in_body,
                               orient_in_parent)
        print "adding a body .."
        a.addBody(body)
        print "adding a joint .."
        a.addJoint(joint)
        print "Creating a ConstantDistanceConstraint.."
        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)

        f = osim.BushingForce("bushing", "ground", "body", osim.Vec3(2, 2, 2),
                              osim.Vec3(1, 1, 1), osim.Vec3(0, 0, 0),
                              osim.Vec3(0, 0, 0))
        a.addForce(f)

        f2 = osim.BushingForce()
        a.addForce(f2)

        f3 = osim.SpringGeneralizedForce()
        a.addForce(f3)

        model = osim.Model(os.path.join(test_dir, "arm26.osim"))
        g = osim.CoordinateActuator('r_shoulder_elev')
        model.addForce(g)
Exemple #2
0
def test_markAdopted():
    a = osim.Model()

    # We just need the following not to not cause a segfault.

    # Model add*
    a.addComponent(osim.PathActuator())
    a.addProbe(osim.Umberger2010MuscleMetabolicsProbe())
    a.addAnalysis(osim.MuscleAnalysis())
    a.addController(osim.PrescribedController())

    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)
    a.addConstraint(constr)

    # Force requires body names. If not provided, you get a segfault.
    f = osim.BushingForce()
    f.setBody1ByName("ground")
    f.setBody2ByName("body")
    a.addForce(f)

    model = osim.Model(os.environ['OPENSIM_HOME'] + "/Models/Arm26/arm26.osim")
    g = osim.CoordinateActuator('r_shoulder_elev')
    model.addForce(g)
def setup_muscle_analysis_xml(trial: str, model: str, directory: str,
                              time_range: list, cut_off_freq: np.float64):
    '''
	NOTE: Any attribute not changed within this function must be changed in the original template 
	file 
	
	Inputs:	trial: trial name, e.g.,  "_12Mar_ss_12ms_01"
			model: model name, e.g., "AB08"
			directory: output directory name
			time_range: start and end times
			cuf_off_frequency: low pass cut-off frequency

	'''

    # Get analyze tool
    analyze_tool = osim.AnalyzeTool()

    # Set tool name
    new_analyze_tool_name = model + trial
    analyze_tool.setName(new_analyze_tool_name)

    # Set the opensim model name
    analyze_tool.setModelFilename(directory + "\\" + model + "\\" + model +
                                  ".osim")

    # Set the results directory
    analyze_tool.setResultsDir(directory + "\\" + model + "\\" + trial)

    # Set the external loads file
    external_loads_file = directory + "\\" + model + "\\" + trial + "\\" + trial + 'ExternalLoads.xml'
    analyze_tool.setExternalLoadsFileName(external_loads_file)

    # Set the coordinates file
    coord_file = directory + "\\" + model + "\\" + trial + "\\" + trial + 'IKResults.mot'
    analyze_tool.setCoordinatesFileName(coord_file)

    # Set low pass cut-off frequency, NOTE: Must be a double (np.float64)
    analyze_tool.setLowpassCutoffFrequency(np.float64(cut_off_freq))

    # Set the time range, NOTE: Must be a double (np.float64)
    analyze_tool.setInitialTime(np.float64(time_range[0]))
    analyze_tool.setFinalTime(np.float64(time_range[-1]))
    ''' Add muscle analysis '''

    analysis_set = analyze_tool.getAnalysisSet()

    muscle_analysis = osim.MuscleAnalysis()

    muscle_analysis.setStartTime(np.float64(time_range[0]))
    muscle_analysis.setEndTime(np.float64(time_range[-1]))
    muscle_analysis.setComputeMoments(
        True)  # Bug, this is not being set to true in the xml file

    analysis_set.cloneAndAppend(muscle_analysis)
    ''' Write file '''

    xml_setup_path = directory + "\\" + model + "\\" + trial + "\\" + trial + "MuscleAnalysisSetup.xml"
    analyze_tool.printToXML(xml_setup_path)
    ''' Temporary fix to set compute moments to true and to remove numerical inaccuracy in times '''

    dom = minidom.parse(xml_setup_path)
    analysis_set = dom.getElementsByTagName("AnalysisSet")
    analysis_set_child = analysis_set.item(0)

    objects_set = analysis_set_child.getElementsByTagName("objects")
    objects_set_child = objects_set.item(0)

    muscle_analysis = objects_set_child.getElementsByTagName("MuscleAnalysis")
    muscle_analysis_child = muscle_analysis.item(0)

    muscle_analysis_child.getElementsByTagName(
        "compute_moments")[0].firstChild.nodeValue = "true"

    dom.getElementsByTagName("initial_time")[0].firstChild.nodeValue = round(
        time_range[0], 3)
    dom.getElementsByTagName("final_time")[0].firstChild.nodeValue = round(
        time_range[-1], 3)
    muscle_analysis_child.getElementsByTagName(
        "start_time")[0].firstChild.nodeValue = round(time_range[0], 3)
    muscle_analysis_child.getElementsByTagName(
        "end_time")[0].firstChild.nodeValue = round(time_range[-1], 3)

    with open(xml_setup_path, 'w') as xml_file:
        dom.writexml(xml_file, addindent='\t', newl='\n', encoding='UTF-8')
Exemple #4
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)
solver.set_optim_convergence_tolerance(1e-4)
solver.set_optim_constraint_tolerance(1e-4)

solution = study.solve()
osim.STOFileAdapter.write(solution.exportToStatesTable(),
                          "exampleHangingMuscle_states.sto")
osim.STOFileAdapter.write(solution.exportToControlsTable(),
                          "exampleHangingMuscle_controls.sto")

# Conduct an analysis using MuscleAnalysis and ProbeReporter.
# Create an AnalyzeTool setup file.
analyze = osim.AnalyzeTool()
analyze.setName("analyze")
analyze.setModelFilename("hanging_muscle.osim")
analyze.setStatesFileName("exampleHangingMuscle_states.sto")
analyze.updAnalysisSet().cloneAndAppend(osim.MuscleAnalysis())
analyze.updAnalysisSet().cloneAndAppend(osim.ProbeReporter())
analyze.updControllerSet().cloneAndAppend(
    osim.PrescribedController("exampleHangingMuscle_controls.sto"))
analyze.printToXML("exampleHangingMuscle_AnalyzeTool_setup.xml")
# Run the analysis.
analyze = osim.AnalyzeTool("exampleHangingMuscle_AnalyzeTool_setup.xml")
analyze.run()

table_force = osim.TimeSeriesTable(
    "analyze_MuscleAnalysis_ActiveFiberForce.sto")
table_velocity = osim.TimeSeriesTable(
    "analyze_MuscleAnalysis_FiberVelocity.sto")
time = table_force.getIndependentColumn()
force = table_force.getDependentColumn("muscle").to_numpy()
velocity = table_velocity.getDependentColumn("muscle").to_numpy()
Exemple #6
0
    def run_analyze_tool(self, trial):
        if self.prefix and not trial.stem.startswith(self.prefix):
            # skip file if user specified a prefix and prefix is not present in current file
            pass
        else:
            print(f"\t{trial.stem}")

            # model
            model = osim.Model(self.model_input) if isinstance(self.model_input, str) is True else self.model_input
            model.initSystem()

            # get starting and ending time
            motion = osim.Storage(f"{trial.resolve()}")
            first_time = motion.getFirstTime()
            last_time = motion.getLastTime()

            # prepare external forces xml file
            if self.xml_forces:
                external_loads = osim.ExternalLoads(self.xml_forces, True)
                if self.prefix:
                    external_loads.setDataFileName(
                        f"{Path(self.ext_forces_dir, trial.stem.replace(f'{self.prefix}_', '')).resolve()}.sto"
                    )
                else:
                    external_loads.setDataFileName(
                        f"{Path(self.ext_forces_dir, trial.stem).resolve()}.sto"
                    )
                external_loads.setExternalLoadsModelKinematicsFileName(
                    f"{trial.resolve()}"
                )
                if self.low_pass:
                    external_loads.setLowpassCutoffFrequencyForLoadKinematics(
                        self.low_pass
                    )
                temp_xml = Path(f"{trial.stem}_temp.xml")
                external_loads.printToXML(f"{temp_xml.resolve()}")  # temporary xml file

            current_class = self.get_class_name()
            params = self.parse_analyze_set_xml(self.xml_input, node=current_class)
            solve_for_equilibrium = False
            if current_class == "StaticOptimization":
                analysis = osim.StaticOptimization(model)
                analysis.setUseModelForceSet(params["use_model_force_set"])
                analysis.setActivationExponent(params["activation_exponent"])
                analysis.setUseMusclePhysiology(params["use_muscle_physiology"])
                analysis.setConvergenceCriterion(
                    params["optimizer_convergence_criterion"]
                )
                analysis.setMaxIterations(int(params["optimizer_max_iterations"]))
            elif current_class == "MuscleAnalysis":
                solve_for_equilibrium = True
                analysis = osim.MuscleAnalysis(model)
                coord = osim.ArrayStr()
                for c in params["moment_arm_coordinate_list"]:
                    coord.append(c)
                analysis.setCoordinates(coord)

                mus = osim.ArrayStr()
                for m in params["muscle_list"]:
                    mus.append(m)
                analysis.setMuscles(mus)
                # analysis.setComputeMoments(params["compute_moments"])
            elif current_class == "JointReaction":
                # construct joint reaction analysis
                analysis = osim.JointReaction(model)
                if params["forces_file"] or self.forces_file:
                    force_file = self.forces_file if self.forces_file else params["forces_file"]
                    analysis.setForcesFileName(force_file)

                joint = osim.ArrayStr()
                for j in params["joint_names"]:
                    joint.append(j)
                analysis.setJointNames(joint)

                body = osim.ArrayStr()
                for b in params["apply_on_bodies"]:
                    body.append(b)
                analysis.setOnBody(body)

                frame = osim.ArrayStr()
                for f in params["express_in_frame"]:
                    frame.append(f)
                analysis.setInFrame(frame)
            else:
                raise ValueError("AnalyzeTool must be called from a child class")
            analysis.setModel(model)
            analysis.setName(current_class)
            analysis.setOn(params["on"])
            analysis.setStepInterval(int(params["step_interval"]))
            analysis.setInDegrees(params["in_degrees"])
            analysis.setStartTime(first_time)
            analysis.setEndTime(last_time)
            model.addAnalysis(analysis)

            if self.print_to_xml is True:
                analysis.printToXML(f"{self.xml_output}/{current_class}_analysis.xml")

            # analysis tool
            analyze_tool = osim.AnalyzeTool(model)
            analyze_tool.setName(trial.stem)
            analyze_tool.setModel(model)
            analyze_tool.setModelFilename(Path(model.toString()).stem)
            analyze_tool.setSolveForEquilibrium(solve_for_equilibrium)

            if self.xml_actuators:
                force_set = osim.ArrayStr()
                force_set.append(self.xml_actuators)
                analyze_tool.setForceSetFiles(force_set)
                analyze_tool.updateModelForces(model, self.xml_actuators)

            analyze_tool.setInitialTime(first_time)
            analyze_tool.setFinalTime(last_time)

            if self.low_pass:
                analyze_tool.setLowpassCutoffFrequency(self.low_pass)

            analyze_tool.setCoordinatesFileName(f"{trial.resolve()}")
            if self.xml_forces:
                analyze_tool.setExternalLoadsFileName(f"{temp_xml}")
            analyze_tool.setLoadModelAndInput(True)
            analyze_tool.setResultsDir(f"{self.sto_output}")

            analyze_tool.run()

            if self.xml_forces:
                temp_xml.unlink()  # delete temporary xml file

            if self.remove_empty_files:
                self._remove_empty_files(directory=self.sto_output)

            if self.contains:
                self._subset_output(directory=self.sto_output, contains=self.contains)
Exemple #7
0
    def run_analyze_tool(self, trial):
        if self.prefix and not trial.stem.startswith(self.prefix):
            # skip file if user specified a prefix and prefix is not present in current file
            pass
        else:
            print(f'\t{trial.stem}')

            # model
            model = osim.Model(self.model_input)
            model.initSystem()

            # get starting and ending time
            motion = osim.Storage(f'{trial.resolve()}')
            first_time = motion.getFirstTime()
            last_time = motion.getLastTime()

            # prepare external forces xml file
            if self.xml_forces:
                external_loads = osim.ExternalLoads(model, self.xml_forces)
                if self.prefix:
                    external_loads.setDataFileName(
                        f"{Path(self.ext_forces_dir, trial.stem.replace(f'{self.prefix}_', '')).resolve()}.sto"
                    )
                else:
                    external_loads.setDataFileName(
                        f"{Path(self.ext_forces_dir, trial.stem).resolve()}.sto"
                    )
                external_loads.setExternalLoadsModelKinematicsFileName(f'{trial.resolve()}')
                if self.low_pass:
                    external_loads.setLowpassCutoffFrequencyForLoadKinematics(self.low_pass)
                temp_xml = Path(f'{trial.stem}_temp.xml')
                external_loads.printToXML(f'{temp_xml.resolve()}')  # temporary xml file

            current_class = self.get_class_name()
            params = self.parse_analyze_set_xml(self.xml_input, node=current_class)
            if current_class == 'StaticOptimization':
                analysis = osim.StaticOptimization(model)
                analysis.setUseModelForceSet(params['use_model_force_set'])
                analysis.setActivationExponent(params['activation_exponent'])
                analysis.setUseMusclePhysiology(params['use_muscle_physiology'])
                analysis.setConvergenceCriterion(params['optimizer_convergence_criterion'])
                analysis.setMaxIterations(int(params['optimizer_max_iterations']))
            elif current_class == 'MuscleAnalysis':
                analysis = osim.MuscleAnalysis(model)
                analysis.setComputeMoments(params['compute_moments'])
            elif current_class == 'JointReaction':
                # construct joint reaction analysis
                analysis = osim.JointReaction(model)
                # analysis.setForcesFileName(
                #     f"{Path(self.muscle_forces_dir, trial.stem).resolve()}_StaticOptimization_force.sto"
                # )

                joint = osim.ArrayStr()
                joint.append(params['joint_names'].replace(' ', ''))
                analysis.setJointNames(joint)

                body = osim.ArrayStr()
                body.append(params['apply_on_bodies'].replace(' ', ''))
                analysis.setOnBody(body)

                frame = osim.ArrayStr()
                frame.append(params['express_in_frame'].replace(' ', ''))
                analysis.setInFrame(frame)
            else:
                raise ValueError('AnalyzeTool must be called from a child class')
            analysis.setModel(model)
            analysis.setName(current_class)
            analysis.setOn(params['on'])
            analysis.setStepInterval(int(params['step_interval']))
            analysis.setInDegrees(params['in_degrees'])
            analysis.setStartTime(first_time)
            analysis.setEndTime(last_time)
            model.addAnalysis(analysis)

            # analysis tool
            analyze_tool = osim.AnalyzeTool(model)
            analyze_tool.setName(trial.stem)
            analyze_tool.setModel(model)
            analyze_tool.setModelFilename(Path(self.model_input).stem)

            if self.xml_actuators:
                force_set = osim.ArrayStr()
                force_set.append(self.xml_actuators)
                analyze_tool.setForceSetFiles(force_set)
                analyze_tool.updateModelForces(model, self.xml_actuators)

            analyze_tool.setInitialTime(first_time)
            analyze_tool.setFinalTime(last_time)

            if self.low_pass:
                analyze_tool.setLowpassCutoffFrequency(self.low_pass)

            analyze_tool.setCoordinatesFileName(f'{trial.resolve()}')
            analyze_tool.setExternalLoadsFileName(f'{temp_xml}')
            analyze_tool.setLoadModelAndInput(True)
            analyze_tool.setResultsDir(f'{self.sto_output}')

            analyze_tool.run()

            if self.xml_forces:
                temp_xml.unlink()  # delete temporary xml file

            if self.remove_empty_files:
                self._remove_empty_files(directory=self.sto_output)