public IEvolvable FindMate(IEvolvable evolvable)
        {
            // return IndividualsSortedByFitness.Take(10).MaxElement(a => evolvable.DifferenceTo(a));

            // sort by difference and then take the best out of the top 10! :D
            return(Individuals.OrderByDescending(a => evolvable.DifferenceTo(a)).Take(10).OrderByDescending(a => a.Fitness).First());

            //return IndividualsSortedByFitness.Take(3).MaxElement(a => evolvable.DifferenceTo(a));
            //return Best;
            //return IndividualsSortedByFitness.MaxElement(a => evolvable.DifferenceTo(a));
        }
Beispiel #2
0
 public void ChangeReputationFor(Actor _actor, int _amount)
 {
     if (Individuals.ContainsKey(_actor))
     {
         Individuals[_actor] += _amount;
     }
     else
     {
         Individuals[_actor] = _amount;
     }
 }
Beispiel #3
0
        public void Evolve()
        {
            var nextGen   = new List <Tree <T> >(MaxPop);
            var selection = Tournament();

            nextGen.AddRange(Crossover(selection));
            nextGen.AddRange(Mutate(selection));
            nextGen.AddRange(Elitism());
            nextGen.AddRange(RampedHalfNHalf(MaxPop - nextGen.Count, MaxDepth, Terminals, Functions, GrowTerminalChance));
            Individuals.Clear();
            Individuals = nextGen;
        }
        public async Task <IActionResult> Create([Bind("IndividualId,Nicnumber,PassportNumber,FullName,DateofBirth,GenderId,Address")] Individuals individuals)
        {
            if (ModelState.IsValid)
            {
                _context.Add(individuals);
                await _context.SaveChangesAsync();

                return(RedirectToAction(nameof(Index)));
            }
            ViewData["GenderId"] = new SelectList(_context.Gender, "GenderId", "Gender1", individuals.GenderId);
            return(View(individuals));
        }
        /// <inheritdoc/>
        public override int GetHashCode()
        {
            // Overflow is fine, just wrap.
            unchecked
            {
                int hash = 17;

                hash *= 23 + Individuals.GetHashCode();

                return(hash);
            }
        }
Beispiel #6
0
        private void ProcessRootLevel(string[] lineArray)
        {
            switch (_currentRecord)
            {
            case GedcomRecordEnum.Individual:
                Individuals.Add(_currentIndividual);
                break;

            case GedcomRecordEnum.Family:
                Families.Add(_currentFamily);
                break;

            case GedcomRecordEnum.Note:
                Notes.Add(_currentNote);
                break;
            }

            if (lineArray[1] == "HEAD")
            {
                _currentRecord    = GedcomRecordEnum.Header;
                _currentSubRecord = GedcomSubRecordEnum.None;
            }
            else if (lineArray[1].IndexOf("@") >= 0)
            {
                switch (lineArray[2])
                {
                case "INDI":
                    _currentRecord     = GedcomRecordEnum.Individual;
                    _currentIndividual = new Individual {
                        Id = lineArray[1]
                    };
                    _currentSubRecord = GedcomSubRecordEnum.None;
                    break;

                case "FAM":
                    _currentRecord = GedcomRecordEnum.Family;
                    _currentFamily = new Family {
                        Id = lineArray[1]
                    };
                    _currentSubRecord = GedcomSubRecordEnum.None;
                    break;

                case "NOTE":
                    _currentRecord = GedcomRecordEnum.Note;
                    _currentNote   = new Note {
                        Id = lineArray[1]
                    };
                    _currentSubRecord = GedcomSubRecordEnum.None;
                    break;
                }
            }
        }
