public static (int, int) GetTwoRandomNumbers(int max)
        {
            var num1 = ProbabilityUtils.GetRandomInt(0, max);
            var num2 = ProbabilityUtils.GetRandomInt(0, max);

            return(Math.Min(num1, num2), Math.Max(num1, num2));
        }
Example #2
0
        public IChromosome Crossover(IChromosome chromosome1, IChromosome chromosome2)
        {
            var vector1 = ((VectorChromosome <T>)chromosome1).GetVector();
            var vector2 = ((VectorChromosome <T>)chromosome2).GetVector();
            var length  = vector1.Length;
            var indexes = ProbabilityUtils.SelectKRandomNumbersNonRepeating(length, ProbabilityUtils.GetRandomInt(0, length));

            var elementsFromParent2 = new HashSet <T>();
            var elementsFromParent2OrderedByIndex = new List <T>();

            foreach (var index in indexes)
            {
                elementsFromParent2.Add(vector2[index]);
                elementsFromParent2OrderedByIndex.Add(vector2[index]);
            }

            var newVector = new T[length];

            for (int index = 0, addedElementsFromParent2 = 0; index < length; index++)
            {
                var elementInParent1 = vector1[index];
                if (!elementsFromParent2.Contains(elementInParent1))
                {
                    newVector[index] = elementInParent1;
                }
                else
                {
                    newVector[index] = elementsFromParent2OrderedByIndex[addedElementsFromParent2];
                    addedElementsFromParent2++;
                }
            }

            return(new VectorChromosome <T>(newVector, mutationManager, evaluator));
        }
Example #3
0
        public IChromosome GenerateChromosome(IMatrix matrix, int maxDiffBetweenNode)
        {
            var tryCount     = 0;
            var distribution = new Dictionary <int, ChromosomePart>();
            var random       = new Random();

            do
            {
                _probability = ProbabilityUtils.AdaptProbability(_probability, tryCount);
                distribution.Clear();

                for (var i = 0; i < matrix.Elements.Length; i++)
                {
                    distribution.Add(i, random.NextDouble() < _probability ? ChromosomePart.First : ChromosomePart.Second);
                }

                tryCount++;
            } while (IsNodeCountValid(distribution, maxDiffBetweenNode) == false);

            return(new Chromosome
            {
                Id = Guid.NewGuid(),
                Distribution = distribution,
                Factors = GetChromosomeFactors(distribution, matrix)
            });
        }
        public void P_CheckIsThreadSafe()
        {
            var attempts   = 1000;
            var trueCount  = 0;
            var falseCount = 0;
            var tasks      = new Task[attempts];

            for (var i = 0; i < attempts; i++)
            {
                tasks[i] = Task.Run(() =>
                {
                    var value = ProbabilityUtils.P(0.5);
                    if (value)
                    {
                        Interlocked.Increment(ref trueCount);
                    }
                    else
                    {
                        Interlocked.Increment(ref falseCount);
                    }
                });
            }
            Task.WaitAll(tasks);

            var marginOfError = attempts * 0.1;

            trueCount.AssertIsWithinRange(attempts * 0.5, marginOfError);
            falseCount.AssertIsWithinRange(attempts * 0.5, marginOfError);
        }
Example #5
0
        public IChromosome Crossover(IChromosome chromosome1, IChromosome chromosome2)
        {
            var vector1 = ((VectorChromosome <T>)chromosome1).GetVector();
            var vector2 = ((VectorChromosome <T>)chromosome2).GetVector();
            var length  = vector1.Length;
            var indexesToTakeFromParent1 = ProbabilityUtils.SelectKRandomNumbersNonRepeating(length, ProbabilityUtils.GetRandomInt(0, length));

            var genomesFromChromosome1 = new HashSet <T>();
            var newVector = new T[length];

            foreach (var index in indexesToTakeFromParent1)
            {
                newVector[index] = vector1[index];
                genomesFromChromosome1.Add(vector1[index]);
            }

            int lastAddedIndexFromChromsome2 = 0;

            for (int i = 0; i < length; i++)
            {
                if (indexesToTakeFromParent1.Contains(i))
                {
                    continue;
                }
                while (genomesFromChromosome1.Contains(vector2[lastAddedIndexFromChromsome2]))
                {
                    lastAddedIndexFromChromsome2++;
                }

                newVector[i] = vector2[lastAddedIndexFromChromsome2];
                lastAddedIndexFromChromsome2++;
            }

            return(new VectorChromosome <T>(newVector, mutationManager, evaluator));
        }
        public IChromosome Crossover(IChromosome chromosome1, IChromosome chromosome2)
        {
            var vector1      = ((VectorChromosome <T>)chromosome1).GetVector();
            var vector2      = ((VectorChromosome <T>)chromosome2).GetVector();
            var length       = vector1.Length;
            var firstElement = vector1[ProbabilityUtils.GetRandomInt(0, vector1.Length)];

            var childArray = new ReapetingAdjacencyMatrix <T>(vector1, vector2).Crossover(firstElement, length);

            return(new VectorChromosome <T>(childArray, mutationManager, evaluator));
        }
