Exemple #1
0
 protected override IEvolvable crossover(IEvolvable other)
 {
     if (other is SelectMutateCrossoverPopulation)
     {
         SelectMutateCrossoverPopulation mate = (SelectMutateCrossoverPopulation)other;
         return(new SelectMutateCrossoverPopulation(
                    this.ParentPopulation,
                    Evolution.RandomInterpolation(random, this.MutationRate, mate.MutationRate),
                    Evolution.RandomInterpolation(random, this.EliteClonePercentage, mate.EliteClonePercentage),
                    Evolution.RandomInterpolation(random, this.SelectedPercentage, mate.SelectedPercentage),
                    Evolution.RandomInterpolation(random, this.NewPopulationSize, mate.NewPopulationSize),
                    0,
                    (int)Evolution.RandomInterpolation(random, this.Resources, mate.Resources),
                    (int)Evolution.RandomInterpolation(random, this.Feedings, mate.Feedings),
                    Evolution.RandomInterpolation(random, this.EnoughFeedingsForBreeding, mate.EnoughFeedingsForBreeding),
                    random,
                    random.NextDouble() < 0.5 ? this.Creator : mate.Creator,
                    0, 0, 0,
                    this.Fitness > mate.Fitness ? this.FitnessHistory.Select(a => a).ToList() : mate.FitnessHistory.Select(a => a).ToList(),
                    this.individuals.Union(mate.individuals).OrderByDescending(a => a.Fitness).Take((int)Evolution.RandomInterpolation(random, this.PopulationSize, mate.PopulationSize)).ToList(),
                    this.BestOfAllTime.Fitness > mate.BestOfAllTime.Fitness ? this.BestOfAllTime : mate.BestOfAllTime,
                    0, 0, Mutations + mate.Mutations, Crossovers + mate.Crossovers, FitnessEvaluations + mate.FitnessEvaluations, 0
                    ));
     }
     else
     {
         return(base.crossover(other));
     }
 }
        /// <summary>
        /// Encode and write a binary representation of the given
        /// <b>IMessage</b> to the given <see cref="DataWriter"/>.
        /// </summary>
        /// <remarks>
        /// Using the passed <see cref="IChannel"/>, the Codec has access to
        /// both the <see cref="IMessageFactory"/> for the <b>IChannel</b>
        /// and the underlying <see cref="IConnection"/>.
        /// </remarks>
        /// <param name="channel">
        /// The <b>IChannel</b> object through which the binary-encoded
        /// <b>IMessage</b> was passed.
        /// </param>
        /// <param name="message">
        /// The <b>IMessage</b> to encode.
        /// </param>
        /// <param name="writer">
        /// The <b>DataWriter</b> to write the binary representation of the
        /// <b>IMessage</b> to.
        /// </param>
        /// <exception cref="IOException">
        /// If an error occurs encoding or writing the <b>IMessage</b>.
        /// </exception>
        /// <seealso cref="ICodec.Encode"/>
        public virtual void Encode(IChannel channel, IMessage message, DataWriter writer)
        {
            Debug.Assert(channel is IPofContext);
            Debug.Assert(message is IPortableObject);

            IPofContext     context   = (IPofContext)channel;
            PofStreamWriter pofwriter = new PofStreamWriter.UserTypeWriter(writer, context, message.TypeId, 0);

            ISerializer serializer = channel.Serializer;

            if (serializer is ConfigurablePofContext)
            {
                ConfigurablePofContext pofCtx = (ConfigurablePofContext)serializer;
                if (pofCtx.IsReferenceEnabled)
                {
                    pofwriter.EnableReference();
                }
            }

            // set the version identifier
            bool       isEvolvable = message is IEvolvable;
            IEvolvable evolvable   = null;

            if (isEvolvable)
            {
                evolvable           = (IEvolvable)message;
                pofwriter.VersionId = Math.Max(evolvable.DataVersion, evolvable.ImplVersion);
            }

            // write the Message properties
            ((IPortableObject)message).WriteExternal(pofwriter);

            // write the future properties
            pofwriter.WriteRemainder(isEvolvable ? evolvable.FutureData : null);
        }
        /// <summary>
        /// Serialize a user type instance to a POF stream by writing its
        /// state using the specified <see cref="IPofWriter"/> object.
        /// </summary>
        /// <remarks>
        /// An implementation of <b>IPofSerializer</b> is required to follow
        /// the following steps in sequence for writing out an object of a
        /// user type:
        /// <list type="number">
        /// <item>
        /// <description>
        /// If the object is evolvable, the implementation must set the
        /// version by calling <see cref="IPofWriter.VersionId"/>.
        /// </description>
        /// </item>
        /// <item>
        /// <description>
        /// The implementation may write any combination of the properties of
        /// the user type by using the "write" methods of the
        /// <b>IPofWriter</b>, but it must do so in the order of the property
        /// indexes.
        /// </description>
        /// </item>
        /// <item>
        /// <description>
        /// After all desired properties of the user type have been written,
        /// the implementation must terminate the writing of the user type by
        /// calling <see cref="IPofWriter.WriteRemainder"/>.
        /// </description>
        /// </item>
        /// </list>
        /// </remarks>
        /// <param name="writer">
        /// The <b>IPofWriter</b> with which to write the object's state.
        /// </param>
        /// <param name="o">
        /// The object to serialize.
        /// </param>
        /// <exception cref="IOException">
        /// If an I/O error occurs.
        /// </exception>
        public virtual void Serialize(IPofWriter writer, object o)
        {
            // set the version identifier
            bool       isEvolvable = o is IEvolvable;
            IEvolvable evolvable   = null;

            if (isEvolvable)
            {
                evolvable        = (IEvolvable)o;
                writer.VersionId =
                    Math.Max(evolvable.DataVersion, evolvable.ImplVersion);
            }

            // POF Annotation processing
            for (IEnumerator enmr = m_tmd.GetAttributes(); enmr.MoveNext();)
            {
                IAttributeMetadata <object> attr = (IAttributeMetadata <object>)enmr.Current;
                attr.Codec.Encode(writer, attr.Index, attr.Get(o));
            }

            // write out any future properties
            Binary remainder = null;

            if (isEvolvable)
            {
                remainder = evolvable.FutureData;
            }
            writer.WriteRemainder(remainder);
        }
        /// <summary>
        /// Deserialize a user type instance from a POF stream by reading its
        /// state using the specified <see cref="IPofReader"/> object.
        /// </summary>
        /// <remarks>
        /// An implementation of <b>IPofSerializer</b> is required to follow
        /// the following steps in sequence for reading in an object of a
        /// user type:
        /// <list type="number">
        /// <item>
        /// <description>
        /// If the object is evolvable, the implementation must get the
        /// version by calling <see cref="IPofWriter.VersionId"/>.
        /// </description>
        /// </item>
        /// <item>
        /// <description>
        /// The implementation may read any combination of the
        /// properties of the user type by using "read" methods of the
        /// <b>IPofReader</b>, but it must do so in the order of the property
        /// indexes.
        /// </description>
        /// </item>
        /// <item>
        /// <description>
        /// After all desired properties of the user type have been read,
        /// the implementation must terminate the reading of the user type by
        /// calling <see cref="IPofReader.ReadRemainder"/>.
        /// </description>
        /// </item>
        /// </list>
        /// </remarks>
        /// <param name="reader">
        /// The <b>IPofReader</b> with which to read the object's state.
        /// </param>
        /// <returns>
        /// The deserialized user type instance.
        /// </returns>
        /// <exception cref="IOException">
        /// If an I/O error occurs.
        /// </exception>
        public virtual object Deserialize(IPofReader reader)
        {
            ITypeMetadata <object> tmd = m_tmd;
            object value = tmd.NewInstance();

            // set the version identifier
            bool       isEvolvable = value is IEvolvable;
            IEvolvable evolvable   = null;

            if (isEvolvable)
            {
                evolvable             = (IEvolvable)value;
                evolvable.DataVersion = reader.VersionId;
            }

            // POF Annotation processing
            for (IEnumerator enmr = tmd.GetAttributes(); enmr.MoveNext();)
            {
                IAttributeMetadata <object> attr = (IAttributeMetadata <object>)enmr.Current;
                attr.Set(value, attr.Codec.Decode(reader, attr.Index));
            }

            // read any future properties
            Binary remainder = reader.ReadRemainder();

            if (isEvolvable)
            {
                evolvable.FutureData = remainder;
            }

            return(value);
        }
