I am trying to find an optimal force pattern which minimizes a cost function in my model. As all optimization routines, it is obvious that it is an iterative procedure. Here is a the algorithm that I am using:
1- create a prescribedForce object
2- while (not minimum)
2-1- add the prescribedForce to the model
2-2- run forward dynamics and calculate the cost
2-3- create a new prescribedForce (which has smaller cost value)
end of while
when I implement this algorithm, it only runs for the first iteration. After that when it reaches to line (2-1) it returns this error:
ModelComponent: Cannot include subcomponent after createSystem().
below you can find a brief version of my cost function, which adds the prescribed force to the model and runs the forward dynamics:
Code: Select all
float calcCost(GAGenome & genome, Model & OsimModel) {
// Creating a prescribed force using the inputs (genome)
double time[73], armForceVec[73];
for (int ii=0; ii<73; ii++){ // mesh size = 5 degree 360/5 = 72
time [ii] = ii*realValues.phenotype(18)/72;
armForceVec [ii] = realValues.phenotype(19)*sin( (2*PI*time [ii]/realValues.phenotype(18)) + realValues.phenotype(20) );
}
const BodySet& theBodySet = OsimModel.getBodySet();
OpenSim::Body& torso = theBodySet.get(12);
PiecewiseLinearFunction *armForceY = new PiecewiseLinearFunction(73, time, armForceVec);
PrescribedForce *prescribedForce = new PrescribedForce(&torso);
prescribedForce->setName("armForce");
prescribedForce->setForceFunctions(new Constant(0.0), armForceY, new Constant(0.0));
prescribedForce->setPointFunctions(new Constant(0.00307226), new Constant(0.36175710), new Constant(0.0));
/*
.
.
.
create a controller for the muscles
.
.
.
*/
OsimModel.addForce(prescribedForce);
OsimModel.addController(muscleController);
/*
.
.
.
run the forward dynamics and calculate the cost
.
.
.
*/
OsimModel.removeController(muscleController);
return(cost);
}
Can I somehow EDIT an existing prescribedForce at each iteration? how?
please note that OsimModel is an input to the function calcCost. I cannot load a new model from a *.osim file at each iteration because it will lead to a great amount of memory leak.
Thanks
Sina