Example #7
0
        public T GetNeighbor(T element)
        {
            var neighbors = adjacencyMatrix[element];

            if (neighbors.Count == 0)
            {
                return(adjacencyMatrix.Keys.ElementAt(ProbabilityUtils.GetRandomInt(adjacencyMatrix.Count)));
            }

            return(neighbors.ElementAt(ProbabilityUtils.GetRandomInt(neighbors.Count)));
        }
Example #8
0
        private VectorChromosome <bool> GetChromosome()
        {
            var vector = new bool[vectorSize];

            for (int i = 0; i < vectorSize; i++)
            {
                vector[i] = ProbabilityUtils.P(0.5);
            }

            return(new VectorChromosome <bool>(vector, mutationManager, evaluator));
        }
        public double[] Mutate(double[] vector)
        {
            for (int i = 0; i < vector.Length; i++)
            {
                if (ProbabilityUtils.P(1.0 / vector.Length))
                {
                    vector[i] = ProbabilityUtils.P(0.5) ? maxValue : minValue;
                }
            }

            return(vector);
        }
Example #10
0
        public double[] Mutate(double[] vector)
        {
            for (int i = 0; i < vector.Length; i++)
            {
                if (ProbabilityUtils.P(1.0 / vector.Length))
                {
                    vector[i] = ProbabilityUtils.GaussianDistribution(standardDeviation, vector[i]).Clip(minValue, maxValue);
                }
            }

            return(vector);
        }
        public int[] Mutate(int[] vector)
        {
            for (int i = 0; i < vector.Length; i++)
            {
                if (ProbabilityUtils.P(1.0 / vector.Length))
                {
                    vector[i] = ProbabilityUtils.GetRandomInt(minValue, maxValue + 1);
                }
            }

            return(vector);
        }
        public double[] Mutate(double[] vector)
        {
            for (int i = 0; i < vector.Length; i++)
            {
                if (ProbabilityUtils.P(1.0 / vector.Length))
                {
                    vector[i] = minValue + ProbabilityUtils.GetRandomDouble() * range;
                }
            }

            return(vector);
        }
Example #13
0
        public bool[] Mutate(bool[] vector)
        {
            for (int i = 0; i < vector.Length; i++)
            {
                if (ProbabilityUtils.P(1.0 / vector.Length))
                {
                    vector[i] = !vector[i];
                }
            }

            return(vector);
        }
        public T[] Mutate(T[] vector)
        {
            int from = ProbabilityUtils.GetRandomInt(vector.Length);
            int to   = ProbabilityUtils.GetRandomInt(vector.Length);

            var temp = vector[to];

            vector[to]   = vector[from];
            vector[from] = temp;

            return(vector);
        }
        public void ProbabilitiesAreEqual_ShouldReturnTrue()
        {
            var mean = 6.32;
            var sd   = 0.47;

            var x = 6;
            var z = ProbabilityUtils.Z(x, mean, sd);

            var p1 = ProbabilityUtils.ProbabilityLessThanX(z);
            var p2 = ProbabilityUtils.ProbabilityLessThanX(x, mean, sd);

            Assert.AreEqual(p1, p2);
        }
Example #16
0
        public IEnumerable <IChromosome> GeneratePopulation(int size)
        {
            var chromosomes = new IChromosome[size];

            for (int i = 0; i < size; i++)
            {
                chromosomes[i] = new MyChromosome(ProbabilityUtils.P(0.5)
                    ? ChromosomeType.OProducer
                    : ChromosomeType.Oc2Producer);
            }

            return(chromosomes);
        }
Example #17
0
        public IChromosome SelectChromosome()
        {
            var randomNumber = ProbabilityUtils.GetRandomDouble();
            var sum          = 0.0;
            var index        = -1;

            while (sum < randomNumber)
            {
                index++;
                sum += evaluations[index];
            }

            return(chromosomes[index]);
        }
Example #18
0
        public void SelectKRandomNumbers_KNumbersSelectedTillTill(int till, int k)
        {
            var numbers = ProbabilityUtils.SelectKRandomNumbersNonRepeating(till, k);

            Assert.AreEqual(k, numbers.Count, "Didn't get enough numbers");
            foreach (var number in numbers)
            {
                Assert.AreEqual(1, numbers.Count(n => n == number), "Found the same index more then once");
            }
            foreach (var number in numbers)
            {
                Assert.IsTrue(number < till, $"{nameof(number)} = {number}, which is bigger than {nameof(till)} = {till}");
            }
        }