Exemple #5
0
        public IEvolvable Crossover(IEvolvable other)
        {
            StencilSpeciesArr mate = (StencilSpeciesArr)other;

            if (this.Equals(mate))
            {
                var result = this.Clone();
                result.Mutate();
                return(result);
            }
            else
            {
                int[] cPerProcessor = (int[])cellsPerProcessor.Clone();
                int   freeCells     = this.Field.Length;

                // initialize field with -1 or cells that are equal in both mates
                Arr <int> field = new Arr <int>(this.Field.SizeX, this.Field.SizeY);
                freeCells -= fillWithEqualGenesOrMinusOne(field, this.Field, mate.Field, cPerProcessor);

                while (freeCells > 0)
                {
                    int position  = field.FreePosition(random.Next(0, freeCells), -1);
                    int processor = suitableValue(random, freeCells, this.Field, mate.Field, position, cPerProcessor);

                    field[position] = processor;
                    cPerProcessor[processor]--;
                    freeCells--;
                }

                StencilSpeciesArr result = new StencilSpeciesArr(this, field);
                result.Optimize(3);
                return(result);
            }
        }
        /// <summary>
        /// Reads a binary-encoded <b>IMessage</b> from the passed
        /// <see cref="DataReader"/> object.
        /// </summary>
        /// <remarks>
        /// Using the passed <see cref="IChannel"/>, the Codec has access to
        /// both the <see cref="IMessageFactory"/> for the <b>IChannel</b>
        /// and the underlying <see cref="IConnection"/>.
        /// </remarks>
        /// <param name="channel">
        /// The <b>IChannel</b> object through which the binary-encoded
        /// <b>IMessage</b> was passed.
        /// </param>
        /// <param name="reader">
        /// The <b>DataReader</b> containing the binary-encoded
        /// <b>IMessage</b>.
        /// </param>
        /// <returns>
        /// The <b>IMessage</b> object encoded in the given
        /// <b>DataReader</b>.
        /// </returns>
        /// <exception cref="IOException">
        /// If an error occurs reading or decoding the <b>IMessage</b>.
        /// </exception>
        public virtual IMessage Decode(IChannel channel, DataReader reader)
        {
            Debug.Assert(channel is IPofContext);

            IPofContext context   = (IPofContext)channel;
            int         typeId    = reader.ReadPackedInt32();
            int         versionId = reader.ReadPackedInt32();
            IPofReader  pofreader = new PofStreamReader.UserTypeReader(reader, context, typeId, versionId);
            IMessage    message   = channel.MessageFactory.CreateMessage(typeId);

            Debug.Assert(message is IPortableObject);

            // set the version identifier
            bool       isEvolvable = message is IEvolvable;
            IEvolvable evolvable   = null;

            if (isEvolvable)
            {
                evolvable             = (IEvolvable)message;
                evolvable.DataVersion = versionId;
            }

            // read the Message properties
            ((IPortableObject)message).ReadExternal(pofreader);

            // read the future properties
            Binary binFuture = pofreader.ReadRemainder();

            if (isEvolvable)
            {
                evolvable.FutureData = binFuture;
            }

            return(message);
        }
