Пример #1
0
        /// <inheritdoc/>
        public int PerformSelection(IGenerateRandom rnd, ISpecies species)
        {
            int     bestIndex = rnd.NextInt(species.Members.Count);
            IGenome best      = species.Members[bestIndex];

            BasicEA.CalculateScoreAdjustment(best, Trainer.ScoreAdjusters);

            for (int i = 0; i < Rounds; i++)
            {
                int     competitorIndex = rnd.NextInt(species.Members.Count);
                IGenome competitor      = species.Members[competitorIndex];

                // only evaluate valid genomes
                if (!double.IsInfinity(competitor.AdjustedScore) &&
                    !double.IsNaN(competitor.AdjustedScore))
                {
                    BasicEA.CalculateScoreAdjustment(competitor,
                                                     Trainer.ScoreAdjusters);
                    if (Trainer.SelectionComparer.IsBetterThan(
                            competitor, best))
                    {
                        best      = competitor;
                        bestIndex = competitorIndex;
                    }
                }
            }
            return(bestIndex);
        }
Пример #2
0
        /// <inheritdoc/>
        public int PerformAntiSelection(IGenerateRandom rnd, ISpecies species)
        {
            int worstIndex = rnd.NextInt(species.Members.Count);
            IGenome worst = species.Members[worstIndex];
            BasicEA.CalculateScoreAdjustment(worst,
                    Trainer.ScoreAdjusters);

            for (int i = 0; i < this.Rounds; i++)
            {
                int competitorIndex = rnd.NextInt(species.Members.Count);
                IGenome competitor = species.Members[competitorIndex];

                // force an invalid genome to lose
                if (double.IsInfinity(competitor.AdjustedScore)
                        || double.IsNaN(competitor.AdjustedScore))
                {
                    return competitorIndex;
                }

                BasicEA.CalculateScoreAdjustment(competitor,
                        Trainer.ScoreAdjusters);
                if (!Trainer.SelectionComparer.IsBetterThan(competitor,
                        worst))
                {
                    worst = competitor;
                    worstIndex = competitorIndex;
                }
            }
            return worstIndex;
        }
Пример #3
0
        /// <inheritdoc/>
        public int PerformAntiSelection(IGenerateRandom rnd, ISpecies species)
        {
            int     worstIndex = rnd.NextInt(species.Members.Count);
            IGenome worst      = species.Members[worstIndex];

            BasicEA.CalculateScoreAdjustment(worst,
                                             Trainer.ScoreAdjusters);

            for (int i = 0; i < this.Rounds; i++)
            {
                int     competitorIndex = rnd.NextInt(species.Members.Count);
                IGenome competitor      = species.Members[competitorIndex];

                // force an invalid genome to lose
                if (double.IsInfinity(competitor.AdjustedScore) ||
                    double.IsNaN(competitor.AdjustedScore))
                {
                    return(competitorIndex);
                }

                BasicEA.CalculateScoreAdjustment(competitor,
                                                 Trainer.ScoreAdjusters);
                if (!Trainer.SelectionComparer.IsBetterThan(competitor,
                                                            worst))
                {
                    worst      = competitor;
                    worstIndex = competitorIndex;
                }
            }
            return(worstIndex);
        }
Пример #4
0
 /// <summary>
 ///     Perform a Fisher-Yates shuffle.
 ///     http://en.wikipedia.org/wiki/Fisher%E2%80%93Yates_shuffle
 /// </summary>
 /// <param name="dataDivisionList">The division list.</param>
 /// <param name="totalCount">Total count across divisions.</param>
 private void PerformShuffle(IList <DataDivision> dataDivisionList,
                             int totalCount)
 {
     for (int i = totalCount - 1; i > 0; i--)
     {
         int n = _rnd.NextInt(i + 1);
         VirtualSwap(dataDivisionList, i, n);
     }
 }
Пример #5
0
        /// <summary>
        ///     Place the cities in random locations.
        /// </summary>
        /// <param name="rnd">Random number.</param>
        private void InitCities(IGenerateRandom rnd)
        {
            _cities = new City[Cities];
            for (int i = 0; i < _cities.Length; i++)
            {
                int xPos = rnd.NextInt(0, MapSize);
                int yPos = rnd.NextInt(0, MapSize);

                _cities[i] = new City(xPos, yPos);
            }
        }
