38 #include "examples/learningSpines/tgCPGCableControl.h"
40 #include "dev/dhustigschultz/BigPuppy_SpineOnly_Stats/BaseQuadModelLearning.h"
47 #include "examples/learningSpines/tgCPGCableControl.h"
49 #include "neuralNet/Neural Network v2/neuralNetwork.h"
51 #include <json/json.h>
88 lp, hp, kt, kp, kv, def, cl, lf, hf),
89 freqFeedbackMin(ffMin),
90 freqFeedbackMax(ffMax),
91 ampFeedbackMin(afMin),
92 ampFeedbackMax(afMax),
93 phaseFeedbackMin(pfMin),
94 phaseFeedbackMax(pfMax),
107 std::string resourcePath) :
115 JSONMGFeedbackControlFM0::~JSONMGFeedbackControlFM0()
127 bool parsingSuccessful = reader.parse( FileHelpers::getFileString(controlFilename.c_str()), root );
128 if ( !parsingSuccessful )
131 std::cout <<
"Failed to parse configuration\n"
132 << reader.getFormattedErrorMessages();
133 throw std::invalid_argument(
"Bad filename for JSON");
137 Json::Value nodeVals = root.get(
"nodeVals",
"UTF-8");
138 Json::Value edgeVals = root.get(
"edgeVals",
"UTF-8");
140 std::cout << nodeVals << std::endl;
142 nodeVals = nodeVals.get(
"params",
"UTF-8");
143 edgeVals = edgeVals.get(
"params",
"UTF-8");
146 array_2D nodeParams = scaleNodeActions(nodeVals);
148 setupCPGs(subject, nodeParams, edgeParams);
150 Json::Value feedbackParams = root.get(
"feedbackVals",
"UTF-8");
151 feedbackParams = feedbackParams.get(
"params",
"UTF-8");
154 m_config.numStates = feedbackParams.get(
"numStates",
"UTF-8").asInt();
155 m_config.numActions = feedbackParams.get(
"numActions",
"UTF-8").asInt();
158 std::string nnFile = controlFilePath + feedbackParams.get(
"neuralFilename",
"UTF-8").asString();
160 nn =
new neuralNetwork(m_config.numStates, m_config.numStates*2, m_config.numActions);
162 nn->loadWeights(nnFile.c_str());
164 initConditions = subject.getSegmentCOM(m_config.segmentNumber);
165 for (
int i = 0; i < initConditions.size(); i++)
167 std::cout << initConditions[i] <<
" ";
169 std::cout << std::endl;
170 #ifdef LOGGING // Conditional compile for data logging
171 m_dataObserver.
onSetup(subject);
174 #if (0) // Conditional Compile for debug info
175 std::cout << *m_pCPGSys << std::endl;
186 if (m_updateTime >= m_config.controlTime)
189 std::vector<double> desComs = getFeedback(subject);
192 std::size_t numControllers = subject.getNumberofMuslces() * 3;
194 double descendingCommand = 0.0;
195 std::vector<double> desComs (numControllers, descendingCommand);
199 m_pCPGSys->
update(desComs, m_updateTime);
201 catch (std::runtime_error& e)
208 #ifdef LOGGING // Conditional compile for data logging
209 m_dataObserver.
onStep(subject, m_updateTime);
215 double currentHeight = subject.getSegmentCOM(m_config.segmentNumber)[1];
216 double currentHeightRear = subject.getSegmentCOM(6)[1];
219 if (currentHeight > m_config.maxHeight || currentHeight < m_config.minHeight || currentHeightRear > m_config.maxHeight || currentHeightRear < m_config.minHeight)
223 throw std::runtime_error(
"Height out of range");
228 static int count = 0;
230 std::cout << m_totalTime << std::endl;
233 std::vector<double> newConditions = subject.getSegmentCOM(m_config.segmentNumber);
235 std::cout <<
"COM: " << newConditions[0] <<
" " << newConditions[1] <<
" " << newConditions[2] <<
" ";
236 std::cout << std::endl;
251 std::vector<double> finalConditions = subject.getSegmentCOM(m_config.segmentNumber);
253 const double newX = finalConditions[0];
254 const double newZ = finalConditions[2];
255 const double oldX = initConditions[0];
256 const double oldZ = initConditions[2];
258 const double distanceMoved = sqrt((newX-oldX) * (newX-oldX) +
259 (newZ-oldZ) * (newZ-oldZ));
263 scores.push_back(-1.0);
267 scores.push_back(distanceMoved);
272 double totalEnergySpent=0;
276 for(std::size_t i=0; i<tmpStrings.size(); i++)
283 const double previousLength = stringHist.
restLengths[j-1];
284 const double currentLength = stringHist.
restLengths[j];
286 double motorSpeed = (currentLength-previousLength);
289 const double workDone = previousTension * motorSpeed;
290 totalEnergySpent += workDone;
294 scores.push_back(totalEnergySpent);
296 std::cout <<
"Dist travelled " << scores[0] << std::endl;
301 bool parsingSuccessful = reader.parse( FileHelpers::getFileString(controlFilename.c_str()), root );
302 if ( !parsingSuccessful )
305 std::cout <<
"Failed to parse configuration\n"
306 << reader.getFormattedErrorMessages();
307 throw std::invalid_argument(
"Bad filename for JSON");
310 Json::Value prevScores = root.get(
"scores", Json::nullValue);
312 Json::Value subScores;
313 subScores[
"distance"] = scores[0];
314 subScores[
"energy"] = scores[1];
316 prevScores.append(subScores);
317 root[
"scores"] = prevScores;
320 payloadLog.open(controlFilename.c_str(),ofstream::out);
322 payloadLog << root << std::endl;
327 for(
size_t i = 0; i < m_spineControllers.size(); i++)
329 delete m_spineControllers[i];
331 m_spineControllers.clear();
334 void JSONMGFeedbackControlFM0::setupCPGs(
BaseQuadModelLearning& subject, array_2D nodeActions, array_4D edgeActions)
339 CPGEquationsFB& m_CPGFBSys = *(tgCast::cast<CPGEquations, CPGEquationsFB>(m_pCPGSys));
341 for (std::size_t i = 0; i < spineMuscles.size(); i++)
347 spineMuscles[i]->attach(pStringControl);
352 m_spineControllers.push_back(pStringControl);
356 for (std::size_t i = 0; i < m_spineControllers.size(); i++)
359 assert(pStringInfo != NULL);
366 if (m_config.useDefault)
368 pStringInfo->setupControl(*p_ipc);
372 pStringInfo->setupControl(*p_ipc, m_config.controlLength);
378 array_2D JSONMGFeedbackControlFM0::scaleNodeActions (Json::Value actions)
380 std::size_t numControllers = actions.size();
381 std::size_t numActions = actions[0].size();
383 array_2D nodeActions(boost::extents[numControllers][numActions]);
385 array_2D limits(boost::extents[2][numActions]);
388 assert(numActions == 5);
390 limits[0][0] = m_config.lowFreq;
391 limits[1][0] = m_config.highFreq;
392 limits[0][1] = m_config.lowAmp;
393 limits[1][1] = m_config.highAmp;
394 limits[0][2] = m_config.freqFeedbackMin;
395 limits[1][2] = m_config.freqFeedbackMax;
396 limits[0][3] = m_config.ampFeedbackMin;
397 limits[1][3] = m_config.ampFeedbackMax;
398 limits[0][4] = m_config.phaseFeedbackMin;
399 limits[1][4] = m_config.phaseFeedbackMax;
401 Json::Value::iterator nodeIt = actions.begin();
404 for( std::size_t i = 0; i < numControllers; i++)
406 Json::Value nodeParam = *nodeIt;
407 for( std::size_t j = 0; j < numActions; j++)
409 nodeActions[i][j] = ( (nodeParam.get(j, 0.0)).asDouble() *
410 (limits[1][j] - limits[0][j])) + limits[0][j];
421 std::vector<double> feedback;
425 double *inputs =
new double[m_config.numStates];
427 std::size_t n = spineCables.size();
428 for(std::size_t i = 0; i != n; i++)
430 std::vector< std::vector<double> > actions;
433 std::vector<double > state = getCableState(cable);
436 for (std::size_t i = 0; i < state.size(); i++)
438 inputs[i]=state[i] / 2.0 + 0.5;
441 double *output =
nn->feedForwardPattern(inputs);
442 vector<double> tmpAct;
443 for(
int j=0;j<m_config.numActions;j++)
445 tmpAct.push_back(output[j]);
447 actions.push_back(tmpAct);
449 std::vector<double> cableFeedback = transformFeedbackActions(actions);
451 feedback.insert(feedback.end(), cableFeedback.begin(), cableFeedback.end());
462 std::vector<double> state;
468 const double maxTension = cable.
getConfig().maxTens;
469 state.push_back((cable.
getTension() - maxTension / 2.0) / maxTension);
474 std::vector<double> JSONMGFeedbackControlFM0::transformFeedbackActions(std::vector< std::vector<double> >& actions)
477 std::vector<double> feedback;
480 const std::size_t numControllers = 1;
481 const std::size_t numActions = m_config.numActions;
483 assert( actions.size() == numControllers);
484 assert( actions[0].size() == numActions);
487 for( std::size_t i = 0; i < numControllers; i++)
489 for( std::size_t j = 0; j < numActions; j++)
491 feedback.push_back(actions[i][j] * 2.0 - 1.0);
Contains the definition of class ImpedanceControl. $Id$.
void update(std::vector< double > &descCom, double dt)
Config(int ss, int tm, int om, int param, int segnum=6, double ct=0.1, double la=0, double ha=30, double lp=-1 *M_PI, double hp=M_PI, double kt=0.0, double kp=1000.0, double kv=100.0, bool def=true, double cl=10.0, double lf=0.0, double hf=30.0, double ffMin=0.0, double ffMax=0.0, double afMin=0.0, double afMax=0.0, double pfMin=0.0, double pfMax=0.0, double maxH=60.0, double minH=1.0)
virtual void onStep(BaseQuadModelLearning &subject, double dt)
std::deque< double > tensionHistory
virtual const double getTension() const
virtual const double getStartLength() const
void setConnectivity(const std::vector< tgCPGActuatorControl * > &allStrings, array_4D edgeParams)
std::deque< double > restLengths
A controller for the template class BaseQuadModelLearning, modified for use on a quadruped.
JSONMGFeedbackControlFM0(JSONMGFeedbackControlFM0::Config config, std::string args, std::string resourcePath="")
Definition of the tgCPGStringControl observer class.
A class to read a learning configuration from a .ini file.
Contains the definition of abstract base class tgSpringCableActuator. Assumes that the string is line...
A series of functions to assist with file input/output.
virtual void onSetup(BaseQuadModelLearning &subject)
Contains the definition of class AnnealEvolution. Adapting NeuroEvolution to do Simulated Annealing...
Contains the definition of class tgBasicActuator.
const Config & getConfig() const
std::vector< T * > find(const tgTagSearch &tagSearch)
virtual void onStep(tgModel &model, double dt)
virtual array_4D scaleEdgeActions(Json::Value edgeParam)
Definition of class CPGEquationsFB.
virtual void onSetup(tgModel &model)
virtual const double getCurrentLength() const
void notifyStep(double dt)
void assignNodeNumberFB(CPGEquationsFB &CPGSys, array_2D nodeParams)
virtual void onTeardown(BaseQuadModelLearning &subject)