Exemple #7
0
 private void set(IEvolvable[] population, int index, IEvolvable value)
 {
     while (contains(population, index, value))
     {
         value.Mutate();
     }
     population[index] = value;
 }
Exemple #8
0
 public IEvolvable Crossover(IEvolvable mate)
 {
     if (ParentPopulation != null)
     {
         ParentPopulation.NoteCrossovers();
     }
     EvolveCrossovers++;
     return(crossover(mate));
 }
Exemple #9
0
        public IEvolvable Crossover(IEvolvable other)
        {
            TestEvolvable result = new TestEvolvable(random, chromosomes.Length);

            for (int i = 0; i < chromosomes.Length; i++)
            {
                result.chromosomes[i] = random.NextDouble() < 0.5 ? this.chromosomes[i] : (other as TestEvolvable).chromosomes[i];
            }
            return(result);
        }
Exemple #10
0
        public double DifferenceTo(IEvolvable other)
        {
            double result = 0;

            for (int i = 0; i < chromosomes.Length; i++)
            {
                result += Math.Abs(this.chromosomes[i] - (other as TestEvolvable).chromosomes[i]);
            }
            return(result);
        }
        /// <summary>
        /// Deserialize a user type instance from a POF stream by reading its
        /// state using the specified <see cref="IPofReader"/> object.
        /// </summary>
        /// <remarks>
        /// An implementation of <b>IPofSerializer</b> is required to follow
        /// the following steps in sequence for reading in an object of a
        /// user type:
        /// <list type="number">
        /// <item>
        /// <description>
        /// If the object is evolvable, the implementation must get the
        /// version by calling <see cref="IPofReader.VersionId"/>.
        /// </description>
        /// </item>
        /// <item>
        /// <description>
        /// The implementation may read any combination of the
        /// properties of the user type by using "read" methods of the
        /// <b>IPofReader</b>, but it must do so in the order of the property
        /// indexes. Additionally, the implementation must call
        /// {@link IPofReader#RegisterIdentity} with the new instance prior
        /// to reading any properties which are user type instances
        /// themselves.
        /// </description>
        /// </item>
        /// <item>
        /// <description>
        /// After all desired properties of the user type have been read,
        /// the implementation must terminate the reading of the user type by
        /// calling <see cref="IPofReader.ReadRemainder"/>.
        /// </description>
        /// </item>
        /// </list>
        /// </remarks>
        /// <param name="pofReader">
        /// The <b>IPofReader</b> with which to read the object's state.
        /// </param>
        /// <returns>
        /// The deserialized user type instance.
        /// </returns>
        /// <exception cref="IOException">
        /// If an I/O error occurs.
        /// </exception>
        public Object Deserialize(IPofReader pofReader)
        {
            try
            {
                IPortableObject po = (IPortableObject)
                                     Activator.CreateInstance(GetTypeForTypeId(pofReader.PofContext, m_nTypeId));

                CacheFactory.Log("Deserializing " + po.GetType(), CacheFactory.LogLevel.Max);

                bool             fEvolvable = po is IEvolvableObject;
                IEvolvableObject et         = fEvolvable ? (IEvolvableObject)po : null;

                int typeId = ((PofStreamReader.UserTypeReader)pofReader).NextPropertyIndex;
                while (typeId > 0)
                {
                    IEvolvable e      = null;
                    IPofReader reader = pofReader.CreateNestedPofReader(typeId);

                    if (fEvolvable)
                    {
                        e             = et.GetEvolvable(typeId);
                        e.DataVersion = reader.VersionId;
                    }

                    po.ReadExternal(reader);

                    Binary binRemainder = reader.ReadRemainder();
                    if (fEvolvable)
                    {
                        e.FutureData = binRemainder;
                    }
                    typeId = ((PofStreamReader.UserTypeReader)pofReader).NextPropertyIndex;
                }

                pofReader.ReadRemainder();
                return(po);
            }
            catch (Exception e)
            {
                String sClass = null;
                try
                {
                    sClass = pofReader.PofContext.GetTypeName(m_nTypeId);
                }
                catch (Exception)
                {
                }

                throw new IOException(
                          "An exception occurred instantiating a IPortableObject"
                          + " user type from a POF stream: type-id=" + m_nTypeId
                          + (sClass == null ? "" : ", class-name=" + sClass)
                          + ", exception=\n" + e, e);
            }
        }
        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));
        }
 private bool contains(List <IEvolvable> list, IEvolvable value)
 {
     for (int i = 0; i < list.Count; i++)
     {
         if (list[i].Equals(value))
         {
             return(true);
         }
     }
     return(false);
 }
