A simple parameter optimization example.
23 import opensim
as osim
29 finalTime = np.pi * np.sqrt(mass / stiffness)
33 model.setName(
'oscillator')
34 model.set_gravity(osim.Vec3(0, 0, 0))
35 body = osim.Body(
'body', np.multiply(0.5, mass), osim.Vec3(0), osim.Inertia(0))
36 model.addComponent(body)
39 marker = osim.Marker(
'marker', body, osim.Vec3(0))
40 model.addMarker(marker)
43 joint = osim.SliderJoint(
'slider', model.getGround(), body)
44 coord = joint.updCoordinate()
45 coord.setName(
'position')
46 model.addComponent(joint)
49 spring = osim.SpringGeneralizedForce()
50 spring.set_coordinate(
'position')
51 spring.setRestLength(0.)
52 spring.setStiffness(stiffness)
53 spring.setViscosity(0.)
54 model.addComponent(spring)
59 moco = osim.MocoStudy()
60 moco.setName(
'oscillator_spring_stiffness')
65 problem = moco.updProblem()
69 problem.setModel(model)
74 problem.setTimeBounds(osim.MocoInitialBounds(0.),
75 osim.MocoFinalBounds(finalTime))
79 problem.setStateInfo(
'/slider/position/value', osim.MocoBounds(-5., 5.),
80 osim.MocoInitialBounds(-0.5),
81 osim.MocoFinalBounds(0.25, 0.75))
85 problem.setStateInfo(
'/slider/position/speed', [-20, 20], [0], [0])
89 problem.addParameter(osim.MocoParameter(
'oscillator_mass',
'body',
'mass',
90 osim.MocoBounds(0, 10)))
94 endpointCost = osim.MocoMarkerFinalGoal()
95 endpointCost.setPointName(
'/markerset/marker')
96 endpointCost.setReferenceLocation(osim.Vec3(0.5, 0, 0))
97 problem.addGoal(endpointCost)
102 solver = moco.initTropterSolver()
105 moco.printToXML(
'optimize_mass.omoco')
109 solution = moco.solve()
110 solution.write(
'optimize_mass_solution.sto')