NTRT Simulator  Version: Master
 All Classes Namespaces Files Functions Variables Typedefs Friends Pages
AppGATests_JSON.cpp
1 /*
2  * Copyright © 2012, United States Government, as represented by the
3  * Administrator of the National Aeronautics and Space Administration.
4  * All rights reserved.
5  *
6  * The NASA Tensegrity Robotics Toolkit (NTRT) v1 platform is licensed
7  * under the Apache License, Version 2.0 (the "License");
8  * you may not use this file except in compliance with the License.
9  * You may obtain a copy of the License at
10  * http://www.apache.org/licenses/LICENSE-2.0.
11  *
12  * Unless required by applicable law or agreed to in writing,
13  * software distributed under the License is distributed on an
14  * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND,
15  * either express or implied. See the License for the specific language
16  * governing permissions and limitations under the License.
17 */
18 
27 // This application
28 
29 // This library
30 
31 #include "helpers/FileHelpers.h"
32 
33 #include "neuralNet/Neural Network v2/neuralNetwork.h"
34 
35 #include <json/json.h>
36 
37 #include <boost/program_options.hpp>
38 // The C++ Standard Library
39 #include <fstream>
40 #include <iostream>
41 #include <stdexcept>
42 #include <string>
43 
44 namespace po = boost::program_options;
45 
48 #ifdef _WIN32
49 
50 // Windows
51 #define rdtsc __rdtsc
52 
53 #else
54 
55 // For everything else
56 unsigned long long rdtsc(){
57  unsigned int lo,hi;
58  __asm__ __volatile__ ("rdtsc" : "=a" (lo), "=d" (hi));
59  return ((unsigned long long)hi << 32) | lo;
60 }
61 
62 #endif
63 
71 int main(int argc, char** argv)
72 {
73  std::cout << "AppGATests" << std::endl;
74 
75  std::string suffix;
76 
77  srand(rdtsc());
78 
79  int nSteps;
80  bool add_blocks;
81  bool add_hills;
82  double startAngle;
83  double goalAngle;
84  std::string lowerPath;
85 
86  /* Required for setting up learning file input/output. */
87  po::options_description desc("Allowed options");
88  desc.add_options()
89  ("help,h", "produce help message")
90  ("steps,s", po::value<int>(&nSteps), "Number of steps per episode to run. Default=60K (60 seconds)")
91  ("learning_controller,l", po::value<std::string>(&suffix), "Which learned controller to write to or use. Default = default")
92  ("blocks,b", po::value<bool>(&add_blocks)->implicit_value(false), "Add a block field as obstacles.")
93  ("hills,H", po::value<bool>(&add_hills)->implicit_value(false), "Use hilly terrain.")
94  ("angle,a", po::value<double>(&startAngle), "Angle of starting rotation for robot. Degrees. Default = 0")
95  ("goal_angle,B", po::value<double>(&goalAngle), "Angle of starting rotation for goal box. Degrees. Default = 0")
96  ("lower_path,P", po::value<std::string>(&lowerPath), "Which resources folder in which you want to store controllers. Default = default")
97  ;
98 
99  po::variables_map vm;
100  po::store(po::parse_command_line(argc, argv, desc), vm);
101  po::notify(vm);
102 
103  std::string fileName = "Config.ini";
104  std::string path = "bmirletz/GATests/";
105 
106  std::string fullPath = FileHelpers::getResourcePath(path);
107 
108  Json::Value root; // will contains the root value after parsing.
109  Json::Reader reader;
110 
111  std::string controlFilename = fullPath + suffix;
112 
113  bool parsingSuccessful = reader.parse( FileHelpers::getFileString(controlFilename.c_str()), root );
114  if ( !parsingSuccessful )
115  {
116  // report to the user the failure and their locations in the document.
117  std::cout << "Failed to parse configuration\n"
118  << reader.getFormattedErrorMessages();
119  throw std::invalid_argument("Bad filename for JSON");
120  }
121 
122  Json::Value feedbackParams = root.get("feedbackVals", "UTF-8");
123  feedbackParams = feedbackParams.get("params", "UTF-8");
124 #if (1)
125  // Setup neural network
126  const int numberOfInputs = feedbackParams.get("numStates", "UTF-8").asInt();
127  const int numberOfOutputs = feedbackParams.get("numActions", "UTF-8").asInt();
128  const int numberHidden = feedbackParams.get("numHidden", "UTF-8").asInt();
129 
130  std::string nnFile = fullPath + feedbackParams.get("neuralFilename", "UTF-8").asString();
131 
132  neuralNetwork* nn = new neuralNetwork(numberOfInputs,numberHidden, numberOfOutputs);
133 
134  nn->loadWeights(nnFile.c_str());
135 
136  std::vector<double> state;
137  for (int i = 0; i < numberOfInputs; i++)
138  {
139  //state.push_back((rand() / (double)RAND_MAX));
140  state.push_back(1.0);
141  }
142  double goal = 1.0 * (double) numberOfOutputs;
143 
144 
145  int steps = 0;
146  double *inputs = new double[numberOfInputs];
147  for (std::size_t i = 0; i < state.size(); i++)
148  {
149  inputs[i] = state[i];
150  }
151 
152  double *output = nn->feedForwardPattern(inputs);
153  double score1 = 0.0;
154  for(std::size_t i = 0; i < numberOfOutputs; i++)
155  {
156  score1 += output[i];
157  }
158 
159  // Test other direction
160  state.clear();
161  for (int i = 0; i < numberOfInputs; i++)
162  {
163  //state.push_back((rand() / (double)RAND_MAX));
164  state.push_back(-1.0);
165  }
166 
167  for (std::size_t i = 0; i < state.size(); i++)
168  {
169  inputs[i] = state[i];
170  }
171 
172  double *output2 = nn->feedForwardPattern(inputs);
173  double score2 = 0.0;
174  for(std::size_t i = 0; i < numberOfOutputs; i++)
175  {
176  score2 += output2[i];
177  if (output2[i] < 0.0)
178  {
179  std::cout << "Negative value! " << output2[i] << std::endl;
180  }
181  }
182 
183  std::vector<double> scores;
184  scores.push_back(score1 - score2);
185  scores.push_back(0.0);
186 #else
187 
188  Json::Value values = feedbackParams.get("neuralParams", "UTF-8");
189 
190  double score1;
191  for (int i = 0; i < values.size(); i++)
192  {
193  score1 += values[i].asDouble() * values[i].asDouble();
194  }
195 
196 
197 #endif
198  Json::Value prevScores = root.get("scores", Json::nullValue);
199 
200  Json::Value subScores;
201  subScores["distance"] = score1;
202  subScores["energy"] = 0.0;
203 
204  prevScores.append(subScores);
205  root["scores"] = prevScores;
206 
207  std::ofstream payloadLog;
208  payloadLog.open(controlFilename.c_str(),std::ofstream::out);
209 
210  payloadLog << root << std::endl;
211 
212  std::cout << "Score " << score1 << std::endl;
213 
214  //Teardown is handled by delete, so that should be automatic
215  return 0;
216 }
int main(int argc, char **argv)
A series of functions to assist with file input/output.
static std::string getResourcePath(std::string relPath)
Definition: FileHelpers.cpp:40
unsigned long long rdtsc()
Rand seeding simular to the evolution and terrain classes.
Definition: tgUtil.cpp:28