Exemple #14
0
        protected virtual IEvolvable crossover(IEvolvable other)
        {
            EvolvablePopulation mate  = (EvolvablePopulation)other;
            EvolvablePopulation child = (EvolvablePopulation)(this.Fitness > mate.Fitness ? this.Clone() : other.Clone());

            foreach (IEvolvable individual in mate.individuals)
            {
                child.individuals.Add(individual.Clone());
            }
            return(child);
        }
Exemple #15
0
        public override IEvolvable Create()
        {
            IEvolvable result = base.Create();

            if ((result as Evolver).Evolvable is EvolvablePopulation)
            {
                ((result as Evolver).Evolvable as EvolvablePopulation).ParentPopulation = this;
            }

            return(result);
        }
Exemple #16
0
 private bool contains(IEvolvable[] population, int index, IEvolvable value)
 {
     for (int i = 0; i < index; i++)
     {
         if (population[i].Equals(value))
         {
             return(true);
         }
     }
     return(false);
 }
 public virtual IEvolvable GetEvolvable(int nTypeId)
 {
     if (m_evolvable == null)
     {
         m_evolvable = new SimpleEvolvable(1);
     }
     if (3 == nTypeId)
     {
         return(m_evolvable);
     }
     return(GetEvolvableHolder().GetEvolvable(nTypeId));
 }
        /// <summary>
        /// Serialize a user type instance to a POF stream by writing its
        /// state using the specified <see cref="IPofWriter"/> object.
        /// </summary>
        /// <remarks>
        /// An implementation of <b>IPofSerializer</b> is required to follow
        /// the following steps in sequence for writing out an object of a
        /// user type:
        /// <list type="number">
        /// <item>
        /// <description>
        /// If the object is evolvable, the implementation must set the
        /// version by calling <see cref="IPofWriter.VersionId"/>.
        /// </description>
        /// </item>
        /// <item>
        /// <description>
        /// The implementation may write any combination of the properties of
        /// the user type by using the "write" methods of the
        /// <b>IPofWriter</b>, but it must do so in the order of the property
        /// indexes.
        /// </description>
        /// </item>
        /// <item>
        /// <description>
        /// After all desired properties of the user type have been written,
        /// the implementation must terminate the writing of the user type by
        /// calling <see cref="IPofWriter.WriteRemainder"/>.
        /// </description>
        /// </item>
        /// </list>
        /// </remarks>
        /// <param name="writer">
        /// The <see cref="IPofWriter"/> with which to write the object's
        /// state.
        /// </param>
        /// <param name="o">
        /// The object to serialize.
        /// </param>
        /// <exception cref="IOException">
        /// If an I/O error occurs.
        /// </exception>
        public virtual void Serialize(IPofWriter writer, object o)
        {
            IPortableObject portable;

            try
            {
                portable = (IPortableObject)o;
            }
            catch (InvalidCastException e)
            {
                string typeName = null;
                try
                {
                    typeName = writer.PofContext.GetTypeName(m_typeId);
                }
                catch (Exception)
                {}

                string actual = o.GetType().FullName;

                throw new IOException(
                          "An exception occurred writing an IPortableObject"
                          + " user type to a POF stream: type-id=" + m_typeId
                          + (typeName == null ? "" : ", class-name=" + typeName)
                          + (actual == null ? "" : ", actual class-name=" + actual)
                          + ", exception=\n" + e);
            }

            // set the version identifier
            bool       isEvolvable = portable is IEvolvable;
            IEvolvable evolvable   = null;

            if (isEvolvable)
            {
                evolvable        = (IEvolvable)portable;
                writer.VersionId =
                    Math.Max(evolvable.DataVersion, evolvable.ImplVersion);
            }

            // write out the object's properties
            portable.WriteExternal(writer);

            // write out any future properties
            Binary remainder = null;

            if (isEvolvable)
            {
                remainder = evolvable.FutureData;
            }
            writer.WriteRemainder(remainder);
        }
        protected virtual IPresentable AsDetailPresentable(string title, IEvolvable evolvable)
        {
            if (evolvable is IPopulation)
            {
                new Presentable("Population", new Label()
                {
                    Content = evolvable.ToString()
                });
            }

            if (evolvable is IPresentable)
            {
                return(new Presentable(title, (evolvable as IPresentable).PresentableControl));
            }

            return(new Presentable(title, new Label()
            {
                Content = evolvable.ToString()
            }));
        }
