Beispiel #1
0
 /// <summary>
 /// Mutates a gene by applying boundary mutation.
 /// </summary>
 /// <param name="gene">An IntegerGene or DoubleGene to be mutated.</param>
 /// <returns></returns>
 public static Gene Mutate(Gene gene)
 {
     if (gene is IntegerGene)
     {
         IntegerGene ig = (IntegerGene)gene;
         if (genX.Utils.Rand.NextDouble() < 0.5)
         {
             ig.Value = ig.Descriptor.MaxValue;
         }
         else
         {
             ig.Value = ig.Descriptor.MinValue;
         }
     }
     else if (gene is DoubleGene)
     {
         DoubleGene dg = (DoubleGene)gene;
         if (genX.Utils.Rand.NextDouble() < 0.5)
         {
             dg.Value = dg.Descriptor.MaxValue;
         }
         else
         {
             dg.Value = dg.Descriptor.MinValue;
         }
     }
     else
     {
         throw new ArgumentException(
                   "Boundary mutation may only apply to IntegerGene or DoubleGene genes.",
                   "gene"
                   );
     }
     return(gene);
 }
Beispiel #2
0
        void Initialize(bool symmetricalBorders)
        {
            DoubleGene gene;

            if (symmetricalBorders)
            {
                gene       = new DoubleGene("OutputBorder", 0, 1);
                gene.Value = 1;
                geneList.Add(gene);
            }
            else
            {
                gene       = new DoubleGene("OutputBorder1", -1, 1);
                gene.Value = -1;
                geneList.Add(gene);

                gene       = new DoubleGene("OutputBorder2", -1, 1);
                gene.Value = 1;
                geneList.Add(gene);
            }

            gene           = new DoubleGene("P", 0, 1);
            gene.Value     = 1;
            gene.IsMutable = false;
            geneList.Add(gene);

            GenesHasChanged();
        }
Beispiel #3
0
 /// <summary>
 /// Mutates a gene by bitwise mutation.
 /// </summary>
 /// <param name="gene"></param>
 /// <returns></returns>
 public static Gene Mutate(Gene gene)
 {
     if (gene is BinaryGene)
     {
         BinaryGene g = (BinaryGene)gene.Clone();
         g.Value = !(BinaryGene)gene;
         return(g);
     }
     else if (gene is DoubleGene)
     {
         DoubleGene g     = (DoubleGene)gene.Clone();
         byte[]     bytes = BitConverter.GetBytes(g.Value);
         BitArray   ba    = new BitArray(bytes);
         int        p     = Utils.Rand.Next(ba.Length);
         ba.Set(p, !ba[p]);
         ba.CopyTo(bytes, 0);
         g.Value = BitConverter.ToDouble(bytes, 0);
         return(g);
     }
     else if (gene is IntegerGene)
     {
         IntegerGene g     = (IntegerGene)gene.Clone();
         byte[]      bytes = BitConverter.GetBytes(g.Value);
         BitArray    ba    = new BitArray(bytes);
         int         p     = Utils.Rand.Next(ba.Length);
         ba.Set(p, !ba[p]);
         ba.CopyTo(bytes, 0);
         g.Value = BitConverter.ToInt32(bytes, 0);
         return(g);
     }
     return((Gene)gene.Clone()); // default
 }
Beispiel #4
0
        public UniformCrossover()
        {
            var gene = new DoubleGene("CrossoverRate", 0, 1);

            gene.Value = 0.1;

            geneList.Add(gene);
        }
Beispiel #5
0
        public static EditDoubleGeneForm ShowDialogue(Window window, DoubleGene _gene, CloseEvent closeFunction = null, string category = null, ISkinFile file = null)
        {
            var form = new EditDoubleGeneForm();

            form.Initialize(_gene, closeFunction, "Edit Gene", true, true, category, file);
            form.Show(window);

            return(form);
        }
Beispiel #6
0
 /// <summary>
 /// Decode the genome to a network.
 /// </summary>
 public override void Decode()
 {
     double[] net = new double[networkChromosome.Genes.Count];
     for (int i = 0; i < net.Length; i++)
     {
         DoubleGene gene = (DoubleGene)networkChromosome.Genes[i];
         net[i] = gene.Value;
     }
     NetworkCODEC.ArrayToNetwork(net, (BasicNetwork)Organism);
 }
