示例#1
0
        public virtual void Cross(IGenome genome1, IGenome genome2)
        {
            SelectionGenome sGenome1 = (SelectionGenome) genome1;
            SelectionGenome sGenome2 = (SelectionGenome) genome2;

            SelectionCrossover(sGenome1, sGenome2);

            sGenome1.InstructionGraph     = null;
            sGenome1.RegisterAssignment   = null;
            sGenome1.InstructionSchedule  = null;
            sGenome1.Modified = true;

            /*
            sGenome1.BestSchedulingGenome = null;
            */

            sGenome2.InstructionGraph     = null;
            sGenome2.RegisterAssignment   = null;
            sGenome2.InstructionSchedule  = null;
            sGenome2.Modified = true;

            /*
            sGenome2.BestSchedulingGenome = null;
            */
        }
示例#2
0
        public virtual void Mutate(IGenome genome, double pMutation)
        {
            SchedulingGenome sGenome = (SchedulingGenome) genome;

            bool mutated = false;

            if (GA.Random.NextDouble() < pScheduleMutation) {
                ScheduleMutation(sGenome);
                mutated = true;
            }

            if (GA.Random.NextDouble() < pRegisterMutation) {
                RegisterMutation(sGenome);
                mutated = true;
            }

            if (GA.Random.NextDouble() < pScheduleCrossSwap) {
                ScheduleCrossSwap(sGenome);
                mutated = true;
            }

            if (GA.Random.NextDouble() < pScheduleCompaction) {
                ScheduleCompaction(sGenome);
                mutated = true;
            }

            if (mutated)
                sGenome.GenerationOfBirth = sGenome.Population.GA.Generation;
        }
 public IMLMethod Decode(IGenome genome)
 {
     var result = new RBFNetwork(_inputCount, _rbfCount, _outputCount);
     var dag = (DoubleArrayGenome) genome;
     Array.Copy(dag.Data, 0, result.LongTermMemory, 0, _size);
     return result;
 }
 /// <summary>
 ///     Construct the parallel task.
 /// </summary>
 /// <param name="genome">The genome.</param>
 /// <param name="theOwner">The owner.</param>
 public ParallelScoreTask(IGenome genome, ParallelScore theOwner)
 {
     owner = theOwner;
     this.genome = genome;
     scoreFunction = theOwner.ScoreFunction;
     adjusters = theOwner.Adjusters;
 }
示例#5
0
 /// <summary>
 /// Record a unique genome
 /// </summary>
 /// <param name="genome">genome to be record</param>
 public void setGenomeLog(IGenome genome)
 {
     xtw.WriteStartElement("Genome");
     xtw.WriteAttributeString("Value", genome.ToString());
     xtw.WriteAttributeString("Fitness", genome.Evaluate().ToString());
     xtw.WriteEndElement();
 }
示例#6
0
 /// <inheritdoc />
 public override void Copy(IGenome source)
 {
     var sourceDouble = (DoubleArrayGenome) source;
     Array.Copy(sourceDouble._data, _data, _data.Length);
     Score = source.Score;
     AdjustedScore = source.AdjustedScore;
 }
        /// <inheritdoc/>
        public override void PerformOperation(EncogRandom rnd, IGenome[] parents,
                int parentIndex, IGenome[] offspring,
                int offspringIndex)
        {
            var target = ObtainGenome(parents, parentIndex, offspring,
                    offspringIndex);

            if (target.LinksChromosome.Count < MinLink)
            {
                // don't remove from small genomes
                return;
            }

            // determine the target and remove
            var index = RangeRandomizer.RandomInt(0, target
                    .LinksChromosome.Count - 1);
            NEATLinkGene targetGene = target.LinksChromosome[index];
            target.LinksChromosome.Remove(targetGene);

            // if this orphaned any nodes, then kill them too!
            if (!IsNeuronNeeded(target, targetGene.FromNeuronId))
            {
                RemoveNeuron(target, targetGene.FromNeuronId);
            }

            if (!IsNeuronNeeded(target, targetGene.ToNeuronId))
            {
                RemoveNeuron(target, targetGene.ToNeuronId);
            }
        }
示例#8
0
 public MateWorker(IGenome theMother, IGenome theFather, IGenome theChild1, IGenome theChild2)
 {
     this._x405fa6c967740d37 = theMother;
     this._xdb6cbc417cc4e418 = theFather;
     this._xa7eb051c3211c54a = theChild1;
     this._x76ad8378bdb66d70 = theChild2;
 }
 /// <inheritdoc/>
 public IGenome Factor(IGenome other)
 {
     MLMethodGenome result = (MLMethodGenome)Factor();
     result.Copy(other);
     result.Population = this.population;
     return result;
 }
 /// <inheritdoc />
 public IGenome Factor(IGenome other)
 {
     var result = new EncogProgram(_context,
                                   new EncogProgramVariables());
     result.Copy(other);
     return result;
 }