Exemple #20
0
        protected static void orderedIndividualsTest(IPopulation population)
        {
            IEvolvable latest = population.Best;

            foreach (IEvolvable next in population.IndividualsSortedByFitness)
            {
                AssertEx.IsLessThanOrEqualTo(next.Fitness, latest.Fitness);
                latest = next;
            }

            foreach (IEvolvable evolvable in population.Individuals)
            {
                Assert.IsNotNull(evolvable);
            }

            foreach (var individual in population.Individuals)
            {
                if (individual is IPopulation)
                {
                    orderedIndividualsTest(individual as IPopulation);
                }
            }
        }
        /// <summary>
        /// Initialize the specified (newly instantiated) PortableObject instance
        /// using the specified reader.
        /// </summary>
        /// <param name="portable">The object to initialize.</param>
        /// <param name="reader">
        /// The PofReader with which to read the object's state.
        /// </param>
        public void Initialize(IPortableObject portable, IPofReader reader)
        {
            // set the version identifier
            bool       isEvolvable = portable is IEvolvable;
            IEvolvable evolvable   = null;

            if (isEvolvable)
            {
                evolvable             = (IEvolvable)portable;
                evolvable.DataVersion = reader.VersionId;
            }

            // read the object's properties
            portable.ReadExternal(reader);

            // read any future properties
            Binary remainder = reader.ReadRemainder();

            if (isEvolvable)
            {
                evolvable.FutureData = remainder;
            }
        }