Beispiel #7
0
 /// <summary>
 /// Perform a perturb mutation on the specified chromosome.
 /// </summary>
 /// <param name="chromosome">The chromosome to mutate.</param>
 public void PerformMutation(Chromosome chromosome)
 {
     foreach (IGene gene in chromosome.Genes)
     {
         if (gene is DoubleGene)
         {
             DoubleGene doubleGene = (DoubleGene)gene;
             double     value      = doubleGene.Value;
             value           += (perturbAmount - (ThreadSafeRandom.NextDouble()) * perturbAmount * 2);
             doubleGene.Value = value;
         }
     }
 }
        /// <summary>
        /// Perform a perturb mutation on the specified chromosome.
        /// </summary>
        /// <param name="chromosome">The chromosome to mutate.</param>
        public void PerformMutation(Chromosome chromosome, GATracker.MatedElement mutatedElement, int childIndex)
        {
            bool usePertubAmount1 = ThreadSafeRandom.NextDouble() <= percentageUsePerturbAmount1;

            foreach (IGene gene in chromosome.Genes)
            {
                if (gene is DoubleGene)
                {
                    if (usePertubAmount1)
                    {
                        if (ThreadSafeRandom.NextDouble() < percentageGenesToPerturb1)
                        {
                            DoubleGene doubleGene   = (DoubleGene)gene;
                            double     value        = doubleGene.Value;
                            double     peturbAmount = (perturbAmount1 - (ThreadSafeRandom.NextDouble()) * perturbAmount1 * 2);

                            mutatedElement.AddChildMutation(new GATracker.MutationRecord(perturbAmount1, peturbAmount), childIndex);

                            value           += peturbAmount;
                            doubleGene.Value = value;
                        }
                    }
                    else
                    {
                        //if (ThreadSafeRandom.NextDouble() < percentageGenesToPerturb1)
                        //{
                        //    DoubleGene doubleGene = (DoubleGene)gene;
                        //    double value = doubleGene.Value;
                        //    double peturbAmount = (perturbAmount1 - (ThreadSafeRandom.NextDouble()) * perturbAmount1 * 2);

                        //    mutatedElement.AddChildMutation(new GATracker.MutationRecord(perturbAmount1, peturbAmount), childIndex);

                        //    value += peturbAmount;
                        //    doubleGene.Value = value;
                        //}
                        if (ThreadSafeRandom.NextDouble() < percentageGenesToPerturb2)
                        {
                            DoubleGene doubleGene   = (DoubleGene)gene;
                            double     value        = doubleGene.Value;
                            double     peturbAmount = (perturbAmount2 - (ThreadSafeRandom.NextDouble()) * perturbAmount2 * 2);

                            mutatedElement.AddChildMutation(new GATracker.MutationRecord(perturbAmount2, peturbAmount), childIndex);

                            value           += peturbAmount;
                            doubleGene.Value = value;
                        }
                    }
                }
            }
        }
Beispiel #9
0
        /// <summary>
        /// Construct a neural network genome.
        /// </summary>
        /// <param name="nga">The neural genetic algorithm.</param>
        /// <param name="network">The network.</param>
        public NeuralGenome(NeuralGeneticAlgorithm nga, BasicNetwork network)
            : base(nga.Helper)
        {
            this.Organism          = network;
            this.networkChromosome = new Chromosome();

            // create an array of "double genes"
            int size = network.Structure.CalculateSize();

            for (int i = 0; i < size; i++)
            {
                IGene gene = new DoubleGene();
                this.networkChromosome.Genes.Add(gene);
            }

            this.Chromosomes.Add(this.networkChromosome);

            Encode();
        }
        /// <summary>
        /// Construct a neural genome.
        /// </summary>
        ///
        /// <param name="network">The network to use.</param>
        public NeuralGenome(BasicNetwork network)
        {
            Organism = network;

            _networkChromosome = new Chromosome();

            // create an array of "double genes"
            int size = network.Structure.CalculateSize();

            for (int i = 0; i < size; i++)
            {
                IGene gene = new DoubleGene();
                _networkChromosome.Genes.Add(gene);
            }

            Chromosomes.Add(_networkChromosome);

            Encode();
        }
Beispiel #11
0
 protected static int GetIntFromGene(DoubleGene gene, int min, int max)
 {
     return(min + (int)Math.Round((max - min) * gene.Value, 0));
 }
Beispiel #12
0
 protected static int GetIntFromGene(DoubleGene gene, int max)
 {
     return(GetIntFromGene(gene, 0, max));
 }