示例#11
0
 /// <inheritdoc />
 public override void Copy(IGenome source)
 {
     var sourceInt = (IntegerArrayGenome) source;
     Array.Copy(sourceInt._data, _data, _data.Length);
     Score = source.Score;
     AdjustedScore = source.AdjustedScore;
 }
 /// <inheritdoc />
 public override double GetCompatibilityScore(IGenome genome1,
                                              IGenome genome2)
 {
     var comp = new CompareEncogProgram();
     double d = comp.Compare((EncogProgram) genome1,
                             (EncogProgram) genome2);
     return d;
 }
 /// <inheritdoc />
 public void PerformOperation(EncogRandom rnd, IGenome[] parents,
                              int parentIndex, IGenome[] offspring,
                              int offspringIndex)
 {
     IEvolutionaryOperator opp = _components.Pick(rnd);
     opp.PerformOperation(rnd, parents, parentIndex, offspring,
                          offspringIndex);
 }
示例#14
0
 /// <param name="theMother">The mother.</param>
 /// <param name="theFather">The father.</param>
 /// <param name="theChild1">The first child.</param>
 /// <param name="theChild2">The second child.</param>
 public MateWorker(IGenome theMother, IGenome theFather,
                   IGenome theChild1, IGenome theChild2)
 {
     _mother = theMother;
     _father = theFather;
     _child1 = theChild1;
     _child2 = theChild2;
 }
示例#15
0
 /// <summary>
 /// Execute Mutation in the genome for reference with based in the rate
 /// </summary>
 /// <param name="genome">Genome</param>
 public void Mutate(IGenome genome)
 {
     if (Helper.Random.NextDouble() < RateMutation)
     {
         int locus = Helper.Random.Next(genome.Length);
         genome[locus] = !genome[locus];
     }
 }
示例#16
0
 /// <summary>
 /// Execute Mutation in the genome for reference with based in the rate
 /// </summary>
 /// <param name="genome">Genome</param>
 public void Mutate(IGenome genome)
 {
     for(int locus = 0; locus < genome.Length; locus++)
     {
         if (Helper.Random.NextDouble() < RatePerGene)
             genome[locus] = !genome[locus];
     }
 }
示例#17
0
 /// <summary>
 /// Create a MateWorker.
 /// </summary>
 /// <param name="mother">The mother.</param>
 /// <param name="father">The father.</param>
 /// <param name="child1">The first child.</param>
 /// <param name="child2">The second child.</param>
 public MateWorker(IGenome mother, IGenome father,
         IGenome child1, IGenome child2)
 {
     this.mother = mother;
     this.father = father;
     this.child1 = child1;
     this.child2 = child2;
 }
 /// <summary>
 ///     Construct a species.
 /// </summary>
 /// <param name="thePopulation">The population the species belongs to.</param>
 /// <param name="theFirst">The first genome in the species.</param>
 public BasicSpecies(IPopulation thePopulation, IGenome theFirst)
 {
     Population = thePopulation;
     BestScore = theFirst.Score;
     GensNoImprovement = 0;
     Age = 0;
     Leader = theFirst;
     _members.Add(theFirst);
 }
示例#19
0
        public virtual void Cross(IGenome genome1, IGenome genome2)
        {
            SchedulingGenome sGenome1 = (SchedulingGenome) genome1;
            SchedulingGenome sGenome2 = (SchedulingGenome) genome2;

            PositionExchangeCrossover(sGenome1, sGenome2);

            sGenome1.GenerationOfBirth = sGenome1.Population.GA.Generation;
            sGenome2.GenerationOfBirth = sGenome2.Population.GA.Generation;
        }
 /// <inheritdoc />
 public void PerformOperation(EncogRandom rnd, IGenome[] parents,
                              int parentIndex, IGenome[] offspring,
                              int offspringIndex)
 {
     var program = (EncogProgram) parents[0];
     EncogProgramContext context = program.Context;
     EncogProgram result = context.CloneProgram(program);
     MutateNode(rnd, result.RootNode);
     offspring[0] = result;
 }
示例#21
0
        /// <summary>
        /// Execute crossover between two genomes and return other two genomes mixed
        /// </summary>
        /// <param name="genome1">Genome</param>
        /// <param name="genome2">Genome</param>
        /// <returns>Two new genomes, that are a mixture of genome1 and genome2</returns>
        public IList<IGenome> Crossover(IGenome genome1, IGenome genome2)
        {
            this.positions.Add(genome1.Length);
            IList<bool> offspring1 = new List<bool>();
            IList<bool> offspring2 = new List<bool>();
            int contParams = 0;
            bool aux = true;
            while (contParams < positions.Count - 1)
            {
                for (int locus = positions[contParams]; locus < positions[contParams + 1]; locus++)
                {
                    if (aux)
                    {
                        offspring1.Add(genome1[locus]);
                        offspring2.Add(genome2[locus]);
                    }
                    else
                    {
                        offspring1.Add(genome2[locus]);
                        offspring2.Add(genome1[locus]);
                    }
                }
                aux = !aux;
                contParams++;
            }
            /*
            bool aux = true;
            int contParams = 0;
            int atual = positions[contParams];

            for (int locus = 0; locus < genome1.Length; locus++)
            {
                if (positions[contParams] == locus)
                {
                    aux = !aux;
                    contParams++;
                }

                if (aux)
                {
                    offspring1.Add(genome1[locus]);
                    offspring2.Add(genome2[locus]);
                }
                else
                {
                    offspring1.Add(genome2[locus]);
                    offspring2.Add(genome1[locus]);
                }
            }
            */
            IList<IGenome> genomes = new List<IGenome>();
            genomes.Add(new BinaryGenome(offspring1));
            genomes.Add(new BinaryGenome(offspring2));
            return genomes;
        }
 /// <inheritdoc />
 public bool Rewrite(IGenome g)
 {
     _rewritten = false;
     var program = (EncogProgram) g;
     ProgramNode node = program.RootNode;
     ProgramNode rewrittenRoot = InternalRewrite(node);
     if (rewrittenRoot != null)
     {
         program.RootNode = rewrittenRoot;
     }
     return _rewritten;
 }
 /// <inheritdoc />
 public bool Rewrite(IGenome g)
 {
     var program = ((EncogProgram) g);
     _rewritten = false;
     ProgramNode rootNode = program.RootNode;
     ProgramNode rewrite = RewriteNode(rootNode);
     if (rewrite != null)
     {
         program.RootNode = rewrite;
     }
     return _rewritten;
 }
