Example #1
0
        public object Translate(IChromosome chromosome)
        {
            // Конструираме невронна мрежа и изчисляваме резултата
            DoubleArrayChromosome dac = (DoubleArrayChromosome)chromosome;
            ActivationNetwork Network = new ActivationNetwork(
                     new BipolarSigmoidFunction(sigmoidAlphaValue),
                     mArchitecture[0], mArchitecture[1], mArchitecture[2]);

            int current = 0;
            int i = 0;

            // Тегла на скрит слой
            for (i = 0; i < mArchitecture[1]; i++)
            {
                for (int j = 0; j < mArchitecture[0]; j++)
                {
                    Network[0][i][j] = dac.Value[current++];
                }
            }

            // Тегла на изходен слой
            for (i = 0; i < mArchitecture[2]; i++)
            {
                for (int j = 0; j < mArchitecture[1]; j++)
                {
                    Network[1][i][j] = dac.Value[current++];
                }
            }

            return Network;
        }
        /// <summary>
        /// Initializes a new instance of the <see cref="Population"/> class.
        /// </summary>
        /// 
        /// <param name="size">Initial size of population.</param>
        /// <param name="ancestor">Ancestor chromosome to use for population creatioin.</param>
        /// <param name="fitnessFunction">Fitness function to use for calculating
        /// chromosome's fitness values.</param>
        /// <param name="selectionMethod">Selection algorithm to use for selection
        /// chromosome's to new generation.</param>
        /// 
        /// <remarks>Creates new population of specified size. The specified ancestor
        /// becomes first member of the population and is used to create other members
        /// with same parameters, which were used for ancestor's creation.</remarks>
        /// 
        /// <exception cref="ArgumentException">Too small population's size was specified. The
        /// exception is thrown in the case if <paramref name="size"/> is smaller than 2.</exception>
        ///
        public QueuePopulation(int size,
                           IChromosome ancestor,
                           IFitnessFunction fitnessFunction,
                           ISelectionMethod selectionMethod)
        {
            if (size < 2)
                throw new ArgumentException("Too small population's size was specified.");

            this.fitnessFunction = fitnessFunction;
            this.selectionMethod = selectionMethod;
            this.size = size;

            // add ancestor to the population
            ancestor.Evaluate(fitnessFunction);
            population.Add(ancestor.Clone());
            // add more chromosomes to the population
            for (int i = 1; i < size; i++)
            {
                // create new chromosome
                IChromosome c = ancestor.CreateNew();
                // calculate it's fitness
                c.Evaluate(fitnessFunction);
                // add it to population
                population.Add(c);
            }
        }
