This example shows creating a custom goal in a plugin library, which allows you to use the custom goal in C++, the command-line, Matlab, Python, and the GUI.See Defining a custom goal or cost.
#include "MocoCustomEffortGoal.h"
#include <OpenSim/Actuators/ActivationCoordinateActuator.h>
#include <OpenSim/Moco/osimMoco.h>
std::unique_ptr<Model> createSlidingMassModel() {
auto model = make_unique<Model>();
model->setName("sliding_mass");
model->set_gravity(SimTK::Vec3(0, 0, 0));
auto* body = new Body("body", 2.0, SimTK::Vec3(0), SimTK::Inertia(0));
model->addComponent(body);
auto* joint = new SliderJoint("slider", model->getGround(), *body);
auto& coord = joint->updCoordinate(SliderJoint::Coord::TranslationX);
coord.setName("position");
model->addComponent(joint);
auto* actu = new CoordinateActuator();
actu->setCoordinate(&coord);
actu->setName("actuator");
actu->setOptimalForce(1);
model->addComponent(actu);
body->attachGeometry(new Sphere(0.05));
model->finalizeConnections();
return model;
}
int main() {
MocoStudy study;
study.setName("sliding_mass");
MocoProblem& problem = study.updProblem();
problem.setModel(createSlidingMassModel());
problem.setTimeBounds(MocoInitialBounds(0), MocoFinalBounds(0, 5));
problem.setStateInfo("/slider/position/value", MocoBounds(-5, 5),
MocoInitialBounds(0), MocoFinalBounds(1));
problem.setStateInfo("/slider/position/speed", {-50, 50}, 0, 0);
problem.setControlInfo("/actuator", MocoBounds(-50, 50));
problem.addGoal<MocoFinalTimeGoal>("time");
problem.addGoal<MocoCustomEffortGoal>("effort");
MocoCasADiSolver& solver = study.initCasADiSolver();
solver.set_num_mesh_intervals(50);
solver.set_verbosity(2);
solver.set_optim_solver("ipopt");
solver.set_optim_ipopt_print_level(4);
solver.set_optim_max_iterations(50);
solver.set_optim_finite_difference_scheme("forward");
solver.set_optim_sparsity_detection("random");
solver.set_optim_write_sparsity("sliding_mass");
MocoTrajectory guess = solver.createGuess("bounds");
guess.resampleWithNumTimes(2);
guess.setTime({0, 0.5});
guess.setState("/slider/position/value", {0.0, 1.0});
solver.setGuess(guess);
MocoSolution solution = study.solve();
std::cout << "Solution status: " << solution.getStatus() << std::endl;
study.visualize(solution);
return EXIT_SUCCESS;
}
The Moco interface is contained within the OpenSim namespace.
Definition: Moco.dox:5