示例#24
0
 public double Evaluate(IGenome genome)
 {
     double fitness = 0;
     for (int i = 0; i < genome.Length; i++)
     {
         if (genome[i])
         {
             fitness += Math.Pow(2, genome.Length - 1 - i);
         }
     }
     return fitness;
 }
        /// <inheritdoc/>
        public override void PerformOperation(EncogRandom rnd, IGenome[] parents, int parentIndex,
                IGenome[] offspring, int offspringIndex)
        {
            int countTrysToAddLink = Owner.MaxTries;

            NEATGenome target = ObtainGenome(parents, parentIndex, offspring,
                    offspringIndex);

            // the link will be between these two neurons
            long neuron1Id = -1;
            long neuron2Id = -1;

            // try to add a link
            while ((countTrysToAddLink--) > 0)
            {
                NEATNeuronGene neuron1 = ChooseRandomNeuron(target, true);
                NEATNeuronGene neuron2 = ChooseRandomNeuron(target, false);

                if (neuron1 == null || neuron2 == null)
                {
                    return;
                }

                // do not duplicate
                // do not go to a bias neuron
                // do not go from an output neuron
                // do not go to an input neuron
                if (!IsDuplicateLink(target, neuron1.Id, neuron2.Id)
                        && (neuron2.NeuronType != NEATNeuronType.Bias)
                        && (neuron2.NeuronType != NEATNeuronType.Input))
                {

                    if (((NEATPopulation)Owner.Population).ActivationCycles != 1
                            || neuron1.NeuronType != NEATNeuronType.Output)
                    {
                        neuron1Id = neuron1.Id;
                        neuron2Id = neuron2.Id;
                        break;
                    }
                }
            }

            // did we fail to find a link
            if ((neuron1Id < 0) || (neuron2Id < 0))
            {
                return;
            }

            double r = ((NEATPopulation)target.Population).WeightRange;
            CreateLink(target, neuron1Id, neuron2Id,
                    RangeRandomizer.Randomize(rnd, -r, r));
            target.SortGenes();
        }
        /// <inheritdoc />
        public void PerformOperation(EncogRandom rnd, IGenome[] parents,
                                     int parentIndex, IGenome[] offspring,
                                     int offspringIndex)
        {
            var parent1 = (EncogProgram) parents[0];
            var parent2 = (EncogProgram) parents[1];
            offspring[0] = null;

            EncogProgramContext context = parent1.Context;
            int size1 = parent1.RootNode.Count;
            int size2 = parent2.RootNode.Count;

            bool done = false;
            int tries = 100;

            while (!done)
            {
                int p1Index = rnd.Next(size1);
                int p2Index = rnd.Next(size2);

                var holder1 = new LevelHolder(p1Index);
                var holder2 = new LevelHolder(p2Index);

                IList<EPLValueType> types = new List<EPLValueType>();
                types.Add(context.Result.VariableType);

                FindNode(rnd, parent1.RootNode, types, holder1);
                FindNode(rnd, parent2.RootNode, types, holder2);

                if (LevelHolder.CompatibleTypes(holder1.Types,
                                                holder2.Types))
                {
                    EncogProgram result = context.CloneProgram(parent1);
                    ProgramNode resultNode = parent1.FindNode(p1Index);
                    ProgramNode p2Node = parent2.FindNode(p2Index);
                    ProgramNode newInsert = context.CloneBranch(result,
                                                                p2Node);
                    result.ReplaceNode(resultNode, newInsert);
                    offspring[0] = result;
                    done = true;
                }
                else
                {
                    tries--;
                    if (tries < 0)
                    {
                        done = true;
                    }
                }
            }
        }
