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 OctahedralGoalControl::~OctahedralGoalControl()
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 std::string nnFile = controlFilePath + feedbackParams.get(
"neuralFilename",
"UTF-8").asString();
118 nn =
new neuralNetwork(m_config.numStates, m_config.numHidden, m_config.numActions);
120 nn->loadWeights(nnFile.c_str());
122 const OctahedralComplex* ocSubject = tgCast::cast<BaseSpineModelLearning, OctahedralComplex>(subject);
123 setupSaddleControllers(ocSubject);
125 initConditions = subject.getSegmentCOM(m_config.segmentNumber);
126 #ifdef LOGGING // Conditional compile for data logging
127 m_dataObserver.
onSetup(subject);
130 #if (0) // Conditional Compile for debug info
131 std::cout << *m_pCPGSys << std::endl;
140 if (m_updateTime >= m_config.controlTime)
144 std::vector<double> desComs = getFeedback(subject);
146 const BaseSpineModelGoal* goalSubject = tgCast::cast<BaseSpineModelLearning, BaseSpineModelGoal>(subject);
148 #endif // Terrain feedback vs goal feedback
151 const BaseSpineModelGoal* goalSubject = tgCast::cast<BaseSpineModelLearning, BaseSpineModelGoal>(subject);
152 setGoalTensions(goalSubject);
154 std::size_t numControllers = subject.getNumberofMuslces() * 3;
156 double descendingCommand = 0.0;
157 std::vector<double> desComs (numControllers, descendingCommand);
161 m_pCPGSys->
update(desComs, m_updateTime);
163 catch (std::runtime_error& e)
170 #ifdef LOGGING // Conditional compile for data logging
171 m_dataObserver.
onStep(subject, m_updateTime);
177 double currentHeight = subject.getSegmentCOM(m_config.segmentNumber)[1];
180 if (currentHeight > 25 || currentHeight < 1.0)
184 throw std::runtime_error(
"Height out of range");
193 std::vector<double> finalConditions = subject.getSegmentCOM(m_config.segmentNumber);
195 const double newX = finalConditions[0];
196 const double newZ = finalConditions[2];
197 const double oldX = initConditions[0];
198 const double oldZ = initConditions[2];
200 const BaseSpineModelGoal* goalSubject = tgCast::cast<BaseSpineModelLearning, BaseSpineModelGoal>(subject);
202 const double distanceMoved = calculateDistanceMoved(goalSubject);
206 scores.push_back(-1.0);
210 scores.push_back(distanceMoved);
215 double totalEnergySpent=0;
217 std::vector<tgSpringCableActuator* > tmpStrings = subject.getAllMuscles();
219 for(std::size_t i=0; i<tmpStrings.size(); i++)
226 const double previousLength = stringHist.
restLengths[j-1];
227 const double currentLength = stringHist.
restLengths[j];
229 double motorSpeed = (currentLength-previousLength);
232 const double workDone = previousTension * motorSpeed;
233 totalEnergySpent += workDone;
237 scores.push_back(totalEnergySpent);
239 std::cout <<
"Dist travelled " << scores[0] << std::endl;
244 bool parsingSuccessful = reader.parse( FileHelpers::getFileString(controlFilename.c_str()), root );
245 if ( !parsingSuccessful )
248 std::cout <<
"Failed to parse configuration\n"
249 << reader.getFormattedErrorMessages();
250 throw std::invalid_argument(
"Bad filename for JSON");
253 Json::Value prevScores = root.get(
"scores", Json::nullValue);
255 Json::Value subScores;
256 subScores[
"distance"] = scores[0];
257 subScores[
"energy"] = totalEnergySpent;
259 prevScores.append(subScores);
260 root[
"scores"] = prevScores;
263 payloadLog.open(controlFilename.c_str(),ofstream::out);
265 payloadLog << root << std::endl;
270 for(
size_t i = 0; i < m_allControllers.size(); i++)
272 delete m_allControllers[i];
274 m_allControllers.clear();
276 for(
size_t i = 0; i < m_allControllers.size(); i++)
278 delete m_saddleControllers[i];
280 m_saddleControllers.clear();
283 void OctahedralGoalControl::setupSaddleControllers(
const OctahedralComplex* subject)
286 const std::vector <tgSpringCableActuator*> allSaddleMuscles = subject->getSaddleMuscles();
288 for (std::size_t i = 0; i < allSaddleMuscles.size(); i++)
304 allSaddleMuscles[i]->getCurrentLength());
306 allSaddleMuscles[i]->attach(pStringControl);
308 m_saddleControllers.push_back(pStringControl);
317 std::vector<double> currentPosition = subject->getSegmentCOM(m_config.segmentNumber);
319 assert(currentPosition.size() == 3);
321 btVector3 currentPosVector(currentPosition[0], currentPosition[1], currentPosition[2]);
323 btVector3 goalPosition = subject->goalBoxPosition();
325 btVector3 desiredHeading = (goalPosition - currentPosVector).normalize();
327 std::vector<double> state;
328 state.push_back(desiredHeading.getX());
329 state.push_back(desiredHeading.getZ());
331 assert(state[0] >= -1.0 && state[0] <= 1.0);
332 assert(state[1] >= -1.0 && state[1] <= 1.0);
334 double *inputs =
new double[m_config.numStates];
337 for (std::size_t i = 0; i < state.size(); i++)
339 inputs[i]=state[i] / 2.0 + 0.5;
342 const int nSeg = subject->getSegments() - 1;
344 double *output =
nn->feedForwardPattern(inputs);
346 vector<double> actions;
347 for(
int j=0;j<m_config.numActions;j++)
349 actions.push_back(output[j]);
352 transformFeedbackActions(actions);
354 assert(m_config.numActions == m_saddleControllers.size() + m_allControllers.size());
355 assert(m_saddleControllers.size() == m_allControllers.size());
357 const OctahedralComplex* octaSubject = tgCast::cast<BaseSpineModelLearning, OctahedralComplex>(subject);
358 const std::vector <tgSpringCableActuator*> allSaddleMuscles = octaSubject->getSaddleMuscles();
359 const std::vector <tgSpringCableActuator*> allCPGMuscles = octaSubject->getAllMuscles();
362 for (
int j = 0; j < m_saddleControllers.size(); j++)
364 double startLength = allSaddleMuscles[j]->getStartLength();
365 m_saddleControllers[j]->updateControlLength(actions[j] * startLength + startLength);
368 for (
int i = 0; i < m_allControllers.size(); i++)
370 double startLength = allCPGMuscles[i]->getStartLength();
372 tgCPGCableControl* mCPGController = tgCast::cast<tgCPGActuatorControl, tgCPGCableControl>(m_allControllers[i]);
Contains the definition of class ImpedanceControl. $Id$.
virtual void onTeardown(BaseSpineModelLearning &subject)
void update(std::vector< double > &descCom, double dt)
std::deque< double > tensionHistory
Implementing the cross-linked octahedral complex spine inspired by Tom Flemons.
OctahedralGoalControl(JSONGoalControl::Config config, std::string args, std::string resourcePath="")
virtual array_4D scaleEdgeActions(Json::Value edgeParam)
virtual void onSetup(BaseSpineModelLearning &subject)
std::deque< double > restLengths
Definition of the tgCPGStringControl observer class.
virtual void onStep(BaseSpineModelLearning &subject, double dt)
Implementing the tetrahedral complex spine inspired by Tom Flemons.
A controller for the template class BaseSpineModelLearning.
A template base class for a tensegrity spine.
Contains the definition of abstract base class tgSpringCableActuator. Assumes that the string is line...
std::vector< double > getGoalFeedback(const BaseSpineModelGoal *subject)
A series of functions to assist with file input/output.
void updateControlLength(double newControlLength)
Contains the definition of class tgBasicActuator.
virtual void onStep(tgModel &model, double dt)
Definition of class CPGEquationsFB.
virtual void onSetup(tgModel &model)
void notifyStep(double dt)