Example #19
0
        public IChromosome SelectChromosome()
        {
            var randomNumber = ProbabilityUtils.GetRandomDouble();
            var sum          = 0.0;
            var index        = -1;

            while (sum < randomNumber)
            {
                index++;
                sum += SortedPopulation[index].Evaluation;
            }

            return(SortedPopulation[index].Chromosome);
        }
        public int[] Mutate(int[] vector)
        {
            var mean = (maxValue + minValue) / 2.0;

            for (int i = 0; i < vector.Length; i++)
            {
                if (ProbabilityUtils.P(1.0 / vector.Length))
                {
                    vector[i] = (int)ProbabilityUtils.GaussianDistribution(standardDeviation, mean).Clip(minValue, maxValue);
                }
            }

            return(vector);
        }
        public void StandardNormalDistribution_FromTables_ShouldReturnTrue()
        {
            var p = ProbabilityUtils.Integral(ProbabilityUtils.StandardNormalPdf, 0, 0.5);

            Assert.AreEqual(0.19, Math.Round(p, 2));

            p = ProbabilityUtils.Integral(ProbabilityUtils.StandardNormalPdf, 0, -1.1);
            Assert.AreEqual(-0.36, Math.Round(p, 2));

            p = ProbabilityUtils.Integral(ProbabilityUtils.StandardNormalPdf, 0, 2.35);
            Assert.AreEqual(0.49, Math.Round(p, 2));

            p = ProbabilityUtils.Integral(ProbabilityUtils.StandardNormalPdf, 0, -1.22);
            Assert.AreEqual(-0.39, Math.Round(p, 2));
        }