Beispiel #13
0
        public void Initialize(DoubleGene _gene, CloseEvent closeFunction = null, string title = null, bool resizable = false, bool isDialog = true, string category = null, ISkinFile file = null)
        {
            Result = _gene;

            base.Initialize(closeFunction, title, resizable, isDialog, category, file);
        }
        public override void AddedToContainer()
        {
            base.AddedToContainer();

            CloseButtonOn = false;

            columnListBox = new ColumnListBox();
            columnListBox.Initialize(7);
            AddDrawBox(columnListBox);
            columnListBox.SetIntOrStringSort(true, false, true, true, true, true, false);
            columnListBox.SetColumnName(0, "Order");
            columnListBox.SetColumnName(1, "Name");
            columnListBox.SetColumnName(2, "ID");
            columnListBox.SetColumnName(3, "Value");
            columnListBox.SetColumnName(4, "Min");
            columnListBox.SetColumnName(5, "Max");
            columnListBox.SetColumnName(6, "IsMutable");
            columnListBox.Width  = 200;
            columnListBox.Height = 200;

            columnListBox.ItemDoubleClicked += delegate(object sender, ColumnListBox.ListBoxRow item, int index)
            {
                int n = 0;
                foreach (var g in geneList)
                {
                    if (g.ID == (uint)item.Values[2])
                    {
                        break;
                    }
                    n++;
                }

                EditDoubleGeneForm.ShowDialogue(Parent, geneList[n], delegate(object _sender)
                {
                    geneList[n] = ((EditDoubleGeneForm)_sender).Result;
                    ReloadListBox();
                });
            };

            ReloadListBox();

            var moveUpButton = new ResizableButton();

            moveUpButton.Initialize();
            AddDrawBox(moveUpButton);
            moveUpButton.Title = "Move Up";
            moveUpButton.FitToText();
            Push.ToTheBottomSideOf(moveUpButton, columnListBox, 3, Push.VerticalAlign.Left);
            moveUpButton.Width  = 200;
            moveUpButton.Click += delegate(object sender)
            {
                if (columnListBox.SelectedRowIndex < 1)
                {
                    return;
                }

                int index = columnListBox.SelectedRowIndex;

                var selected = geneList[index];
                var upper    = geneList[index - 1];
                geneList[index - 1] = selected;
                geneList[index]     = upper;

                ReloadListBox();

                columnListBox.SelectedRowIndex = index - 1;
            };

            var moveDownButton = new ResizableButton();

            moveDownButton.Initialize();
            AddDrawBox(moveDownButton);
            moveDownButton.Title = "Move Down";
            moveDownButton.FitToText();
            Push.ToTheBottomSideOf(moveDownButton, moveUpButton, 3, Push.VerticalAlign.Left);
            moveDownButton.Width  = 200;
            moveDownButton.Click += delegate(object sender)
            {
                if (columnListBox.SelectedRowIndex == -1 ||
                    columnListBox.SelectedRowIndex == columnListBox.Values.Count - 1)
                {
                    return;
                }

                int index = columnListBox.SelectedRowIndex;

                var selected = geneList[index];
                var lower    = geneList[index + 1];
                geneList[index + 1] = selected;
                geneList[index]     = lower;

                ReloadListBox();

                columnListBox.SelectedRowIndex = index + 1;
            };

            var createGeneButton = new ResizableButton();

            createGeneButton.Initialize();
            AddDrawBox(createGeneButton);
            createGeneButton.Title = "Create New Gene";
            createGeneButton.FitToText();
            Push.ToTheBottomSideOf(createGeneButton, moveDownButton, 3, Push.VerticalAlign.Left);
            createGeneButton.Width  = 200;
            createGeneButton.Click += delegate(object sender)
            {
                var dGene = new DoubleGene();
                dGene.SetMinMaxValue(0, 1, 0);
                dGene.IsMutable = true;

                EditDoubleGeneForm.ShowDialogue(Parent, dGene, delegate(object _sender)
                {
                    geneList.Add(((EditDoubleGeneForm)_sender).Result);
                    ReloadListBox();
                });
            };

            var deleteGeneButton = new ResizableButton();

            deleteGeneButton.Initialize();
            AddDrawBox(deleteGeneButton);
            deleteGeneButton.Title = "Delete Gene";
            deleteGeneButton.FitToText();
            Push.ToTheBottomSideOf(deleteGeneButton, createGeneButton, 3, Push.VerticalAlign.Left);
            deleteGeneButton.Width  = 200;
            deleteGeneButton.Click += delegate(object sender)
            {
                if (columnListBox.SelectedRow != null)
                {
                    var findID = (uint)columnListBox.SelectedRow.Values[2];

                    int n = 0;
                    foreach (var g in geneList)
                    {
                        if (g.ID == findID)
                        {
                            geneList.RemoveAt(n);
                            ReloadListBox();
                            break;
                        }
                        n++;
                    }
                }
            };

            var okButton = new ResizableButton();

            okButton.Initialize();
            AddDrawBox(okButton);
            okButton.Title = "OK";
            okButton.FitToText();
            Push.ToTheBottomSideOf(okButton, deleteGeneButton, 3, Push.VerticalAlign.Left);
            okButton.Width  = 200;
            okButton.Click += delegate(object sender)
            {
                Close();
            };

            Wrap();

            columnListBox.Alignment    = DrawBoxAlignment.GetFull();
            moveUpButton.Alignment     = DrawBoxAlignment.GetLeftRightBottom();
            moveDownButton.Alignment   = DrawBoxAlignment.GetLeftRightBottom();
            createGeneButton.Alignment = DrawBoxAlignment.GetLeftRightBottom();
            deleteGeneButton.Alignment = DrawBoxAlignment.GetLeftRightBottom();
            okButton.Alignment         = DrawBoxAlignment.GetLeftRightBottom();

            X = (Parent.Width / 2) - (Width / 2);
            Y = (Parent.Height / 2) - (Height / 2);
        }
 public IGene GetNewGene()
 {
     IGene instance = new DoubleGene();
     return instance;
 }
