public Tuple<IIndividual<Wrapper<LearningObject>>, IIndividual<Wrapper<LearningObject>>> CrossoverFunc(IIndividual<Wrapper<LearningObject>> individualA, IIndividual<Wrapper<LearningObject>> individualB)
        {
            int minlen = Math.Min(individualA.Chromosome.Genes.Count, individualB.Chromosome.Genes.Count);
            Tuple<IIndividual<Wrapper<LearningObject>>, IIndividual<Wrapper<LearningObject>>> tmpTuple;
            if (minlen > 2)
            {
                var fistChild = CrossIndividuals(individualA, individualB);
                var secondChild = CrossIndividuals(individualB, individualA);
                tmpTuple = new Tuple<IIndividual<Wrapper<LearningObject>>, IIndividual<Wrapper<LearningObject>>>(fistChild, secondChild);
            }
            else
            {
                IIndividual<Wrapper<LearningObject>> ind1 = new Individual<Wrapper<LearningObject>>();
                foreach (var gene in individualA.Chromosome.Genes)
                {
                    ind1.Chromosome.Genes.Add(new Wrapper<LearningObject>(gene.Used, gene.Value));
                }

                IIndividual<Wrapper<LearningObject>> ind2 = new Individual<Wrapper<LearningObject>>();
                foreach (var gene in individualB.Chromosome.Genes)
                {
                    ind2.Chromosome.Genes.Add(new Wrapper<LearningObject>(gene.Used, gene.Value));
                }

                tmpTuple = new Tuple<IIndividual<Wrapper<LearningObject>>, IIndividual<Wrapper<LearningObject>>>(ind1, ind2);
            }

            return tmpTuple;
        }
예제 #2
0
파일: Population.cs 프로젝트: jswk/GA-BO
 public bool containsIndividual(IIndividual ind)
 {
     foreach (var i in individuals)
         if (i.GetHashCode() == ind.GetHashCode())
             return true;
     return false;
 }
예제 #3
0
 /// <summary>
 /// Constructor
 /// </summary>
 public Population(int size,
     IIndividual ancestor,
     IFitnessFunction fitnessFunction,
     ISelection selectionMethod,
     int numberIterations)
 {
     FitnessFunction = fitnessFunction;
     Selection = Replacement = selectionMethod;
     PopulationSize = size;
     firstSelectionCount = size;
     firstReplacementCount = ((int)(size / 2)) % 2 == 0 ? (int)(size / 2) : (int)(size / 2) + 1;
     iterations = numberIterations;
     // Agregar el ancestro a la poblacion
     ancestor.Evaluate(fitnessFunction);
     Individuals.Add(ancestor);
     // Se agregan mas cromosomas a la poblacion
     for (int i = 1; i < size; i++)
     {
         // Se crea un nuevo cromosoma al azar
         IIndividual c = ancestor.CreateRandomIndividual();
         // se calcula su aptitud
         c.Evaluate(fitnessFunction);
         // Se lo agrega a la poblacion
         Individuals.Add(c);
     }
 }
 public StrongholdWisdom(ENTITY[] entitys, IIndividual player, IMapGate gate, IMapFinder finder)
 {
     _Ids = new Queue<Guid>();
     _Entitys = entitys;
     _Player = player;
     _Gate = gate;
     _Finder = finder;
 }
예제 #5
0
 /// <summary>
 /// Constructor
 /// </summary>
 public Population(int size,
     IIndividual ancestor,
     IFitnessFunction fitnessFunction,
     ISelection selectionMethod,
     double randomSelectionPortion,
     int iterations)
     : this(size, ancestor, fitnessFunction, selectionMethod, iterations)
 {
     randomSelectionPortion = Math.Max(0, Math.Min(0.5, randomSelectionPortion));
 }
 public static void MutationFunc(IIndividual<Wrapper<MyValuableClass>> individual, IGAconfiguration gaConfiguration)
 {
     foreach (var gene in individual.Chromosome.Genes)
     {
         if (gaConfiguration.MutationProbability != null && GAUtils.GetProbability(gaConfiguration.MutationProbability.Value))
         {
             gene.Value.MyVal += GAUtils.GetNextDouble() > 0.5 ? -1 : 1;
         }
     }
 }
예제 #7
0
 /// <summary>
 /// Constructor
 /// </summary>
 public Population(int size,
     IIndividual ancestor,
     IFitnessFunction fitnessFunction,
     ISelection selectionMethod,
     int iterations,
     double mutationRate)
     : this(size, ancestor, fitnessFunction, selectionMethod, iterations)
 {
     MutationRate = mutationRate;
 }
