#include "brain/neural_network.h" #include "brain/neuron.h" NeuralNetwork::NeuralNetwork(std::istream &&networkConfigFile, int numberOfSensors, int numberOfOutputs) { _biasNode = std::make_shared(); for (int i=0; i(i); } for (int i=0; i(i); } parseFile(std::move(networkConfigFile)); } NeuralNetwork::NeuralNetwork(std::istream &&networkConfigFile, std::vector sensorInitialValues, int numberOfOutputs) { _biasNode = std::make_shared(); for (int i=0; i(i); sensor->setActivation(sensorInitialValues.at(i) ? 1 : 0); _sensors[i] = sensor; } for (int i=0; i(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) { bool sensorExists = _sensors.count(id) > 0; if (!sensorExists) { _sensors[id] = std::make_shared(id); } return _sensors.at(id); } std::shared_ptr NeuralNetwork::findOrAddNeuron(int id) { bool isOutput = _outputs.count(id) > 0; if (isOutput) { return _outputs.at(id); } bool hiddenNeuronExists = _hiddenNodes.count(id) > 0; if (!hiddenNeuronExists) { _hiddenNodes[id] = std::make_shared(id); } return _hiddenNodes.at(id); } void NeuralNetwork::setInput(int inputIndex, double activation) { _sensors.at(inputIndex)->setActivation(activation); } int NeuralNetwork::findMaxOutputIndex() const { double currentMaxActivation = 0; int currentMaxIndex = 0; for (std::pair> outputPair : _outputs) { double activation = outputPair.second->activation(); if (activation >= currentMaxActivation) { currentMaxActivation = activation; currentMaxIndex = outputPair.first; } } return currentMaxIndex; }