Example #3
0
        public void Collect(GeneticAlgorithmStatus status)
        {
            _iterations.Add(new IterationData()
            {
                AverageFitness = status.CurrentPopulation.AvgFitness,
                PopulationFitness = status.CurrentPopulation.Fitness,
                NumberOfIteration = status.IterationNumber,
                BestChromosomeValue = status.BestChromosome.Value,

                SelectionOverhead = status.SelectionOverhead,
                CrossoverOverhead = status.CrossoverOverhead,
                MutationOverhead = status.MutationOverhead,
                RepairOverhead = status.RepairOverhead,
                TransformOverhead = status.TransformOverhead,
                EvaluationOverhead = status.EvaluationOverhead,

                IterationTimeInMillis = status.IterationTimeInMillis
            });

            if (status.BestChromosome.Value > _bestChromosomeValue)
            {
                _bestChromosomeValue = status.BestChromosome.Value;
                _bestChromosome = status.BestChromosome.Clone();
            }
        }
        /// <summary>
        /// Draws the specified best chromosome.
        /// </summary>
        /// <param name="bestChromosome">The best chromosome.</param>
        public override void Draw(IChromosome bestChromosome)
        {
            var best = bestChromosome as EquationChromosome;

            var genes = best.GetGenes();
            Console.WriteLine("Equation: {0} + 2*{1} + 3*{2} + 4*{3} = {4}", genes[0], genes[1], genes[2], genes[3], EqualityFitness.GetEquationResult(best));
        }
        public IChromosome[] evolve(IChromosome alpha, IChromosome beta)
        {
            IChromosome[] offspring = new IChromosome[2];
            offspring[0] = new Chromosome(0, new char[alpha.Alleles.Length]);
            offspring[1] = new Chromosome(0, new char[alpha.Alleles.Length]);

            int half = alpha.Alleles.Length/2;
            int count = 0;

            for (int i = 0; i < half; i++)
            {
                offspring[0].Alleles[i] = alpha.Alleles[i];
                count++;
            }

            for (int j = count; j < beta.Alleles.Length - 1; j++)
            {
                offspring[0].Alleles[j] = beta.Alleles[j];
            }

            for (int i = 0; i < half; i++)
            {
                offspring[1].Alleles[i] = beta.Alleles[i];
                count++;
            }

            for (int j = count; j < beta.Alleles.Length - 1; j++)
            {
                offspring[1].Alleles[j] = alpha.Alleles[j];
            }

            return offspring;
        }
        /// <summary>
        /// Evaluates chromosome.
        /// </summary>
        /// 
        /// <param name="chromosome">Chromosome to evaluate.</param>
        /// 
        /// <returns>Returns chromosome's fitness value.</returns>
        ///
        /// <remarks>The method calculates fitness value of the specified
        /// chromosome.</remarks>
        ///
        public double Evaluate( IChromosome chromosome )
        {
            // get function in polish notation
            string function = chromosome.ToString( );

            // go through all the data
            double error = 0.0;
            for ( int i = 0, n = data.GetLength( 0 ); i < n; i++ )
            {
                // put next X value to variables list
                variables[0] = data[i, 0];
                // avoid evaluation errors
                try
                {
                    // evalue the function
                    double y = PolishExpression.Evaluate( function, variables );
                    // check for correct numeric value
                    if ( double.IsNaN( y ) )
                        return 0;
                    // get the difference between evaluated Y and real Y
                    // and sum error
                    error += Math.Abs( y - data[i, 1] );
                }
                catch
                {
                    return 0;
                }
            }

            // return optimization function value
            return 100.0 / ( error + 1 );
        }
        /// <summary>
        /// Mutate the specified chromosome.
        /// </summary>
        /// <param name="chromosome">The chromosome.</param>
        /// <param name="probability">The probability to mutate each chromosome.</param>
        protected override void PerformMutate(IChromosome chromosome, float probability)
        {
            ExceptionHelper.ThrowIfNull("chromosome", chromosome);

            var genesLength = chromosome.Length;

            if (m_mutableGenesIndexes == null || m_mutableGenesIndexes.Length == 0)
            {
                if (m_allGenesMutable)
                {
                    m_mutableGenesIndexes = Enumerable.Range(0, genesLength).ToArray();
                }
                else
                {
                    m_mutableGenesIndexes = RandomizationProvider.Current.GetInts(1, 0, genesLength);
                }
            }

            foreach (var i in m_mutableGenesIndexes)
            {
                if (i >= genesLength)
                {
                    throw new MutationException(this, "The chromosome has no gene on index {0}. The chromosome genes length is {1}.".With(i, genesLength));
                }

                if (RandomizationProvider.Current.GetDouble() <= probability)
                {
                    chromosome.ReplaceGene(i, chromosome.GenerateGene(i));
                }
            }
        }
        /// <summary>
        /// Realizuje algorytm selekcji.
        /// </summary>
        /// <param name="population">Populacja poddawana selekcji.</param>
        /// <returns>Zbiór osobników populacji, wybranych w wyniku selekcji do następnej generacji.</returns>
        public IChromosome[] Select(IChromosome[] population)
        {
            if (population.Length < 2)
            {
                return population;
            }

            IChromosome[] subpopulation = population.Where(ch => ch.Evaluate() > 0).ToArray();
            Double totalFitness = subpopulation.Sum(ch => ch.Evaluate());

            Int32 newPopulationSize = (Int32)PopulationSize.ComputeSize(subpopulation);
            IChromosome[] result = new IChromosome[newPopulationSize];

            for (Int32 i = 0; i < newPopulationSize; i++)
            {
                Double ptr = RandomGenerator.NextDouble();
                Double sum = 0.0;
                for (Int32 j = 0; j < subpopulation.Length; ++j)
                {
                    sum += subpopulation[j].Evaluate() / totalFitness;
                    if (sum > ptr)
                    {
                        result[i] = subpopulation[j];
                        break;
                    }
                }
            }
            return result;
        }
        /// <summary>
        /// Realizuje algorytm selekcji.
        /// </summary>
        /// <param name="population">Populacja poddawana selekcji.</param>
        /// <returns>Zbiór osobników populacji, wybranych w wyniku selekcji do następnej generacji.</returns>
        public IChromosome[] Select(IChromosome[] population)
        {
            if (population.Length < 2)
            {
                return population;
            }

            IChromosome[] subpopulation = population.Where(ch => ch.Evaluate() > 0).ToArray();
            Double totalFitness = subpopulation.Sum(ch => ch.Evaluate());

            Int32 newPopulationSize = (Int32)PopulationSize.ComputeSize(subpopulation);
            IChromosome[] result = new IChromosome[newPopulationSize];

            Double ptrstep = 1.0 / newPopulationSize;
            Double ptr = RandomGenerator.NextDouble() * ptrstep;

            Int32 pos = 0;
            Double sum = 0.0;
            for (Int32 i = 0; i < subpopulation.Length; i++)
            {
                for (sum += subpopulation[i].Evaluate() / totalFitness; sum > ptr; ptr += ptrstep)
                {
                    result[pos++] = subpopulation[i];

                    if (pos == newPopulationSize)
                    {
                        return result;
                    }
                }
            }

            // it shouldn't happen
            Debug.Assert(false);
            return result;
        }
    //retorna a quantidade de rainhas a salvo
    public double Evaluate(IChromosome chromosome)
    {
        this.individo = (ShortArrayChromosome)chromosome;
        nCasas = individo.Length;
        double ret = 0;
        int[,] tabuleiro = new int[nCasas, nCasas];

        // primeiro representamos o tabuleiro com 0 e 1
        gerarTabuleiro(tabuleiro);

        // agora verificamos quantas rainhas estao a salvo, este será o nosso
        // retorno da função fitness
        for (int i = 0; i < nCasas; i++)
        {
            for (int j = 0; j < nCasas; j++)
            {
                if (tabuleiro[i, j] == 1)
                {
                    if (!temAtacante(tabuleiro, i, j))
                    {
                        ret++;
                    }
                }
            }
        }
        return ret;
    }
        /// <summary>
        /// Performs the evaluation against the specified chromosome.
        /// </summary>
        /// <param name="chromosome">The chromosome to be evaluated.</param>
        /// <returns>The fitness of the chromosome.</returns>
        public double Evaluate(IChromosome chromosome)
        {
            var c = chromosome as GhostwriterChromosome;
            var text = c.BuildText();

            return EvaluateFunc(text);
        }
Example #12
0
 public void Roulette()
 {
     IChromosome<int>[] a = new IChromosome<int>[] { new DigitalChromosome().GenerateFromArray(new int[] { 9, 9, 9 }),
     new DigitalChromosome().GenerateFromArray(new int[] { 7, 7, 7 }) };
     RouletteSelection<int> selection = new RouletteSelection<int>();
     IChromosome<int>[] res = selection.Select(a, x => x.ToArray().Sum(), 1);
 }