예제 #8
0
        public IIndividual BreedWith(IIndividual mate)
        {
            if (mate == this)
            {
                return null;
            }

            var newGenome = Current.Zip((mate as Individual).Current, (father, mother) => Random.Next(0, 100) > 50 ? father : mother);

            return CreateIndividual(newGenome);
        }
        public static double IndividualEvaluateFunc(IIndividual<Wrapper<MyValuableClass>> individual)
        {
            int ff = individual.Chromosome.Genes.Sum(gene => gene.Value.MyVal);
            foreach (var gene in individual.Chromosome.Genes)
            {
                ff +=gene.Value.MyVal;
            }

            ff = Math.Abs(ff);
            return ff;
        }
예제 #10
0
 public void Left(IIndividual individual)
 {
     Visible visible;
     if (_Set.TryGetValue(individual.Id, out visible))
     {
         this._QuadTree.Remove(visible);
         this._Set.Remove(individual.Id);
         _EntranceSet.Remove(visible);
         visible.Release();
     }
 }
예제 #11
0
        private void _Join(IIndividual individual)
        {
            var v = new Visible(individual);
            v.Initial();
            this._Set.Add(individual.Id , v);
            this._QuadTree.Insert(v);

            if(individual.EntityType == ENTITY.ENTRANCE)
            {
                _EntranceSet.Add(v);
            }
        }
예제 #12
0
파일: Island.cs 프로젝트: jswk/GA-BO
 private void actualizeBest()
 {
     lock (currentPopulation)
     {
             foreach (IIndividual ind in currentPopulation.individuals)
                 if (ind.value() < bestIndividual.value())
                 {
                     bestIndividual = ind.duplicate();
                     Console.WriteLine("best " + bestIndividual.value());
                 }
         //get best from current population
     }
 }
예제 #13
0
        public void Cross(IIndividual parent1, IIndividual parent2)
        {
            /* Скрещивание между двумя родителями */
            int crossPoint = rand.Next(1, parent1.Genes.Count);

            Child1 = new GameEnvironment();
            Child2 = new GameEnvironment();

            Child1.Genes.Clear();
            Child2.Genes.Clear();

            Child1.Genes.AddRange(parent1.Genes.GetRange(0, crossPoint));
            Child1.Genes.AddRange(parent2.Genes.GetRange(crossPoint, parent2.Genes.Count - crossPoint));

            Child2.Genes.AddRange(parent2.Genes.GetRange(0, crossPoint));
            Child2.Genes.AddRange(parent1.Genes.GetRange(crossPoint, parent1.Genes.Count - crossPoint));
        }
        /// <summary>
        /// Evalua al individuo
        /// </summary>
        /// <param name="chromosome">
        /// Individuo a evaluar
        /// </param>
        /// <returns>
        /// Retorna el valor de aptitud del individuo
        /// </returns>
        public double Evaluate(IIndividual chromosome)
        {
            // obtener el individuo en notacion polaca
            string function = chromosome.ToString();
            double fitness = 0;
            //Se suma un error inicial proporcional a la longitud de la expresion
            //double error = ((double)function.Length)/1000;
            // para cada linea de la tabla de verdad
            for (int i = 0, n = data.GetLength(0); i < n; i++)
            {
                // cargamos el valor de los 4 bits de entrada
                variables[0] = data[i, 0];
                variables[1] = data[i, 1];
                variables[2] = data[i, 2];
                variables[3] = data[i, 3];
                try
                {
                    // evaluamos el arbol generado con estas variables
                    bool y = PolishBooleanExpression.Evaluate(function, variables);

                    // si el arbol generado difiere de la solucion
                    //se agranda el error en 1 unidad
                    //error += (y == data[i,4]) ? 0 : 1 ;
                    fitness += (y == data[i, 4]) ? 1 : 0;
                    if (i == 15 && (y == data[i, 4]))
                        fitness += 0.25;
                }
                catch
                {
                    return 0;
                }
            }

            fitness = (fitness - 16.25 < double.Epsilon) ? Math.Pow(fitness, 4) : Math.Pow(fitness, 3);
            if (fitness > 0.0)
            {
                fitness -= ((double)function.Length);
            }

            return fitness;
            //return data.GetLength(0) + 1/ (error + 1);
        }
        public static Tuple<IIndividual<Wrapper<MyValuableClass>>, IIndividual<Wrapper<MyValuableClass>>> CrossoverFunc(IIndividual<Wrapper<MyValuableClass>> individualA, IIndividual<Wrapper<MyValuableClass>> individualB)
        {
            IIndividual<Wrapper<MyValuableClass>> ind1 = new Individual<Wrapper<MyValuableClass>>();
            IIndividual<Wrapper<MyValuableClass>> ind2 = new Individual<Wrapper<MyValuableClass>>();
            int minLen = Math.Min(individualA.Chromosome.Genes.Count, individualB.Chromosome.Genes.Count);
            int crossPoint = GAUtils.GetRandom(0, minLen);
            for (int i = 0; i < minLen; i++)
            {
                if (i < crossPoint)
                {
                    ind1.Chromosome.Genes.Add((Wrapper<MyValuableClass>)individualA.Chromosome.Genes[i].Clone());
                    ind2.Chromosome.Genes.Add((Wrapper<MyValuableClass>)individualB.Chromosome.Genes[i].Clone());
                }
                else
                {
                    ind1.Chromosome.Genes.Add((Wrapper<MyValuableClass>)individualB.Chromosome.Genes[i].Clone());
                    ind2.Chromosome.Genes.Add((Wrapper<MyValuableClass>)individualA.Chromosome.Genes[i].Clone());
                }
            }

            Tuple<IIndividual<Wrapper<MyValuableClass>>, IIndividual<Wrapper<MyValuableClass>>> tmpTuple = new Tuple<IIndividual<Wrapper<MyValuableClass>>, IIndividual<Wrapper<MyValuableClass>>>(ind1, ind2);
            return tmpTuple;
        }