Пример #6
0
        /// <summary>
        ///     Run the example.
        /// </summary>
        public void Run()
        {
            _cities      = new double[CityCount][];
            _currentPath = new int[CityCount];
            _backupPath  = new int[CityCount];
            _bestPath    = new int[CityCount];

            // place the cities in a circle
            double ratio = (2 * Math.PI) / _cities.Length;

            for (int cityNumber = 0; cityNumber < _cities.Length; cityNumber++)
            {
                _cities[cityNumber]    = new double[2];
                _cities[cityNumber][0] = (int)(Math.Cos(ratio * cityNumber) * (MapSize / 2) + (MapSize / 2));
                _cities[cityNumber][1] = (int)(Math.Sin(ratio * cityNumber) * (MapSize / 2) + (MapSize / 2));
            }

            // pick a random city order
            _currentPath = new int[CityCount];
            for (int i = 0; i < _currentPath.Length; i++)
            {
                int  city;
                bool foundCity;

                do
                {
                    city      = _rnd.NextInt(CityCount);
                    foundCity = false;
                    for (int j = 0; j < i; j++)
                    {
                        if (city == _currentPath[j])
                        {
                            foundCity = true;
                        }
                    }
                } while (foundCity);

                _currentPath[i] = city;
            }

            // now begin main loop, and find a minimum
            while (!Done)
            {
                Iteration();
                Console.WriteLine("Iteration #" + K + ", Best Score=" + BestScore + "," + Status);
            }

            foreach (var item in _bestPath)
            {
                Console.Write(item + " ");
            }
            Console.WriteLine();
        }
Пример #7
0
        /// <summary>
        ///     Generate a random path through cities.
        /// </summary>
        /// <param name="rnd">Random number generator.</param>
        /// <returns>A genome.</returns>
        private IntegerArrayGenome RandomGenome(IGenerateRandom rnd)
        {
            var result = new IntegerArrayGenome(_cities.Length);

            int[] organism = result.Data;
            var   taken    = new bool[_cities.Length];

            for (int i = 0; i < organism.Length - 1; i++)
            {
                int icandidate;
                do
                {
                    icandidate = rnd.NextInt(0, organism.Length);
                } while (taken[icandidate]);
                organism[i]       = icandidate;
                taken[icandidate] = true;
                if (i == organism.Length - 2)
                {
                    icandidate = 0;
                    while (taken[icandidate])
                    {
                        icandidate++;
                    }
                    organism[i + 1] = icandidate;
                }
            }
            return(result);
        }
Пример #8
0
        /// <inheritdoc/>
        public int PerformSelection(IGenerateRandom rnd, ISpecies species)
        {
            int top = Math.Max((int)(species.Members.Count * _percent),
                               1);

            return(rnd.NextInt(top));
        }
Пример #9
0
        /// <summary>
        /// Choose the next node for an ant to visit.  This is based on probability.
        /// </summary>
        /// <param name="currentIndex">The step we are at in the path.</param>
        /// <param name="ant">The ant being evaluated.</param>
        /// <returns>The node we will move into.</returns>
        private int PickNextNode(int currentIndex, DiscreteAnt ant)
        {
            if (currentIndex == 0 || Random.NextDouble() < PR)
            {
                int index;
                do
                {
                    index = Random.NextInt(0, _graph.Count);
                } while (ant.WasVisited(index));
                return(index);
            }

            double[] prob = CalculateProbability(currentIndex, ant);

            double r   = Random.NextDouble();
            double sum = 0;

            for (int i = 0; i < _graph.Count; i++)
            {
                sum += prob[i];
                if (sum >= r)
                {
                    return(i);
                }
            }
            // should not happen!
            return(-1);
        }
Пример #10
0
        /// <summary>
        /// Generate a random sample.
        /// </summary>
        private void GeneraterandomSample()
        {
            for (int i = 0; i < _batchSize; i++)
            {
                bool uniqueFound = true;
                int  t;

                // Generate a unique index
                do
                {
                    t = _random.NextInt(0, _dataset.Count);

                    for (int j = 0; j < i; j++)
                    {
                        if (_randomSample[j] == t)
                        {
                            uniqueFound = false;
                            break;
                        }
                    }
                } while (!uniqueFound);

                // Record it
                _randomSample[i] = t;
            }
        }