Beispiel #7
0
        /// <summary>
        /// Resizes the Subpopulation to a new size.  If the size is smaller, then
        /// the Subpopulation is truncated such that the higher indexed individuals
        /// may be deleted.If the size is larger, then the resulting Subpopulation will have
        /// null individuals (this almost certainly is not what you will want).
        /// </summary>
        /// <remarks>
        /// BRS: This should NEVER result in any null individuals (we're using List{T}).
        /// By changing the capacity of a list lower we free memory up for garbage collection.
        /// If what is wanted is explicit increase in capacity then we should probably have
        /// a "forceNewCapacity" flag as a second argument.
        /// </remarks>
        /// <param name="toThis">A new "Capacity" value.</param>
        public void Resize(int toThis)
        {
            var n = Individuals.Count - toThis;

            if (n <= 0)
            {
                return;         // list will grow on its own
            }
            // Hopefully this is faster than reallocating
            // and copying to a new, smaller list. Note
            // that the current Capacity of the list stays the same.
            Individuals.RemoveFromTopDesctructively(n);
        }
Beispiel #8
0
        private void AddEliteFromPreviousGeneration(List <Individual> elitisms)
        {
            if (Elitism > 0)
            {
                var worstIndividuals = Individuals.OrderBy(s => s.Fitness).Take(Elitism).ToList();

                for (var i = 0; i < elitisms.Count; i++)
                {
                    var index = Individuals.IndexOf(Individuals.Where(s => s.Fitness == worstIndividuals[i].Fitness).FirstOrDefault());
                    Individuals[index] = elitisms[i];
                }
            }
        }
Beispiel #9
0
        /**
         * Remove the individuals from current subspecies who have been mark as
         * eliminate the remain individuals will be allow to reproduce
         */
        public void RemovePoorFitnessIndividuals()
        {
            // create a new list, contain the non eliminate individuals
            IList <Individual> remainIndividuals = new List <Individual>();

            foreach (var ind in Individuals.Cast <NEATIndividual>())
            {
                if (!ind.Eliminate)
                {
                    remainIndividuals.Add(ind);
                }
            }
            Individuals = remainIndividuals;
        }
        public void CreatePopulation(Individual gen)
        {
            Individual first = new Individual();

            first.Copy(gen);
            Individuals.Add(first);

            for (int i = 1; i < NumbersOfIndividuals; ++i)
            {
                Individual individual = new Individual();
                individual.CopyGenome(Individuals[i - 1]);
                JGen.Mutation.SwapTwo(individual);
                Individuals.Add(individual);
            }
        }
        /// <summary>
        /// Returns a genome from the individual in this generation with the lowest number of completed matches.
        /// </summary>
        /// <returns>genome of a competetor from this generation</returns>
        public string PickCompetitor()
        {
            List <Individual> validCompetitors = Individuals
                                                 .OrderBy(i => i.MatchesPlayed)
                                                 .ThenBy(i => _rng.NextDouble())
                                                 .ToList();

            var best = validCompetitors.FirstOrDefault();

            //Debug.Log("Picked Individual has played " + best.MatchesPlayed);
            if (best != null)
            {
                return(best.Genome);
            }
            return(null);
        }
Beispiel #12
0
        /// <summary>
        /// Select individuals radomly. The individual can be selected only once.
        /// </summary>
        /// <param name="count">Number of individual to select</param>
        /// <returns></returns>
        private IReadOnlyList <Individual> SelectIndividualsRadomly(int count)
        {
            var selectedIndividuals = new List <Individual>();

            var individuals = Individuals.ToList();

            for (int i = 0; i < count; i++)
            {
                var individual = individuals[_random.Next(0, individuals.Count - 1)];

                individuals.Remove(individual);
                selectedIndividuals.Add(individual);
            }

            return(selectedIndividuals);
        }
        public void DeleteIndividual(Individual individual)
        {
            Requires.NotNull("individual", individual);

            string individualId = GEDCOMUtil.CreateId("I", individual.Id);

            //Remove from internal List
            Individuals.Remove(individual);

            GEDCOMIndividualRecord record = _document.SelectIndividualRecord(individualId);

            if (record == null)
            {
                //record not in repository
                throw new ArgumentOutOfRangeException();
            }

            _document.RemoveRecord(record);

            //see if individual is a child in a family
            var familyRecord = _document.SelectChildsFamilyRecord(individualId);

            if (familyRecord != null)
            {
                //remove child from family
                RemoveIndividualFromFamilyRecord(individual, familyRecord, GEDCOMTag.CHIL);
            }

            if (individual.Sex == Sex.Male)
            {
                //see if individual is a husband in a family
                foreach (GEDCOMFamilyRecord fRecord in _document.SelectHusbandsFamilyRecords(individualId))
                {
                    //remove husband from family
                    RemoveIndividualFromFamilyRecord(individual, fRecord, GEDCOMTag.HUSB);
                }
            }
            else
            {
                //see if individual is a wife in a family
                foreach (GEDCOMFamilyRecord fRecord in _document.SelectWifesFamilyRecords(individualId))
                {
                    //remove wife from family
                    RemoveIndividualFromFamilyRecord(individual, fRecord, GEDCOMTag.WIFE);
                }
            }
        }
