Beispiel #1
0
        public static Genome Breed(Genome One, Genome Two)
        {
            Genome New = new Genome(One.Net.NumInputs, One.Net.NumOutputs, One.Net.NeuronsPerHiddenLayer, One.Net.NumHiddenLayers);

            for (int x = 0; x < One.Net.Layers.Count; x++) // Loop though all the layers
            {
                New.Net.Layers.Add(new NeuronLayer()); // Create a new layer

                for (int y = 0; y < One.Net.Layers[x].Neurons.Count; y++) // Loop through all the neurons
                {
                    New.Net.Layers[x].Neurons.Add(new Neuron()); // Create a new neuron

                    for (int z = 0; z < One.Net.Layers[x].Neurons[y].Weights.Count; z++) // Loop through all the weights
                    {
                        // Randomly decide on a parent weight to inherit
                        if (Generator.Next(0, 2) == 0)
                        {
                            New.Net.Layers[x].Neurons[y].Weights.Add(One.Net.Layers[x].Neurons[y].Weights[z]);
                        }
                        else
                        {
                            New.Net.Layers[x].Neurons[y].Weights.Add(Two.Net.Layers[x].Neurons[y].Weights[z]);
                        }
                    }
                }
            }

            return New;
        }
 public static int Mutation(Genome<int> genom)
 {
     _mutatePoint = Rnd.Next(0, 31);
     int temp = (1 << _mutatePoint);
     _child1 = genom.Parameter ^ temp;
     return _child1;
 }
        public override void CalcFitnessDefault(Genome genome)
        {
            genome.Fitness = 0;
            Genome tempGenome = genome.Copy();
            tempGenome.Add(1);

            int[,] matrix = new int[,]
                             {
            //								{ 0,  5,  8, 11,  4,  7 },
            //								{ 5,  0, 10,  4,  9, 12 },
            //								{ 8, 10,  0,  6, 17,  8 },
            //								{11,  4,  6,  0,  6,  5 },
            //								{ 4,  9, 17,  6,  0, 11 },
            //								{ 7, 12,  8,  5, 11,  0 }
                                { 0,  5,  8, 11,  4,  7,  3, 16,  4,  7 },
                                { 5,  0, 10,  4,  9, 12,  9,  7,  6, 12 },
                                { 8, 10,  0,  6, 17,  8,  4,  8,  9,  6 },
                                {11,  4,  6,  0,  6,  5, 10,  5,  7,  4 },
                                { 4,  9, 17,  6,  0, 11,  5,  3,  9, 13 },
                                { 7, 12,  8,  5, 11,  0,  6,  4,  3,  5 },
                                { 3,  9,  4, 10,  5,  6,  0, 10, 11,  5 },
                                {16,  7,  8,  5,  3,  4, 10,  0, 12,  8 },
                                { 4,  6,  9,  7,  9,  3, 11, 12,  0,  9 },
                                { 7, 12,  6,  4, 13,  5,  5,  8,  9,  0 }
                             };

            foreach (double gene in genome) {
                genome.Fitness += matrix[(int)gene - 1,(int)tempGenome[tempGenome.IndexOf(gene)+1]-1];
            }
        }
Beispiel #4
0
        public override void CalcFitnessDefault(Genome genome)
        {
            //			Genome genome = new GenomeReal(new double[] {0.0,0.0,0.0,0.0,0.0});
            genome.Fitness = 0;

            // Summenformeln
            double a = 0.0, b = 0.0;
            // Exponenten
            double c = 0.0, d = 0.0;
            double i = 0.0;

            foreach (double gene in genome)
            {
                // sum(xi²)
                a = a + (gene * gene);
                // sum[cos(2PI*xi²)]
                b = b + Math.Cos(2*Math.PI*gene);
                i++;
            }

            c = 0.2 * Math.Sqrt(a/i);
            d = b/i;
            genome.Fitness = 20.0 + Math.Exp(1.0) - 20.0 * Math.Exp (c) - Math.Exp(d);

            //			genome.Fitness = 20.0 + Math.Exp(1.0) - 20.0 * Math.Exp (0.2 * Math.Sqrt(a/i)) - Math.Exp(b/i);

            genome.Fitness *= genome.Fitness < 0 ? -1 : 1;
            //			Console.WriteLine(genome.Fitness);
        }
Beispiel #5
0
 // RIGHT HERE IS WHERE YOU SHOULD ADD NEW GENES!
 Genome generateDefaultGenome()
 {
     Genome result = new Genome(this);
     result.addGene("Ferocity", new Chromosome(0.8, 0.1f));
     result.addGene("Cunning", new Chromosome(0.4, 0.5f));
     result.addGene("PackSense", new Chromosome(0.5, 0.8f));
     return result;
 }
Beispiel #6
0
 // Generates a mutated genome from an existing one
 public Genome(Genome genome, float mutationRate, WolfController manager)
 {
     this.manager = manager;
     fitness = 0;
     chromosomes = genome.copyChromosomes();
     foreach(Chromosome gene in chromosomes.Values) {
         gene.mutate(mutationRate);
     }
 }
    public List<Genome> GenerateOffspring(Genome other)
    {
        // Crossover, mutation

        // First crossover actor blueprints
        //Then do locations
        // ....   we preserve the basic structuring of the gene (if you wish, multiple genes)

        return new List<Genome>();
    }
Beispiel #8
0
    public static GameObject CreateAgent(GameObject agent, Vector3 location, Quaternion rotation, GameMap gameMap, Genome genome)
    {
        GameObject newAgent = Agent.CreateAgent(agent, location, rotation, gameMap);

        TrainingAgent ta = newAgent.GetComponent<TrainingAgent>();

        ta.brain = genome;

        return newAgent;
    }
 public void Mutate(Genome genome)
 {
     for (int i = 0; i < genome.Chromosome.Count(); i++)
     {
         if (_rand.NextDouble() <= MutationRate)
         {
             genome.MutateGeneAt(i, _rand.NextClamped() * PerturbationRate);
         }
     }
 }
Beispiel #10
0
 void Awake()
 {
     // Add deserialsiation here!
     FileLoader<Genome> genomeFile = new FileLoader<Genome>();
     loadedGenome = genomeFile.LoadFromFile("SavedBest.gtac");
     if(loadedGenome == null)
     {
         loadedGenome = generateDefaultGenome();
     }
 }