示例#27
0
        public override void EvaluatePopulation(Population pop, EvolutionAlgorithm ea)
        {
            // Evaluate in single-file each genome within the population.
            // Only evaluate new genomes (those with EvaluationCount==0).
            FoodGatherParams.fillLookups();
            FoodGatherParams.fillFood();
            int count = pop.GenomeList.Count;

            for (int i = 0; i < count; i++)
            {
                IGenome g = pop.GenomeList[i];
                if (g.EvaluationCount != 0)
                {
                    continue;
                }

                INetwork network = g.Decode(activationFn);
                if (network == null)
                {       // Future genomes may not decode - handle the possibility.
                    g.Fitness = EvolutionAlgorithm.MIN_GENOME_FITNESS;
                }
                else
                {
                    g.Fitness          = Math.Max(networkEvaluator.EvaluateNetwork(network), EvolutionAlgorithm.MIN_GENOME_FITNESS);
                    g.ObjectiveFitness = g.Fitness;
                }

                // Reset these genome level statistics.
                g.TotalFitness    = g.Fitness;
                g.EvaluationCount = 1;

                // Update master evaluation counter.
                evaluationCount++;
            }
            if (requestResolutionUp == true)
            {
                requestResolutionUp          = false;
                requestResolutionDown        = false;
                FoodGatherParams.resolution *= 2;
            }
            else if (requestResolutionDown == true)
            {
                requestResolutionUp   = false;
                requestResolutionDown = false;
                if (FoodGatherParams.resolution > 4)
                {
                    FoodGatherParams.resolution /= 2;
                }
            }
        }
示例#28
0
文件: Test.cs 项目: afalz/NEAT
        public void Init()
        {
            genome = new Genome();

            inputNode  = new Node(NodeType.Input, 0);
            outputNode = new Node(NodeType.Output, 0);

            genome.Nodes.Add(inputNode);
            genome.Nodes.Add(outputNode);

            gene = new Gene(inputNode, outputNode, Genome.GetNextInnovation());

            genome.Genes.Add(gene);
        }
        /// <inheritdoc/>
        public void PerformOperation(EncogRandom rnd, IGenome[] parents, int parentIndex,
                IGenome[] offspring, int offspringIndex)
        {
            DoubleArrayGenome parent = (DoubleArrayGenome)parents[parentIndex];
            offspring[offspringIndex] = parent.Population.GenomeFactory.Factor();
            DoubleArrayGenome child = (DoubleArrayGenome)offspring[offspringIndex];

            for (int i = 0; i < parent.Size; i++)
            {
                double value = parent.Data[i];
                value += (perturbAmount - (rnd.NextDouble() * perturbAmount * 2));
                child.Data[i] = value;
            }
        }
示例#30
0
        /// <inheritdoc />
        public bool Rewrite(IGenome g)
        {
            var program = ((EncogProgram)g);

            _rewritten = false;
            ProgramNode rootNode = program.RootNode;
            ProgramNode rewrite  = RewriteNode(rootNode);

            if (rewrite != null)
            {
                program.RootNode = rewrite;
            }
            return(_rewritten);
        }
示例#31
0
        public static IGenome CreateGenomePreserveID(IGenome seedGenome, IdGenerator idGenerator)
        {
            NeatGenome newGenome = new NeatGenome((NeatGenome)seedGenome, idGenerator.NextGenomeId);

            // Reset the connection weights

            //in this particular instance, we would take a snapshot of the genome AFTER mutation for WIN purposes. But we don't track genomes yet
            foreach (ConnectionGene connectionGene in newGenome.ConnectionGeneList)
            {
                connectionGene.Weight += (0.1 - Utilities.NextDouble() * 0.2);
            }

            return(newGenome);
        }
示例#32
0
        /// <summary>
        /// Determine the given genome's species and return that species. If the genome does not
        /// match one of the existing species then we return null to indicate a new species.
        /// </summary>
        /// <param name="genome"></param>
        /// <returns></returns>
        private Species DetermineSpecies(EvolutionAlgorithm ea, IGenome genome)
        {
            //----- Performance optimization. Check against parent species IDs first.
            Species parentSpecies1 = null;
            Species parentSpecies2 = null;

            // Parent1. Not set in initial population.
            if (genome.ParentSpeciesId1 != -1)
            {
                parentSpecies1 = (Species)speciesTable[genome.ParentSpeciesId1];
                if (parentSpecies1 != null)
                {
                    if (IsGenomeInSpecies(genome, parentSpecies1, ea))
                    {
                        return(parentSpecies1);
                    }
                }
            }

            // Parent2. Not set if result of asexual reproduction.
            if (genome.ParentSpeciesId2 != -1)
            {
                parentSpecies2 = (Species)speciesTable[genome.ParentSpeciesId2];
                if (parentSpecies2 != null)
                {
                    if (IsGenomeInSpecies(genome, parentSpecies2, ea))
                    {
                        return(parentSpecies2);
                    }
                }
            }

            //----- Not in parent species. Systematically compare against all species.
            foreach (Species compareWithSpecies in speciesTable.Values)
            {
                // Don't compare against the parent species again.
                if (compareWithSpecies == parentSpecies1 || compareWithSpecies == parentSpecies2)
                {
                    continue;
                }

                if (IsGenomeInSpecies(genome, compareWithSpecies, ea))
                {                       // We have found matching species.
                    return(compareWithSpecies);
                }
            }

            //----- The genome is not a member of any existing species.
            return(null);
        }
        /// <summary>
        ///     Ends the generation.
        /// </summary>
        /// <param name="genomesNumber">Genomes number to keep on generation.</param>
        public void End(int genomesNumber)
        {
            Genomes = Genomes
                      .Where(ValidateChromosome)
                      .OrderByDescending(c => c.Fitness.Value)
                      .ToList();

            if (Genomes.Count > genomesNumber)
            {
                Genomes = Genomes.Take(genomesNumber).ToList();
            }

            BestGenome = Genomes.First();
        }