예제 #16
0
 public abstract bool ValidateSolution(IIndividual individual);
 public int CompareTo(IIndividual <IPolygonGene> other)
 => Fitness.CompareTo(other.Fitness);
예제 #18
0
 public IEnumerable <TodoList> GetAllTodoLists(IIndividual individual)
 {
     return(TodoListRepository.GetAll((individual)));
 }
예제 #19
0
 public GeneticIndividual(IIndividual <T> individual)
 {
     Individual  = individual ?? throw new ArgumentNullException(nameof(individual));
     Chromosomes = new Chromosome <T> [individual.NumberOfChromosomes];
 }
 private void _AttachDamage(IIndividual individual, float damage)
 {
     HitForce hit = new HitForce();
     hit.Damage = damage;
     _AttachHit(individual , hit);
 }
예제 #21
0
파일: Island.cs 프로젝트: jswk/GA-BO
        private void run()
        {
            currentPopulation = factory.createPopulation();
            bestIndividual = currentPopulation.individuals[0].duplicate();
            while (keepGoing)
            {
               IIndividual outResult = null;
               while(arrivingIndividuals.TryDequeue(out outResult))
               {
                   swapPopulation(outResult);
               } // change individuals for new

               List<IIndividual> bestsToExchange = getBestsToExchange();
               supervisor.exchangeIndividuals(this,bestsToExchange);
                // sending a best part of population to supervisior
               lock (currentPopulation)
               {
                   currentPopulation = factory.nextPopulation(currentPopulation);
               }
               actualizeBest();
                // it produces start population first, then tries to rechange population using indiviudals from queue.
               // then produce next generation of population
                // produce new populations using factory, exchange best individuals with supervisor, add arriving individuals to population...
            }
        }
        private IIndividual<Wrapper<LearningObject>> CrossIndividuals(IIndividual<Wrapper<LearningObject>> individualA, IIndividual<Wrapper<LearningObject>> individualB)
        {
            IIndividual<Wrapper<LearningObject>> ind1 = new Individual<Wrapper<LearningObject>>();
            IIndividual<Wrapper<LearningObject>> ind2 = new Individual<Wrapper<LearningObject>>();

            int length = individualA.Chromosome.Genes.Count;
            int crossPoint = GAUtils.GetRandom(1, length - 1);  //Both are equal length

            foreach (var gene in individualA.Chromosome.Genes)
            {
                ind1.Chromosome.Genes.Add(new Wrapper<LearningObject>(gene.Used, gene.Value));
            }

            foreach (var gene in individualB.Chromosome.Genes)
            {
                ind2.Chromosome.Genes.Add(new Wrapper<LearningObject>(gene.Used, gene.Value));
            }

            for (int i = 0; i < crossPoint; i++)
            {
                if (!ind1.Chromosome.Genes[i].Value.Equals(ind2.Chromosome.Genes[i].Value))
                {
                    for (int j = i + 1; j < length; j++)
                    {
                        if (ind1.Chromosome.Genes[i].Value.Equals(ind2.Chromosome.Genes[j].Value))
                        {
                            var tmpVal = ind2.Chromosome.Genes[i];
                            ind2.Chromosome.Genes[i] = ind2.Chromosome.Genes[j];
                            ind2.Chromosome.Genes[j] = tmpVal;
                            break;
                        }
                    }
                }
                else
                {
                    ind2.Chromosome.Genes[i].Used = ind1.Chromosome.Genes[i].Used;
                }
            }
            return ind2;
        }