Exemple #22
0
        public void Feed(double resources)
        {
            FoodConsumedInLifetime += resources;
            FoodForMutation        += resources;
            FoodForReproduction    += resources;

            if (FoodForMutation >= FoodNeededForMutation)
            {
                (population as IndividualMutateAndCrossoverPopulation).AddChild(this.clone());
                Mutate();
                FoodForMutation -= FoodNeededForMutation;

                FoodNeededForMutation     = mutate(random, FoodNeededForMutation, 1, 100, 10);
                FoodNeededForReproduction = mutate(random, FoodNeededForReproduction, 1, 100, 10);
            }

            if (FoodForReproduction >= FoodNeededForReproduction)
            {
                IEvolvable mate  = (population as IndividualMutateAndCrossoverPopulation).FindMate(this);
                IEvolvable child = this.Crossover(mate);
                (population as IndividualMutateAndCrossoverPopulation).AddChild(child);
                FoodForReproduction -= FoodNeededForReproduction;
            }
        }
 protected override IEvolvable crossover(IEvolvable other)
 {
     if (other is IndividualMutateAndCrossoverPopulation)
     {
         IndividualMutateAndCrossoverPopulation mate = (IndividualMutateAndCrossoverPopulation)other;
         return(new IndividualMutateAndCrossoverPopulation(
                    this.ParentPopulation,
                    Evolution.RandomInterpolation(random, this.MaxSize, mate.MaxSize),
                    new List <IEvolvable>(),
                    (int)Evolution.RandomInterpolation(random, this.FoodForPopulation, mate.FoodForPopulation),
                    random,
                    random.NextDouble() < 0.5 ? this.Creator : mate.Creator,
                    0, 0, 0,
                    this.Fitness > mate.Fitness ? this.FitnessHistory.Select(a => a).ToList() : mate.FitnessHistory.Select(a => a).ToList(),
                    this.individuals.Union(mate.individuals).OrderByDescending(a => a.Fitness).Take((int)Evolution.RandomInterpolation(random, this.PopulationSize, mate.PopulationSize)).ToList(),
                    this.BestOfAllTime.Fitness > mate.BestOfAllTime.Fitness ? this.BestOfAllTime : mate.BestOfAllTime,
                    0, 0, Mutations + mate.Mutations, Crossovers + mate.Crossovers, FitnessEvaluations + mate.FitnessEvaluations, 0
                    ));
     }
     else
     {
         return(base.crossover(other));
     }
 }
 protected override double differenceTo(IEvolvable other)
 {
     return(other is Evolver?Evolvable.DifferenceTo((other as Evolver).Evolvable) : Evolvable.DifferenceTo(other));
 }
 protected override IEvolvable crossover(IEvolvable mate)
 {
     return(new Evolver(population, mate is Evolver ? Evolvable.Crossover((mate as Evolver).Evolvable) : Evolvable.Crossover(mate)));
 }
 public Evolver(IPopulation population, IEvolvable evolvable) : base(population)
 {
     Evolvable = evolvable;
 }
 protected Population(ICreator creator, Random random, List <IEvolvable> individuals, IEvolvable bestOfAllTime, int populationSize, long generations, long mutations, long crossovers, long fitnessEvaluations, double foodConsumedInLifetime) : base(foodConsumedInLifetime)
 {
     construct(creator, random, individuals, bestOfAllTime, populationSize, generations, mutations, crossovers, fitnessEvaluations);
 }