示例#34
0
        public string fetchNextBodyJSON()
        {
            //we have a genome and a network from the genome
            IGenome genome = fetchNextGenome();
            bool    isEmpty;
            var     body = genomeIntoBodyJSON(genome, out isEmpty);

            while (isEmpty)
            {
                body = genomeIntoBodyJSON(genome, out isEmpty);
            }

            return(body);
        }
示例#35
0
        public double Calc(IGenome genome)
        {
            var _endNode             = genome.Map.EndNode;
            var lastnode             = genome.ListNodes.Last();
            var startnode            = genome.ListNodes.First();
            var HeuristicMaxDistance = Heuristic.Calc(Abs(startnode.X - _endNode.X), Abs(startnode.Y - _endNode.Y));
            var HeuristicValue       = Heuristic.Calc(Abs(lastnode.X - _endNode.X), Abs(lastnode.Y - _endNode.Y));
            var penalty = (double)0;

            if (lastnode.Collision)
            {
                penalty = Penalty * (HeuristicValue / HeuristicMaxDistance);
            }
            return(penalty + HeuristicValue);
        }
示例#36
0
        //Todo REFINE... adding highest fitness might
        //not correspond with most novel?
        public void add_most_novel(Population p)
        {
            double  max_novelty = 0;
            IGenome best        = null;

            for (int i = 0; i < p.GenomeList.Count; i++)
            {
                if (p.GenomeList[i].Fitness > max_novelty)
                {
                    best        = p.GenomeList[i];
                    max_novelty = p.GenomeList[i].Fitness;
                }
            }
            archive.Add(best);
        }
示例#37
0
 public bool IsEqual(IGenome genome)
 {
     if (ListNodes.Count != genome.ListNodes.Count)
     {
         return(false);
     }
     for (int i = 0; i < ListNodes.Count; i++)
     {
         if (ListNodes[i] != genome.ListNodes[i])
         {
             return(false);
         }
     }
     return(true);
 }
示例#38
0
        private IGenome <int, int> TryMutate(IGenome <int, int> genome)
        {
            int[] positions = new int[genome.Genes.Count];

            for (int k = 0; k < positions.Length; k++)
            {
                positions[k] = genome.Genes[k];
            }

            SwapTwo(positions);

            List <int> genes = new List <int>(positions);

            return(new Genome(genes));
        }
 public GenomeSnippetSource(string chrom, IGenome genome, int genomeContextSize, int buffer = 300, ChrReference chrReference = null)
 {
     _genomeContextSize = genomeContextSize;
     _buffer            = buffer;
     if (chrReference != null)
     {
         _chrReference          = chrReference;
         _loadedOwnChrReference = false;
     }
     else
     {
         _chrReference          = genome.GetChrReference(chrom);
         _loadedOwnChrReference = true;
     }
 }
示例#40
0
        /// <inheritdoc/>
        public IMLMethod Decode(IGenome genome)
        {
            var neatGenome = (NEATGenome)genome;
            var pop        = (NEATPopulation)neatGenome.Population;
            IList <NEATNeuronGene> neuronsChromosome = neatGenome.NeuronsChromosome;
            IList <NEATLinkGene>   linksChromosome   = neatGenome.LinksChromosome;

            if (neuronsChromosome[0].NeuronType != NEATNeuronType.Bias)
            {
                throw new NeuralNetworkError(
                          "The first neuron must be the bias neuron, this genome is invalid.");
            }

            var links = new List <NEATLink>();
            var afs   = new IActivationFunction[neuronsChromosome.Count];

            for (int i = 0; i < afs.Length; i++)
            {
                afs[i] = neuronsChromosome[i].ActivationFunction;
            }

            IDictionary <long, int> lookup = new Dictionary <long, int>();

            for (int i = 0; i < neuronsChromosome.Count; i++)
            {
                NEATNeuronGene neuronGene = neuronsChromosome[i];
                lookup[neuronGene.Id] = i;
            }

            // loop over connections
            for (int i = 0; i < linksChromosome.Count; i++)
            {
                NEATLinkGene linkGene = linksChromosome[i];
                if (linkGene.Enabled)
                {
                    links.Add(new NEATLink(lookup[linkGene.FromNeuronId],
                                           lookup[linkGene.ToNeuronId], linkGene.Weight));
                }
            }

            links.Sort();

            NEATNetwork network = new NEATNetwork(neatGenome.InputCount,
                                                  neatGenome.OutputCount, links, afs);

            network.ActivationCycles = pop.ActivationCycles;
            return(network);
        }