Example #13
0
		public Organism ( IChromosome cs , float fitness )
		{
			GeneticUtil.CHECKNULLARG( cs );
			this.m_chromosome = cs;
			this.Fitness = fitness;
			this.ID = Organism.generator.GetUniqueID();
			this.GenerationID = -1;
		}
        /// <summary>
        /// Performs the evaluation against the specified chromosome.
        /// </summary>
        /// <param name="chromosome">The chromosome to be evaluated.</param>
        /// <returns>The fitness of the chromosome.</returns>
        public double Evaluate(IChromosome chromosome)
        {
            var equalityChromosome = chromosome as EquationChromosome;

            var fitness = Math.Abs(m_getEquationResult(equalityChromosome.GetGenes()) - m_expectedResult);

            return fitness * -1;
        }
        /// <summary>
        /// Draws the sample;
        /// </summary>
        public void Draw(IChromosome bestChromosome)
        {
            var c = bestChromosome as TspChromosome;
            Console.WriteLine("Distance: {0:n2}", c.Distance);

			//var cities = bestChromosome.GetGenes ().Select (g => g.Value.ToString ()).ToArray ();
            //Console.WriteLine("City tour: {0}", String.Join(", ", cities));
        }
 /// <summary>
 /// Initializes a new instance of the <see cref="AutoConfigFitness"/> class.
 /// </summary>
 /// <param name="targetFitness">The target fitness.</param>
 /// <param name="targetChromosome">The target chromosome.</param>
 public AutoConfigFitness(IFitness targetFitness, IChromosome targetChromosome)
 {
     m_targetFitness = targetFitness;
     m_targetChromosome = targetChromosome;
     PopulationMinSize = 100;
     PopulationMaxSize = 100;
     Termination = new TimeEvolvingTermination(TimeSpan.FromSeconds(30));
     TaskExecutor = new LinearTaskExecutor();
 }
Example #17
0
 public void OnePointCrossoverTest()
 {
     IChromosome<int> a = new DigitalChromosome().GenerateFromArray(new int[] { 1, 2, 3, 4 });
     IChromosome<int> b = new DigitalChromosome().GenerateFromArray(new int[] { 4, 3, 2, 1 });
     OnePointCrossover<int> cross = new OnePointCrossover<int>(2);
     IChromosome<int>[] res = cross.Crossover(a, b);
     IChromosome<int>[] exp = new IChromosome<int>[2] { new DigitalChromosome().GenerateFromArray(new int[] { 1, 2, 2, 1 }), new DigitalChromosome().GenerateFromArray(new int[] { 4, 3, 3, 4 }) };
     CollectionAssert.AreEqual(res, exp);
 }
Example #18
0
 public void CicleCrossoverTest2()
 {
     IChromosome<int> a = new DigitalChromosome().GenerateFromArray(new int[] { 1, 2, 3, 4, 5, 6 });
     IChromosome<int> b = new DigitalChromosome().GenerateFromArray(new int[] { 2, 4, 5, 1, 6, 3 });
     CicleCrossover<int> cross = new CicleCrossover<int>(6);
     IChromosome<int>[] res = cross.Crossover(a, b);
     IChromosome<int>[] exp = new IChromosome<int>[2] { new DigitalChromosome().GenerateFromArray(new int[] { 1, 2, 5, 4, 6, 3 }), new DigitalChromosome().GenerateFromArray(new int[] { 2, 4, 3, 1, 5, 6 }) };
     CollectionAssert.AreEqual(res, exp);
 }
Example #19
0
        /// <summary>
        /// Evaluates the specified chromosome.
        /// </summary>
        /// <param name="chromosome">The chromosome.</param>
        /// <returns>The chromosome fitness.</returns>
        public double Evaluate(IChromosome chromosome)
        {
            // a + 2b + 3c + 4d = 30
            var equalityChromosome = chromosome as EquationChromosome;

            var fitness = Math.Abs(GetEquationResult(equalityChromosome) - 30);

            return fitness * -1;
        }
Example #20
0
 public void GoldenCrossoverTest()
 {
     IChromosome<int> a = new DigitalChromosome().GenerateFromArray(new int[] { 1, 2, 3, 4, 5 });
     IChromosome<int> b = new DigitalChromosome().GenerateFromArray(new int[] { 5, 4, 3, 2, 1 });
     GoldenCrossover<int> cross = new GoldenCrossover<int>(5);
     IChromosome<int>[] res = cross.Crossover(a, b);
     IChromosome<int>[] exp = new IChromosome<int>[2] { new DigitalChromosome().GenerateFromArray(new int[] { 1, 2, 3, 2, 1 }), new DigitalChromosome().GenerateFromArray(new int[] { 5, 4, 3, 4, 5 }) };
     CollectionAssert.AreEqual(res, exp);
 }
Example #21
0
        public double Evaluate(IChromosome chromosome)
        {
            var chromo = chromosome as GPCustomTree;
            if (chromo == null)
                return 0;
            var notes = chromo.GenerateNotes();

            return ComputeFitness(notes.ToArray());
        }
Example #22
0
        public double Evaluate(IChromosome chromosome)
        {
            double n = 9;
            var x = (int)chromosome.GetGene(0).Value;
            var y = (int)chromosome.GetGene(1).Value;
            double f1 = System.Math.Pow(15 * x * y * (1 - x) * (1 - y) * System.Math.Sin(n * System.Math.PI * x) * System.Math.Sin(n * System.Math.PI * y), 2);

            return f1;
        }
        private static IChromosome CreateOffspring(IChromosome leftParent, IChromosome rightParent, int leftParentPoint, int rightParentPoint)
        {
            var offspring = leftParent.CreateNew();

            offspring.Resize(leftParentPoint + (rightParent.Length - rightParentPoint));
            offspring.ReplaceGenes(0, leftParent.GetGenes().Take(leftParentPoint).ToArray());
            offspring.ReplaceGenes(leftParentPoint, rightParent.GetGenes().Skip(rightParentPoint).ToArray());

            return offspring;
        }