Beispiel #11
0
 internal static List<Genome> Except(List<Genome> genomes, Genome except)
 {
     List<Genome> selected = new List<Genome>();
     foreach (Genome selected_genome in genomes)
     {
         if (selected_genome != except)
         {
             selected.Add(selected_genome);
         }
     }
     return selected;
 }
Beispiel #12
0
    public void Breed()
    {
        Genome[] bestGenomes = GetBestCases(4);
        List<Genome> children = new List<Genome>();

        Genome best = new Genome();
        best.SetFitness(0.0f);
        best.SetId(bestGenomes[0].GetId());
        best.SetGenes(bestGenomes[0].GetGenes());
        //Mutate(best);
        children.Add(best);

        Genome[] babies = CrossOver(bestGenomes[0], bestGenomes[1]);
        Mutate(babies[0]);
        Mutate(babies[1]);
        children.Add(babies[0]);
        children.Add(babies[1]);

        babies = CrossOver(bestGenomes[0], bestGenomes[2]);
        Mutate(babies[0]);
        Mutate(babies[1]);
        children.Add(babies[0]);
        children.Add(babies[1]);

        babies = CrossOver(bestGenomes[0], bestGenomes[3]);
        Mutate(babies[0]);
        Mutate(babies[1]);
        children.Add(babies[0]);
        children.Add(babies[1]);

        babies = CrossOver(bestGenomes[1], bestGenomes[2]);
        Mutate(babies[0]);
        Mutate(babies[1]);
        children.Add(babies[0]);
        children.Add(babies[1]);

        babies = CrossOver(bestGenomes[1], bestGenomes[3]);
        Mutate(babies[0]);
        Mutate(babies[1]);
        children.Add(babies[0]);
        children.Add(babies[1]);

        int remainingChildren = (totalPopulation - children.Count);
        for (int i = 0; i < remainingChildren; i++) {
            children.Add(this.CreateNewGenome(bestGenomes[0].GetGenes().Count));
        }

        ClearPopulation();
        population = children;

        currentGenome = 0;
        generation++;
    }
Beispiel #13
0
 public bool ContainsGenome(Genome genome)
 {
     for (int i = 0; i <= oldGeneration.Count -1; i++)
     {
         if (oldGeneration[i].IsEqual(genome))
             return true;
         if (i <= curGeneration.Count -1)
             if (curGeneration[i].IsEqual(genome))
                 return true;
     }
     return false;
 }
Beispiel #14
0
 //convert hashtable into class
 public static Genome getGenome(Genome g, Hashtable genome)
 {
     g.rads = GenomeUtils.getValue ("rads", genome);
     g.joints = GenomeUtils.getValue ("joints", genome);
     g.length = GenomeUtils.getValue ("length", genome);
     g.divs = GenomeUtils.getValue ("divs", genome);
     g.angles = GenomeUtils.getValue ("angles", genome);
     g.start = GenomeUtils.getValue ("start", genome);
     g.end = GenomeUtils.getValue ("end", genome);
     g.width = GenomeUtils.getValue ("width", genome);
     return g;
 }
        public static void Sort(Genome<int> genom)
        {
            int temp = genom.Parameter;

            for (int i = 0; i < 31; i++)
            {
                int check = temp & 1 << i;
                if (check == (1 << i))
                {
                    genom.ItemsPicked.Add(Selection[i]);
                }
            }
        }
        /// <summary>
        /// Create a Feedforward Network with the given number of layers and neurons filled with the given weights from the genome
        /// </summary>
        /// <param name="inputs">Number of input neurons</param>
        /// <param name="outputNeurons">Number of output neurons</param>
        /// <param name="hiddenLayers">Number of hidden neuron layers</param>
        /// <param name="neuronsPerHiddenLayer">Number of neurons per hidden layer</param>
        public FeedforwardNetwork(int inputs, int outputNeurons, int hiddenLayers, int neuronsPerHiddenLayer, Genome genome)
        {
            InputNeuronCount = inputs;
            OutputNeuronCount = outputNeurons;
            Genome = genome;

            var allweights = genome.Chromosome;

            var lastOutputCount = setHiddenLayers(inputs, hiddenLayers, neuronsPerHiddenLayer, allweights);
            var usedWeightCount = _hiddenLayers.Sum(x => x.AllWeights.Count());

            _outputLayer = new NeuronLayer(outputNeurons, lastOutputCount, allweights.Skip(usedWeightCount));
        }
        public virtual Genome CrossoverNew(Genome genomeStart, Genome genomeEnd)
        {
            Genome genomeOutput = new Genome(genomeStart);
            double crossMethod = RngStatic.NextDoublePositive();
            if (crossMethod < 0.5)
            {
                //Single point CO
                int limit = (genomeStart.MoveCount > genomeEnd.MoveCount) ? genomeEnd.MoveCount : genomeStart.MoveCount;
                int swapPoint = RngStatic.Next(0, limit);

                for (int i = 0; i < limit; i++)
                {
                    if (i < swapPoint) genomeOutput.Moves[i] = genomeStart.Moves[i];
                    else genomeOutput.Moves[i] = genomeEnd.Moves[i];
                }
                genomeOutput.MoveCount = genomeEnd.MoveCount;
            }
            if (crossMethod < 0.8)
            {
                //Double point CO
                int limit = (genomeStart.MoveCount > genomeEnd.MoveCount) ? genomeEnd.MoveCount : genomeStart.MoveCount;
                int swapPoint1 = RngStatic.Next(0, limit);
                int swapPoint2 = RngStatic.Next(0, limit);

                if (swapPoint2 < swapPoint1)
                {
                    int tempPoint = swapPoint1;
                    swapPoint1 = swapPoint2;
                    swapPoint2 = tempPoint;
                }
                for (int i = 0; i < limit; i++)
                {
                    if (i < swapPoint1 || i > swapPoint2) genomeOutput.Moves[i] = genomeStart.Moves[i];
                    else genomeOutput.Moves[i] = genomeEnd.Moves[i];
                }
                genomeOutput.MoveCount = limit;
            }
            else
            {
                //Random mix
                int limit = (genomeStart.MoveCount > genomeEnd.MoveCount) ? genomeEnd.MoveCount : genomeStart.MoveCount;

                for (int i = 0; i < limit; i++)
                {
                    if (RngStatic.NextDoublePositive() < 0.5) genomeOutput.Moves[i] = genomeStart.Moves[i];
                    else genomeOutput.Moves[i] = genomeEnd.Moves[i];
                }
                genomeOutput.MoveCount = limit;
            }
            return genomeOutput;
        }
        public IEnumerable<Genome> Crossover(Genome mother, Genome father)
        {
            if (_rand.NextDouble() <= CrossoverRate && !mother.Equals(father))
            {
                var crossoverPoint = _rand.Next(mother.Chromosome.Count());

                yield return new Genome(mother.Chromosome.Take(crossoverPoint).Concat(father.Chromosome.Skip(crossoverPoint)));
                yield return new Genome(father.Chromosome.Take(crossoverPoint).Concat(mother.Chromosome.Skip(crossoverPoint)));
            }
            else
            {
                yield return new Genome(father.Chromosome);
                yield return new Genome(mother.Chromosome);
            }
        }
