37 #include "examples/learningSpines/tgCPGCableControl.h"
38 #include "examples/learningSpines/tgSCASineControl.h"
47 #include "examples/learningSpines/tgCPGCableControl.h"
49 #include "neuralNet/Neural Network v2/neuralNetwork.h"
51 #include <json/json.h>
69 std::string resourcePath) :
76 OctahedralTensionControl::~OctahedralTensionControl()
87 bool parsingSuccessful = reader.parse( FileHelpers::getFileString(controlFilename.c_str()), root );
88 if ( !parsingSuccessful )
91 std::cout <<
"Failed to parse configuration\n"
92 << reader.getFormattedErrorMessages();
93 throw std::invalid_argument(
"Bad filename for JSON");
97 Json::Value nodeVals = root.get(
"nodeVals",
"UTF-8");
98 Json::Value edgeVals = root.get(
"edgeVals",
"UTF-8");
100 nodeVals = nodeVals.get(
"params",
"UTF-8");
101 edgeVals = edgeVals.get(
"params",
"UTF-8");
104 array_2D nodeParams = scaleNodeActions(nodeVals);
106 setupCPGs(subject, nodeParams, edgeParams);
108 Json::Value feedbackParams = root.get(
"feedbackVals",
"UTF-8");
109 feedbackParams = feedbackParams.get(
"params",
"UTF-8");
112 m_config.numStates = feedbackParams.get(
"numStates",
"UTF-8").asInt();
113 m_config.numActions = feedbackParams.get(
"numActions",
"UTF-8").asInt();
114 m_config.numHidden = feedbackParams.get(
"numHidden",
"UTF-8").asInt();
116 Json::Value goalParams = root.get(
"goalVals",
"UTF-8");
117 goalParams = goalParams.get(
"params",
"UTF-8");
120 m_config.goalStates = goalParams.get(
"numStates",
"UTF-8").asInt();
121 m_config.goalActions = goalParams.get(
"numActions",
"UTF-8").asInt();
122 m_config.goalHidden = goalParams.get(
"numHidden",
"UTF-8").asInt();
124 std::string nnFile_goal = controlFilePath + goalParams.get(
"neuralFilename",
"UTF-8").asString();
126 nn_goal =
new neuralNetwork(m_config.goalStates, m_config.goalHidden, m_config.goalActions);
128 nn_goal->loadWeights(nnFile_goal.c_str());
130 const OctahedralComplex* ocSubject = tgCast::cast<BaseSpineModelLearning, OctahedralComplex>(subject);
131 setupSaddleControllers(ocSubject);
133 initConditions = subject.getSegmentCOM(m_config.segmentNumber);
134 #ifdef LOGGING // Conditional compile for data logging
135 m_dataObserver.
onSetup(subject);
138 #if (0) // Conditional Compile for debug info
139 std::cout << *m_pCPGSys << std::endl;
148 if (m_updateTime >= m_config.controlTime)
151 std::vector<double> desComs = getFeedback(subject);
153 const BaseSpineModelGoal* goalSubject = tgCast::cast<BaseSpineModelLearning, BaseSpineModelGoal>(subject);
158 std::size_t numControllers = subject.getNumberofMuslces() * 3;
160 double descendingCommand = 0.0;
161 std::vector<double> desComs (numControllers, descendingCommand);
165 m_pCPGSys->
update(desComs, m_updateTime);
167 catch (std::runtime_error& e)
174 #ifdef LOGGING // Conditional compile for data logging
175 m_dataObserver.
onStep(subject, m_updateTime);
181 double currentHeight = subject.getSegmentCOM(m_config.segmentNumber)[1];
184 if (currentHeight > 25 || currentHeight < 1.0)
188 throw std::runtime_error(
"Height out of range");
197 std::vector<double> finalConditions = subject.getSegmentCOM(m_config.segmentNumber);
199 const double newX = finalConditions[0];
200 const double newZ = finalConditions[2];
201 const double oldX = initConditions[0];
202 const double oldZ = initConditions[2];
204 const BaseSpineModelGoal* goalSubject = tgCast::cast<BaseSpineModelLearning, BaseSpineModelGoal>(subject);
206 const double distanceMoved = calculateDistanceMoved(goalSubject);
210 scores.push_back(-1.0);
214 scores.push_back(distanceMoved);
219 double totalEnergySpent=0;
221 std::vector<tgSpringCableActuator* > tmpStrings = subject.getAllMuscles();
223 for(std::size_t i=0; i<tmpStrings.size(); i++)
230 const double previousLength = stringHist.
restLengths[j-1];
231 const double currentLength = stringHist.
restLengths[j];
233 double motorSpeed = (currentLength-previousLength);
236 const double workDone = previousTension * motorSpeed;
237 totalEnergySpent += workDone;
241 scores.push_back(totalEnergySpent);
243 std::cout <<
"Dist travelled " << scores[0] << std::endl;
248 bool parsingSuccessful = reader.parse( FileHelpers::getFileString(controlFilename.c_str()), root );
249 if ( !parsingSuccessful )
252 std::cout <<
"Failed to parse configuration\n"
253 << reader.getFormattedErrorMessages();
254 throw std::invalid_argument(
"Bad filename for JSON");
257 Json::Value prevScores = root.get(
"scores", Json::nullValue);
259 Json::Value subScores;
260 subScores[
"distance"] = scores[0];
261 subScores[
"energy"] = totalEnergySpent;
263 prevScores.append(subScores);
264 root[
"scores"] = prevScores;
267 payloadLog.open(controlFilename.c_str(),ofstream::out);
269 payloadLog << root << std::endl;
274 for(
size_t i = 0; i < m_allControllers.size(); i++)
276 delete m_allControllers[i];
278 m_allControllers.clear();
280 for(
size_t i = 0; i < m_allControllers.size(); i++)
282 delete m_saddleControllers[i];
284 m_saddleControllers.clear();
289 void OctahedralTensionControl::setupSaddleControllers(
const OctahedralComplex* subject)
292 const std::vector <tgSpringCableActuator*> allSaddleMuscles = subject->getSaddleMuscles();
294 for (std::size_t i = 0; i < allSaddleMuscles.size(); i++)
310 allSaddleMuscles[i]->getCurrentLength());
312 allSaddleMuscles[i]->attach(pStringControl);
314 m_saddleControllers.push_back(pStringControl);
322 const int nSeg = subject->getSegments() - 1;
328 const btVector3 currentPosVector = subject->getSegmentCOMVector(m_config.segmentNumber);
330 const btVector3 goalPosition = subject->goalBoxPosition();
332 btVector3 desiredHeading = (goalPosition - currentPosVector).normalize();
336 const btVector3 firstSegment = subject->getSegmentCOMVector(0);
337 const btVector3 secondSegment = subject->getSegmentCOMVector(1);
339 btVector3 currentHeading = (firstSegment - secondSegment).normalize();
341 std::vector<double> state;
342 state.push_back(desiredHeading.getX());
343 state.push_back(desiredHeading.getZ());
344 state.push_back(currentHeading.getX());
345 state.push_back(currentHeading.getZ());
347 double *inputs =
new double[m_config.goalStates];
348 for (std::size_t i = 0; i < state.size(); i++)
350 assert(state[i] >= -1.0 && state[i] <= 1.0);
355 double *output = nn_goal->feedForwardPattern(inputs);
357 vector<double> actions;
360 for(
int j=0;j<m_config.goalActions;j++)
362 std::cout << output[j] <<
" ";
364 std::cout << std::endl;
367 for(
int j=0;j<m_config.goalActions;j++)
369 actions.push_back(output[j]);
372 transformFeedbackActions(actions);
374 assert(m_config.goalActions * nSeg == m_allControllers.size() + m_saddleControllers.size());
376 assert(m_config.goalActions %2 == 0);
379 for (
int i = 0; i != nSeg; i++)
381 for(
int j=0;j<m_config.goalActions;j++)
383 if (j < m_config.goalActions / 2)
385 m_allControllers[i * m_config.goalActions / 2 + j]->updateTensionSetpoint(actions[j] * m_config.tensFeedback + m_config.tensFeedback);
389 m_saddleControllers[i * m_config.goalActions /2 + j - m_config.goalActions / 2]->updateTensionSetpoint(actions[j] * m_config.tensFeedback + m_config.tensFeedback);
Contains the definition of class ImpedanceControl. $Id$.
void update(std::vector< double > &descCom, double dt)
std::deque< double > tensionHistory
virtual std::vector< double > getGoalFeedback(const BaseSpineModelGoal *subject)
Implementing the cross-linked octahedral complex spine inspired by Tom Flemons.
virtual void onStep(BaseSpineModelLearning &subject, double dt)
A controller for the template class BaseSpineModelLearning.
virtual array_4D scaleEdgeActions(Json::Value edgeParam)
std::deque< double > restLengths
Definition of the tgCPGStringControl observer class.
Implementing the tetrahedral complex spine inspired by Tom Flemons.
A template base class for a tensegrity spine.
virtual void onTeardown(BaseSpineModelLearning &subject)
Contains the definition of abstract base class tgSpringCableActuator. Assumes that the string is line...
A series of functions to assist with file input/output.
Contains the definition of class tgBasicActuator.
virtual void onSetup(BaseSpineModelLearning &subject)
virtual void onStep(tgModel &model, double dt)
Definition of class CPGEquationsFB.
OctahedralTensionControl(JSONGoalControl::Config config, std::string args, std::string resourcePath="")
virtual void onSetup(tgModel &model)
void notifyStep(double dt)