Example #24
0
        public IList<IChromosome> Select(IList<IChromosome> population, int count)
        {
            UpdateFitnessAll(population);

            IChromosome[] r = new IChromosome[count];
            for (int i=0; i<count; i++) {
                r[i] = this.SelectionMechanism.Select(population);
            }
            return r;
        }
        public double Evaluate(IChromosome chromosome)
        {
            NeuralNetwork network = ((NetworkChromosome)chromosome).ToNetwork(
                this.numHiddenLayers, this.numNeuronsPerHiddenLayer, this.numInputs, this.numOutputs);

            double error = CalculateError(ref this.dataset, ref network);

            // fitness function increases as the chromosome gets better
            return 1.0 / (error + 1.0);
        }
        public double Evaluate(IChromosome chromosome)
        {
            ProgramChromosome programChromosome = (ProgramChromosome) chromosome;
            Debug.Assert(this.totalSlots == programChromosome.SlotCount);
            Program program = this.ChromosomeToProgram(programChromosome);

            int starsEaten;
            this.puzzle.TrySolveWith(program, out starsEaten);
            return starsEaten + 1;
        }
Example #27
0
 public void Fibonacci()
 {
     IChromosome<int> a = new DigitalChromosome().GenerateFromArray(new int[] { 1, 2, 3, 4, 5, 6 });
     IChromosome<int> b = new DigitalChromosome().GenerateFromArray(new int[] { 6, 5, 4, 3, 2, 1 });
     FibonacciCrossover<int> cross = new FibonacciCrossover<int>(6);
     IChromosome<int>[] res = cross.Crossover(a, b);
     IChromosome<int>[] exp = new IChromosome<int>[2] { new DigitalChromosome().GenerateFromArray(new int[] { 1, 5, 3, 3, 2, 6 })
         , new DigitalChromosome().GenerateFromArray(new int[] { 6, 2, 4, 4, 5, 1 }) };
     CollectionAssert.AreEqual(res, exp);
 }
Example #28
0
 public void Elite()
 {
     IChromosome<int>[] a = new IChromosome<int>[] { new DigitalChromosome().GenerateFromArray(new int[] { 9, 9, 9 }),
     new DigitalChromosome().GenerateFromArray(new int[] { 7, 7, 7 }), new DigitalChromosome().GenerateFromArray(new int[] { 3, 3, 3 }),
     new DigitalChromosome().GenerateFromArray(new int[] { 2, 2, 2 }), new DigitalChromosome().GenerateFromArray(new int[] { 7, 7, 7 }), new DigitalChromosome().GenerateFromArray(new int[] { 7, 7, 7 }),
     new DigitalChromosome().GenerateFromArray(new int[] { 7, 7, 7 }) };
     EliteSelection<int> selection = new EliteSelection<int>(2);
     IChromosome<int>[] res = selection.Select(a, x => x.ToArray().Sum(), 6);
     CollectionAssert.AreEqual(new IChromosome<int>[] { new DigitalChromosome().GenerateFromArray(new int[] { 9, 9, 9 }),
     new DigitalChromosome().GenerateFromArray(new int[] { 7, 7, 7 }) }, res.Take(2).ToArray());
 }
Example #29
0
 /// <summary>
 /// Konstruktor.
 /// </summary>
 /// <param name="prototype">Osobnik-wzorzec, który będzie kopiowany na potrzeby utworzenia populacji.</param>
 /// <param name="initialSize">Początkowy rozmiar populacji.</param>
 public DefaultPopulation(IChromosome prototype, UInt32 initialSize)
 {
     Generation = 0;
     Specimens = new IChromosome[initialSize];
     for (Int32 i = 0; i < initialSize; ++i)
     {
         IChromosome chromosome = prototype.Clone();
         chromosome.Randomize();
         Specimens[i] = chromosome;
     }
 }
 public void Crossover(IChromosome chromosome)
 {
     double crossoverPoint = BitChromosome.random.Next(0, this.length - 1);
     Genes.BitGene aux = null;
     BitChromosome bitChromosome = (BitChromosome)chromosome;
     for (int i = 0; i <= crossoverPoint; ++i)
     {
         aux = this.bits[i];
         this.bits[i] = bitChromosome.bits[i];
         bitChromosome.bits[i] = aux;
     }
 }
Example #31
0
        /// <summary>
        /// Creates a new population.
        /// </summary>
        /// <param name="population">The current population.</param>
        /// <param name="elite">The elite operator.</param>
        /// <param name="mutate">The mutate operator.</param>
        /// <param name="crossover">The crossover operator.</param>
        /// <param name="diversify">The diversify operator.</param>
        /// <returns></returns>
        public Population CreateNewPopulation(Population population, IElite elite, IMutate mutate, ICrossOver crossover, IDiversify diversify)
        {
            IChromosome parent1, parent2;
            IChromosome child1 = null, child2 = null;

            // create a new population
            var nextPopulation = new Population();

            // copy all elites to the new population
            elite?.Process(population, nextPopulation);

            // make sure the population is diversified enough
            diversify?.Process(nextPopulation, population.Count);

            // while next population is not filled completely
            while (nextPopulation.Count < population.Count)
            {
                // select 2 parents
                DoTournament(population, out parent1, out parent2);

                // perform crossover so we get 2 children
                crossover?.Process(parent1, parent2, out child1, out child2);

                // mutate both children
                mutate?.Process(child1);
                mutate?.Process(child2);

                // and add the children to the next population
                nextPopulation.Add(child1);
                if (nextPopulation.Count < population.Count)
                {
                    nextPopulation.Add(child2);
                }
            }
            return(nextPopulation);
        }