Beispiel #19
0
        public override void CalcFitnessDefault(Genome genome)
        {
            //throw new NotImplementedException ();
            //Genome genome = new GenomeReal(new double[] {0.0,0.0,0.0,0.0,0.0});
            genome.Fitness = 0;

            double a = 0.0;

            foreach (double gene in genome)
            {
                a += gene * gene;
            }
            genome.Fitness = Math.Sqrt(a);
            //Console.WriteLine(genome.Fitness);
        }
Beispiel #20
0
    public void SpawnWolf(Vector2 spawnPoint)
    {
        GameObject newWolf = (GameObject) Instantiate(wolfPrefab);

        Vector3 wolfPos = spawnPoint.ToWorldCoords();
        wolfPos.y += 0.5f;
        newWolf.transform.position = wolfPos;
        newWolf.transform.parent = this.transform;
        Brain wolfBrain = newWolf.GetComponent<Brain>();
        Genome newGenome = new Genome(bestGenome, baseMutationRate, this);
        aliveWolves.Add(newGenome);
        wolfBrain.memory.SetValue(new MemoryEntry("Genome", newGenome));
        wolfBrain.memory.SetValue(new MemoryEntry("StartPoint", spawnPoint));
        wolfBrain.Init(boxes, allObjects);
    }
		public void GenomeToString()
		{
			// Arrange
			Genome genome = new Genome(6);
			genome.SetGeneOn(0);
			genome.SetGeneOn(1);
			genome.SetGeneOn(2);
			genome.SetGeneOn(4);

			// Act
			string bitstring = genome.ToString();

			// Assert
			Assert.That(bitstring, Is.EqualTo("111 010 (7,2)"));
		}
        /// <summary>
        /// Create a Feedforward Network with the given number of layers and neurons, a random genome will be created
        /// </summary>
        /// <param name="inputs">Number of input neurons</param>
        /// <param name="outputNeurons">Number of output neurons</param>
        /// <param name="hiddenLayers">Number of hidden neuron layers</param>
        /// <param name="neuronsPerHiddenLayer">Number of neurons per hidden layer</param>
        public FeedforwardNetwork(int inputs, int outputNeurons, int hiddenLayers, int neuronsPerHiddenLayer)
        {
            InputNeuronCount = inputs;
            OutputNeuronCount = outputNeurons;
            var lastOutputCount = setHiddenLayers(inputs, hiddenLayers, neuronsPerHiddenLayer);
            _outputLayer = new NeuronLayer(outputNeurons, lastOutputCount);

            var allWeights = new List<double>();
            foreach (var layer in _hiddenLayers)
            {
                allWeights.AddRange(layer.AllWeights);
            }
            allWeights.AddRange(_outputLayer.AllWeights);

            Genome = new Genome(allWeights, 0.0);
        }
Beispiel #23
0
    public void evolve()
    {
        int reproduced;

        string appendText = "\nGeneration "+generation+"";
        generation++;
        File.AppendAllText(path, appendText, Encoding.UTF8);

        for(int i = 0; i < population.Count; i++){
            if(population[i].fitness < 100)
                continue;
            appendText = "\nFitness: "+population[i].fitness+"\nWeights: ";
            File.AppendAllText (path,appendText,Encoding.UTF8);

            for(int j = 0; j < population[i].weights.Count; j++){
                appendText = population[i].weights[j]+" ";
                File.AppendAllText (path,appendText,Encoding.UTF8);
            }
        }

        sortByFitness();
        for(int i = 0; i < 20; i++){
            population.RemoveAt(i); // Remove lowest 20 individuals
        }

        while(population.Count < popSize){
            Genome child1 = new Genome();
            Genome child2 = new Genome();
            reproduced = crossover(rouletteWheelSelection(), rouletteWheelSelection(), child1.weights, child2.weights);
            if(reproduced != -1){
                if(reproduced == 0){
                    child1.enemyType = 0;
                    child2.enemyType = 0;
                }
                else if(reproduced == 1){
                    child1.enemyType = 1;
                    child2.enemyType = 1;
                }
                mutate(child1.weights);
                mutate(child2.weights);

                population.Add (child1);
                population.Add (child2);
            }
        }
    }
        public static int[] Crossover(Genome<int> parent1, Genome<int> parent2)
        {
            _crossPoint = Rnd.Next(1, 32);

            int temp = (1 << _crossPoint) - 1;
            _child1 = parent1.Parameter & temp;
            _child2 = parent2.Parameter & temp;

            temp = Int32.MaxValue - temp;
            _child1 = _child1 | (parent2.Parameter & temp);
            _child2 = _child2 | (parent1.Parameter & temp);

            var crossedGenomes = new int[2];
            crossedGenomes[0] = _child1;
            crossedGenomes[1] = _child2;
            return crossedGenomes;
        }