예제 #23
0
        public List <IIndividual> Evolve(List <IIndividual> initPop)
        {
            int popSize            = initPop.Count;
            List <IIndividual> pop = initPop;

            // 开始进化
            int cnt  = 0;
            int iGen = 0;

            while (true)
            {
                if (cnt > MaxCount)
                {
                    break;
                }

                // 计算所有个体的误差 查找最优子代
                List <double> errs = new List <double>();
                IIndividual   best = pop[0];
                errs.Add(best.Error(Data));
                double minErr   = errs[0];
                bool   findBest = false;
                for (int i = 1; i < popSize; ++i)
                {
                    errs.Add(pop[i].Error(Data));
                    if (errs[i] < minErr)
                    {
                        best     = pop[i];
                        minErr   = errs[i];
                        findBest = true;
                    }
                }

                if (findBest)
                {
                    cnt = 0;
                }
                else
                {
                    cnt++;
                }

                // 输出最优个体
                Console.WriteLine(iGen);
                Console.WriteLine(best.ExprString);
                Console.WriteLine("error: " + minErr);
                Console.WriteLine();

                // 备份最好个体
                GEPIndividual bestBackup = (GEPIndividual)best.Clone();

                // 锦标赛选择 变异
                List <IIndividual> newPop = new List <IIndividual>();
                for (int i = 0; i < popSize; i += 2)
                {
                    if (errs[i] < errs[i + 1])
                    {
                        pop[i].Mutate();
                        pop[i].Optimize(Data);
                        newPop.Add(pop[i]);
                    }
                    else
                    {
                        pop[i + 1].Mutate();
                        pop[i + 1].Optimize(Data);
                        newPop.Add(pop[i + 1]);
                    }
                }

                // 交叉
                for (int i = 0; i < popSize / 4; ++i)
                {
                    int           r1 = RandomUtil.U(0, popSize / 2);
                    int           r2 = RandomUtil.U(0, popSize / 2);
                    GEPIndividual p1 = (GEPIndividual)newPop[r1].Clone();
                    GEPIndividual p2 = (GEPIndividual)newPop[r2].Clone();
                    p1.Cross(p2);
                    p1.Optimize(Data);
                    p2.Optimize(Data);
                    newPop.Add(p1);
                    newPop.Add(p2);
                }

                // 保留精英
                newPop[0] = bestBackup;

                pop = newPop;

                iGen++;
            }

            return(pop);
        }
 /// <summary>
 /// Mutate the specified individual.
 /// </summary>
 /// <param name="individual">The individual.</param>
 /// <param name="mutation_probabilty">The probability to mutate each indiviudal.</param>
 public abstract void Mutate(IIndividual individual, float mutation_probabilty);