Example #32
0
        /// <summary>
        /// Creates the child.
        /// </summary>
        /// <param name="firstParent">First parent.</param>
        /// <param name="secondParent">Second parent.</param>
        /// <param name="swapIndexes">The swap indexes.</param>
        /// <returns>
        /// The child.
        /// </returns>
        protected virtual IChromosome CreateChild(IChromosome firstParent, IChromosome secondParent, int[] swapIndexes)
        {
            // ...suppose that in the second parent in the second, third
            // and sixth positions are selected. The elements in these positions are 4, 6 and 5 respectively...
            var secondParentSwapGenes = secondParent.GetGenes()
                                        .Select((g, i) => new { Gene = g, Index = i })
                                        .Where((g) => swapIndexes.Contains(g.Index))
                                        .ToArray();

            var firstParentGenes = firstParent.GetGenes();

            // ...in the first parent, these elements are present at the fourth, fifth and sixth positions...
            var firstParentSwapGenes = firstParentGenes
                                       .Select((g, i) => new { Gene = g, Index = i })
                                       .Where((g) => secondParentSwapGenes.Any(s => s.Gene == g.Gene))
                                       .ToArray();

            var child = firstParent.CreateNew();
            var secondParentSwapGensIndex = 0;

            for (int i = 0; i < firstParent.Length; i++)
            {
                // Now the offspring are equal to parent 1 except in the fourth, fifth and sixth positions.
                // We add the missing elements to the offspring in the same order in which they appear in the second parent.
                if (firstParentSwapGenes.Any(f => f.Index == i))
                {
                    child.ReplaceGene(i, secondParentSwapGenes[secondParentSwapGensIndex++].Gene);
                }
                else
                {
                    child.ReplaceGene(i, firstParentGenes[i]);
                }
            }

            return(child);
        }
Example #33
0
        internal static bool HasVcfPositionsOnInterval(string s, IChromosome chromosome, int start, int end)
        {
            string[] rawLines = s.OptimizedSplit('\n');

            foreach (string line in rawLines)
            {
                string[] cols = line.Split('\t', 3);
                if (cols.Length < 2)
                {
                    continue;
                }

                string chromosomeName = cols[0];
                string positionString = cols[1];

                if (chromosomeName != chromosome.EnsemblName && chromosomeName != chromosome.UcscName)
                {
                    continue;
                }
                if (!int.TryParse(positionString, out int position))
                {
                    continue;
                }

                if (position > end)
                {
                    break;
                }
                if (position >= start && position <= end)
                {
                    return(true);
                }
            }

            return(false);
        }
Example #34
0
    public double Evaluate(IChromosome chromosome)
    {
        var genes          = chromosome.GetGenes();
        var distanceSum    = 0.0;
        var lastPointIndex = Convert.ToInt32(genes[0].Value, CultureInfo.InvariantCulture);
        var pointsIndexes  = new List <int>();

        foreach (var g in genes)
        {
            var currentPointIndex = Convert.ToInt32(g.Value, CultureInfo.InvariantCulture);
            distanceSum   += CalcDistanceTwoPoints(Points[currentPointIndex], Points[lastPointIndex]);
            lastPointIndex = currentPointIndex;

            pointsIndexes.Add(lastPointIndex);
        }

        distanceSum += CalcDistanceTwoPoints(Points[pointsIndexes.Last()], Points[pointsIndexes.First()]);

        var fitness = 1.0 - (distanceSum / (Points.Count * 1000.0));

        ((TspChromosome)chromosome).Distance = distanceSum;

        var diff = Points.Count - pointsIndexes.Distinct().Count();

        if (diff > 0)
        {
            fitness /= diff;
        }

        if (fitness < 0)
        {
            fitness = 0;
        }

        return(fitness);
    }
Example #35
0
        public double Evaluate(IChromosome chromosome)
        {
            var autoConfigChromosome = chromosome as AutoConfigChromosome;
            var selection            = autoConfigChromosome.Selection;
            var crossover            = autoConfigChromosome.Crossover;
            var mutation             = autoConfigChromosome.Mutation;
            var population           = new Population(PopulationMinSize, PopulationMaxSize, m_targetChromosome);

            var ga = new GeneticAlgorithm(population, m_targetFitness, selection, crossover, mutation);

            ga.Termination  = Termination;
            ga.TaskExecutor = TaskExecutor;

            try
            {
                ga.Start();
            }
            catch (Exception)
            {
                return(0);
            }

            return(ga.BestChromosome.Fitness.Value);
        }
Example #36
0
 public ClinVarItem(IChromosome chromosome,
                    int position,
                    int stop,
                    IEnumerable <string> alleleOrigins,
                    string altAllele,
                    string variantType,
                    string id,
                    ReviewStatusEnum reviewStatus,
                    IEnumerable <string> medGenIds,
                    IEnumerable <string> omimIds,
                    IEnumerable <string> orphanetIds,
                    IEnumerable <string> phenotypes,
                    string referenceAllele,
                    string significance,
                    IEnumerable <long> pubmedIds = null,
                    long lastUpdatedDate         = long.MinValue
                    )
 {
     Chromosome      = chromosome;
     Start           = position;
     Stop            = stop;
     AlleleOrigins   = alleleOrigins;
     AlternateAllele = altAllele;
     VariantType     = variantType;
     Id               = id;
     MedGenIDs        = medGenIds;
     OmimIDs          = omimIds;
     OrphanetIDs      = orphanetIds;
     Phenotypes       = phenotypes;
     ReferenceAllele  = referenceAllele;
     Significance     = significance;
     PubmedIds        = pubmedIds;
     LastUpdatedDate  = lastUpdatedDate;
     IsAlleleSpecific = null;
     ReviewStatus     = reviewStatus;
 }