Пример #11
0
        /// <summary>
        /// Init the observations to random clusters.  Use the "Init Random" algorithm. The Random Partition method first
        /// randomly assigns a cluster to each observation and then proceeds to the update step, thus computing the initial mean to be the centroid of the cluster's randomly assigned points.
        ///
        /// </summary>
        /// <param name="theObservations">The observations to cluster.</param>
        public void InitRandom(IList <BasicData> theObservations)
        {
            int dimensions = FindDimensions(theObservations);

            // create the clusters
            for (int i = 0; i < _k; i++)
            {
                _clusters.Add(new Cluster(dimensions));
            }

            // assign each observation to a random cluster
            foreach (BasicData observation in theObservations)
            {
                int     clusterIndex = _randomGeneration.NextInt(_k);
                Cluster cluster      = _clusters[clusterIndex];
                cluster.Observations.Add(observation);
            }

            // handle any empty clusters
            foreach (Cluster cluster in _clusters)
            {
                if (cluster.Observations.Count == 0)
                {
                    bool done = false;
                    while (!done)
                    {
                        int     sourceIndex = _randomGeneration.NextInt(_k);
                        Cluster source      = _clusters[sourceIndex];
                        if (source != cluster && source.Observations.Count > 1)
                        {
                            int       sourceObservationIndex = _randomGeneration.NextInt(source.Observations.Count);
                            BasicData sourceObservation      = source.Observations[sourceObservationIndex];
                            source.Observations.RemoveAt(sourceObservationIndex);
                            cluster.Observations.Add(sourceObservation);
                            done = true;
                        }
                    }
                }
            }

            // calculate initial centers
            UpdateStep();
        }
Пример #12
0
        public override void MoveToNeighbor()
        {
            // pick the first point to swap
            int pt1 = _rnd.NextInt(_currentHolder.Length);

            // pick the second point to swap, can't be the same as the first
            int pt2;

            do
            {
                pt2 = _rnd.NextInt(_currentHolder.Length);
            } while (pt1 == pt2);

            // swap them
            double temp = _currentHolder[pt1];

            _currentHolder[pt1] = _currentHolder[pt2];
            _currentHolder[pt2] = temp;
        }
Пример #13
0
        /// <summary>
        ///     Run the example.
        /// </summary>
        public void Run()
        {
            // Generate a random set of items.
            for (int n = 0; n < NumItemsToChoose; n++)
            {
                _profit[n] = _rnd.NextInt(ItemMaxValue);
                _weight[n] = _rnd.NextInt(ItemMaxWeight);
            }

            // now begin main loop, and find a minimum
            while (!Done)
            {
                Iteration();
                Console.WriteLine("Iteration #" + K + ", Best Score=" + BestScore + "," + Status);
            }


            // print results
            Console.WriteLine("item" + "\t" + "profit" + "\t" + "weight" + "\t" + "take");
            for (int n = 0; n < NumItemsToChoose; n++)
            {
                Console.WriteLine((n + 1) + "\t" + _profit[n] + "\t" + _weight[n] + "\t" + _bestTaken[n]);
            }
        }
Пример #14
0
        private void updateTimer_Tick(object sender, EventArgs e)
        {
            iteration++;
            if (iteration > 100)
            {
                updateTimer.Enabled = false;
            }


            var idx = (int)rnd.NextInt(samples.Length);
            var c   = samples[idx];

            train.TrainPattern(c);
            train.AutoDecay();
            DrawMap();
            //System.out.println("Iteration " + i + ","+ this.train.toString());
        }
Пример #15
0
        /// <inheritdoc />
        public void PerformOperation(IGenerateRandom rnd, IGenome[] parents, int parentIndex,
                                     IGenome[] offspring, int offspringIndex)
        {
            var mother     = (IntegerArrayGenome)parents[parentIndex];
            var father     = (IntegerArrayGenome)parents[parentIndex + 1];
            var offspring1 = (IntegerArrayGenome)_owner.Population.GenomeFactory.Factor();
            var offspring2 = (IntegerArrayGenome)_owner.Population.GenomeFactory.Factor();

            offspring[offspringIndex]     = offspring1;
            offspring[offspringIndex + 1] = offspring2;

            int geneLength = mother.Count;

            // the chromosome must be cut at two positions, determine them
            int cutpoint1 = rnd.NextInt(geneLength - _cutLength);
            int cutpoint2 = cutpoint1 + _cutLength;

            // keep track of which genes have been taken in each of the two
            // offspring, defaults to false.
            var taken1 = new HashSet <int>();
            var taken2 = new HashSet <int>();

            // handle cut section
            for (int i = 0; i < geneLength; i++)
            {
                if (!((i < cutpoint1) || (i > cutpoint2)))
                {
                    offspring1.Copy(father, i, i);
                    offspring2.Copy(mother, i, i);
                    taken1.Add(father.Data[i]);
                    taken2.Add(mother.Data[i]);
                }
            }

            // handle outer sections
            for (int i = 0; i < geneLength; i++)
            {
                if ((i < cutpoint1) || (i > cutpoint2))
                {
                    offspring1.Data[i] = GetNotTaken(mother, taken1);
                    offspring2.Data[i] = GetNotTaken(father, taken2);
                }
            }
        }
