From 2e6ecf423c8228ac8de4badf4fc2d037a876b7ff Mon Sep 17 00:00:00 2001 From: Justin Worthe Date: Sat, 1 Aug 2015 22:50:00 +0200 Subject: Reading network from file --- src/brain/neural_network.cpp | 103 +++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 103 insertions(+) (limited to 'src/brain/neural_network.cpp') diff --git a/src/brain/neural_network.cpp b/src/brain/neural_network.cpp index 2d3b902..15eedca 100644 --- a/src/brain/neural_network.cpp +++ b/src/brain/neural_network.cpp @@ -3,6 +3,8 @@ NeuralNetwork::NeuralNetwork(std::istream &&networkConfigFile, int numberOfSensors, int numberOfOutputs) { + _biasNode = std::make_shared(); + for (int i=0; i(i)); @@ -11,6 +13,107 @@ NeuralNetwork::NeuralNetwork(std::istream &&networkConfigFile, int numberOfSenso { _outputs.push_back(std::make_shared(i)); } + + parseFile(std::move(networkConfigFile)); +} + +void NeuralNetwork::parseFile(std::istream &&file) +{ + double weight; + for (std::string src, dest; + file >> src && file >> dest && file >> weight; ) + { + char srcType = src.at(0); + int srcId = std::stoi(src.substr(1)); + char destType = dest.at(0); + int destId = std::stoi(dest.substr(1)); + + std::shared_ptr source; + std::shared_ptr destination; + switch (srcType) + { + case 's': + source = findOrAddSensor(srcId); + break; + case 'b': + source = _biasNode; + break; + case 'n': + source = findOrAddNeuron(srcId); + break; + default: + throw 1; + } + switch (destType) + { + case 'n': + destination = findOrAddNeuron(destId); + break; + default: + throw 1; + } + + addLink(source, destination, weight); + } + +} + +void NeuralNetwork::addLink(std::shared_ptr source, std::shared_ptr destination, double weight) +{ + auto link = std::make_shared(source, weight); + destination->addInput(link); +} + +std::shared_ptr NeuralNetwork::findOrAddSensor(int id) +{ + std::shared_ptr result; + for (auto node : _sensors) + { + if (node->id() == id) + { + result = node; + break; + } + } + if (!result) + { + result = std::make_shared(id); + _sensors.push_back(result); + } + return result; +} + +std::shared_ptr NeuralNetwork::findOrAddNeuron(int id) +{ + std::shared_ptr result; + for (auto node : _hiddenNodes) + { + if (node->id() == id) + { + result = node; + break; + } + } + if (result) + { + return result; + } + for (auto node : _outputs) + { + if (node->id() == id) + { + result = node; + break; + } + } + if (result) + { + return result; + } + + result = std::make_shared(id); + _hiddenNodes.push_back(result); + return result; } void NeuralNetwork::setInput(int inputIndex, double activation) -- cgit v1.2.3