Beispiel #16
0
        /// <summary>
        /// Calculates the objective based on Ackley's function.
        /// </summary>
        /// <param name="c"></param>
        /// <returns></returns>
        /// <remarks>
        /// Ackley's function is given by:
        ///
        ///             F(x) = 20 + e
        ///                    - 20*exp(-0.2*sqrt((1/n)*Sum(i=1,n) {x_i^2}))
        ///                    - exp((1/n)*Sum(i=1,n){cos(2*pi*x_i)})

        /// </remarks>
        public static double AckleyMinimizationObjective(Chromosome c)
        {
            int n = c.Genes.Length;

            DoubleGene[] x = new DoubleGene[c.Genes.Length];
            Array.Copy(c.Genes, x, c.Genes.Length);  // performs type casting for each element
            double f;
            double objective;


            // Split the equation into three parts:
            // F(x) =
            //  (a)    20 + e
            //  (b)    - 20*exp(-0.2*sqrt((1/n)*Sum(i=1,n) {x_i^2}))
            //  (c)    - exp((1/n)*Sum(i=1,n){cos(2*pi*x_i)})


            //
            // Calculate the (c) part.
            //
            double f_c = 0;

            for (int i = 0; i < n; i++)
            {
                f_c += Math.Cos(2 * Math.PI * x[i].Value);
            }
            f_c *= (1.0 / n);
            f_c  = -Math.Exp(f_c);

            //
            // Calculate the (b) part
            //
            double f_b = 0;

            for (int i = 0; i < n; i++)
            {
                double sum;
                sum  = (x[i].Value * x[i].Value) / n;
                f_b += sum;
            }
            f_b  = Math.Sqrt(f_b);
            f_b *= -0.2;
            f_b  = Math.Exp(f_b);
            f_b *= -20.0;

            //
            // Calculate the (a) part
            //
            double f_a = 0;

            f_a = 20.0 + Math.E;


            //
            // Calculate the total as (a) + (b) + (c)
            //
            f = f_a + f_b + f_c;

            objective = Math.Abs(f);

            return(objective);
        }
Beispiel #17
0
 protected static double GetDoubleFromGene(DoubleGene gene, double max)
 {
     return(GetDoubleFromGene(gene, 0, max));
 }
Beispiel #18
0
 protected static double GetDoubleFromGene(DoubleGene gene, double min, double max)
 {
     return(min + (max - min) * gene.Value);
 }
