public void GPIndividualWriteAndRead() { // First we'll set up a Fitness for the Individual var rand = new MersenneTwisterFast(0); // Initialize some required context var state = new SimpleEvolutionState(); var initializer = new GPInitializer(); state.Initializer = initializer; // Required for GPTree.WriteTree(...) var constraints = new GPTreeConstraints { Name = "TestTreeConstraints" }; //initializer.TreeConstraints var tree = new GPTree(); var f = new KozaFitness(); f.SetStandardizedFitness(null, float.MaxValue); const int n = 10; f.Trials = new List <double>(n); for (var i = 0; i < n; i++) { f.Trials.Add(rand.NextDouble()); } // Now we can create and initialize the Individual var ind = new GPIndividual(); var ind2 = new GPIndividual(); // We'll read back into this instance ind.Trees = new GPTree[1]; // This is the set of genes ind.Trees[0] = new GPTree(); ind.Fitness = f; ind.Evaluated = true; using (var ms = new MemoryStream()) { var writer = new BinaryWriter(ms); ind.WriteIndividual(null, writer); ms.Position = 0; var reader = new BinaryReader(ms); ind2.Fitness = new SimpleFitness(); ind2.ReadIndividual(null, reader); Assert.IsTrue(ind.Fitness.EquivalentTo(ind2.Fitness)); Assert.IsTrue(ind2.Fitness.IsIdeal); Assert.IsTrue(ind.Equals(ind2)); // Genetically equivalent Assert.AreEqual(ind.Trees.Length, ind2.Trees.Length); } }
public void KozaFitnessWriteAndRead() { var rand = new MersenneTwisterFast(0); var f = new KozaFitness(); // Standardized fitness ranges from 0.0f inclusive to PositiveInfinity exclusive where 0.0f is ideal // Adjusted fitness ranges from 0.0f inclusive to 1.0f exclusive, where higher is better f.SetStandardizedFitness(null, float.MaxValue); // Set up some random Trials just to check that they get transmitted const int n = 10; f.Trials = new List <double>(n); for (var i = 0; i < n; i++) { f.Trials.Add(rand.NextDouble() * double.MaxValue); // in the half-open interval [0.0, double.MaxValue) } using (var ms = new MemoryStream()) { var writer = new BinaryWriter(ms); f.WriteFitness(null, writer); // Write ms.Position = 0; var reader = new BinaryReader(ms); var f2 = new KozaFitness(); f2.ReadFitness(null, reader); // Read // Compare Assert.AreEqual(f.Value, f2.Value); // Value is same // KozaFitness defines 'Value' as AdjustedFitness [0.0, 1.0), i.e. zero is valid but one is not Assert.IsTrue(f.Value < 1.0f && f2.Value < 1.0f); Assert.IsFalse(f2.IsIdeal); // Fitness is ideal Assert.AreEqual(f2.Trials.Count, f.Trials.Count); // Number of trials is the same for (var i = 0; i < f.Trials.Count; i++) { Assert.AreEqual((double)f.Trials[i], (double)f2.Trials[i]); // Trial values are all the same } } }