示例#41
0
        /// <inheritdoc/>
        public IMLMethod Decode(IGenome genome)
        {
            var neatGenome = (NEATGenome)genome;
            var pop = (NEATPopulation)neatGenome.Population;
            IList<NEATNeuronGene> neuronsChromosome = neatGenome.NeuronsChromosome;
            IList<NEATLinkGene> linksChromosome = neatGenome.LinksChromosome;

            if (neuronsChromosome[0].NeuronType != NEATNeuronType.Bias)
            {
                throw new NeuralNetworkError(
                        "The first neuron must be the bias neuron, this genome is invalid.");
            }

            var links = new List<NEATLink>();
            var afs = new IActivationFunction[neuronsChromosome.Count];

            for (int i = 0; i < afs.Length; i++)
            {
                afs[i] = neuronsChromosome[i].ActivationFunction;
            }

            IDictionary<long, int> lookup = new Dictionary<long, int>();
            for (int i = 0; i < neuronsChromosome.Count; i++)
            {
                NEATNeuronGene neuronGene = neuronsChromosome[i];
                lookup[neuronGene.Id] = i;
            }

            // loop over connections
            for (int i = 0; i < linksChromosome.Count; i++)
            {
                NEATLinkGene linkGene = linksChromosome[i];
                if (linkGene.Enabled)
                {
                    links.Add(new NEATLink(lookup[linkGene.FromNeuronId],
                            lookup[linkGene.ToNeuronId], linkGene.Weight));
                }

            }

            links.Sort();

            NEATNetwork network = new NEATNetwork(neatGenome.InputCount,
                    neatGenome.OutputCount, links, afs);

            network.ActivationCycles = pop.ActivationCycles;
            return network;
        }
示例#42
0
        public IGenome <int, int> Mutate(IGenome <int, int> genome)
        {
            int value = this.evaluator.Evaluate(genome);

            IGenome <int, int> newgenome = this.TryMutate(genome);
            int ntries   = 0;
            int maxtries = genome.Genes.Count * genome.Genes.Count / 4;

            while (this.evaluator.Evaluate(newgenome) >= value && ntries < maxtries)
            {
                ntries++;
                newgenome = this.TryMutate(genome);
            }

            return(newgenome);
        }
        /// <inheritdoc />
        public void PerformOperation(EncogRandom rnd, IGenome[] parents,
                                     int parentIndex, IGenome[] offspring,
                                     int offspringIndex)
        {
            var program = (EncogProgram) parents[0];
            EncogProgramContext context = program.Context;
            EncogProgram result = context.CloneProgram(program);

            IList<EPLValueType> types = new List<EPLValueType>();
            types.Add(context.Result.VariableType);
            var globalIndex = new int[1];
            globalIndex[0] = rnd.Next(result.RootNode.Count);
            FindNode(rnd, result, result.RootNode, types, globalIndex);

            offspring[0] = result;
        }
        /// <summary>
        ///     Creates the initial generation.
        /// </summary>
        public virtual void CreateInitialGeneration(IGenome initialGenome)
        {
            var genomes = new List <IGenome>();

            if (initialGenome != null)
            {
                genomes.Add(initialGenome);
            }

            genomes.AddRange(GeneticAlgorithm.Instance()
                             .GetModel()
                             .GetGenerationEvolver()
                             .EvolveInitialGeneration(genomes));

            CreateNewGeneration(genomes);
        }
示例#45
0
        private float ComputeDist(IGenome genome)
        {
            var dist = 0f;

            var genes     = genome.Genes;
            var lastPoint = Locations[(genes.Last().Value as ClonableIndex).index];

            foreach (var gene in genes)
            {
                var pos = Locations[(gene.Value as ClonableIndex).index];
                dist += Vector2.Distance(
                    pos,
                    lastPoint);
                lastPoint = pos;
            }
            return(dist);
        }
示例#46
0
        public IGenome Breed(IGenome mate)
        {
            List <IGene> offspringGenes = new List <IGene>();

            // Find disjoint or excess genes
            IEnumerable <IGene> genes         = Genes.Concat(mate.Genes);
            IGenome             mostFitGenome = Fitness > mate.Fitness ? this : mate;

            foreach (IGene gene in genes)
            {
                if (offspringGenes.Any(g => g.Innovation == gene.Innovation))
                {
                    continue;
                }

                List <IGene> comparedGenes = genes.Where(g => g.Innovation == gene.Innovation).ToList();

                if (comparedGenes.Count > 1) // Matching gene
                {
                    IGene chosenGene = comparedGenes[new Random().Next(2)].Copy();

                    if (comparedGenes[0].IsExpressed == false || comparedGenes[1].IsExpressed == false)
                    {
                        chosenGene.IsExpressed = new Random().NextDouble() < GeneParameters.InheritedGeneChanceOfReExpression;
                    }

                    offspringGenes.Add(chosenGene);
                }
                else if (comparedGenes.Count == 1) // Disjoint or excess gene
                {
                    bool addGene = (Fitness == mate.Fitness && new Random().Next(2) == 0) ||
                                   (mostFitGenome.Genes.FirstOrDefault(mfg => mfg == comparedGenes[0]) != null);

                    if (addGene == true && !offspringGenes.Any(og => og.Innovation == comparedGenes[0].Innovation))
                    {
                        offspringGenes.Add(comparedGenes[0].Copy());
                    }
                }
            }

            return(new Genome()
            {
                Nodes = GenomeHelper.GetNodesFromGenes(offspringGenes).ToList(),
                Genes = offspringGenes
            });
        }
