Exemplo n.º 1
0
        /// <summary>
        /// Adds gene between two nodes.
        /// There cannot be two genes between same nodes.
        /// </summary>
        private void AddGene(Random rnd, ref int innovation, List <Gene> allGenes)
        {
            int latter;
            int first;

            do
            {
                first = rnd.Next(0, Nodes.Count);
            }while(Nodes[first].Type == NodeType.Output);
            Node input = Nodes[first];
            Node output;
            int  j = 0;

            do
            {
                latter = rnd.Next(0, Nodes.Count);
                output = Nodes[latter];
                ++j;
                if (j > 10 && input.Layer >= output.Layer)
                {
                    for (int i = 0; i < Nodes.Count; i++)
                    {
                        if (input.Layer < Nodes[i].Layer)
                        {
                            output = Nodes[i];
                        }
                    }
                }
            } // SHOULD NOT PICK THE SAME LAYER
            while (input.Layer >= output.Layer);

            Gene gene = null;

            foreach (var item in allGenes)
            {
                if (item.In.Number == input.Number && item.Out.Number == output.Number)
                {
                    gene      = item.ShallowCopy();
                    gene.In   = input;
                    gene.Type = GeneType.Enabled;
                    gene.Out  = output;
                    break;
                }
            }

            if (gene == null)
            {
                gene = new Gene(input, output, 0f, GeneType.Enabled, ++innovation);
                var g = gene.ShallowCopy();
                g.Type = GeneType.AddGene;
                allGenes.Add(g);
            }
            if (Genes.ContainsValue(gene))
            {
                return;
            }
            gene.Weight = gene.AssignRandomWeight(rnd);
            gene.In.OutgoingConnections.Add(gene);
            Genes.Add(gene.Innovation, gene);
        }