Beispiel #25
0
        public void Read(Genome.GenomeType genomeType, SnpCollection snps, CancellationToken cancel, Progress progress) {
            if (snps == null) throw new ArgumentNullException("The SnpCollection cannot be null.");
            if (this.filename == null) throw new ArgumentNullException("filename cannot be null.");
            if (String.IsNullOrWhiteSpace(filename)) throw new ArgumentOutOfRangeException("filename cannot be empty.");

            this.comments.Clear();
            if (this.genome == null) {
                this.genome = new Genome(1, 23);
            } else {
                this.genome.Clear();
            }
            if (genomeType == Dna.Genome.GenomeType.Ftdna) {
                ReadFtdnaGenome(snps, cancel, progress);
            } else {
                Read23AndMeGenome(snps, cancel, progress);
            }
            if (String.IsNullOrWhiteSpace(this.genome.Name)) this.genome.Name = Path.GetFileNameWithoutExtension(this.filename);
        }
 public static int Comparison(Genome g1, Genome g2)
 {
     if (g1.Fitness < g2.Fitness)
     {
         return -1;
     }
     else if (g1.Fitness == g2.Fitness)
     {
         return 0;
     }
     else if (g1.Fitness > g2.Fitness)
     {
         return 1;
     }
     else
     {
         return 0;
     }
 }
Beispiel #27
0
    public GameObject spawnHumanImmediate(Vector2 location, Quaternion? rotationNullable, Genome genome)
    {
        Quaternion rotation = rotationNullable.HasValue? rotationNullable.Value: Quaternion.LookRotation(transform.forward, Vector3.zero - map.cellIndexToWorld(location));

        GameObject human;

        if(Options.Testing) {
            human = TrainingAgent.CreateAgent(Human, map.cellIndexToWorld(location), rotation, this, genome);
        }
        else {
            human = HumanAgent.CreateAgent(Human, map.cellIndexToWorld(location), rotation, this, genome);
        }

        HumansOnMap.Add(human);

        ++totalHumansSpawned;

        return human;
    }
Beispiel #28
0
    public static Genome Breeding(Genome g1, Genome g2)
    {
        Genome child = new Genome();

        if(g1.traits.Count == g2.traits.Count)
        {
            for(int i=0;i<g1.traits.Count;++i)
            {
                TraitLeveler tl = new TraitLeveler();
                if (UnityEngine.Random.Range(0, 1.0f) <= 0.5f)
                    tl.trait = g1.traits[i].trait;
                else
                    tl.trait = g2.traits[i].trait;

                tl.currentLevel = 0;
                tl.currentExp = 0;
                child.traits.Add(tl);
            }
        }
        return child;
    }
Beispiel #29
0
    // Create a population
    public Population(int populationSize, bool initialise)
    {
        genomes = new Genome[populationSize];

        if (initialise)
        {
            /*
            int nrInput = 25000; // 25000
            int[] nrHiddenNodes = { 1, 1 };
            int nrOutput = 1;
            */

            int[] layers = {25000, 2};

            for (int i = 0; i < size(); i++)
            {
                //Genome newGenome = new Genome(nrInput, nrHiddenNodes, nrOutput);
                Genome newGenome = new Genome(layers);
                saveGenome(i, newGenome);
            }
        }
    }
Beispiel #30
0
        public override void CalcFitnessDefault(Genome genome)
        {
            genome.Fitness = 0;

            //1 + sum[i = 1 bis n, xi² / 400n] - prod[i = 1 bis n, cos(xi / wurzel(i))]
            // −512 ≤ xi ≤ 511, 1 ≤ i ≤ n (n = 5, 10, 15, 20, 25, 30, 40, . . .),

            double a = 0.0;
            double b = 1.0;
            double i = 1.0;

            foreach (double gene in genome)
            {
                // sum[i = 1 bis n, xi² / 400n]
                a += gene * gene;
                // prod[i = 1 bis n, cos(xi / wurzel(i))]
                b *= Math.Cos(gene / Math.Sqrt(i));

                i++;
            }
            genome.Fitness = 1.0 + a / (400.0 * genome.Count) - b;
        }
Beispiel #31
0
        public void AgeIsCorrectlyPrinted()
        {
            string description = new Genome(age: 3).ToString();

            Assert.True(description.Contains("Age: 3"), $"Genome's age is not printed. Print was: {description}.");
        }
Beispiel #32
0
        public void DefaultAgeIsZero()
        {
            var genome = new Genome();

            Assert.Equal(0, genome.Age);
        }
Beispiel #33
0
    private void NextGen()
    {
        Global.game.restart();
        generation++;
        float         totalFitness   = 0;
        float         leftPopulation = population * (1 - survivalChance);
        List <Genome> nextGenomes    = new List <Genome>();

        foreach (Species species in speciesList)
        {
            totalFitness += species.GetFitness();
        }

        for (int i = 0; i < (int)(population * survivalChance); i++)
        {
            nextGenomes.Add(nets[i].GetGenome());
        }

        foreach (Species species in speciesList)
        {
            for (int i = 0; i < (int)(species.GetFitness() / totalFitness * leftPopulation); i++)
            {
                Genome parent1 = species.GetRandomGenome(random);
                Genome parent2 = species.GetRandomGenome(random);
                Genome child   = new Genome();

                if (networkMap[parent1].GetFitness() > networkMap[parent2].GetFitness())
                {
                    child = GenomeUtils.Crossover(parent1, parent2, random);
                }
                else
                {
                    child = GenomeUtils.Crossover(parent2, parent1, random);
                }
                nextGenomes.Add(child);
            }
        }

        while (nextGenomes.Count < population)
        {
            Genome parent1 = speciesList[0].GetRandomGenome(random);
            Genome parent2 = speciesList[0].GetRandomGenome(random);
            Genome child   = new Genome();

            if (networkMap[parent1].GetFitness() > networkMap[parent2].GetFitness())
            {
                child = GenomeUtils.Crossover(parent1, parent2, random);
            }

            else
            {
                child = GenomeUtils.Crossover(parent2, parent1, random);
            }

            nextGenomes.Add(child);
        }

        foreach (Genome genome in nextGenomes)
        {
            double roll = random.NextDouble();

            if (roll < weightMutationChance)
            {
                genome.Mutate(randomWeightChance, random);
            }
            else if (roll < weightMutationChance + addNodeChance)
            {
                genome.AddNodeMutation(random);
            }
            else if (roll < weightMutationChance + addNodeChance + addConnectionChance)
            {
                genome.AddConnectionMutation(random);
            }
        }

        foreach (Species species in speciesList)
        {
            species.Reset();
        }
        genomes = nextGenomes;
    }