Beispiel #14
0
        /**
         * Adjust the fitness of the individuals within this subspecies. We will use
         * the adjusted fitness to determine the expected offsprings within each
         * subspecies.
         */
        public void AdjustFitness(IEvolutionState state, int dropoffAge, double ageSignificance)
        {
            int ageDebt = (Age - AgeOfLastImprovement + 1) - dropoffAge;

            if (ageDebt == 0)
            {
                ageDebt = 1;
            }

            foreach (NEATIndividual ind in Individuals.Cast <NEATIndividual>())
            {
                // start to adjust the fitness with age information
                ind.AdjustedFitness = ind.Fitness.Value;

                // Make fitness decrease after a stagnation point dropoffAge
                // Added an if to keep species pristine until the dropoff point
                if (ageDebt >= 1)
                {
                    ind.AdjustedFitness = ind.AdjustedFitness * 0.01;
                }

                // Give a fitness boost up to some young age (niching)
                // The age-significance parameter is a system parameter
                // If it is 1, then young species get no fitness boost
                if (Age <= 10)
                {
                    ind.AdjustedFitness = ind.AdjustedFitness * ageSignificance;
                }

                // Do not allow negative fitness
                if (ind.AdjustedFitness < 0.0)
                {
                    ind.AdjustedFitness = 0.0001;
                }

                // Share fitness with the species
                // This is the explicit fitness sharing, where the the original
                // fitness
                // are dividing by the number of individuals in the species.
                // By using this, a species cannot afford to become too big even if
                // many of its
                // individual perform well
                ind.AdjustedFitness = ind.AdjustedFitness / Individuals.Count;
            }
        }
Beispiel #15
0
        private Individual SelectIndividualByTournament()
        {
            var set = Individuals.OrderBy(x => random.NextDouble());

            Individual[] competitors = set.Take(tournamentGroupSize).ToArray();
            Individual   winner      = competitors[0];

            for (int i = 1; i < competitors.Length; i++)
            {
                if (winner.Fitness < competitors[i].Fitness)
                {
                    winner = competitors[i];
                }
            }


            return(winner);
        }
Beispiel #16
0
 public void Truncate(int toThis)
 {
     // if we're dealing with an actual List<T> then reducing the capacity
     // is the easiest and fastest way to truncate. If it's an array
     // or some other form of IList<T>, then we need to use the interface.
     if (Individuals is List <Individual> list)
     {
         list.Capacity = toThis; // Reclaims memory! ;-)
     }
     else
     {
         // NOTE: The individuals removed are returned (in their original relative order),
         // but we have no use for them here. When the return value goes out of scope
         // the garbage collector will decide when to reclaim the memory.
         Individuals.RemoveFromTopDesctructively(Individuals.Count - toThis);
         // TODO: Decide whether or not we should call TrimExcess() to reduce capacity.
     }
 }
        /// <summary>
        /// Returns a genome from the individuals in this generation with the lowest number of completed matches.
        /// If any competitorsAlreadyInMatch are provided this returns the individual with the fewest matches against any of those individuals.
        /// </summary>
        /// <param name="genomeToCompeteWith"></param>
        /// <returns>genome of a competetor from this generation</returns>
        private string PickCompetitor(List <string> competitorsAlreadyInMatch)
        {
            List <Individual> validCompetitors = Individuals
                                                 .Where(i => !competitorsAlreadyInMatch.Contains(i.Genome))
                                                 .OrderBy(i => i.CountPreviousMatchesAgainst(competitorsAlreadyInMatch))
                                                 .ThenBy(i => i.MatchesPlayed)
                                                 .ThenBy(i => _rng.NextDouble())
                                                 .ToList();


            var best = validCompetitors.FirstOrDefault();

            //Debug.Log("Picked Individual has played " + best.MatchesPlayed);
            if (best != null)
            {
                return(best.Genome);
            }
            return(null);
        }