示例#47
0
        /// <inheritdoc />
        public void Rewrite(IGenome prg)
        {
            bool done = false;

            while (!done)
            {
                done = true;

                foreach (IRewriteRule rule in _rewriteRules)
                {
                    if (rule.Rewrite(prg))
                    {
                        done = false;
                    }
                }
            }
        }
示例#48
0
        public double CalculateScore(IGenome genome)
        {
            double result = 0.0;

            var path = (int[])genome.Organism;

            for (int i = 0; i < cities.Length - 1; i++)
            {
                City city1 = cities[path[i]];
                City city2 = cities[path[i + 1]];

                double dist = city1.Proximity(city2);
                result += dist;
            }

            return(result);
        }
        /// <inheritdoc />
        public double CalculateAdjustment(IGenome genome)
        {
            double score = genome.Score;
            double result = 0;

            if (genome.Size > ComplexityPenaltyThreshold)
            {
                int over = genome.Size - ComplexityPenaltyThreshold;
                int range = ComplexityPentaltyFullThreshold
                            - ComplexityPenaltyThreshold;
                double complexityPenalty = ((ComplexityFullPenalty - ComplexityPenalty)/range)
                                           *over;
                result = (score*complexityPenalty);
            }

            return result;
        }
示例#50
0
        /// <inheritdoc />
        public IGenome MutateGenome(IGenome genome)
        {
            if (null == genome)
            {
                throw new ArgumentNullException(nameof(genome));
            }

            var clone = genome.Clone();

            for (var count = 0; count < mutationsCount; count++)
            {
                var index = random.Next(clone.Length);
                clone.Replace(index, opCodeGenerator.NextOpCode());
            }

            return(clone);
        }
        /// <inheritdoc />
        public double CalculateAdjustment(IGenome genome)
        {
            double score  = genome.Score;
            double result = 0;

            if (genome.Size > ComplexityPenaltyThreshold)
            {
                int over  = genome.Size - ComplexityPenaltyThreshold;
                int range = ComplexityPentaltyFullThreshold
                            - ComplexityPenaltyThreshold;
                double complexityPenalty = ((ComplexityFullPenalty - ComplexityPenalty) / range)
                                           * over;
                result = (score * complexityPenalty);
            }

            return(result);
        }
        /// <summary>
        /// Perform one generation.
        /// </summary>
        public virtual void Iteration(GATracker gaTracker)
        {
            int countToMate          = (int)(Population.Genomes.Count * PercentToMate);
            int matingPopulationSize = (int)(Population.Genomes.Count * MatingPopulation);

            //The only individuals we want to preserve is the mating population.
            //i.e. everything but the mating population gets replaced.
            int newOffspringCount = Population.Genomes.Count - matingPopulationSize;
            int newOffspringIndex = Population.Genomes.Count - newOffspringCount;

            int offspringCount = countToMate * 2;

            //int offspringIndex = Population.Genomes.Count - offspringCount;

            //TaskGroup group = EngineConcurrency.Instance.CreateTaskGroup();

            // mate and form the next generation
            //20 < 80
            while (newOffspringIndex < newOffspringCount + matingPopulationSize)
            {
                for (int i = 0; i < countToMate; i++)
                {
                    IGenome mother    = Population.Genomes[i];
                    int     fatherInt = (int)(ThreadSafeRandom.NextDouble() * matingPopulationSize);
                    IGenome father    = Population.Genomes[fatherInt];
                    IGenome child1    = Population.Genomes[newOffspringIndex];
                    IGenome child2    = Population.Genomes[newOffspringIndex + 1];

                    GATracker.MatedElement matedElement = new GATracker.MatedElement(i, fatherInt, newOffspringIndex, newOffspringIndex + 1);
                    MateWorker             worker       = new MateWorker(mother, father, child1, child2, matedElement);

                    //EngineConcurrency.Instance.ProcessTask(worker, group);
                    worker.Run();

                    //Add the matedElement to the GATracker
                    gaTracker.AddMatedElement(matedElement);

                    newOffspringIndex += 2;
                }
            }

            //group.WaitForComplete();

            // sort the next generation
            Population.Sort();
        }
示例#53
0
        private void AddGenomeToSpeciesTable(EvolutionAlgorithm ea, IGenome genome)
        {
            Species species = DetermineSpecies(ea, genome);

            if (species == null)
            {
                species = new Species();

                // Completely new species. Generate a speciesID.
                species.SpeciesId = nextSpeciesId++;
                speciesTable.Add(species.SpeciesId, species);
            }

            //----- The genome is a member of an existing species.
            genome.SpeciesId = species.SpeciesId;
            species.Members.Add(genome);
        }
示例#54
0
        /// <inheritdoc />
        public void PurgeInvalidGenomes()
        {
            // remove any invalid genomes
            int speciesNum = 0;

            while (speciesNum < Species.Count)
            {
                ISpecies species = Species[speciesNum];

                int genomeNum = 0;
                while (genomeNum < species.Members.Count)
                {
                    IGenome genome = species.Members[genomeNum];
                    if (double.IsInfinity(genome.Score) ||
                        double.IsInfinity(genome.AdjustedScore) ||
                        double.IsNaN(genome.Score) ||
                        double.IsNaN(genome.AdjustedScore))
                    {
                        species.Members.Remove(genome);
                    }
                    else
                    {
                        genomeNum++;
                    }
                }

                // is the species now empty?
                if (species.Members.Count == 0)
                {
                    Species.Remove(species);
                }
                else
                {
                    // new leader needed?
                    if (!species.Members.Contains(species.Leader))
                    {
                        species.Leader    = species.Members[0];
                        species.BestScore = species.Leader.AdjustedScore;
                    }

                    // onto the next one!
                    speciesNum++;
                }
            }
        }