Beispiel #34
0
 private void AddSynapsesToNeuron(Neuron neuron, List <Neuron> previousLayer, ref int genomeIndex, Genome genome)
 {
     foreach (var previousNeuron in previousLayer)
     {
         var nextWeight = genome.Weights[genomeIndex];
         genomeIndex++;
         var synapse = new Synapse(previousNeuron, nextWeight);
         neuron.Inputs.Add(synapse);
     }
 }
Beispiel #35
0
 public List <Connection> FindCandidateConnectionsForNewNode(Genome g)
 {
     return(g.EnabledConnections);
 }
Beispiel #36
0
 public GenomeProvider(IInnovationPointGenerator nodeGenerator, IInnovationPointGenerator connectionGenerator, IRandom random, Genome grandFather)
 {
     _GenomeGrandfather = grandFather;
     _random            = random;
 }
Beispiel #37
0
 private static Connection AddConnection(Genome genome, int from, int to)
 {
     return(genome.AddConnection(genome.Nodes.Single(n => n.Number == from), genome.Nodes.Single(n => n.Number == to)));
 }
Beispiel #38
0
 public RobotNN(RobotPHX robot)
 {
     Robot    = robot;
     Network  = NetworkFactory.CreateDefaultNetwork(new float[] {});
     Genotype = new Genome(Network.Weights);
 }
Beispiel #39
0
 public GenomeProvider(IInnovationPointGenerator nodeGenerator, IInnovationPointGenerator connectionGenerator, IRandom random)
 {
     _GenomeGrandfather = GenerateTemplateGenome(nodeGenerator, connectionGenerator);
     _random            = random;
 }
Beispiel #40
0
    public static Genome CrossOver(Genome parent1, Genome parent2, Fitter f)
    {
        Genome child = new Genome();

        var rand = new Random();

        // Add Disjoint and Excess Connections from Fitter Parent
        if (f == Fitter.Parent1)
        {
            // Add all nodes from the fitter parent
            foreach (Node n in parent1.Nodes.Values)
            {
                child.AddNodeCopy(n);
            }
            foreach (Connection c in parent1.Connections.Values)
            {
                if (!parent2.Connections.ContainsKey(c.Innovation))
                {
                    child.AddConnectionCopy(c);
                }
            }
        }
        else
        {
            foreach (Node n in parent2.Nodes.Values)
            {
                child.AddNodeCopy(n);
            }
            foreach (Connection c in parent2.Connections.Values)
            {
                if (!parent1.Connections.ContainsKey(c.Innovation))
                {
                    child.AddConnectionCopy(c);
                }
            }
        }

        // Go through again to add all the matching gene randomly
        foreach (Connection c1 in parent1.Connections.Values)
        {
            foreach (Connection c2 in parent2.connections.Values)
            {
                // If matching gene --> pick randomly (50/50)
                if (c1.Innovation == c2.Innovation)
                {
                    if (rand.Next(0, 2) == 0)
                    {
                        child.AddConnectionCopy(c1);
                    }
                    else
                    {
                        child.AddConnectionCopy(c2);
                    }
                    // Randomly enable disabled inherited connection
                    if (!c1.Expressed && !c2.Expressed)
                    {
                        double r = rand.NextDouble();
                        if (r < NEATController.ENABLE_CHANCE)
                        {
                            c2.Expressed = true;
                        }
                    }
                }
            }
        }

        return(child);
    }