Beispiel #18
0
        public IndividualGroup(IndividualType type,
                               int count,
                               IVariables v) : base(type, count)
        {
            var geneticQualities = Utility.NextGaussianNonNegativeSymbols(10,
                                                                          v.SdQuality,
                                                                          count);

            for (var i = 0; i < count; i++)
            {
                var individual = new Individual(
                    type, i + 1,
                    geneticQualities[i],
                    Utility.NextGaussianNonNegative(geneticQualities[i], v.SdPheno)
                    );

                Individuals.Add(individual);
            }
        }
        public void AddIndividual(Individual individual)
        {
            Requires.NotNull("individual", individual);

            //Add to internal List
            Individuals.Add(individual);

            //Add underlying GEDCOM record
            individual.Id = _document.Records.GetNextId(GEDCOMTag.INDI).ToString();

            var record = new GEDCOMIndividualRecord(individual.Id);
            var name   = new GEDCOMNameStructure(String.Format("{0} /{1}/", individual.FirstName, individual.LastName), record.Level + 1);

            record.Name = name;
            record.Sex  = individual.Sex;
            _document.AddRecord(record);

            //Update Family Info
            UpdateFamilyDetails(individual);
        }
        public double[] ToArray()
        {
            int num_individuals = Individuals.Count();

            double[] res = new double[num_individuals * num_variables + 2];
            int      pos = 2;

            res[0] = num_individuals;
            res[1] = num_variables;

            for (int i = 0; i < num_individuals; i++)
            {
                Individual ind = individuals.ElementAt(i);
                for (int j = 0; j < num_variables; j++)
                {
                    res[pos++] = ind[j];
                }
            }
            return(res);
        }
    public Individuals[] Iniciate(Individuals[] population)
    {
        Individuals[] newPopulation = new Individuals[Individuals.PopulationSize];
        int           tempRd;
        int           k = 0; // controle de qual individuo esta cruzando

        for (int i = 0; i < Individuals.PopulationSize; i++)
        {
            char[] newNotes = new char[Individuals.Size];
            int[]  newTimes = new int[Individuals.Size];

            newPopulation[i] = new Individuals();
            if ((k <= 47) && ((i % 2) == 0) && (i != 0))
            {
                k = k + 2;
            }

            for (int iNotes = 0; iNotes < Individuals.Size; iNotes++)
            {
                Random random = new Random();
                tempRd = random.Next(0, 2);

                if (tempRd == 0)
                {
                    newNotes[iNotes] = population[k].getNotesAt(iNotes);
                    newTimes[iNotes] = population[k].getTimesAt(iNotes);
                }
                else
                {
                    newNotes[iNotes] = population[k + 1].getNotesAt(iNotes);
                    newTimes[iNotes] = population[k + 1].getTimesAt(iNotes);
                }
            }
            newPopulation[i].setNotes(newNotes);
            newPopulation[i].setTimes(newTimes);
        }

        return(Selection(population, Mutation(newPopulation)));
    }
        private void ProcessFamilies()
        {
            Families = new List <Family>();

            foreach (var gedcomRecord in _document.FamilyRecords)
            {
                var familyRecord = (GEDCOMFamilyRecord)gedcomRecord;
                var family       = new Family
                {
                    Id        = familyRecord.GetId(),
                    HusbandId = GEDCOMUtil.GetId(familyRecord.Husband),
                    WifeId    = GEDCOMUtil.GetId(familyRecord.Wife),
                    TreeId    = DEFAULT_TREE_ID
                };

                ProcessFacts(family, familyRecord.Events);

                ProcessMultimedia(family, familyRecord.Multimedia);

                ProcessNotes(family, familyRecord.Notes);

                ProcessCitations(family, familyRecord.SourceCitations);

                foreach (string child in familyRecord.Children)
                {
                    var childId = GEDCOMUtil.GetId(child);
                    if (!string.IsNullOrEmpty(childId))
                    {
                        var individual = Individuals.SingleOrDefault(ind => ind.Id == childId);
                        if (individual != null)
                        {
                            individual.MotherId = family.WifeId;
                            individual.FatherId = family.HusbandId;
                        }
                    }
                }
                Families.Add(family);
            }
        }
        static void Main(string[] args)
        {
            Individuals.PopulationSize = 50;
            int NGeracoes = 20;

            Individuals[] population = new Individuals[Individuals.PopulationSize];

            for (int i = 0; i < population.Length; i++)
            {
                population[i] = new Individuals();
                population[i].Initiate();
                population[i].FitnessCalculate();
            }
            population = AG.OrderBy(population);
            Output.scoreGenerator(population, "populacaooriginal.ly");

            AG  ag = new AG();
            int g  = 0;

            using (StreamWriter writer = new StreamWriter("melhores.ods", true))
            {
                writer.WriteLine("Geracoes:," + NGeracoes + ",Tamanho da Populacao," + Individuals.PopulationSize);
                writer.WriteLine("Selecionados," + Individuals.PopulationSize * 0.3 + ",Mutação, 0.10");
            }

            do
            {
                population = ag.Iniciate(population);

                using (StreamWriter writer = new StreamWriter("melhores.ods", true))
                {
                    writer.WriteLine("Geracao:," + g + ",Fitness," + population[0].getFitness());
                }
                g++;
            } while ((g < NGeracoes) && (population[0].getFitness() > 0));
            Output.scoreGenerator(population, "novapopulacao.ly");
        }
