Page 1 of 1

BodyKinematics python

Posted: Wed Apr 17, 2024 11:21 pm
by lishuaifu2022
I want to use BodyKinematics to obtain the position of the center of mass of the body part throughout the experiment. How should I achieve this in python?

Re: BodyKinematics python

Posted: Tue Jun 04, 2024 3:13 am
by yuusutiia
I successfully obtained the COM by python just now. I am glad to share you my program. Hope it can help you.

this is my code to calculate COM from motion file.

Code: Select all

import opensim as osim

# model file and trc file
model = osim.Model(r'D:\OpenSim 4.5\Kitaura.osim')
state = model.initSystem()
motion = osim.Storage(r'D:\OpenSim 4.5\1.mot')


#analyze set
a_tool = osim.AnalyzeTool()
a_tool.setModel(model)
a_tool.setCoordinatesFileName(r'D:\OpenSim 4.5\1.mot')
a_tool.setLowpassCutoffFrequency(6)
a_tool.setStatesFromMotion(state,motion,True)

#body kinematics
bk_tool = osim.BodyKinematics()
bk_tool.setModel(model)
bk_tool.setName('test')

#analyze
analysis_set = a_tool.getAnalysisSet()
analysis_set.cloneAndAppend(bk_tool)
a_tool.addAnalysisSetToModel()
a_tool.setResultsDir(r'D:\OpenSim 4.5')
a_tool.setCoordinatesFileName('pos.sto')
a_tool.setStatesFileName('states.sto')
a_tool.setSpeedsFileName('ves.sto')

a_tool.run()
This is my code do inverse kinematics analyze with trc file.

Code: Select all

import opensim as osim
import os

model_file = 'I:/model/tabata.osim'
trc_folder = 'I:/lift/tabata/'
output_folder = 'I:/model/'

trc_files = [f for f in os.listdir(trc_folder) if f.endswith('.trc')]

for trc_file in trc_files:
    model = osim.Model(model_file)
    state = model.initSystem()
    trc_path = os.path.join(trc_folder, trc_file)
    output_motion_file = os.path.join(output_folder, trc_file.replace('.trc', '.mot'))

    marker_data = osim.MarkerData(trc_path)

    ik_tool = osim.InverseKinematicsTool()
    ik_tool.setModel(model)
    ik_tool.setMarkerDataFileName(trc_path)
    ik_tool.set_output_motion_file(output_motion_file)
    ik_tool.run()