Example #22
0
        public IChromosome SelectChromosome()
        {
            ChromosomeEvaluationPair bestChromosome = null;

            for (int i = 0; i < tournamentSize; i++)
            {
                var chromosome = population[ProbabilityUtils.GetRandomInt(0, population.Count())];
                if (bestChromosome == null || chromosome.Evaluation > bestChromosome.Evaluation)
                {
                    bestChromosome = chromosome;
                }
            }

            return(bestChromosome.Chromosome);
        }
        public void GetRandomDouble_CheckIsThreadSafe()
        {
            var receivedValues = new ConcurrentDictionary <double, byte>();
            var tasks          = new Task[1000];

            for (var i = 0; i < 1000; i++)
            {
                tasks[i] = Task.Run(() =>
                {
                    var value      = ProbabilityUtils.GetRandomDouble();
                    var addedValue = receivedValues.TryAdd(value, 1);
                    Assert.IsTrue(addedValue, $"Value {value} already in dictionary");
                });
            }
            Task.WaitAll(tasks);
        }
        public IChromosome Crossover(IChromosome chromosome1, IChromosome chromosome2)
        {
            var type1 = ((MyChromosome)chromosome1).Type;
            var type2 = ((MyChromosome)chromosome2).Type;

            if (type1 == ChromosomeType.OProducer && type2 == ChromosomeType.OProducer)
            {
                return(new MyChromosome(ChromosomeType.OProducer));
            }
            if (type1 == ChromosomeType.Oc2Producer && type2 == ChromosomeType.Oc2Producer)
            {
                return(new MyChromosome(ChromosomeType.Oc2Producer));
            }

            return(new MyChromosome(ProbabilityUtils.P(0.5) ? ChromosomeType.OProducer : ChromosomeType.Oc2Producer));
        }
        /// <summary>
        /// Returns the neighbor with the smallest set of neighbors, and removes the original element.
        /// </summary>
        public T GetNeighbor(T element)
        {
            var neighbors = adjacencyMatrix[element];

            Remove(element, neighbors);
            if (neighbors.Count == 0)
            {
                return(adjacencyMatrix.Keys.ElementAt(ProbabilityUtils.GetRandomInt(adjacencyMatrix.Count)));
            }

            if (!selectNeighborWithLeastNeighbors)
            {
                return(neighbors.ElementAt(ProbabilityUtils.GetRandomInt(neighbors.Count)));
            }

            var elemenetsWithMinNeighbors = FindNeighborsWithLeaseNeighbors(neighbors);

            return(elemenetsWithMinNeighbors[ProbabilityUtils.GetRandomInt(elemenetsWithMinNeighbors.Count)]);
        }
        public T[] Mutate(T[] vector)
        {
            (var start, var end) = ComponetsUtils.GetTwoRandomNumbers(vector.Length + 1);
            var insertionIndex       = ProbabilityUtils.GetRandomInt(vector.Length - (end - start));
            var vectorWithoutStretch = new T[vector.Length - (end - start)];

            for (int i = 0; i < start; i++)
            {
                vectorWithoutStretch[i] = vector[i];
            }
            for (int addTo = start, addFrom = end; addFrom < vector.Length; addFrom++, addTo++)
            {
                vectorWithoutStretch[addTo] = vector[addFrom];
            }

            var newVector = new T[vector.Length];

            for (int i = 0; i < insertionIndex; i++)
            {
                newVector[i] = vectorWithoutStretch[i];
            }
            if (inversionSttretch)
            {
                for (int addTo = insertionIndex, addFrom = end - 1; addFrom >= start; addFrom--, addTo++)
                {
                    newVector[addTo] = vector[addFrom];
                }
            }
            else
            {
                for (int addTo = insertionIndex, addFrom = start; addFrom < end; addFrom++, addTo++)
                {
                    newVector[addTo] = vector[addFrom];
                }
            }
            for (int addTo = insertionIndex + (end - start), addFrom = insertionIndex; addTo < vector.Length; addFrom++, addTo++)
            {
                newVector[addTo] = vectorWithoutStretch[addFrom];
            }

            return(newVector);
        }
        public T[] Mutate(T[] vector)
        {
            var toRemove = ProbabilityUtils.GetRandomInt(vector.Length);
            var insertAt = ProbabilityUtils.GetRandomInt(vector.Length);

            var newVector = new T[vector.Length];

            if (toRemove < insertAt)
            {
                for (int i = 0; i < toRemove; i++)
                {
                    newVector[i] = vector[i];
                }
                for (int i = toRemove; i < insertAt; i++)
                {
                    newVector[i] = vector[i + 1];
                }
                newVector[insertAt] = vector[toRemove];
                for (int i = insertAt + 1; i < vector.Length; i++)
                {
                    newVector[i] = vector[i];
                }
            }
            else
            {
                for (int i = 0; i < insertAt; i++)
                {
                    newVector[i] = vector[i];
                }
                newVector[insertAt] = vector[toRemove];
                for (int i = insertAt + 1; i <= toRemove; i++)
                {
                    newVector[i] = vector[i - 1];
                }
                for (int i = toRemove + 1; i < vector.Length; i++)
                {
                    newVector[i] = vector[i];
                }
            }

            return(newVector);
        }
        public IChromosome Crossover(IChromosome chromosome1, IChromosome chromosome2)
        {
            (var shortVectorChromosome, var longVectorChromosome) =
                Utils.OrderChromosomes <T>(chromosome1, chromosome2);

            var newVector = new T[longVectorChromosome.GetVector().Length];
            var index     = 0;

            for (; index < shortVectorChromosome.GetVector().Length; index++)
            {
                newVector[index] = ProbabilityUtils.P(0.5)
                    ? shortVectorChromosome.GetVector()[index]
                    : longVectorChromosome.GetVector()[index];
            }
            for (; index < longVectorChromosome.GetVector().Length; index++)
            {
                newVector[index] = longVectorChromosome.GetVector()[index];
            }

            return(new VectorChromosome <T>(newVector, mutationManager, evaluator));
        }
Example #29
0
        private void FillPool(int requestedChromosomes, IChromosome[] chromosomes, double[] evaluations)
        {
            var pointer         = ProbabilityUtils.GetRandomDouble() / requestedChromosomes;
            var increment       = 1.0 / requestedChromosomes;
            var sum             = 0.0;
            var chromosomeIndex = -1;
            var poolChromosomes = new IChromosome[requestedChromosomes];

            for (int i = 0; i < requestedChromosomes; i++)
            {
                while (sum <= pointer)
                {
                    chromosomeIndex++;
                    sum += evaluations[chromosomeIndex];
                }
                poolChromosomes[i] = chromosomes[chromosomeIndex];
                pointer           += increment;
            }

            pool = new ChromosomePool(poolChromosomes);
        }
Example #30
0
        public void GaussianDistribution_CommonNumbersAreMoreLikely(double mean, double sd)
        {
            var smallCount = 0;
            var bigCount   = 0;

            for (int i = 0; i < 100; i++)
            {
                var value = ProbabilityUtils.GaussianDistribution(sd, mean);
                Console.WriteLine(value);
                if (value >= mean + sd || value <= mean - sd)
                {
                    bigCount++;
                }
                else
                {
                    smallCount++;
                }
            }

            Assert.IsTrue(smallCount > bigCount, $"Got to many big genomes. Big numberes = {bigCount}; small numbers = {smallCount}");
        }