Beispiel #24
0
        /// <summary>
        /// Enumerates all possible <see cref="Occurrence">Occurrences</see> that group <see cref="Individuals"/>.
        /// </summary>
        /// <returns>All possible <see cref="Occurrence">Occurrences</see> that group <see cref="Individuals"/>.</returns>
        public IEnumerable <Occurrence> EnumerateOccurrences()
        {
            // this implementation is wrong and should be fixed. https://github.com/RobinsonWM/GroupSplitter/issues/1
            // it seems to work well for targetGroupSize = 2
            for (int h = 0; h < Individuals.Count; h++)
            {
                var individuals = Individuals.ToArray();
                for (int i = h; i < Individuals.Count; i++)
                {
                    for (int j = 0; j < individuals.Length; j++)
                    {
                        var swap = individuals[j];
                        individuals[j] = individuals[i];
                        individuals[i] = swap;

                        var occurrence = BuildOccurrenceFromAdjacentElements(individuals);
                        if (!DoesOccurrenceContainExemptMeetings(occurrence))
                        {
                            yield return(occurrence);
                        }
                    }
                }
            }
        }
Beispiel #25
0
 private Guid GetIdOfRandomChromosome()
 {
     return(Individuals[Random.Next() % Individuals.Count()].Id);
 }
Beispiel #26
0
 private Chromosome <GeneType> GetChromosome(Guid Id)
 {
     return(Individuals.Where(x => x.Id == Id).FirstOrDefault());
 }
Beispiel #27
0
 public Individual[] OrderByFitness()
 {
     return(Individuals.OrderByDescending(x => x.Fitness).ToArray());
 }
Beispiel #28
0
        public override double CalculateLostFecundity( )
        {
            TotalPhenoQuality = Individuals.Sum(x => x.PhenotypicQuality);

            return(LostFecundity = TotalPhenoQuality - TotalFecundity);
        }
 /// <summary>
 /// Create a population with additional GA information
 /// </summary>
 /// <param name="population">Individuals to store</param>
 /// <param name="number">N-th generation in a GA</param>
 public NumberedPopulation(Population <TIndividual, TGene> population, int number) : base(population)
 {
     Number     = number;
     TopFitness = Individuals.Select(i => i.Fitness).Max();
 }
Beispiel #30
0
 public Melody BestIndividual()
 {
     return(Individuals.OrderByDescending(i => i.Fitness).FirstOrDefault());
 }