Beispiel #41
0
        public void AllResultsRequestReturnsAllStoredResults()
        {
            // Create genomes.
            var genome1 = new Genome(age: 1);

            genome1.SetGene("a", new Allele <int>(1));
            var genome2 = new Genome(age: 2);

            genome2.SetGene("a", new Allele <int>(2));

            // Create instances.
            var instance1 = new TestInstance("1");
            var instance2 = new TestInstance("2");

            // Create results.
            var result1 = new TestResult(TimeSpan.FromMilliseconds(1));
            var result2 = new TestResult(TimeSpan.FromMilliseconds(2));
            var result3 = new TestResult(TimeSpan.FromMilliseconds(3));

            // Store some results.
            ActorRefImplicitSenderExtensions.Tell(
                this._resultStorageActorRef,
                new EvaluationResult <TestInstance, TestResult>(
                    new GenomeInstancePair <TestInstance>(new ImmutableGenome(genome1), instance1),
                    result1));
            ActorRefImplicitSenderExtensions.Tell(
                this._resultStorageActorRef,
                new EvaluationResult <TestInstance, TestResult>(
                    new GenomeInstancePair <TestInstance>(new ImmutableGenome(genome1), instance2),
                    result2));
            ActorRefImplicitSenderExtensions.Tell(
                this._resultStorageActorRef,
                new EvaluationResult <TestInstance, TestResult>(
                    new GenomeInstancePair <TestInstance>(new ImmutableGenome(genome2), instance1),
                    result3));

            // Ask for all results.
            ActorRefImplicitSenderExtensions.Tell(this._resultStorageActorRef, new AllResultsRequest());
            var results = this.ExpectMsg <AllResults <TestInstance, TestResult> >();

            // Check returned results are associated with correct genomes.
            Assert.Equal(2, results.RunResults.Count);
            Assert.True(
                results.RunResults.Keys.Select(g => g.CreateMutableGenome()).Any(g => Tuner.Genomes.Genome.GenomeComparer.Equals(g, genome1)),
                "Expected different genome.");
            Assert.True(
                results.RunResults.Keys.Select(g => g.CreateMutableGenome()).Any(g => Tuner.Genomes.Genome.GenomeComparer.Equals(g, genome2)),
                "Expected different genome.");

            // Check all results have been returned.
            var resultsFirstGenome = new Dictionary <TestInstance, TestResult>(
                results.RunResults.Single(
                    kvp => Tuner.Genomes.Genome.GenomeComparer.Equals(kvp.Key.CreateMutableGenome(), genome1)).Value);

            Assert.Equal(2, resultsFirstGenome.Count);
            Assert.Equal(result1.Runtime, resultsFirstGenome[instance1].Runtime);
            Assert.Equal(result2.Runtime, resultsFirstGenome[instance2].Runtime);
            var resultsSecondGenome = new Dictionary <TestInstance, TestResult>(
                results.RunResults.Single(
                    kvp => Tuner.Genomes.Genome.GenomeComparer.Equals(kvp.Key.CreateMutableGenome(), genome2)).Value);

            Assert.Single(resultsSecondGenome);
            Assert.Equal(result3.Runtime, resultsSecondGenome[instance1].Runtime);
        }
    private bool isLearning = true;     //If a real player is playing the game

    // Use this for initialization
    void Start()
    {
        GetComponent <BoxCollider2D> ().enabled = false;

        isLearning = (genomes.Count < 4);
        if (!isLearning && Utils.actualGenome >= genomes.Count)
        {
            print("Acabou de jogar os genomas");
            Utils.clearCrossOversFolder();
            genomes = Utils.loadAllGenomes();              //Force GENOMES root folder

            List <Genome> bestGenomes = Utils.naturalSelection(genomes, 4);
            Utils.clearGenomesFolder();

            for (int i = 0; i < bestGenomes.Count; i++)
            {
                Utils.persistInJson(bestGenomes[i], genomeBasePath + i + "_");
            }

            //New Crossovers + Mutations
            for (int i = 0; i < 4; i++)
            {
                for (int j = 0; j < 4; j++)
                {
                    if (i == j)
                    {
                        continue;
                    }

                    Genome g = Genetic.crossOver(bestGenomes [i], bestGenomes [j]);
                    g = Genetic.mutate(g);
                    Utils.persistInJson(g, "Genomes/CrossedOvers/genome_" + i + "_" + j + "_");
                }
            }

            genomes            = Utils.loadAllGenomes();
            Utils.actualGenome = 0;
        }
        sprites          = Resources.LoadAll <Sprite> ("Art/Player/Standing");
        crouchingSprites = Resources.LoadAll <Sprite> ("Art/Player/Crouching");

        GameObject.Find("Canvas").GetComponent <Canvas> ().enabled = false;

        //Load Cactus
        foreach (GameObject c in GameObject.FindGameObjectsWithTag("cactus"))
        {
            int cacType;
            switch (c.name)
            {
            case "cactus_1":
                cacType = 1;
                break;

            case "cactus_2":
                cacType = 2;
                break;

            case "cactus_3":
                cacType = 3;
                break;

            default:
                cacType = 1;
                break;
            }
            Cactus toAdd = new Cactus()
            {
                type     = cacType,
                position = c.transform.position
            };
            cactus.Add(toAdd);
        }
    }
Beispiel #43
0
 /// <summary>
 /// Initializes a new instance of the <see cref="GenomeTest"/> class.
 /// </summary>
 public GenomeTest()
 {
     this._genome = new Genome();
 }
Beispiel #44
0
    /// <summary>
    /// Constructor of a generation info container. Save the best genome and do an arithmetic average of each gen
    /// </summary>
    /// <param name="motorcycles"></param>
    /// <param name="ID"></param>
    public Generation(List <Motorcycle> motorcycles, int ID)
    {
        m_ID = ID;

        // Save the best genome and best score
        m_bestGenome = new Genome(motorcycles[0].genome());
        m_bestScore  = motorcycles[motorcycles.Count - 1].score();

        // Get all available genes for later average calculation
        List <FGenID> fGenIDs = motorcycles[0].genome().GetFGenesKeys();
        List <IGenID> iGenIDs = motorcycles[0].genome().GetIGenesKeys();
        List <BGenID> bGenIDs = motorcycles[0].genome().GetBGenesKeys();

        m_fGenesAverage = new Dictionary <FGenID, float>();
        m_iGenesAverage = new Dictionary <IGenID, float>();
        m_bGenesAverage = new Dictionary <BGenID, float>();

        // Add all the genes and inialize to 0
        foreach (FGenID fGenID in fGenIDs)
        {
            m_fGenesAverage.Add(fGenID, 0.0f);
        }
        foreach (IGenID iGenID in iGenIDs)
        {
            m_iGenesAverage.Add(iGenID, 0.0f);
        }
        foreach (BGenID bGenID in bGenIDs)
        {
            m_bGenesAverage.Add(bGenID, 0.0f);
        }

        m_scoreAverage = 0.0f;

        // Summatory of each motorcycle gen
        foreach (Motorcycle motorcycle in motorcycles)
        {
            m_scoreAverage += motorcycle.score();

            foreach (FGenID fGenID in fGenIDs)
            {
                m_fGenesAverage[fGenID] += motorcycle.genome().GetGen(fGenID).Value();
            }
            foreach (IGenID iGenID in iGenIDs)
            {
                m_iGenesAverage[iGenID] += motorcycle.genome().GetGen(iGenID).Value();
            }
            foreach (BGenID bGenID in bGenIDs)
            {
                if (motorcycle.genome().GetGen(bGenID).Value())
                {
                    m_bGenesAverage[bGenID] += 1.0f;
                }
            }
        }

        // Divide each summatory by the number of motorcycles
        int nMotorcycles = motorcycles.Count;

        m_scoreAverage *= 1.0f / (float)nMotorcycles;

        foreach (FGenID fGenID in fGenIDs)
        {
            m_fGenesAverage[fGenID] *= 1.0f / (float)nMotorcycles;
        }
        foreach (IGenID iGenID in iGenIDs)
        {
            m_iGenesAverage[iGenID] *= 1.0f / (float)nMotorcycles;
        }
        foreach (BGenID bGenID in bGenIDs)
        {
            m_bGenesAverage[bGenID] *= 1.0f / (float)nMotorcycles;
        }

        // Save the string for later
        m_bestGenomeString    = BestGenomeToString();
        m_averageGenomeString = AverageToString();
    }
Beispiel #45
0
        public void AgeIsSetCorrectly()
        {
            var genome = new Genome(35);

            Assert.Equal(35, genome.Age);
        }
 public JsonGenome(Genome genome)
 {
     NumberOfInputNodes  = genome.NumberOfInputNodes;
     NumberOfOutputNodes = genome.NumberOfOutputNodes;
     Layers = genome.Layers;
 }