Beispiel #19
0
        public override void AddedToContainer()
        {
            base.AddedToContainer();

            CloseButtonOn = false;

            var builder = new FieldBuilder();

            builder.BuildSessionStart(this);

            var symmetricalBordersCheckBox = builder.AddCheckBoxField("Symmetrical Borders: ");

            symmetricalBordersCheckBox.Checked = sigmoid.SymmetricalBorders;

            builder.AddLabelField("P: ");
            var pMin     = builder.AddDoubleField("Min: ");
            var pMax     = builder.AddDoubleField("Max: ");
            var pVal     = builder.AddDoubleField("Value: ");
            var pMutable = builder.AddCheckBoxField("IsMutable: ");

            builder.AddVerticalMargin(4);

            builder.AddLabelField("Output-Border: ");
            var o1Min     = builder.AddDoubleField("Min: ");
            var o1Max     = builder.AddDoubleField("Max: ");
            var o1Val     = builder.AddDoubleField("Value: ");
            var o1Mutable = builder.AddCheckBoxField("IsMutable: ");

            var switchBox = new SwitchBox();

            switchBox.Initialize();
            builder.AddDrawBoxAsField(switchBox, DrawBoxAlignment.GetLeftRight());

            var emptyPanel = new Panel();

            emptyPanel.Initialize();

            switchBox.AddDrawBox(emptyPanel, "symmetrical");

            var panel = new Panel();

            panel.Initialize();

            var builder2 = new FieldBuilder();

            builder2.BuildSessionStart(panel);
            builder2.AddLabelField("Output-Border 2: ");
            var o2Min     = builder2.AddDoubleField("Min: ");
            var o2Max     = builder2.AddDoubleField("Max: ");
            var o2Val     = builder2.AddDoubleField("Value: ");
            var o2Mutable = builder2.AddCheckBoxField("IsMutable: ");

            builder2.BuildSessionEnd();

            switchBox.AddDrawBox(panel, "non-symmetrical");

            int largestHeight = 0;

            foreach (var p in switchBox.DrawBoxList)
            {
                if (p.Height > largestHeight)
                {
                    largestHeight = panel.Height;
                }
            }

            switchBox.Width  = builder.FieldWidth;
            switchBox.Height = largestHeight;

            if (sigmoid.GeneList.Count != 0)
            {
                var o1Gene = (DoubleGene)sigmoid.GeneList[0];
                o1Min.Value       = o1Gene.Min;
                o1Max.Value       = o1Gene.Max;
                o1Val.Value       = o1Gene.Value;
                o1Mutable.Checked = o1Gene.IsMutable;

                int n = 1;

                if (!sigmoid.SymmetricalBorders)
                {
                    var o2Gene = (DoubleGene)sigmoid.GeneList[n++];
                    o2Min.Value       = o2Gene.Min;
                    o2Max.Value       = o2Gene.Max;
                    o2Val.Value       = o2Gene.Value;
                    o2Mutable.Checked = o2Gene.IsMutable;
                }

                var pGene = (DoubleGene)sigmoid.GeneList[n++];
                pMin.Value       = pGene.Min;
                pMax.Value       = pGene.Max;
                pVal.Value       = pGene.Value;
                pMutable.Checked = pGene.IsMutable;
            }

            if (sigmoid.SymmetricalBorders)
            {
                switchBox.SelectDrawBoxWithKey("symmetrical");
            }
            else
            {
                switchBox.SelectDrawBoxWithKey("non-symmetrical");
            }

            symmetricalBordersCheckBox.CheckedChanged += delegate(object sender, bool newValue)
            {
                if (newValue)
                {
                    switchBox.SelectDrawBoxWithKey("symmetrical");
                }
                else
                {
                    switchBox.SelectDrawBoxWithKey("non-symmetrical");
                }
            };

            builder.AddResizableButtonField("OK", delegate(object sender)
            {
                Close();
            }, FieldBuilder.ResizableButtonOrientation.Left);

            builder.BuildSessionEnd();

            IsClosing += delegate(object sender)
            {
                geneList.Clear();

                var _o1Gene = new DoubleGene();
                _o1Gene.SetMinMaxValue(o1Min.Value, o1Max.Value, o1Val.Value);
                _o1Gene.IsMutable = o1Mutable.Checked;
                geneList.Add(_o1Gene);

                if (!symmetricalBordersCheckBox.Checked)
                {
                    var _o2Gene = new DoubleGene();
                    _o2Gene.SetMinMaxValue(o2Min.Value, o2Max.Value, o2Val.Value);
                    _o2Gene.IsMutable = pMutable.Checked;
                    geneList.Add(_o2Gene);
                }

                var _pGene = new DoubleGene();
                _pGene.SetMinMaxValue(pMin.Value, pMax.Value, pVal.Value);
                _pGene.IsMutable = pMutable.Checked;
                geneList.Add(_pGene);
            };

            CanResizeFormVertically = false;

            X = (Parent.Width / 2) - (Width / 2);
            Y = (Parent.Height / 2) - (Height / 2);
        }