예제 #25
0
파일: ContactHead.cs 프로젝트: athulg/C-
 public ContactHead(IIndividual builder)
 {
     _builder = builder;
 }
        public double IndividualEvaluateFunc(IIndividual<Wrapper<LearningObject>> individual)
        {
            double fitnessFunction = 0;
            HashSet<Wrapper<LearningObject>> currentSetOfLO = new HashSet<Wrapper<LearningObject>>();
            HashSet<Wrapper<LearningObject>> temporarySetOfLO = new HashSet<Wrapper<LearningObject>>();
            HashSet<Wrapper<LearningObject>> setofConnectedLOs = new HashSet<Wrapper<LearningObject>>();

            foreach (var courseOutcome in _task.Outcomes)
            {
                foreach (var gene in individual.Chromosome.Genes)
                {
                    if (gene.Used) //if gene is switched on in the gene
                    {
                        foreach (var loOutcome in gene.Value.Outcomes)
                        {
                            Relation.RelationType relationType;
                            if (IsConnected(loOutcome.KnowledgeId, courseOutcome.KnowledgeId, out relationType))
                            {
                                switch (relationType)
                                {
                                    case Relation.RelationType.NoConnection:
                                        fitnessFunction += COEFFICIENT_FOR_EXACT_CONNECTION;
                                        break;
                                    case Relation.RelationType.SuggestedOrder:
                                        fitnessFunction += COEFFICIENT_FOR_SUGGESTEDORDER_CONNECTION;
                                        break;
                                    case Relation.RelationType.IsRequiredBy:
                                        fitnessFunction += COEFFICIENT_FOR_ISREQUIREDBY_CONNECTION;
                                        break;
                                    case Relation.RelationType.HasPart:
                                        fitnessFunction += COEFFICIENT_FOR_HASPART_CONNECTION;
                                        break;
                                    default:
                                        throw new Exception("Relation type is not proper");
                                }

                                int levelsDiffNum = Math.Abs(loOutcome.BloomsLevel - courseOutcome.BloomsLevel);
                                fitnessFunction += Math.Pow(COEFFICIENT_FOR_EACH_LEVEL_OF_DIFFERENCE_BY_LEVEL, levelsDiffNum);
                                temporarySetOfLO.Add(gene);
                            }
                            else
                            {
                                fitnessFunction += COEFFICIENT_FOR_USELESCONNECTION_CONNECTION;
                            }
                        }
                    }
                }
            }

            do
            {
                foreach (var item in currentSetOfLO)
                {
                    setofConnectedLOs.Add(item);
                }
                currentSetOfLO = new HashSet<Wrapper<LearningObject>>(temporarySetOfLO);
                temporarySetOfLO = new HashSet<Wrapper<LearningObject>>();

                foreach (var selectedItem in currentSetOfLO)
                {
                    foreach (var gene in individual.Chromosome.Genes)
                    {
                        if (gene.Used)
                        {
                            if (!setofConnectedLOs.Contains(gene) && !currentSetOfLO.Contains(gene))
                            {
                                foreach (var selecteditemPrerequisite in selectedItem.Value.Prerequisites)
                                {
                                    foreach (var newObjectOutcome in gene.Value.Outcomes)
                                    {
                                        Relation.RelationType relationType;
                                        if (IsConnected(newObjectOutcome.KnowledgeId, selecteditemPrerequisite.KnowledgeId, out relationType))
                                        {
                                            switch (relationType)
                                            {
                                                case Relation.RelationType.NoConnection:
                                                    fitnessFunction += COEFFICIENT_FOR_EXACT_CONNECTION;
                                                    break;
                                                case Relation.RelationType.SuggestedOrder:
                                                    fitnessFunction += COEFFICIENT_FOR_SUGGESTEDORDER_CONNECTION;
                                                    break;
                                                case Relation.RelationType.IsRequiredBy:
                                                    fitnessFunction += COEFFICIENT_FOR_ISREQUIREDBY_CONNECTION;
                                                    break;
                                                case Relation.RelationType.HasPart:
                                                    fitnessFunction += COEFFICIENT_FOR_HASPART_CONNECTION;
                                                    break;
                                                default:
                                                    throw new Exception("Relation type is not proper");

                                            }
                                            temporarySetOfLO.Add(gene);
                                            int levelsDiffNum = Math.Abs(newObjectOutcome.BloomsLevel - selecteditemPrerequisite.BloomsLevel);
                                            fitnessFunction += Math.Pow(COEFFICIENT_FOR_EACH_LEVEL_OF_DIFFERENCE_BY_LEVEL,
                                                levelsDiffNum);
                                        }
                                        else
                                        {
                                            fitnessFunction += COEFFICIENT_FOR_USELESCONNECTION_CONNECTION;
                                        }
                                    }
                                }
                            }
                        }
                    }
                }

            } while (temporarySetOfLO.Any());

            foreach (var item in currentSetOfLO)
            {
                setofConnectedLOs.Add(item);
            }

            int usedGenesNum = individual.Chromosome.Genes.Count(gene => gene.Used);

            fitnessFunction += (usedGenesNum - setofConnectedLOs.Count) * COEFFICIENT_FOR_REDUNDANT_LO_IN_COURSE;

            //Fines for number of LOs
            HashSet<ObjectId> variousDomainsInCourse = new HashSet<ObjectId>();
            foreach (var gene in individual.Chromosome.Genes)
            {
                if (gene.Used)
                {
                    variousDomainsInCourse.Add(gene.Value.Domain.Id);
                    fitnessFunction += COEFFICIENT_FOR_EACH_LO_USING;
                }
            }
            //Fines for variety of LOs domains in course
            fitnessFunction += Math.Pow( COEFFICIENT_FOR_VARIETY_OF_DOMAINS_IN_COURSE, variousDomainsInCourse.Count);

            return fitnessFunction;
        }
예제 #27
0
        /// <summary>
        /// Compares two individual by their fitness values. Lower fitness go first.
        /// </summary>
        /// <param name="other">The individual to compare to.</param>
        /// <returns>An integer specifying whether this individual is less than, equal to, or greater than other.</returns>
        public int CompareTo(IIndividual other)
        {
            if (other == null) return 1;

            return this.Fitness.CompareTo(other.Fitness);
        }
        private void _AttachHit(IIndividual target, HitForce hit_force)
        {
            if (_Attacked.Contains(target.Id) == false)
            {
                _Attacked.Add(target.Id);

                if (_Caster.HasHit() && _HitNextsEvent !=null)
                    _HitNextsEvent(_Caster.Data.HitNexts);

                target.AttachHit(_Player.Id , hit_force);

            }
        }
예제 #29
0
        public double CountMatches(IIndividual <T> individual)
        {
            var index = 0;

            return(individual.Genotype.Count(bit => (matches[index++].Equals(1)).Equals(bit)));
        }
예제 #30
0
 public IIndividual <Rule> Crossover(IIndividual <Rule> other, int point)
 {
     return(new RuleIndividual(rules.Take(point - 1).Concat(new [] { rules[point].Crossover(other.Genotype[point], point) }).Concat(other.Genotype.Skip(point))));
 }