Example #37
0
        /// <summary>
        /// retrieves the next gene. Returns false if there are no more genes available
        /// </summary>
        private HgncGene Next()
        {
            string line = _reader.ReadLine();

            if (line == null)
            {
                return(null);
            }

            var cols = line.Split('\t');

            if (cols.Length != 49)
            {
                throw new InvalidDataException($"Expected 48 columns but found {cols.Length} when parsing the gene entry:[{line}]");
            }

            try
            {
                int         hgncId       = int.Parse(cols[HgncIdIndex].Substring(5));
                string      symbol       = cols[SymbolIndex];
                IChromosome chromosome   = GetChromosome(cols[LocationIndex]);
                string      entrezGeneId = GetId(cols[EntrezIdIndex]);
                string      ensemblId    = GetId(cols[EnsemblIdIndex]);

                return(new HgncGene(chromosome, -1, -1, symbol, entrezGeneId, ensemblId, hgncId));
            }
            catch (Exception)
            {
                Console.WriteLine("Offending line: {0}", line);
                for (var i = 0; i < cols.Length; i++)
                {
                    Console.WriteLine("- col {0}: [{1}]", i, cols[i]);
                }
                throw;
            }
        }
Example #38
0
        public static double Eval(IChromosome sudokuChromosome, SudokuBoard sudokuBoard, int populationSize, double fitnessThreshold, int generationNb)
        {
            var fitness   = new SudokuFitness(sudokuBoard);
            var selection = new EliteSelection();
            var crossover = new UniformCrossover();
            var mutation  = new UniformMutation();

            var population = new Population(populationSize, populationSize, sudokuChromosome);
            var ga         = new GeneticAlgorithm(population, fitness, selection, crossover, mutation)
            {
                Termination = new OrTermination(new ITermination[]
                {
                    new FitnessThresholdTermination(fitnessThreshold),
                    new GenerationNumberTermination(generationNb)
                })
            };

            ga.Start();

            var bestIndividual = ((ISudokuChromosome)ga.Population.BestChromosome);
            var solutions      = bestIndividual.GetSudokus();

            return(solutions.Max(solutionSudoku => fitness.Evaluate(solutionSudoku)));
        }
Example #39
0
        public double Evaluate(IChromosome chromosome)
        {
            var pizza   = new int[_inputModel.Rows, _inputModel.Columns];
            var score   = 0;
            var penalty = 0;
            var slices  = (chromosome as PizzaCutterChromosome)?.GetSlices(_slices) ?? new List <Slice>();

            foreach (var slice in slices)
            {
                for (var i = slice.StartRow; i <= slice.EndRow; i++)
                {
                    for (var j = slice.StartColumn; j <= slice.EndColumn; j++)
                    {
                        pizza[i, j]++;
                    }
                }
                score++;
            }

            var everythingValid = true;

            foreach (var cell in pizza)
            {
                if (cell == 0)
                {
                    penalty += 2;
                }
                else if (cell > 1)
                {
                    penalty        += (cell - 1) * 3;
                    everythingValid = false;
                }
            }

            return(everythingValid ? score * 10 : score - penalty);
        }
Example #40
0
        /// <summary>
        /// Report prograss the same as in bse class
        /// </summary>
        /// <param name="currentEvoution"></param>
        /// <param name="avgFitness"></param>
        /// <param name="ch"></param>
        /// <param name="runType"></param>
        public override void ReportProgress(int currentEvoution, float avgFitness, IChromosome ch, int runType)
        {
            if (ch == null)
            {
                return;
            }
            base.ReportProgress(currentEvoution, avgFitness, ch, runType);

            // When fitness is changed, model needs to be refreshed
            if (prevFitness < ch.Fitness)
            {
                var fitStr = ch.Fitness;
                if (chkOptimumType.Checked)
                {
                    fitStr = -1 * ch.Fitness;
                }

                eb_currentFitness.Text = Math.Round(fitStr, 5).ToString("#.#####");

                prevFitness = ch.Fitness;
                eb_bestSolutionFound.Text = currentEvoution.ToString();
                UpdateOptimizationResult(ch);
            }
        }
Example #41
0
        public double Evaluate(IChromosome chromosome)
        {
            for (var geneIndex = 0; geneIndex < SettingsLoader.Data.Genes.Count; geneIndex++)
            {
                var geneName  = SettingsLoader.Data.Genes[geneIndex].Name;
                var geneValue = chromosome.GetGene(geneIndex).ToString();

                _engineOperator.SetOption(geneName, geneValue);
            }

            while (true)
            {
                try
                {
                    _engineOperator.ApplyOptions();
                    break;
                }
                catch
                {
                    _engineOperator.Restart();
                    _engineOperator.LoadEpd(SettingsLoader.Data.PositionsDatabasePath);
                }
            }

            var stopwatch   = Stopwatch.StartNew();
            var error       = _engineOperator.Evaluate(SettingsLoader.Data.ScalingConstant);
            var fitness     = 1.0 - error;
            var elapsedTime = (double)stopwatch.ElapsedMilliseconds / 1000;

            var chromosomeRequest = RequestsFactory.CreateChromosomeRequest(_testId, fitness, elapsedTime, chromosome);

            _webService.SendChromosomeData(chromosomeRequest).GetAwaiter().GetResult();

            Console.WriteLine($"[{DateTime.Now}] Run done! Fitness: {fitness}");
            return(fitness);
        }
        private MutableExon[] ReadExons(IChromosome chromosome)
        {
            var cols = GetColumns("Exons");

            int numExons = int.Parse(cols[1]);

            if (numExons == 0)
            {
                return(null);
            }

            var exons    = new MutableExon[numExons];
            var colIndex = 2;

            for (var i = 0; i < numExons; i++)
            {
                int start = int.Parse(cols[colIndex++]);
                int end   = int.Parse(cols[colIndex++]);
                var phase = (byte)(int.Parse(cols[colIndex++]) + 1);
                exons[i] = new MutableExon(chromosome, start, end, phase);
            }

            return(exons);
        }