Пример #16
0
        /// <inheritdoc />
        public void PerformOperation(IGenerateRandom rnd, IGenome[] parents, int parentIndex,
            IGenome[] offspring, int offspringIndex)
        {
            var mother = (IntegerArrayGenome) parents[parentIndex];
            var father = (IntegerArrayGenome) parents[parentIndex + 1];
            var offspring1 = (IntegerArrayGenome) _owner.Population.GenomeFactory.Factor();
            var offspring2 = (IntegerArrayGenome) _owner.Population.GenomeFactory.Factor();

            offspring[offspringIndex] = offspring1;
            offspring[offspringIndex + 1] = offspring2;

            int geneLength = mother.Count;

            // the chromosome must be cut at two positions, determine them
            int cutpoint1 = rnd.NextInt(geneLength - _cutLength);
            int cutpoint2 = cutpoint1 + _cutLength;

            // keep track of which genes have been taken in each of the two
            // offspring, defaults to false.
            var taken1 = new HashSet<int>();
            var taken2 = new HashSet<int>();

            // handle cut section
            for (int i = 0; i < geneLength; i++)
            {
                if (!((i < cutpoint1) || (i > cutpoint2)))
                {
                    offspring1.Copy(father, i, i);
                    offspring2.Copy(mother, i, i);
                    taken1.Add(father.Data[i]);
                    taken2.Add(mother.Data[i]);
                }
            }

            // handle outer sections
            for (int i = 0; i < geneLength; i++)
            {
                if ((i < cutpoint1) || (i > cutpoint2))
                {
                    offspring1.Data[i] = GetNotTaken(mother, taken1);
                    offspring2.Data[i] = GetNotTaken(father, taken2);
                }
            }
        }
Пример #17
0
        /// <summary>
        /// 
        /// </summary>
        /// <param name="rnd"></param>
        /// <param name="parent"></param>
        /// <param name="current"></param>
        /// <param name="index"></param>
        /// <param name="reservoir"></param>
        private void InternalSampleRandomNode(IGenerateRandom rnd, TreeGenomeNode parent, TreeGenomeNode current,
            int[] index, RandomNodeResult reservoir)
        {
            int currentIndex = index[0];
            index[0]++;

            // determine if we replace the reservoir
            int j = rnd.NextInt(0, currentIndex + 1);
            if (j == 0)
            {
                reservoir.Parent = parent;
                reservoir.Child = current;
            }

            // traverse on to the children
            foreach (TreeGenomeNode child in current.Children)
            {
                InternalSampleRandomNode(rnd, current, child, index, reservoir);
            }
        }
Пример #18
0
        /// <summary>
        ///
        /// </summary>
        /// <param name="rnd"></param>
        /// <param name="parent"></param>
        /// <param name="current"></param>
        /// <param name="index"></param>
        /// <param name="reservoir"></param>
        private void InternalSampleRandomNode(IGenerateRandom rnd, TreeGenomeNode parent, TreeGenomeNode current,
                                              int[] index, RandomNodeResult reservoir)
        {
            int currentIndex = index[0];

            index[0]++;

            // determine if we replace the reservoir
            int j = rnd.NextInt(0, currentIndex + 1);

            if (j == 0)
            {
                reservoir.Parent = parent;
                reservoir.Child  = current;
            }

            // traverse on to the children
            foreach (TreeGenomeNode child in current.Children)
            {
                InternalSampleRandomNode(rnd, current, child, index, reservoir);
            }
        }