예제 #31
0
파일: Island.cs 프로젝트: jswk/GA-BO
 // change the worst individual in population to another individual
 private void swapPopulation(IIndividual individual)
 {
     IIndividual worstIndividual = null;
     lock (currentPopulation)
     {
         foreach (IIndividual ind in currentPopulation.individuals)
         {
             if (ind.GetHashCode() == individual.GetHashCode()) //if we already have such individual, do not let him in
                 return;
             if (worstIndividual == null)
             {
                 worstIndividual = ind;
             }
             if (ind.value() > worstIndividual.value())
             {
                 worstIndividual = ind;
             }
         }
         var i = currentPopulation.individuals.IndexOf(worstIndividual);
         currentPopulation.individuals[i] = individual; //changing the worst for new.
         //but using this way we could add a lot of weak Individuals and change only one in population if addaing individuals are weak than existing on the island
     }
 }
예제 #32
0
        public IIndividual <bool> Solve()
        {
            var matcher = GetMatcher(@"Data\data1.txt");
            Func <IIndividual <bool>, double> fitnessFunction = matcher.CountMatches;

            const int maximumIterations = 20; //This is fast, we may as well do loads.

            IIndividual <bool> best = null;
            var logger = new AverageLogger();

            for (var run = 0.0; run <= 2; run += 0.1)
            {
                Console.WriteLine("Running one with pop=" + run);

                var iteration = 0;
                var fitness   = 0; //This is the fitness sum so far, for later averaging.

                while (iteration++ < maximumIterations)
                {
                    //Make a new population with some reasonable default values
                    var population = new Population <IIndividual <bool>, bool>(100, 64,
                                                                               (size, rng) => new BoolIndividual(size, rng), ind => ind, fitnessFunction);
                    population.MutationMultiplier = run;
                    //and a logger
                    var runLogger = new FitnessLogger();

                    var i = 0;
                    while (true)
                    {
                        //Run a generation
                        var generation = population.Generation();
                        //Find the best individual
                        best = generation.OrderBy(fitnessFunction).Last();
                        //Find the average fitness
                        var average = generation.Select(fitnessFunction).Sum() / generation.Count;
                        //Log what we have
                        runLogger.LogFitness(fitnessFunction(best), average);

                        if ((int)fitnessFunction(best) == 64)
                        {
                            //If we've found the correct answer, we need to add how long it took us to the total and stop
                            fitness += i;
                            break;
                        }
                        if (i++ > 500)
                        {
                            //If we've taken way too long, we just add how far we've got and stop trying
                            fitness += i;
                            break;
                        }
                    }

                    //Every run we save how it went for later crunching
                    runLogger.Save("one-mutation-" + run + ".csv");
                }
                //And we log how long everything took us, on average.
                logger.LogFitness(fitness / maximumIterations);
            }
            logger.Save("one-mutation-runs.csv");
            return(best);
        }
예제 #33
0
 private static int MyCompare(IIndividual x, IIndividual y)
 {
     return x.value().CompareTo(y.value());
 }
예제 #34
0
 public double CountMatches(IIndividual <Rule> individual)
 {
     return(CountMatches(individual, false));
 }
예제 #35
0
 public Population(int size)
 {
     Individuals = new IIndividual[size];
 }
예제 #36
0
 public int CompareTo(IIndividual other, ICompareCriteria criteria)
 {
     return(criteria.Compare(this, other));
 }
예제 #37
0
 public TodoList GetTodoListForUserID(string listID, IIndividual individual)
 {
     throw new NotImplementedException();
 }
예제 #38
0
 public IIndividual GetReplacement(IPopulation population, IIndividual incompatibleIndividual,
                                   IGenotype[] parents)
 {
     return(incompatibleIndividual);
 }
        public bool Equals(IIndividual <IPolygonGene> other)
        {
            PolygonIndividual compared = other as PolygonIndividual;

            return(compared?.Polygon == this.Polygon && compared?.Name == this.Name);
        }
예제 #40
0
 public void ReplaceIndividual(IIndividual existingIndividual, IIndividual individual)
 {
     population.Remove(existingIndividual);
     population.Add(individual);
 }
예제 #41
0
 public abstract void MakeSolutionValid(IIndividual individual);
예제 #42
0
 protected double getIndividualFitness(IIndividual ind)
 {
     // assumes fitness > 0
     return((_config.maximize) ? ind.value() : 1.0 / ind.value());
 }
예제 #43
0
 public virtual int CompareTo([AllowNull] IIndividual other)
 {
     return(this.Fitness - other.Fitness);
 }
예제 #44
0
 public void SetCurrentActor(IIndividual actor)
 {
     CurrentActor = actor;
 }
 public double GetValue(IIndividual x)
 {
     return(Function(x.Phenotype));
 }
