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 JSONStatsFeedbackControl::~JSONStatsFeedbackControl()
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;
184 std::vector<double> structureCOM = subject.getCOM(m_config.segmentNumber);
186 for(std::size_t i=0; i<3; i++)
188 metrics.push_back(structureCOM[i]);
193 Json::Value prevMetrics = root.get(
"metrics", Json::nullValue);
195 Json::Value subMetrics;
196 subMetrics[
"initial COM x"] = metrics[0];
197 subMetrics[
"initial COM y"] = metrics[1];
198 subMetrics[
"initial COM z"] = metrics[2];
200 prevMetrics.append(subMetrics);
201 root[
"metrics"] = prevMetrics;
204 payloadLog.open(controlFilename.c_str(),ofstream::out);
206 payloadLog << root << std::endl;
213 if (m_updateTime >= m_config.controlTime)
216 std::vector<double> desComs = getFeedback(subject);
219 std::size_t numControllers = subject.getNumberofMuslces() * 3;
221 double descendingCommand = 0.0;
222 std::vector<double> desComs (numControllers, descendingCommand);
226 m_pCPGSys->
update(desComs, m_updateTime);
228 catch (std::runtime_error& e)
235 #ifdef LOGGING // Conditional compile for data logging
236 m_dataObserver.
onStep(subject, m_updateTime);
242 double currentHeight = subject.getSegmentCOM(m_config.segmentNumber)[1];
245 if (currentHeight > m_config.maxHeight || currentHeight < m_config.minHeight)
249 throw std::runtime_error(
"Height out of range");
253 static int count = 0;
255 std::cout << m_totalTime << std::endl;
258 std::vector<double> structureCOM = subject.getCOM(m_config.segmentNumber);
259 std::cout <<
"COM: " << structureCOM[0] <<
" " << structureCOM[1] <<
" " << structureCOM[2] <<
" ";
260 std::cout << std::endl;
266 for(std::size_t i=0; i<tmpStrings.size(); i++)
268 std::cout <<
"Muscle " << i <<
": " << tmpStrings[i]->getTension() << std::endl;
285 std::vector<double> finalConditions = subject.getSegmentCOM(m_config.segmentNumber);
287 const double newX = finalConditions[0];
288 const double newZ = finalConditions[2];
289 const double oldX = initConditions[0];
290 const double oldZ = initConditions[2];
292 const double distanceMoved = sqrt((newX-oldX) * (newX-oldX) +
293 (newZ-oldZ) * (newZ-oldZ));
297 scores.push_back(-1.0);
301 scores.push_back(distanceMoved);
306 double totalEnergySpent=0;
310 for(std::size_t i=0; i<tmpStrings.size(); i++)
317 const double previousLength = stringHist.
restLengths[j-1];
318 const double currentLength = stringHist.
restLengths[j];
320 double motorSpeed = (currentLength-previousLength);
323 const double workDone = previousTension * motorSpeed;
324 totalEnergySpent += workDone;
328 scores.push_back(totalEnergySpent);
331 std::vector<double> structureCOM = subject.getCOM(m_config.segmentNumber);
333 for(std::size_t i=0; i<3; i++)
335 metrics.push_back(structureCOM[i]);
338 std::cout <<
"Dist travelled " << scores[0] << std::endl;
343 bool parsingSuccessful = reader.parse( FileHelpers::getFileString(controlFilename.c_str()), root );
344 if ( !parsingSuccessful )
347 std::cout <<
"Failed to parse configuration\n"
348 << reader.getFormattedErrorMessages();
349 throw std::invalid_argument(
"Bad filename for JSON");
352 Json::Value prevScores = root.get(
"scores", Json::nullValue);
353 Json::Value prevMetrics = root.get(
"metrics", Json::nullValue);
355 Json::Value subScores;
356 subScores[
"distance"] = scores[0];
357 subScores[
"energy"] = scores[1];
359 Json::Value subMetrics;
360 subMetrics[
"final COM x"] = metrics[0];
361 subMetrics[
"final COM y"] = metrics[1];
362 subMetrics[
"final COM z"] = metrics[2];
364 prevScores.append(subScores);
365 prevMetrics.append(subMetrics);
367 root[
"scores"] = prevScores;
368 root[
"metrics"] = prevMetrics;
371 payloadLog.open(controlFilename.c_str(),ofstream::out);
373 payloadLog << root << std::endl;
378 for(
size_t i = 0; i < m_spineControllers.size(); i++)
380 delete m_spineControllers[i];
382 m_spineControllers.clear();
385 void JSONStatsFeedbackControl::setupCPGs(
BaseQuadModelLearning& subject, array_2D nodeActions, array_4D edgeActions)
390 CPGEquationsFB& m_CPGFBSys = *(tgCast::cast<CPGEquations, CPGEquationsFB>(m_pCPGSys));
392 for (std::size_t i = 0; i < spineMuscles.size(); i++)
398 spineMuscles[i]->attach(pStringControl);
403 m_spineControllers.push_back(pStringControl);
407 for (std::size_t i = 0; i < m_spineControllers.size(); i++)
410 assert(pStringInfo != NULL);
417 if (m_config.useDefault)
419 pStringInfo->setupControl(*p_ipc);
423 pStringInfo->setupControl(*p_ipc, m_config.controlLength);
429 array_2D JSONStatsFeedbackControl::scaleNodeActions (Json::Value actions)
431 std::size_t numControllers = actions.size();
432 std::size_t numActions = actions[0].size();
434 array_2D nodeActions(boost::extents[numControllers][numActions]);
436 array_2D limits(boost::extents[2][numActions]);
439 assert(numActions == 5);
441 limits[0][0] = m_config.lowFreq;
442 limits[1][0] = m_config.highFreq;
443 limits[0][1] = m_config.lowAmp;
444 limits[1][1] = m_config.highAmp;
445 limits[0][2] = m_config.freqFeedbackMin;
446 limits[1][2] = m_config.freqFeedbackMax;
447 limits[0][3] = m_config.ampFeedbackMin;
448 limits[1][3] = m_config.ampFeedbackMax;
449 limits[0][4] = m_config.phaseFeedbackMin;
450 limits[1][4] = m_config.phaseFeedbackMax;
452 Json::Value::iterator nodeIt = actions.begin();
455 for( std::size_t i = 0; i < numControllers; i++)
457 Json::Value nodeParam = *nodeIt;
458 for( std::size_t j = 0; j < numActions; j++)
460 nodeActions[i][j] = ( (nodeParam.get(j, 0.0)).asDouble() *
461 (limits[1][j] - limits[0][j])) + limits[0][j];
472 std::vector<double> feedback;
476 double *inputs =
new double[m_config.numStates];
478 std::size_t n = spineCables.size();
479 for(std::size_t i = 0; i != n; i++)
481 std::vector< std::vector<double> > actions;
484 std::vector<double > state = getCableState(cable);
487 for (std::size_t i = 0; i < state.size(); i++)
489 inputs[i]=state[i] / 2.0 + 0.5;
492 double *output =
nn->feedForwardPattern(inputs);
493 vector<double> tmpAct;
494 for(
int j=0;j<m_config.numActions;j++)
496 tmpAct.push_back(output[j]);
498 actions.push_back(tmpAct);
500 std::vector<double> cableFeedback = transformFeedbackActions(actions);
502 feedback.insert(feedback.end(), cableFeedback.begin(), cableFeedback.end());
513 std::vector<double> state;
519 const double maxTension = cable.
getConfig().maxTens;
520 state.push_back((cable.
getTension() - maxTension / 2.0) / maxTension);
525 std::vector<double> JSONStatsFeedbackControl::transformFeedbackActions(std::vector< std::vector<double> >& actions)
528 std::vector<double> feedback;
531 const std::size_t numControllers = 1;
532 const std::size_t numActions = m_config.numActions;
534 assert( actions.size() == numControllers);
535 assert( actions[0].size() == numActions);
538 for( std::size_t i = 0; i < numControllers; i++)
540 for( std::size_t j = 0; j < numActions; j++)
542 feedback.push_back(actions[i][j] * 2.0 - 1.0);
Contains the definition of class ImpedanceControl. $Id$.
JSONStatsFeedbackControl(JSONStatsFeedbackControl::Config config, std::string args, std::string resourcePath="")
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)
std::deque< double > tensionHistory
virtual const double getTension() const
virtual const double getStartLength() const
virtual void onStep(BaseQuadModelLearning &subject, double dt)
void setConnectivity(const std::vector< tgCPGActuatorControl * > &allStrings, array_4D edgeParams)
std::deque< double > restLengths
virtual void onSetup(BaseQuadModelLearning &subject)
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...
virtual void onTeardown(BaseQuadModelLearning &subject)
A series of functions to assist with file input/output.
Contains the definition of class AnnealEvolution. Adapting NeuroEvolution to do Simulated Annealing...
Contains the definition of class tgBasicActuator.
A controller for the template class BaseSpineModelLearning more metrics, such as center of mass of e...
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)