Beispiel #47
0
    private void SetupLayer(List <Neuron> currentLayer, int neuronCount, List <Neuron> previousLayer, string neuronNamePrefix, ref int weightIndex, Genome genome)
    {
        for (var neuronId = 0; neuronId < neuronCount; neuronId++)
        {
            var neuron = new Neuron(neuronNamePrefix + neuronId);

            AddSynapsesToNeuron(neuron, previousLayer, ref weightIndex, genome);
            currentLayer.Add(neuron);
        }
    }
Beispiel #48
0
 public void PutWeights(Genome genome)
 {
     brain.PutWeights(genome.Weights);
 }
Beispiel #49
0
 /// <summary>
 /// Add Genome to Species and Update it's ID
 /// </summary>
 public void Add(Genome genome)
 {
     Genomes.Add(genome);
     genome.SpeciesID = this.ID;
 }
Beispiel #50
0
        public void Should_Transfer_subroutes()
        {
            var settings = new GASettings();
            var service  = A.Fake <IRouteService>();
            var random   = A.Fake <IRandom>();
            var map      = A.Dummy <Roteiro>();
            var locals   = Enumerable.Range(0, 6).Select(e => new Local(e.ToString())
            {
                Latitude = e, Longitude = e
            }).ToArray();

            A.CallTo(() => service.GetRouteAsync(A <Local> ._, A <Local> ._))
            .Returns(new Rota {
                Metros = 1
            });

            A.CallTo(() => service.GetRouteAsync(locals[1], locals[4]))
            .Returns(new Rota {
                Metros = 0
            }).Once();

            A.CallTo(() => service.GetRouteAsync(locals[3], locals[2]))
            .Returns(new Rota {
                Metros = 0
            }).Once();

            A.CallTo(() => random.Next(A <int> ._, A <int> ._))
            .Returns(1);

            A.CallTo(() => random.Next(A <int> ._, A <int> ._))
            .ReturnsNextFromSequence(
                // mon to dad
                0   // indice da rota a extrair a subrota
                , 2 // quantidade de locais a extrais da rota
                , 1 // indice do primeiro local da subrota

                // dad to mon
                , 1 // indice da rota a extrair a subrota
                , 1 // quantidade de locais a extrais da rota
                , 0 // indice do primeiro local da subrota
                );

            var mon = new Genome(map, settings)
            {
                Trucks = new[] {
                    new Truck {
                        Locals = new[] { locals[0], locals[1], locals[2] }
                    },
                    new Truck {
                        Locals = new[] { locals[3], locals[4], locals[5] }
                    }
                }
            };

            var dad = new Genome(map, settings)
            {
                Trucks = new[] {
                    new Truck {
                        Locals = new[] { locals[5], locals[4], locals[3] }
                    },
                    new Truck {
                        Locals = new[] { locals[3], locals[2], locals[1] }
                    }
                }
            };


            var cx     = new SubRouteInsertionCrossover(settings, random, service);
            var result = cx.Make(mon, dad);

            result.First().Trucks[0].Locals.Should()
            .BeEquivalentTo(new[] { locals[5], locals[4], locals[1], locals[2], locals[3] });

            result.Last().Trucks[0].Locals.Should()
            .BeEquivalentTo(new[] { locals[0], locals[1], locals[2], locals[3] });
        }
Beispiel #51
0
 protected override void Initialize(Genome<byte> genome)
 {
     for(int i = 0; i < ChromoLength; ++i)
         genome.Values[i] = (byte)Random.Next(0, 255);
 }
Beispiel #52
0
        //Place home;
        //Place location;
        // These are in PhysObject as well - not sure if they need to be mirrored here for access.

        public Agent(Place _location, Agent _father, Agent _mother, Agent _master, int dateBorn) : base(_location)
        {
            genome = Genome.Combination(_father.genome, _mother.genome);
            SetHome(_mother.GetHome());
        }
Beispiel #53
0
 public bool Evaluate(Genome gi) => Evaluate(gi._weights.ToArray(), new Dictionary <string, float>(gi._metrics));
Beispiel #54
0
 public Agent(Place _location, int dateBorn) : base(_location)
 {
     genome = new Genome();             // Random
 }
Beispiel #55
0
 public void MutateWeights()
 {
     genome.WeightMutation();
     gameObject.GetComponent <GenomePrinter>().Draw(genome);
     Genome.DebugPrint(genome);
 }
Beispiel #56
0
    //selects from the population based on selection type specified in constructor
    public List <Genome> Select(Population p, string userSelection = "")
    {
        var selectionPool = new List <Genome>();
        var size          = p._size;
        var genomes       = p._genomes;
        var fitnesses     = p._fitnesses;

        switch (_selectionType)
        {
        //this is when the user interactively chooses after each generation the best candidates
        case "god mode":

            string[] indices        = userSelection.Split(' ');
            int      selectionCount = indices.Length;

            //if user doesn't choose any, just use the whole population again as parents
            if (userSelection == "")
            {
                selectionPool = p._genomes.Select(x => x).ToList();
                Debug.Log("Warning : No user choice specified, whole generation used as parents");
            }
            else
            {
                for (int i = 0; i < size; i++)
                {
                    string mod = indices[i % selectionCount];
                    selectionPool.Add(p._genomes[int.Parse(mod)]);
                }
            }
            break;

        //tournament selection of size 2, preserves rank so preferable to fitness proportional apparently (see metaheuristics book)
        //I suspect this is only the case at large scale and if you tend towards high fitnesses in all candidates
        //should make 2 a variable
        case "tournament":

            for (int i = 0; i < size; i++)
            {
                //choose two values (n = 2)
                int    r    = UnityEngine.Random.Range(0, size);
                int    r2   = UnityEngine.Random.Range(0, size);
                Genome best = fitnesses[r] >= fitnesses[r2] ? genomes[r] : genomes[r2];
                selectionPool.Add(best);
            }

            break;

        //random selection of breeding genomes from the cdf
        case "fitnessProportional":

            List <Genome> cdf = Cdf(genomes, fitnesses);

            for (int i = 0; i < size; i++)
            {
                int r = UnityEngine.Random.Range(0, cdf.Count);
                selectionPool.Add(cdf[r]);
            }
            break;

        //step through the cdf in steps of cdf.count / size, and picks random item in each step range
        //can be more representative than fitnessProportional
        case "stochasticUniversalSampling":

            cdf = Cdf(genomes, fitnesses);

            for (int i = 0; i < size; i++)
            {
                int r = UnityEngine.Random.Range((cdf.Count / size) * i, (cdf.Count / size) * (i + 1));
                selectionPool.Add(cdf[r]);
            }
            break;

        //takes the top 5 by fitness and then fills the selection pool with size /5 of those
        //by far the best for the tests I've run so far
        //should make 5 a variable
        case "truncated":

            for (int i = 0; i < 5; i++)
            {
                for (int j = 0; j < (size / 5); j++)
                {
                    //genomes is already ordered so it's fairly simple
                    selectionPool.Add(genomes[i]);
                }
            }
            break;
        }

        //shuffle the selection pool randomly
        System.Random rand = new System.Random();
        selectionPool = new List <Genome>(selectionPool.OrderBy(x => rand.Next()));

        return(selectionPool);
    }