Exemple #28
0
 protected SelectMutateCrossoverPopulation(IPopulation population, double mutationRate, double eliteClonePercentage, double selectedPercentage, double newPopulationSize, int breedingsSoFar, double resources, int feedings, double enoughFeedingsForBreeding, Random random, ICreator creator, int evolvableMutations, int evolvableCrossovers, int evolvableFitnessEvaluations, List <double> fitnessHistory, List <IEvolvable> individuals, IEvolvable bestOfAllTime, int populationSize, long generations, long mutations, long crossovers, long fitnessEvaluations, double foodConsumedInLifetime) : base(population, random, creator, evolvableMutations, evolvableCrossovers, evolvableFitnessEvaluations, fitnessHistory, individuals, bestOfAllTime, populationSize, generations, mutations, crossovers, fitnessEvaluations, foodConsumedInLifetime)
 {
     construct(mutationRate, eliteClonePercentage, selectedPercentage, newPopulationSize, breedingsSoFar, resources, feedings, enoughFeedingsForBreeding);
 }
Exemple #29
0
 public override double DifferenceTo(IEvolvable other)
 {
     throw new NotImplementedException();
 }
Exemple #30
0
        protected virtual void breed()
        {
            IEvolvable[] newPopulation      = new IEvolvable[(int)NewPopulationSize];
            int          newPopulationIndex = 0;

            measureFitness();

            var orderedPopulation = individuals.OrderByDescending(a => a.Fitness).ToArray();

            // clone the elite
            for (; newPopulationIndex < (int)Math.Min(PopulationSize, NewPopulationSize * EliteClonePercentage); newPopulationIndex++)
            {
                newPopulation[newPopulationIndex] = orderedPopulation[newPopulationIndex].Clone();
            }

            // mutate some
            for (int i = 0; i < PopulationSize; i++)
            {
                if (random.NextDouble() <= MutationRate)
                {
                    individuals[i].Mutate();
                }
            }

            orderedPopulation = individuals.OrderByDescending(a => a.Fitness).ToArray();

            // select the best
            for (int oldPopulationIndex = 0; newPopulationIndex < (int)Math.Min(PopulationSize, NewPopulationSize * SelectedPercentage); newPopulationIndex++, oldPopulationIndex++)
            {
                set(newPopulation, newPopulationIndex, orderedPopulation[oldPopulationIndex]);
            }

            if (newPopulationIndex <= 1)
            {
                for (; newPopulationIndex < (int)NewPopulationSize; newPopulationIndex++)
                {
                    set(newPopulation, newPopulationIndex, orderedPopulation[0].Clone());
                }
            }
            else
            {
                int parents = newPopulationIndex;
                // crossover to repopulate
                for (; newPopulationIndex < (int)NewPopulationSize; newPopulationIndex++)
                {
                    int parentIndex1 = random.Next(0, parents);
                    int parentIndex2 = random.Next(0, parents - 1);
                    if (parentIndex1 <= parentIndex2)
                    {
                        parentIndex2++;
                    }
                    set(newPopulation, newPopulationIndex, newPopulation[parentIndex1].Crossover(newPopulation[parentIndex2]));
                }
            }

            this.individuals = newPopulation.OrderByDescending(a => a.Fitness).ToList();

            Generations++;

            invalidateCaches();
        }