예제 #46
0
 private void _Attach(IIndividual[] actors)
 {
     foreach (var actor in actors)
     {
         _Attach(actor);
     }
 }
        private void MutationFunc(IIndividual<Wrapper<LearningObject>> individual, IGAconfiguration gaConfiguration)
        {
            if (gaConfiguration.MutationProbability != null)
            {
                foreach (var gene in individual.Chromosome.Genes)
                {
                    if (GAUtils.GetProbability(gaConfiguration.MutationProbability.Value))
                    {
                        gene.Used = !gene.Used;
                    }
                }

                for (int i = 0; i < individual.Chromosome.Genes.Count; i++)
                {
                    if (GAUtils.GetProbability(gaConfiguration.MutationProbability.Value))
                    {
                        int newPos = GAUtils.GetRandom(0, individual.Chromosome.Genes.Count);
                        if (i != newPos)
                        {
                            var tmpVal = individual.Chromosome.Genes[newPos];
                            individual.Chromosome.Genes[newPos] = individual.Chromosome.Genes[i];
                            individual.Chromosome.Genes[i] = tmpVal;
                        }
                    }
                }
            }
        }
예제 #48
0
 public InverOverPopulation(float changeParentProbability, int size)
 {
     ChangeParentProbability = changeParentProbability;
     Individuals             = new IIndividual[size];
 }
 double IndividualEvaluateFunc(IIndividual<Wrapper<LearningObject>> individual)
 {
     return GAUtils.GetRandom(0, 1000);
     //return 0;
 }
예제 #50
0
        private Regulus.CustomType.Polygon.CollisionResult _Collide(IIndividual individual, Polygon polygon, Vector2 velocity)
        {
            var result = Polygon.Collision(polygon, individual.Mesh, velocity);

            return(result);
        }
예제 #51
0
 private static int MyCompare(IIndividual x, IIndividual y)
 {
     return(x.value().CompareTo(y.value()));
 }
예제 #52
0
 public Visible(IIndividual noumenon)
 {
     this.Noumenon = noumenon;
 }
예제 #53
0
 private Regulus.CustomType.Polygon.CollisionResult _Collide(IIndividual individual, Polygon polygon, Vector2 velocity)
 {
     var result = Polygon.Collision(polygon, individual.Mesh, velocity);
     return result;
 }
예제 #54
0
 public void JoinStaff(IIndividual individual)
 {
     this._Join(individual);
 }
예제 #55
0
 public Niche(IIndividual referece)
 {
     Reference = referece;
     Members   = new List <IIndividual>();
     Members.Add(Reference);
 }
예제 #56
0
        /// <summary>
        /// Performs crossover to generate a new child. The crossover type is specifed in the
        /// Settings property.
        /// </summary>
        /// <param name="mate">The individual to crossover with.</param>
        /// <returns>A new child individual</returns>
        public IIndividual Crossover(IIndividual mate)
        {
            if (mate.GetType() != typeof(LanderIndividual))
            {
                throw new ArgumentException("Mate must be a LanderIndividual");
            }

            // Get the weights in a easier to use form.
            this.weights = this.neuralNet.GetAllWeights();
            List<double> mateWeights = ((LanderIndividual)mate).neuralNet.GetAllWeights();

            // Create the child weights with a copy of this individual's weights initially
            List<double> childWeights = new List<double>(this.weights);

            switch (this.settings.CrossoverAlgorithm)
            {
                case LanderIndividualSettings.CrossoverType.OnePoint:
                    // Copy the mate's weights into the first section
                    int crossoverPoint = this.RandomGenerator.Next(this.weights.Count);
                    for (var i = 0; i < crossoverPoint; i++)
                    {
                        childWeights[i] = mateWeights[i];
                    }
                    break;
                case LanderIndividualSettings.CrossoverType.TwoPoint:
                    // Copy the mate's weights into the first section
                    int firstPoint = this.RandomGenerator.Next(this.weights.Count);
                    int secondPoint = this.RandomGenerator.Next(this.weights.Count);

                    if (secondPoint < firstPoint)
                    {
                        int temp = firstPoint;
                        firstPoint = secondPoint;
                        secondPoint = temp;
                    }

                    for (var i = 0; i < firstPoint; i++)
                    {
                        childWeights[i] = mateWeights[i];
                    }

                    for (var i = secondPoint; i < childWeights.Count; i++)
                    {
                        childWeights[i] = mateWeights[i];
                    }
                    break;
                case LanderIndividualSettings.CrossoverType.Uniform:
                    for (int i = 0; i < childWeights.Count; i++)
                    {
                        if (RandomGenerator.NextDouble() < 0.5)
                        {
                            childWeights[i] = mateWeights[i];
                        }
                    }
                    break;
                default:
                    throw new ArgumentException("Lander individual crossover type not supported");
            }

            // Create the new child
            LanderIndividual child = new LanderIndividual(this.RandomGenerator);
            child.Settings = this.Settings;
            child.neuralNet.SetAllWeights(childWeights);

            return child;
        }
예제 #57
0
 protected double getIndividualFitness(IIndividual ind)
 {
     // assumes fitness > 0
     return (_config.maximize) ? ind.value() : 1.0 / ind.value();
 }