示例#55
0
        public override IGenome Calc(IGenome baby)
        {
            var rand = RandomFactory.Rand;

            if (rand.NextDouble() > MutationRate || baby.ListNodes.Count < 3)
            {
                return(baby);
            }
            var listcount   = baby.ListNodes.Count;
            var randomPoint = rand.Next(1, listcount);
            var tempNumber  = baby.ListNodes[randomPoint];

            baby.ListNodes.RemoveAt(randomPoint);
            var insertAt = rand.Next(1, listcount);

            baby.ListNodes.Insert(insertAt, tempNumber);
            return(baby);
        }
        public override IGenome Calc(IGenome baby)
        {
            var rand = GAResolver.Resolve <IRandom>();

            if (rand.NextDouble() > MutationRate)
            {
                return(baby);
            }

            var i = (int)Math.Floor(rand.NextDouble() * baby.Gens.Count());

            // choose the bit to swap
            var qtdBits = (int)Math.Floor(8 * rand.NextDouble());

            baby.Gens[i] ^= 1 << qtdBits;

            return(baby);
        }
示例#57
0
        public IGenome <int, int> Mutate(IGenome <int, int> genome, int nmutations)
        {
            int[] positions = new int[genome.Genes.Count];

            for (int k = 0; k < positions.Length; k++)
            {
                positions[k] = genome.Genes[k];
            }

            for (int l = 0; l < nmutations; l++)
            {
                SwapTwo(positions);
            }

            List <int> genes = new List <int>(positions);

            return(new Genome(genes));
        }
        public List <IGenome> Generate(int size, IFitnessFunction fitnessFunction)
        {
            List <IGenome>   population = new List <IGenome>();
            FlipGeneMutation flip       = new FlipGeneMutation();

            for (int i = 0; i < size; i += 2)
            {
                population.Add(new BinaryGenome(DefaultParameter.genomeSize));
                population[i].SetFitnessFunction(fitnessFunction);

                IGenome genome = (BinaryGenome)population[i].Clone();
                flip.Mutate(genome);
                population.Add(genome);
                population[i + 1].SetFitnessFunction(fitnessFunction);
            }

            return(population);
        }
        public override IGenome Calc(IGenome baby)
        {
            var rand = GAResolver.Resolve <IRandom>();

            if (rand.NextDouble() > MutationRate)
            {
                return(baby);
            }

            int       listcount   = baby.Gens.Count;
            const int minSpanSize = 3;

            if (listcount <= minSpanSize)
            {
                return(baby);
            }

            int beg, end;

            beg = end = 0;

            var spanSize = rand.Next(minSpanSize, listcount);

            beg = rand.Next(1, listcount - spanSize);
            end = beg + spanSize;

            var lstTemp = new List <int>();

            for (int i = beg; i < end; i++)
            {
                lstTemp.Add(baby.Gens[beg]);
                baby.Gens.RemoveAt(beg);
            }
            lstTemp.Reverse();
            var count = 0;

            for (int i = beg; i < end; i++)
            {
                baby.Gens.Insert(i, lstTemp[count]);
                count++;
            }
            return(baby);
        }
示例#60
0
        /// <summary>
        /// Mate two genomes. Will loop over all chromosomes.
        /// </summary>
        ///
        /// <param name="father">The father.</param>
        /// <param name="child1">The first child.</param>
        /// <param name="child2">The second child.</param>
        public void Mate(IGenome father, IGenome child1,
                         IGenome child2)
        {
            int motherChromosomes = Chromosomes.Count;
            int fatherChromosomes = father.Chromosomes.Count;

            if (motherChromosomes != fatherChromosomes)
            {
                throw new GeneticError(
                          "Mother and father must have same chromosome count, Mother:"
                          + motherChromosomes + ",Father:"
                          + fatherChromosomes);
            }

            for (int i = 0; i < fatherChromosomes; i++)
            {
                Chromosome motherChromosome     = _chromosomes[i];
                Chromosome fatherChromosome     = father.Chromosomes[i];
                Chromosome offspring1Chromosome = child1.Chromosomes[i];
                Chromosome offspring2Chromosome = child2.Chromosomes[i];

                _ga.Crossover.Mate(motherChromosome,
                                   fatherChromosome, offspring1Chromosome,
                                   offspring2Chromosome);

                if (ThreadSafeRandom.NextDouble() < _ga.MutationPercent)
                {
                    _ga.Mutate.PerformMutation(
                        offspring1Chromosome);
                }

                if (ThreadSafeRandom.NextDouble() < _ga.MutationPercent)
                {
                    _ga.Mutate.PerformMutation(
                        offspring2Chromosome);
                }
            }

            child1.Decode();
            child2.Decode();
            _ga.PerformCalculateScore(child1);
            _ga.PerformCalculateScore(child2);
        }