Example #43
0
        public double Evaluate(IChromosome chromosome)
        {
            DoubleArrayChromosome doubleChromosome = (DoubleArrayChromosome)chromosome;

            string[] s_genes = doubleChromosome.ToString().Split();
            double[] d_genes = new double[s_genes.Length];
            double   sum     = 0;

            for (int i = 0; i < d_genes.Length; i++)
            {
                d_genes[i] = Double.Parse(s_genes[i]);
            }

            double error = xorSim.getError(d_genes);

            if (error == 0)
            {
                return(0);
            }
            else
            {
                return(1 / xorSim.getError(d_genes));
            }
        }
        public void Crossover(IChromosome<T> parent1, IChromosome<T> parent2, out IChromosome<T> offspring1, out IChromosome<T> offspring2)
        {
            offspring1 = new Chromosome<T>(parent1.Genes);
            offspring2 = new Chromosome<T>(parent2.Genes);
            int length = parent1.Length;

                for (int i = 0; i < length; i++)
                {
                    double p1 = (double)(object)parent1[i];
                    double p2 = (double)(object)parent2[i];
                    double average1 = m_Alpha * p1 + (1 - m_Alpha) * p2;
                    double average2 = m_Alpha * p2 + (1 - m_Alpha) * p1;
                    
                    offspring1[i] = (T)(object)average1;
                }

                offspring2 = null;
            }
Example #45
0
 public static string ToNormalNotation(IChromosome chromosome)
 {
     return(ToNormalNotation(ToLiteral(chromosome.ToString())));
 }
Example #46
0
 public bool Equals(IChromosome other) => UcscName == other.UcscName;
        private static void WritePredictions(PredictionWriter writer, IReadOnlyList <MutableTranscript> transcripts,
                                             Func <MutableTranscript, string> predictionFunc, IChromosome chromosome)
        {
            var predictionDict = new Dictionary <string, List <int> >(StringComparer.Ordinal);

            for (var transcriptIndex = 0; transcriptIndex < transcripts.Count; transcriptIndex++)
            {
                var    transcript     = transcripts[transcriptIndex];
                string predictionData = predictionFunc(transcript);
                if (predictionData == null)
                {
                    continue;
                }

                if (predictionDict.TryGetValue(predictionData, out var transcriptIdList))
                {
                    transcriptIdList.Add(transcriptIndex);
                }
                else
                {
                    predictionDict[predictionData] = new List <int> {
                        transcriptIndex
                    }
                };
            }

            writer.Write(chromosome, predictionDict);
        }
