summaryrefslogtreecommitdiff
path: root/src/brain/neural_network.cpp
diff options
context:
space:
mode:
Diffstat (limited to 'src/brain/neural_network.cpp')
-rw-r--r--src/brain/neural_network.cpp103
1 files changed, 103 insertions, 0 deletions
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<BiasNode>();
+
for (int i=0; i<numberOfSensors; ++i)
{
_sensors.push_back(std::make_shared<Sensor>(i));
@@ -11,6 +13,107 @@ NeuralNetwork::NeuralNetwork(std::istream &&networkConfigFile, int numberOfSenso
{
_outputs.push_back(std::make_shared<Neuron>(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<NeuralNode> source;
+ std::shared_ptr<Neuron> 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<NeuralNode> source, std::shared_ptr<Neuron> destination, double weight)
+{
+ auto link = std::make_shared<NeuralLink>(source, weight);
+ destination->addInput(link);
+}
+
+std::shared_ptr<Sensor> NeuralNetwork::findOrAddSensor(int id)
+{
+ std::shared_ptr<Sensor> result;
+ for (auto node : _sensors)
+ {
+ if (node->id() == id)
+ {
+ result = node;
+ break;
+ }
+ }
+ if (!result)
+ {
+ result = std::make_shared<Sensor>(id);
+ _sensors.push_back(result);
+ }
+ return result;
+}
+
+std::shared_ptr<Neuron> NeuralNetwork::findOrAddNeuron(int id)
+{
+ std::shared_ptr<Neuron> 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<Neuron>(id);
+ _hiddenNodes.push_back(result);
+ return result;
}
void NeuralNetwork::setInput(int inputIndex, double activation)