Пример #19
0
        /// <summary>
        ///     Split a list into two sublists by randomly shuffling the values (without replacement).
        /// </summary>
        /// <typeparam name="T">The type that the lists contain.</typeparam>
        /// <param name="list">The list to split/shuffle.</param>
        /// <param name="ratio">The size of the first retuerned list.</param>
        /// <param name="rnd">A random number generator to split the lists.</param>
        /// <returns>A list containing the two split lists.</returns>
        public static IList <IList <T> > Split <T>(IList <T> list, double ratio, IGenerateRandom rnd)
        {
            IList <IList <T> > result = new List <IList <T> >();
            var aCount = (int)(list.Count * ratio);

            var a = new List <T>();
            var b = new List <T>();

            result.Add(a);
            result.Add(b);

            b.AddRange(list);

            for (var i = 0; i < aCount; i++)
            {
                var idx = rnd.NextInt(0, b.Count);
                a.Add(b[idx]);
                b.RemoveAt(idx);
            }

            return(result);
        }
Пример #20
0
        /// <inheritdoc />
        public void PerformOperation(IGenerateRandom rnd, IGenome[] parents, int parentIndex, IGenome[] offspring,
                                     int offspringIndex)
        {
            var              parent1   = (TreeGenome)parents[parentIndex];
            EvaluateTree     eval      = parent1.Evaluator;
            var              off1      = (TreeGenome)_owner.Population.GenomeFactory.Factor(parent1);
            RandomNodeResult off1Point = eval.SampleRandomNode(rnd, off1.Root);

            int            len            = rnd.NextInt(1, _maxGraftLength + 1);
            TreeGenomeNode randomSequence = eval.Grow(rnd, len);

            if (off1Point.Parent == null)
            {
                off1.Root = randomSequence;
            }
            else
            {
                int idx = off1Point.Parent.Children.IndexOf(off1Point.Child);
                off1Point.Parent.Children[idx] = randomSequence;
            }

            offspring[0] = off1;
        }
Пример #21
0
        /// <inheritdoc />
        public void PerformOperation(IGenerateRandom rnd, IGenome[] parents, int parentIndex,
            IGenome[] offspring, int offspringIndex)
        {
            var mother = (IArrayGenome) parents[parentIndex];
            var father = (IArrayGenome) parents[parentIndex + 1];
            var offspring1 = (IArrayGenome) _owner.Population.GenomeFactory.Factor();
            var offspring2 = (IArrayGenome) _owner.Population.GenomeFactory.Factor();

            offspring[offspringIndex] = offspring1;
            offspring[offspringIndex + 1] = offspring2;

            int geneLength = mother.Count;

            // the chromosome must be cut at two positions, determine them
            int cutpoint1 = rnd.NextInt(geneLength - _cutLength);
            int cutpoint2 = cutpoint1 + _cutLength;

            // handle cut section
            for (int i = 0; i < geneLength; i++)
            {
                if (!((i < cutpoint1) || (i > cutpoint2)))
                {
                    offspring1.Copy(father, i, i);
                    offspring2.Copy(mother, i, i);
                }
            }

            // handle outer sections
            for (int i = 0; i < geneLength; i++)
            {
                if ((i < cutpoint1) || (i > cutpoint2))
                {
                    offspring1.Copy(mother, i, i);
                    offspring2.Copy(father, i, i);
                }
            }
        }
Пример #22
0
        /// <summary>
        ///     The constructor.
        /// </summary>
        /// <param name="k">The number of folds.</param>
        /// <param name="training">The training set.</param>
        /// <param name="rnd">A random number generator.</param>
        public CrossValidate(int k, IEnumerable <BasicData> training, IGenerateRandom rnd)
        {
            IList <BasicData> temp = new List <BasicData>();

            temp = temp.Union(training).ToList();

            // Setup k validation sets.
            for (int i = 0; i < k; i++)
            {
                _folds.Add(new CrossValidateFold());
            }

            // Divide over the k sets.
            int leaveOutSet = 0;

            while (temp.Count > 0)
            {
                int       idx  = rnd.NextInt(temp.Count);
                BasicData item = temp[idx];
                temp.RemoveAt(idx);

                _folds[leaveOutSet].ValidationSet.Add(item);
                for (int includeSet = 0; includeSet < _folds.Count; includeSet++)
                {
                    if (includeSet != leaveOutSet)
                    {
                        _folds[includeSet].TrainingSet.Add(item);
                    }
                }

                leaveOutSet++;
                if (leaveOutSet >= k)
                {
                    leaveOutSet = 0;
                }
            }
        }