예제 #58
0
        //Epic name for a function.
        //Kills, replaces and chooses who mutates or crossovers
        private void Reap()
        {
            var pop    = _Population;
            var newPop = new List <EvaluatedIndividual>(pop.Count);

            //Elite:
            for (var ii = 0; ii < EliteIndexEnd; ++ii)
            {
                newPop.Add(pop[ii]);
            }

            //Changed individuals
            for (int ii = EliteIndexEnd; ii < EliminateIndexBegin; ++ii)
            {
                int dice = _Rng.Next(0, 12);
                if (dice < VariationSettings.SurvivalRatio)
                {
                    newPop.Add(pop[ii]); //Individual survived by chance
                }
                else if (dice < VariationSettings.SurvivalRatio + VariationSettings.MutationRatio)
                {
                    //Mutated
                    int         mutatedIndex = _Rng.Next(0, EliminateIndexBegin);
                    IIndividual newInd       = pop[mutatedIndex]
                                               .Individual
                                               .Mutate(MutationProbability, _mutationSigma, _Rng);
                    newPop.Add(newInd.ToEI());
                }
                else
                {
                    //Crossover
                    var parents      = new List <IIndividual>(5);
                    var numOfParents = _Rng.Next(2, 5); //pick 2,3 or 4 parents
                    while (parents.Count < numOfParents)
                    {
                        //Pick a random surviving parent
                        var index = _Rng.Next(0, EliminateIndexBegin);
                        //Select him probabilistically based on rank (index)
                        float prob = ((float)(pop.Count - index)) / pop.Count;//Probability
                        if (_Rng.ProbabilityPass(prob))
                        {
                            parents.Add(pop[index].Individual);
                        }
                    }
                    //Add the crossed individual
                    newPop.Add(_Crossover(parents, _Rng).ToEI());
                }
            }

            //Fresh individuals for the failing percent
            for (var ii = EliminateIndexBegin; ii < pop.Count; ++ii)
            {
                EvaluatedIndividual ei;
                if (_Rng.Next(0, 2) == 0)
                {
                    ei = _Generate(_Rng).ToEI();
                }
                else
                {
                    int index = _Rng.Next(0, EliteIndexEnd);
                    ei =
                        pop[index]
                        .Individual
                        .Mutate(MutationProbability, _mutationSigma, _Rng)
                        .ToEI();
                }
                newPop.Add(ei);
            }

            _Population = newPop;
        }
예제 #59
0
 private void _Attach(IIndividual actor)
 {
     if (_Targets.ContainsKey(actor.Id) == false)
     {
         _Targets.Add(actor.Id , actor);
     }
 }
예제 #60
0
        public List <IIndividual> Execute(Action <int, double, double> logTabuSearch, Action <List <double> > logOutro,
                                          IIndividual initialSolution = null, int startingTabuSearchForLogging = 0)
        {
            var bestFitnesses  = new List <double>();
            var finalSolutions = new List <IIndividual>();

            for (var i = 0; i < Parameters.NumAlgorithmIterations; i++)
            {
                var numTabuSearches = 0;

                var currentSolution = initialSolution ?? InitialSolution(Problem.CityIds);

                var bestSolution = currentSolution.DeepCopy();
                var bestFitness  = Problem.Fitness(bestSolution);

                var tabuList = new LinkedList <IIndividual>();
                tabuList.AddFirst(bestSolution);

                var neighbourhoodHasPotentialSolutions = true;

                while (numTabuSearches < Parameters.NumTabuSearches && neighbourhoodHasPotentialSolutions)
                {
                    var neighbourhoodWithFitness = NeighbourhoodWithFitness(currentSolution);

                    if (neighbourhoodWithFitness == null)
                    {
                        Console.WriteLine("NeighbourhoodWithFitness is null.");
                        return(null);
                    }

                    var bestOfNeighbourhood = Best(neighbourhoodWithFitness, tabuList);

                    if (bestOfNeighbourhood.Item1 == null)
                    {
                        neighbourhoodHasPotentialSolutions = false;
                        continue;
                    }

                    currentSolution = bestOfNeighbourhood.Item1;

                    if (bestOfNeighbourhood.Item2 > bestFitness)
                    {
                        bestSolution = currentSolution;
                        bestFitness  = bestOfNeighbourhood.Item2;
                    }

                    logTabuSearch(numTabuSearches + startingTabuSearchForLogging, bestFitness, bestOfNeighbourhood.Item2);

                    tabuList = UpdateTabuList(tabuList, currentSolution);

                    Console.WriteLine(
                        $"TABU SEARCH iteration: {i} tabu search: {numTabuSearches} bestFitness: {bestFitness}");
                    numTabuSearches++;
                }

                bestFitnesses.Add(bestFitness);
                finalSolutions.Add(bestSolution);
            }

            logOutro(bestFitnesses);
            return(finalSolutions);
        }