Example #48
0
        private static (PredictionCacheStaging Staging, Prediction[] Predictions) GetPredictionStaging(ILogger logger,
                                                                                                       string description, IEnumerable <ITranscript> transcripts, IChromosome chromosome, IReadOnlyList <Prediction> oldPredictions,
                                                                                                       PredictionCacheReader reader, Func <ITranscript, int> indexFunc, int numRefSeqs)
        {
            logger.Write($"- retrieving {description} predictions... ");

            var indexSet          = GetUniqueIndices(transcripts, indexFunc);
            var lut               = reader.Header.Lut;
            var predictionsPerRef = GetPredictions(indexSet, chromosome, numRefSeqs, oldPredictions);
            var staging           = new PredictionCacheStaging(reader.Header.Header, lut, predictionsPerRef);

            logger.WriteLine($"found {indexSet.Count} predictions.");
            return(staging, predictionsPerRef[chromosome.Index]);
Example #49
0
 private static string GetOutputStub(IChromosome chromosome, Source source) => Path.Combine(_outputDirectory,
                                                                                            $"{chromosome.UcscName}_{_referencePosition}_{_referenceEndPosition}_{GetSource(source)}");
 public double Evaluate(IChromosome chromosome)
 {
     return(Evaluate((ScheduleChromosome)chromosome));
 }
Example #51
0
        static void OneGAStart()
        {
            try {
                mostBestChromosome = null;
                var population = GetIntPopulation();
                var fitness    = GetFitness();
                var selection  = GetSelection();
                var crossover  = GetCrossover();
                var mutation   = GetMutation();


                var ga = GA = new GeneticAlgorithm(population, fitness, selection, crossover, mutation);
                ga.FitnessIsIdempotent = false;
                ga.Termination         = GetTermination();

                Log.Information("Generation: The strongest algorithm GITC.");

                var latestFitness = 0.0;

                ga.PopulationPrepared += (sender, e) => {
                    ResultMap.Reset();
                    ResultMap.EvalResults(GA);
                };

                ga.GenerationRan += (sender, e) => {
                    var bestChromosome = ga.Population.CurrentGeneration.BestChromosome;
                    var bestFitness    = bestChromosome.Fitness.Value;

                    if (mostBestChromosome == null)
                    {
                        mostBestChromosome = bestChromosome;
                        mostBestChromosomes.Add(mostBestChromosome);
                    }
                    else if (!mostBestChromosomes.Any(x => x.Equals(bestChromosome)))
                    {
                        var result = ResultMap.GetFightResult(mostBestChromosome, bestChromosome, 5);
                        if (result < 0)
                        {
                            mostBestChromosome = bestChromosome;
                            mostBestChromosomes.Add(mostBestChromosome);
                            Log.Warning("Most Best Chromosome changed to: {0}", mostBestChromosome.GetTransferedString());
                        }
                    }


                    latestFitness = bestFitness;
                    var phenotype = bestChromosome.GetTransferedString();

                    Log.Information(
                        "Generation {0,2}: List: \r\n\t{1}",
                        ga.GenerationsNumber,
                        string.Join("\r\n\t",
                                    ga.Population.CurrentGeneration.Chromosomes
                                    .OrderByDescending(x => x.Fitness)
                                    .Select(x => "R#" + String.Format("{0,3}", x.Fitness) + " -> " + x.GetTransferedString())
                                    )
                        );
                    Log.Warning(
                        "Generation {0,2}: Best: ({1}) = {2}. Most Best Chromosome: ({3})",
                        ga.GenerationsNumber,
                        phenotype,
                        bestFitness,
                        mostBestChromosome.GetTransferedString()
                        );
                };

                ga.Start();
            } catch (Exception e) {
                Log.Error(e, "Exception is occured while");
            }

            //Console.WriteLine("Generation is ended.");
            Log.Warning("Most Best Chromosome equal: ({0})", mostBestChromosome.GetTransferedString());
            Log.Information("Generation is ended.");
        }
Example #52
0
 private static void AddChromosome(IChromosome chromosome)
 {
     RefIndexToChromosome[chromosome.Index]      = chromosome;
     RefNameToChromosome[chromosome.EnsemblName] = chromosome;
     RefNameToChromosome[chromosome.UcscName]    = chromosome;
 }
Example #53
0
        private void ShowView(string guid)
        {
            try
            {
                Cursor.Current = Cursors.WaitCursor;
                var p = Controller.GetView(guid);
                this.Text             = "Start Page";
                Controller.ActiveView = p;
                if (p == null)
                {
                    return;
                }
                else if (p is ProjectController)
                {
                    var pController = p as ProjectController;

                    //set new data on panel
                    if (pController.Project.DataSet == null)
                    {
                        expPanel1.ResetExperimentalPanel();
                    }
                    else
                    {
                        expPanel1.SetDataSet(pController.Project.DataSet);
                    }

                    //project info
                    infoPanel1.InfoText = pController.Project.ProjectInfo;

                    //prepare callbacks for update model from GUI
                    expPanel1.CreateModel = CreateModel;
                    expPanel1.UpdateModel = UpdateModel;

                    //set windows title
                    this.Text = pController.Project.FilePath;
                }//show model on view
                else if (p is ModelController)
                {
                    var mController = p as ModelController;
                    mController.SetActiveData();
                    //function set
                    var funs = mController.GetFunctionset();
                    funPanel1.ResetFunctionSet();
                    funPanel1.FunctionSetFromString(funs);

                    //parameters
                    var gpType     = mController.Model.ExpData.GetOutputColumnType();
                    var gpEncoding = mController.Model.ExpData.GetOutputColumnEncoding();
                    parPanel1.InitializeControls(gpType, gpEncoding);
                    //set parameters from active data
                    parPanel1.ParametersFromString(mController.GetParameters());

                    // GP run
                    //set termination criteria is included
                    mController.SetRunPanel(mController.ActiveData.RunPanelData);
                    runPanel1.ActivatePanel(mController.ActiveData.RunPanelData);

                    //GP Solution
                    resPanel1.EvaluateResults = mController.Model.ModelEvaluation;
                    if (mController.Model.Factory.ProgresReport.BestSolution != null)
                    {
                        IChromosome sol = mController.Model.Factory.ProgresReport.BestSolution as IChromosome;
                        resPanel1.ReportResult(sol, mController.Model.Factory.Parameters);
                    }
                    else
                    {
                        resPanel1.ReportResult(null, null);
                    }

                    //GP Validation
                    mController.SetTestPanel(mController.ActiveData.TestPanelData);
                    testPanel1.ActivatePanel(mController.ActiveData.TestPanelData);

                    //set windows title
                    this.Text = mController.Parent.Project.FilePath;

                    mController.IsActive = true;
                }
            }
            catch (Exception)
            {
                throw;
            }
            finally
            {
                //back normal cursor
                Cursor.Current = Cursors.Default;
            }
        }
Example #54
0
 public PhylopItem(IChromosome chromosome, int position, double score)
 {
     Chromosome = chromosome;
     Position   = position;
     Score      = Math.Round(score, 1, MidpointRounding.AwayFromZero);
 }
Example #55
0
        public void Draw(IChromosome bestChromosome)
        {
            var c = bestChromosome as GhostwriterChromosome;

            Console.WriteLine("Text: {0}", c.GetText());
        }
Example #56
0
 /// <summary>
 /// Add chromosome to the population.
 /// </summary>
 ///
 /// <param name="chromosome">Chromosome to add to the population.</param>
 ///
 /// <remarks><para>The method adds specified chromosome to the current population.
 /// Manual adding of chromosome maybe useful, when it is required to add some initialized
 /// chromosomes instead of random.</para>
 ///
 /// <para><note>Adding chromosome manually should be done very carefully, since it
 /// may break the population. The manually added chromosome must have the same type
 /// and initialization parameters as the ancestor passed to constructor.</note></para>
 /// </remarks>
 ///
 public void AddChromosome(IChromosome chromosome)
 {
     chromosome.Evaluate(fitnessFunction);
     population.Add(chromosome);
 }
 public ResultDictionary(FightExecuter fightExecuter)
 {
     Chromosomes        = new Dictionary <int, IChromosome>();
     BestChromosome     = null;
     this.FightExecuter = fightExecuter;
 }
Example #58
0
 public bool PassedTheEnd(IChromosome chromosome, int position) => _genomicRangeChecker.OutOfRange(chromosome, position);
Example #59
0
        private Chromosome setBestSolution(IChromosome chromosome)
        {
            var c = chromosome.Clone(true) as Chromosome;

            return(c);
        }
 public int GetFightResult(IChromosome chromosome1, IChromosome chromosome2, int count)
 {
     return(FightExecuter.GetCompetitionResult(chromosome1, chromosome2, count));
 }