Пример #23
0
        /// <inheritdoc />
        public void PerformOperation(IGenerateRandom rnd, IGenome[] parents, int parentIndex,
                                     IGenome[] offspring, int offspringIndex)
        {
            var mother     = (IArrayGenome)parents[parentIndex];
            var father     = (IArrayGenome)parents[parentIndex + 1];
            var offspring1 = (IArrayGenome)_owner.Population.GenomeFactory.Factor();
            var offspring2 = (IArrayGenome)_owner.Population.GenomeFactory.Factor();

            offspring[offspringIndex]     = offspring1;
            offspring[offspringIndex + 1] = offspring2;

            int geneLength = mother.Count;

            // the chromosome must be cut at two positions, determine them
            int cutpoint1 = rnd.NextInt(geneLength - _cutLength);
            int cutpoint2 = cutpoint1 + _cutLength;

            // handle cut section
            for (int i = 0; i < geneLength; i++)
            {
                if (!((i < cutpoint1) || (i > cutpoint2)))
                {
                    offspring1.Copy(father, i, i);
                    offspring2.Copy(mother, i, i);
                }
            }

            // handle outer sections
            for (int i = 0; i < geneLength; i++)
            {
                if ((i < cutpoint1) || (i > cutpoint2))
                {
                    offspring1.Copy(mother, i, i);
                    offspring2.Copy(father, i, i);
                }
            }
        }
Пример #24
0
        /// <summary>
        ///     The constructor.
        /// </summary>
        /// <param name="k">The number of folds.</param>
        /// <param name="training">The training set.</param>
        /// <param name="rnd">A random number generator.</param>
        public CrossValidate(int k, IEnumerable<BasicData> training, IGenerateRandom rnd)
        {
            IList<BasicData> temp = new List<BasicData>();
            temp = temp.Union(training).ToList();

            // Setup k validation sets.
            for (int i = 0; i < k; i++)
            {
                _folds.Add(new CrossValidateFold());
            }

            // Divide over the k sets.
            int leaveOutSet = 0;

            while (temp.Count > 0)
            {
                int idx = rnd.NextInt(temp.Count);
                BasicData item = temp[idx];
                temp.RemoveAt(idx);

                _folds[leaveOutSet].ValidationSet.Add(item);
                for (int includeSet = 0; includeSet < _folds.Count; includeSet++)
                {
                    if (includeSet != leaveOutSet)
                    {
                        _folds[includeSet].TrainingSet.Add(item);
                    }
                }

                leaveOutSet++;
                if (leaveOutSet >= k)
                {
                    leaveOutSet = 0;
                }
            }
        }
Пример #25
0
        /// <inheritdoc />
        public void PerformOperation(IGenerateRandom rnd, IGenome[] parents, int parentIndex, IGenome[] offspring,
            int offspringIndex)
        {
            var parent1 = (TreeGenome) parents[parentIndex];
            EvaluateTree eval = parent1.Evaluator;
            var off1 = (TreeGenome) _owner.Population.GenomeFactory.Factor(parent1);
            RandomNodeResult off1Point = eval.SampleRandomNode(rnd, off1.Root);

            int len = rnd.NextInt(1, _maxGraftLength + 1);
            TreeGenomeNode randomSequence = eval.Grow(rnd, len);

            if (off1Point.Parent == null)
            {
                off1.Root = randomSequence;
            }
            else
            {
                int idx = off1Point.Parent.Children.IndexOf(off1Point.Child);
                off1Point.Parent.Children[idx] = randomSequence;
            }

            offspring[0] = off1;
        }
Пример #26
0
 /// <inheritdoc/>
 public int PerformSelection(IGenerateRandom rnd, ISpecies species)
 {
     int top = Math.Max((int)(species.Members.Count * _percent),
             1);
     return rnd.NextInt(top);
 }
Пример #27
0
 /// <summary>
 /// Choose a random opcode, choose between only nodes. 
 /// </summary>
 /// <param name="rnd">A random number generator.</param>
 /// <returns>A random opcode.</returns>
 public int ChooseRandomNodeOpcode(IGenerateRandom rnd)
 {
     return rnd.NextInt(VarConstOpcode);
 }
Пример #28
0
 /// <summary>
 /// Choose a random opcode, choose between only leafs.
 /// </summary>
 /// <param name="rnd">A random number generator.</param>
 /// <returns>A random opcode.</returns>
 public int ChooseRandomLeafOpcode(IGenerateRandom rnd)
 {
     return VarConstOpcode + rnd.NextInt(NumVar + NumConst);
 }