Beispiel #57
0
    //takes two genomes as input and crosses them
    public void Cross(Genome p1, Genome p2, bool variableGenomeLength, int seed)
    {
        //randomly pick a gene from each genome to cross
        int geneChoice1 = UnityEngine.Random.Range(0, p1._genome.Length);
        int geneChoice2 = UnityEngine.Random.Range(0, p2._genome.Length);

        //get randomly selected genes from each genome
        var p1Gene = p1._genome[geneChoice1];
        var p2Gene = p2._genome[geneChoice2];

        System.Random random = new System.Random(seed);
        int           xPt1   = random.Next(0, p1Gene.Length); //1st crossover pt on first genome
        int           yPt1   = random.Next(0, p2Gene.Length); //1st crossover pt on second genome

        //essentially a two sided clamp, restricting the max dist between xPt1 and yPt1, restricts the gene growth so the fractals don't blow out!
        //also restricts the values to  be within the length of the genome
        int growthCap = Math.Max(_maxGeneGrowth, Math.Abs(yPt1 - xPt1));

        if (xPt1 < yPt1)
        {
            yPt1 = random.Next(0, Math.Min(xPt1 + growthCap, p2Gene.Length));
        }
        else
        {
            yPt1 = random.Next(Math.Max(Math.Min(xPt1 - growthCap, p2Gene.Length), 0), p2Gene.Length);
        }

        //if genomes all have the same length then cross at same point to maintain lengths
        if (!variableGenomeLength)
        {
            yPt1 = xPt1;
        }

        string crossedString1, crossedString2;

        //determines which crossover type to apply
        switch (_crossoverType)
        {
        //cuts the genotype at one point and swaps genes
        case "OnePt":

            crossedString1 = p1Gene.Substring(0, xPt1) + p2Gene.Substring(yPt1);

            p1.SetGene(geneChoice1, crossedString1);

            crossedString2 = p2Gene.Substring(0, yPt1) + p1Gene.Substring(xPt1);

            p2.SetGene(geneChoice2, crossedString2);

            break;

        //cuts the genotype at two points and swaps genes
        //not tested for L system evolution, worked in text/image
        case "TwoPt":

            int xPt2 = UnityEngine.Random.Range(0, p1Gene.Length);     //2nd crossover pt on first genome
            int yPt2 = UnityEngine.Random.Range(0, p2Gene.Length);     //2nd crossover pt on second genome

            if (!variableGenomeLength)
            {
                yPt2 = xPt2;
            }                                               //if all genomes the same length, use the same 2nd crossover pt
            if (variableGenomeLength)
            {
                yPt1 = Math.Min(xPt1, yPt1); xPt1 = yPt1;
            }

            int xmin = Math.Min(xPt1, xPt2);
            int xmax = Math.Max(xPt1, xPt2);

            int ymin = Math.Min(yPt1, yPt2);
            int ymax = Math.Max(yPt1, yPt2);

            crossedString1 = p1Gene.Substring(0, xmin) + p2Gene.Substring(ymin, ymax - ymin) + p1Gene.Substring(xmax);
            crossedString2 = p2Gene.Substring(0, ymin) + p1Gene.Substring(xmin, xmax - xmin) + p2Gene.Substring(ymax);

            p1.SetGene(geneChoice1, crossedString1);
            p2.SetGene(geneChoice2, crossedString2);

            break;

        //swaps genes by index depending on the swap rate
        case "Uniform":

            float  swapRate = 0.1f;
            char[] chars1   = p1Gene.ToCharArray();
            char[] chars2   = p2Gene.ToCharArray();

            int minLength = Math.Min(chars1.Length, chars2.Length);     //only swaps up till the end of shortest genome

            for (int i = 0; i < minLength; i++)
            {
                //if under swapRate swap genes at index
                if (UnityEngine.Random.Range(0f, 1f) < swapRate)
                {
                    char temp = chars1[i];
                    chars1[i] = chars2[i];
                    chars2[i] = temp;
                }
            }

            p1.SetGene(geneChoice1, new string(chars1));
            p2.SetGene(geneChoice2, new string(chars2));

            break;
        }
    }
Beispiel #58
0
 public XORNNProvider(IInnovationPointGenerator nodeGenerator, IInnovationPointGenerator connectionGenerator, IRandom random, Genome grandFather)
 {
     _nodeGenerator       = nodeGenerator;
     _connectionGenerator = connectionGenerator;
     _random      = random;
     _grandFather = grandFather;
 }
 InnerCrossover(Genome <CPPNNEATGeneCollection, MandelbrotCPPNNEATPhenome> partner)
 {
     return(new MandelbrotCPPNNEATGenome((MandelbrotCPPNNEATGA)Parent, (MandelbrotCPPNNEATGenome)this, (MandelbrotCPPNNEATGenome)partner));
 }
Beispiel #60
0
 public RobotNN(RobotPHX robot, Genome genome)
 {
     Robot    = robot;
     Genotype = genome;
     Network  = NetworkFactory.CreateDefaultNetwork(Genotype.GetWeights());
 }