/// <summary> /// Tries to load a new genome out of the data /// </summary> /// <param name="data"></param> public void LoadGenome(ref JsonWriterReader.GenomeData data) { if (data.weights.Count != 0) { Genome bestGenome = CreateGenomeWithoutWeights(); bestGenome.weights = data.weights; if (_population.Count > 0) {//if there are already memebers, find the worst one to replace int worstGenome = 0; float fitness = _population[0].fitness; for (int i = 1; i < _population.Count; i++) { if (_population[i].fitness < fitness) { fitness = _population[i].fitness; worstGenome = i; } } _population[worstGenome].id = bestGenome.id; _population[worstGenome].weights = bestGenome.weights; } else {//otherwise just add it into the population _population.Add(bestGenome); } } }
/// <summary> /// Loads the best genome into all of the agents. /// </summary> void LoadBestGenomes() { JsonWriterReader.GenomeData data = LoadBestGenome(); NeuralNetwork neuralNetwork = new NeuralNetwork(); if (data != null) {//if the data isn't null //create the best genome Genome genome = _geneticAlgorithm.CreateGenomeFromData(LoadBestGenome()); //set up a neural network with that genome neuralNetwork.SetupFromGenome(genome, _networkStructure); for (int i = 0; i < _agents.Count; i++) {//set each member with that network _agents[i].InitializeNeuralNetwork(neuralNetwork); } } else {//otherwise create a new neural network for each memeber. for (int i = 0; i < _agents.Count; i++) { neuralNetwork.Create(_networkStructure); _agents[i].InitializeNeuralNetwork(neuralNetwork); } } }
/// <summary> /// Loads the best genome to add into the population. /// </summary> void LoadBestGenomeIntoPopulation() { JsonWriterReader.GenomeData data = LoadBestGenome(); if (data != null) {//if not null, add it into the population _geneticAlgorithm.LoadGenome(ref data); } }
/// <summary> /// Saves currently the best genome /// </summary> void SaveBestGenome() { Genome bestGenome = _geneticAlgorithm.GetBestGenome(); JsonWriterReader.GenomeData data = new JsonWriterReader.GenomeData(bestGenome.weights); string path = "BestGenomeWeights-" + data.weights.Count + "_Generation-" + _geneticAlgorithm.generation; JsonWriterReader.WriteJson(path + ".json", ref data); }
/// <summary> /// Takes in the given data and if its not empty, /// It generated a new genome with the data from the weights. /// Otherwise it creates a new random genome /// </summary> /// <param name="data"></param> /// <returns></returns> public Genome CreateGenomeFromData(JsonWriterReader.GenomeData data) { if (data.weights.Count != 0) { Genome bestGenome = CreateGenomeWithoutWeights(); bestGenome.weights = data.weights; return(bestGenome); } else { return(CreateNewGenome()); } }