Пример #29
0
 /// <summary>
 /// Choose a random opcode, choose between only leafs.
 /// </summary>
 /// <param name="rnd">A random number generator.</param>
 /// <returns>A random opcode.</returns>
 public int ChooseRandomLeafOpcode(IGenerateRandom rnd)
 {
     return(VarConstOpcode + rnd.NextInt(NumVar + NumConst));
 }
Пример #30
0
 /// <summary>
 /// Choose a random opcode, choose between only nodes.
 /// </summary>
 /// <param name="rnd">A random number generator.</param>
 /// <returns>A random opcode.</returns>
 public int ChooseRandomNodeOpcode(IGenerateRandom rnd)
 {
     return(rnd.NextInt(VarConstOpcode));
 }
Пример #31
0
 /// <summary>
 /// Choose a random opcode, choose between both leafs and nodes.
 /// </summary>
 /// <param name="rnd">A random number generator.</param>
 /// <returns>A random opcode.</returns>
 public int ChooseRandomOpcode(IGenerateRandom rnd)
 {
     return(rnd.NextInt(0, OpcodeCount));
 }
Пример #32
0
        /// <summary>
        ///     Generate a random path through cities.
        /// </summary>
        /// <param name="rnd">Random number generator.</param>
        /// <returns>A genome.</returns>
        private IntegerArrayGenome RandomGenome(IGenerateRandom rnd)
        {
            var result = new IntegerArrayGenome(_cities.Length);
            int[] organism = result.Data;
            var taken = new bool[_cities.Length];

            for (int i = 0; i < organism.Length - 1; i++)
            {
                int icandidate;
                do
                {
                    icandidate = rnd.NextInt(0, organism.Length);
                } while (taken[icandidate]);
                organism[i] = icandidate;
                taken[icandidate] = true;
                if (i == organism.Length - 2)
                {
                    icandidate = 0;
                    while (taken[icandidate])
                    {
                        icandidate++;
                    }
                    organism[i + 1] = icandidate;
                }
            }
            return result;
        }
Пример #33
0
        /// <summary>
        ///     Place the cities in random locations.
        /// </summary>
        /// <param name="rnd">Random number.</param>
        private void InitCities(IGenerateRandom rnd)
        {
            _cities = new City[Cities];
            for (int i = 0; i < _cities.Length; i++)
            {
                int xPos = rnd.NextInt(0, MapSize);
                int yPos = rnd.NextInt(0, MapSize);

                _cities[i] = new City(xPos, yPos);
            }
        }
Пример #34
0
 /// <inheritdoc />
 public object Sample(IGenerateRandom rnd)
 {
     return(_categories[rnd.NextInt(_categories.Count)]);
 }
Пример #35
0
        /// <inheritdoc/>
        public int PerformSelection(IGenerateRandom rnd, ISpecies species)
        {
            int bestIndex = rnd.NextInt(species.Members.Count);
            IGenome best = species.Members[bestIndex];
            BasicEA.CalculateScoreAdjustment(best, Trainer.ScoreAdjusters);

            for (int i = 0; i < Rounds; i++)
            {
                int competitorIndex = rnd.NextInt(species.Members.Count);
                IGenome competitor = species.Members[competitorIndex];

                // only evaluate valid genomes
                if (!double.IsInfinity(competitor.AdjustedScore)
                        && !double.IsNaN(competitor.AdjustedScore))
                {
                    BasicEA.CalculateScoreAdjustment(competitor,
                            Trainer.ScoreAdjusters);
                    if (Trainer.SelectionComparer.IsBetterThan(
                            competitor, best))
                    {
                        best = competitor;
                        bestIndex = competitorIndex;
                    }
                }
            }
            return bestIndex;
        }
Пример #36
0
 /// <inheritdoc />
 public object Sample(IGenerateRandom rnd)
 {
     return _categories[rnd.NextInt(_categories.Count)];
 }
Пример #37
0
 /// <summary>
 /// Choose a random opcode, choose between both leafs and nodes. 
 /// </summary>
 /// <param name="rnd">A random number generator.</param>
 /// <returns>A random opcode.</returns>
 public int ChooseRandomOpcode(IGenerateRandom rnd)
 {
     return rnd.NextInt(0, OpcodeCount);
 }