Example #1
0
        public override IOperation Apply()
        {
            BinaryVector   binaryVector = BinaryVectorParameter.ActualValue;
            OneBitflipMove move         = OneBitflipMoveParameter.ActualValue;
            double         moveQuality  = QualityParameter.ActualValue.Value;

            if (binaryVector[move.Index])
            {
                moveQuality -= 1.0;
            }
            else
            {
                moveQuality += 1.0;
            }

            if (MoveQualityParameter.ActualValue == null)
            {
                MoveQualityParameter.ActualValue = new DoubleValue(moveQuality);
            }
            else
            {
                MoveQualityParameter.ActualValue.Value = moveQuality;
            }
            return(base.Apply());
        }
 private OneMaxSolution(OneMaxSolution original, Cloner cloner)
     : base(original, cloner)
 {
     binaryVector = cloner.Clone(original.binaryVector);
     quality      = cloner.Clone(original.quality);
     Initialize();
 }
        private static double Donate(BinaryVector solution, double fitness, BinaryVector source, IEnumerable <int> cluster, BinaryProblem problem, IRandom rand, out bool changed)
        {
            // keep track of which bits flipped to make the donation
            List <int> flipped = new List <int>();

            foreach (var index in cluster)
            {
                if (solution[index] != source[index])
                {
                    flipped.Add(index);
                    solution[index] = !solution[index];
                }
            }
            changed = flipped.Count > 0;
            if (changed)
            {
                double newFitness = problem.Evaluate(solution, rand);
                // if the original is strictly better, revert the change
                if (problem.IsBetter(fitness, newFitness))
                {
                    foreach (var index in flipped)
                    {
                        solution[index] = !solution[index];
                    }
                }
                else
                {
                    // new solution is no worse than original, keep change to solution
                    fitness = newFitness;
                }
            }
            return(fitness);
        }
Example #4
0
        public Prediction <LblT> Predict(BinaryVector example)
        {
            Prediction <LblT> pred = new Prediction <LblT>();
            double            sum  = 0;

            for (int i = 0; i < mIdxToLbl.Length; i++)
            {
                //Console.WriteLine("Predicting for {0}", mIdxToLbl[i]);
                double pc = ((double)mExampleCount[i] + 2.0 / (double)mIdxToLbl.Length) / ((double)mDatasetCount + 2.0); // class prior probability estimate
                foreach (int featIdx in example)
                {
                    double pFeat;
                    if (mFeatureProb[i].TryGetValue(featIdx, out pFeat))
                    {
                        pc *= pFeat;
                    }
                    else if (mFeaturePriors.TryGetValue(featIdx, out pFeat))
                    {
                        pc *= 2.0 * pFeat / ((double)mExampleCount[i] + 2.0);
                    }
                }
                pred.Inner.Add(new KeyDat <double, LblT>(pc, mIdxToLbl[i]));
                sum += pc;
            }
            if (mNormalize && sum > 0)
            {
                for (int i = 0; i < pred.Count; i++)
                {
                    KeyDat <double, LblT> score = pred[i];
                    pred.Inner[i] = new KeyDat <double, LblT>(score.Key / sum, score.Dat);
                }
            }
            pred.Inner.Sort(DescSort <KeyDat <double, LblT> > .Instance);
            return(pred);
        }
Example #5
0
        public override double Evaluate(BinaryVector vector, IRandom random)
        {
            double[] f_i; //useful for debugging
            double   quality = Evaluate(vector, GeneInteractions, Weights, InteractionSeed.Value, out f_i, Q, P);

            return(quality);
        }
        public override IOperation Apply()
        {
            BinaryVector   binaryVector = BinaryVectorParameter.ActualValue;
            OneBitflipMove move         = OneBitflipMoveParameter.ActualValue;

            BinaryVector newSolution = new BinaryVector(binaryVector);

            newSolution[move.Index] = !newSolution[move.Index];

            DoubleValue quality = KnapsackEvaluator.Apply(newSolution,
                                                          KnapsackCapacityParameter.ActualValue,
                                                          PenaltyParameter.ActualValue,
                                                          WeightsParameter.ActualValue,
                                                          ValuesParameter.ActualValue).Quality;

            double moveQuality = quality.Value;

            if (MoveQualityParameter.ActualValue == null)
            {
                MoveQualityParameter.ActualValue = new DoubleValue(moveQuality);
            }
            else
            {
                MoveQualityParameter.ActualValue.Value = moveQuality;
            }
            return(base.Apply());
        }
Example #7
0
        // In the GECCO paper, Figure 1
        private double iterate()
        {
            // Create a random solution
            BinaryVector solution = new BinaryVector(tracker.Length);

            for (int i = 0; i < solution.Length; i++)
            {
                solution[i] = random.Next(2) == 1;
            }
            double fitness = tracker.Evaluate(solution, random);

            fitness = HillClimber.ImproveToLocalOptimum(tracker, solution, fitness, random);
            AddIfUnique(solution, 0);

            for (int level = 0; level < pyramid.Count; level++)
            {
                var    current    = pyramid[level];
                double newFitness = LinkageCrossover.ImproveUsingTree(current.Tree, current.Solutions, solution, fitness, tracker, random);
                // add it to the next level if its a strict fitness improvement
                if (tracker.IsBetter(newFitness, fitness))
                {
                    fitness = newFitness;
                    AddIfUnique(solution, level + 1);
                }
            }
            return(fitness);
        }
 public OneMaxSolution(BinaryVector binaryVector, DoubleValue quality)
     : base()
 {
     this.binaryVector = binaryVector;
     this.quality      = quality;
     Initialize();
 }
Example #9
0
        // In the GECCO paper, Section 2.1
        public static double ImproveToLocalOptimum(BinaryProblem problem, BinaryVector solution, double fitness, IRandom rand)
        {
            var tried = new HashSet <int>();

            do
            {
                var options = Enumerable.Range(0, solution.Length).Shuffle(rand);
                foreach (var option in options)
                {
                    if (tried.Contains(option))
                    {
                        continue;
                    }
                    solution[option] = !solution[option];
                    double newFitness = problem.Evaluate(solution, rand);
                    if (problem.IsBetter(newFitness, fitness))
                    {
                        fitness = newFitness;
                        tried.Clear();
                    }
                    else
                    {
                        solution[option] = !solution[option];
                    }
                    tried.Add(option);
                }
            } while (tried.Count != solution.Length);
            return(fitness);
        }
        protected override int Score(BinaryVector individual, int trapIndex, int trapSize)
        {
            int partial = base.Score(individual, trapIndex, trapSize);

            // introduce plateaus using integer division
            return((Offset + partial) / StepSize);
        }
        public static double CalculateSimilarity(BinaryVector left, BinaryVector right)
        {
            if (left == null || right == null)
            {
                throw new ArgumentException("Cannot calculate similarity because one or both of the provided scopes is null.");
            }
            if (left.Length != right.Length)
            {
                throw new ArgumentException("Cannot calculate similarity because the provided solutions have different lengths.");
            }
            if (left == right)
            {
                return(1.0);
            }

            double similarity = 0.0;

            for (int i = 0; i < left.Length; i++)
            {
                if (left[i] == right[i])
                {
                    similarity++;
                }
            }
            return(similarity / left.Length);
        }
Example #12
0
        public static double Evaluate(BinaryVector vector, BoolMatrix interactions, DoubleArray weights, int seed, out double[] f_i, int q, double p)
        {
            long x = Encode(vector);

            long[]   g = Encode(interactions);
            double[] w = Normalize(weights);
            f_i = new double[interactions.Columns];
            return(F(x, g, w, (long)seed, ref f_i, q, p));
        }
Example #13
0
        public Prediction <LblT> Predict(BinaryVector example)
        {
            Utils.ThrowException(example == null ? new ArgumentNullException("example") : null);
            Prediction <LblT> pred = new Prediction <LblT>();
            double            sum  = 0;

            for (int i = 0; i < mIdxToLbl.Length; i++)
            {
                double pc;
                if (!mLogSumExpTrick)
                {
                    pc = ((double)mExampleCount[i] + 2.0 / (double)mIdxToLbl.Length) / ((double)mDatasetCount + 2.0); // class prior probability estimate
                    foreach (int featIdx in example)
                    {
                        double pFeat;
                        if (mFeatureProb[i].TryGetValue(featIdx, out pFeat))
                        {
                            pc *= pFeat;
                        }
                        else if (mFeaturePriors.TryGetValue(featIdx, out pFeat))
                        {
                            pc *= 2.0 * pFeat / ((double)mExampleCount[i] + 2.0); // m-estimate (m = 2, feature count = 0)
                        }
                    }
                }
                else // log-sum-exp trick (slower but prevents underflowing)
                {
                    pc = Math.Log(((double)mExampleCount[i] + 2.0 / (double)mIdxToLbl.Length) / ((double)mDatasetCount + 2.0));
                    foreach (int featIdx in example)
                    {
                        double pFeat;
                        if (mFeatureProb[i].TryGetValue(featIdx, out pFeat))
                        {
                            pc += Math.Log(pFeat);
                        }
                        else if (mFeaturePriors.TryGetValue(featIdx, out pFeat))
                        {
                            pc += Math.Log(2.0 * pFeat / ((double)mExampleCount[i] + 2.0));
                        }
                    }
                    pc = Math.Exp(pc);
                }
                pred.Inner.Add(new KeyDat <double, LblT>(pc, mIdxToLbl[i]));
                sum += pc;
            }
            if (mNormalize && sum > 0)
            {
                for (int i = 0; i < pred.Count; i++)
                {
                    KeyDat <double, LblT> score = pred[i];
                    pred.Inner[i] = new KeyDat <double, LblT>(score.Key / sum, score.Dat);
                }
            }
            pred.Inner.Sort(DescSort <KeyDat <double, LblT> > .Instance);
            return(pred);
        }
        public static ItemArray <IItem> Apply(IItem initiator, IItem guide, PercentValue n)
        {
            if (!(initiator is BinaryVector) || !(guide is BinaryVector))
            {
                throw new ArgumentException("Cannot relink path because one of the provided solutions or both have the wrong type.");
            }
            if (n.Value <= 0.0)
            {
                throw new ArgumentException("RelinkingAccuracy must be greater than 0.");
            }

            BinaryVector firstInitiator  = initiator.Clone() as BinaryVector;
            BinaryVector firstGuide      = guide.Clone() as BinaryVector;
            BinaryVector secondInitiator = firstGuide.Clone() as BinaryVector;
            BinaryVector secondGuide     = firstInitiator.Clone() as BinaryVector;

            if (firstInitiator.Length != firstGuide.Length)
            {
                throw new ArgumentException("The solutions are of different length.");
            }

            IList <BinaryVector> solutions = new List <BinaryVector>();

            for (int i = 0; i < firstInitiator.Length / 2; i++)
            {
                if (firstInitiator[i] != firstGuide[i])
                {
                    firstInitiator[i] = firstGuide[i];
                    solutions.Add(firstInitiator.Clone() as BinaryVector);
                }
                int j = secondInitiator.Length - 1 - i;
                if (secondInitiator[j] != secondGuide[j])
                {
                    secondInitiator[j] = secondGuide[j];
                    solutions.Add(secondInitiator.Clone() as BinaryVector);
                }
            }

            IList <IItem> selection = new List <IItem>();

            if (solutions.Count > 0)
            {
                int noSol = (int)(solutions.Count * n.Value);
                if (noSol <= 0)
                {
                    noSol++;
                }
                double stepSize = (double)solutions.Count / (double)noSol;
                for (int i = 0; i < noSol; i++)
                {
                    selection.Add(solutions.ElementAt((int)((i + 1) * stepSize - stepSize * 0.5)));
                }
            }

            return(new ItemArray <IItem>(selection));
        }
Example #15
0
 private EvaluationTracker(EvaluationTracker original, Cloner cloner)
     : base(original, cloner)
 {
     problem               = cloner.Clone(original.problem);
     maxEvaluations        = original.maxEvaluations;
     BestQuality           = original.BestQuality;
     Evaluations           = original.Evaluations;
     BestFoundOnEvaluation = original.BestFoundOnEvaluation;
     BestSolution          = cloner.Clone(original.BestSolution);
 }
Example #16
0
        public static long Encode(BinaryVector v)
        {
            long x = 0;

            for (int i = 0; i < 64 && i < v.Length; i++)
            {
                x |= (v[i] ? (long)1 : (long)0) << i;
            }
            return(x);
        }
 public KnapsackSolution(BinaryVector binaryVector, DoubleValue quality, IntValue capacity, IntArray weights, IntArray values)
     : base()
 {
     this.binaryVector = binaryVector;
     this.capacity     = capacity;
     this.weights      = weights;
     this.values       = values;
     this.quality      = quality;
     Initialize();
 }
 protected KnapsackSolution(KnapsackSolution original, Cloner cloner)
     : base(original, cloner)
 {
     this.binaryVector = cloner.Clone(original.binaryVector);
     this.quality      = cloner.Clone(original.quality);
     this.capacity     = cloner.Clone(original.capacity);
     this.weights      = cloner.Clone(original.weights);
     this.values       = cloner.Clone(original.values);
     Initialize();
 }
Example #19
0
        protected override void Run(CancellationToken cancellationToken)
        {
            // Set up the algorithm
            if (SetSeedRandomly)
            {
                Seed = new System.Random().Next();
            }
            pyramid = new List <Population>();
            seen.Clear();
            random.Reset(Seed);
            tracker = new EvaluationTracker(Problem, MaximumEvaluations);

            // Set up the results display
            Results.Add(new Result("Iterations", new IntValue(0)));
            Results.Add(new Result("Evaluations", new IntValue(0)));
            Results.Add(new Result("Best Solution", new BinaryVector(tracker.BestSolution)));
            Results.Add(new Result("Best Quality", new DoubleValue(tracker.BestQuality)));
            Results.Add(new Result("Evaluation Best Solution Was Found", new IntValue(tracker.BestFoundOnEvaluation)));
            var table = new DataTable("Qualities");

            table.Rows.Add(new DataRow("Best Quality"));
            var iterationRows = new DataRow("Iteration Quality");

            iterationRows.VisualProperties.LineStyle = DataRowVisualProperties.DataRowLineStyle.Dot;
            table.Rows.Add(iterationRows);
            Results.Add(new Result("Qualities", table));

            table = new DataTable("Pyramid Levels");
            table.Rows.Add(new DataRow("Levels"));
            Results.Add(new Result("Pyramid Levels", table));

            table = new DataTable("Stored Solutions");
            table.Rows.Add(new DataRow("Solutions"));
            Results.Add(new Result("Stored Solutions", table));

            // Loop until iteration limit reached or canceled.
            for (ResultsIterations = 0; ResultsIterations < MaximumIterations; ResultsIterations++)
            {
                double fitness = double.NaN;

                try {
                    fitness = iterate();
                    cancellationToken.ThrowIfCancellationRequested();
                } finally {
                    ResultsEvaluations           = tracker.Evaluations;
                    ResultsBestSolution          = new BinaryVector(tracker.BestSolution);
                    ResultsBestQuality           = tracker.BestQuality;
                    ResultsBestFoundOnEvaluation = tracker.BestFoundOnEvaluation;
                    ResultsQualitiesBest.Values.Add(tracker.BestQuality);
                    ResultsQualitiesIteration.Values.Add(fitness);
                    ResultsLevels.Values.Add(pyramid.Count);
                    ResultsSolutions.Values.Add(seen.Count);
                }
            }
        }
Example #20
0
 public static bool BinaryVectorIsEqualByPosition(BinaryVector p1, BinaryVector p2) {
   bool equal = (p1.Length == p2.Length);
   if (equal) {
     for (int i = 0; i < p1.Length; i++) {
       if (!p1[i].Equals(p2[i])) {
         equal = false;
         break;
       }
     }
   }
   return equal;
 }
        public override IOperation Apply()
        {
            BinaryVector   binaryVector = BinaryVectorParameter.ActualValue;
            OneBitflipMove move         = OneBitflipMoveParameter.ActualValue;
            BoolMatrix     interactions = GeneInteractionsParameter.ActualValue;
            DoubleArray    weights      = WeightsParameter.ActualValue;
            int            seed         = InteractionSeedParameter.ActualValue.Value;
            double         moveQuality  = QualityParameter.ActualValue.Value;
            int            q            = QParameter.ActualValue.Value;
            double         p            = PParameter.ActualValue.Value;

            List <int> affectedFitnessComponents = new List <int>();

            for (int c = 0; c < interactions.Columns; c++)
            {
                if (interactions[move.Index, c])
                {
                    affectedFitnessComponents.Add(c);
                }
            }
            BinaryVector moved = new BinaryVector(binaryVector);

            MovedBinaryVectorParameter.ActualValue = moved;
            moved[move.Index] = !moved[move.Index];
            if (affectedFitnessComponents.Count * 2 > interactions.Columns)
            {
                double[] f_i;
                moveQuality = NKLandscape.Evaluate(moved, interactions, weights, seed, out f_i, q, p);
            }
            else
            {
                long     x = NKLandscape.Encode(binaryVector);
                long     y = NKLandscape.Encode(moved);
                long[]   g = NKLandscape.Encode(interactions);
                double[] w = NKLandscape.Normalize(weights);
                foreach (var c in affectedFitnessComponents)
                {
                    moveQuality -= w[c % w.Length] * NKLandscape.F_i(x, c, g[c], seed, q, p);
                    moveQuality += w[c % w.Length] * NKLandscape.F_i(y, c, g[c], seed, q, p);
                }
            }

            if (MoveQualityParameter.ActualValue == null)
            {
                MoveQualityParameter.ActualValue = new DoubleValue(moveQuality);
            }
            else
            {
                MoveQualityParameter.ActualValue.Value = moveQuality;
            }
            return(base.Apply());
        }
Example #22
0
        public static ClassifierResult <LblT> Classify <LblT>(BinaryVector <int> .ReadOnly bin_vec, SparseMatrix <double> .ReadOnly lambdas, LblT[] idx_to_lbl)
        {
            DotProductSimilarity  dot_prod            = new DotProductSimilarity();
            SparseVector <double> vec                 = ModelUtils.ConvertExample <SparseVector <double> >(bin_vec);
            ArrayList <KeyDat <double, LblT> > scores = new ArrayList <KeyDat <double, LblT> >();

            foreach (IdxDat <SparseVector <double> .ReadOnly> row in lambdas)
            {
                double score = Math.Exp(dot_prod.GetSimilarity(row.Dat, vec));
                scores.Add(new KeyDat <double, LblT>(score, idx_to_lbl[row.Idx]));
            }
            return(new ClassifierResult <LblT>(scores));
            // *** for some reason, the code below is slower than the one currently in use

            /*ClassifierResult<LblT> classifier_result = new ClassifierResult<LblT>();
             * foreach (IdxDat<SparseVector<double>.ReadOnly> row in lambdas)
             * {
             *  int i = 0, j = 0;
             *  int a_count = bin_vec.Count;
             *  int b_count = row.Dat.Count;
             *  double dot_prod = 0;
             *  List<int> a_idx = bin_vec.Inner.Inner;
             *  ArrayList<int> b_idx = row.Dat.Inner.InnerIdx;
             *  ArrayList<double> b_dat = row.Dat.Inner.InnerDat;
             *  int a_idx_i = a_idx[0];
             *  int b_idx_j = b_idx[0];
             *  while (true)
             *  {
             *      if (a_idx_i < b_idx_j)
             *      {
             *          if (++i == a_count) { break; }
             *          a_idx_i = a_idx[i];
             *      }
             *      else if (a_idx_i > b_idx_j)
             *      {
             *          if (++j == b_count) { break; }
             *          b_idx_j = b_idx[j];
             *      }
             *      else
             *      {
             *          dot_prod += b_dat[j];
             *          if (++i == a_count || ++j == b_count) { break; }
             *          a_idx_i = a_idx[i];
             *          b_idx_j = b_idx[j];
             *      }
             *  }
             *  double score = Math.Exp(dot_prod);
             *  classifier_result.Inner.Add(new KeyDat<double, LblT>(score, idx_to_lbl[row.Idx]));
             * }
             * classifier_result.Inner.Sort(new DescSort<KeyDat<double, LblT>>());
             * return classifier_result;*/
        }
 public void SinglePositionBitflipManipulatorApplyTest() {
   TestRandom random = new TestRandom();
   BinaryVector parent, expected;
   // The following test is based on Michalewicz, Z. 1999. Genetic Algorithms + Data Structures = Evolution Programs. Third, Revised and Extended Edition, Spring-Verlag Berlin Heidelberg, p. 21.
   random.Reset();
   random.IntNumbers = new int[] { 4 };
   parent = new BinaryVector(new bool[] { true, true, true, false, false, false, false, false, false, 
     false, true, true, true, true, true, true, false, false, false, true, false, true});
   expected = new BinaryVector(new bool[] { true, true, true, false, true, false, false, false, false, 
     false, true, true, true, true, true, true, false, false, false, true, false, true});
   SinglePositionBitflipManipulator.Apply(random, parent);
   Assert.IsTrue(Auxiliary.BinaryVectorIsEqualByPosition(expected, parent));
 }
        private static int MedianBit(BinaryVector x)
        {
            var activeIndices = x.Select((b, i) => new { b, i }).Where(v => v.b).ToList();

            if (activeIndices.Count > 0)
            {
                return(activeIndices[activeIndices.Count / 2].i);
            }
            else
            {
                return(0);
            }
        }
        public void NPointCrossoverApplyTest()
        {
            TestRandom   random = new TestRandom();
            BinaryVector parent1, parent2, expected, actual;
            IntValue     n;
            bool         exceptionFired;

            // The following test is based on Eiben, A.E. and Smith, J.E. 2003. Introduction to Evolutionary Computation. Natural Computing Series, Springer-Verlag Berlin Heidelberg, p. 48
            random.Reset();
            n = new IntValue(1);
            random.IntNumbers = new int[] { 4 };
            parent1           = new BinaryVector(new bool[] { false, false, false, false, true, false, false, false, false });
            parent2           = new BinaryVector(new bool[] { true, true, false, true, false, false, false, false, true });
            expected          = new BinaryVector(new bool[] { false, false, false, false, false, false, false, false, true });
            actual            = NPointCrossover.Apply(random, parent1, parent2, n);
            Assert.IsTrue(Auxiliary.BinaryVectorIsEqualByPosition(actual, expected));

            // The following test is based on Eiben, A.E. and Smith, J.E. 2003. Introduction to Evolutionary Computation. Natural Computing Series, Springer-Verlag Berlin Heidelberg, p. 48
            random.Reset();
            n = new IntValue(2);
            random.IntNumbers = new int[] { 4, 5 };
            parent1           = new BinaryVector(new bool[] { false, false, false, false, true, false, false, false, false });
            parent2           = new BinaryVector(new bool[] { true, true, false, true, false, false, false, false, true });
            expected          = new BinaryVector(new bool[] { false, false, false, false, false, false, false, false, false });
            actual            = NPointCrossover.Apply(random, parent1, parent2, n);
            Assert.IsTrue(Auxiliary.BinaryVectorIsEqualByPosition(actual, expected));

            // The following test is based on Eiben, A.E. and Smith, J.E. 2003. Introduction to Evolutionary Computation. Natural Computing Series, Springer-Verlag Berlin Heidelberg, p. 48
            random.Reset();
            n = new IntValue(2);
            random.IntNumbers = new int[] { 4, 5 };
            parent2           = new BinaryVector(new bool[] { false, false, false, false, true, false, false, false, false });
            parent1           = new BinaryVector(new bool[] { true, true, false, true, false, false, false, false, true });
            expected          = new BinaryVector(new bool[] { true, true, false, true, true, false, false, false, true });
            actual            = NPointCrossover.Apply(random, parent1, parent2, n);
            Assert.IsTrue(Auxiliary.BinaryVectorIsEqualByPosition(actual, expected));

            // The following test is not based on any published examples
            random.Reset();
            random.IntNumbers = new int[] { 2 };
            parent1           = new BinaryVector(new bool[] { false, true, true, false, false }); // this parent is longer
            parent2           = new BinaryVector(new bool[] { false, true, true, false });
            exceptionFired    = false;
            try {
                actual = NPointCrossover.Apply(random, parent1, parent2, n);
            }
            catch (System.ArgumentException) {
                exceptionFired = true;
            }
            Assert.IsTrue(exceptionFired);
        }
Example #26
0
    public void NPointCrossoverApplyTest() {
      TestRandom random = new TestRandom();
      BinaryVector parent1, parent2, expected, actual;
      IntValue n;
      bool exceptionFired;
      // The following test is based on Eiben, A.E. and Smith, J.E. 2003. Introduction to Evolutionary Computation. Natural Computing Series, Springer-Verlag Berlin Heidelberg, p. 48
      random.Reset();
      n = new IntValue(1);
      random.IntNumbers = new int[] { 4 };
      parent1 = new BinaryVector(new bool[] { false, false, false, false, true, false, false, false, false });
      parent2 = new BinaryVector(new bool[] { true, true, false, true, false, false, false, false, true });
      expected = new BinaryVector(new bool[] { false, false, false, false, false, false, false, false, true });
      actual = NPointCrossover.Apply(random, parent1, parent2, n);
      Assert.IsTrue(Auxiliary.BinaryVectorIsEqualByPosition(actual, expected));

      // The following test is based on Eiben, A.E. and Smith, J.E. 2003. Introduction to Evolutionary Computation. Natural Computing Series, Springer-Verlag Berlin Heidelberg, p. 48
      random.Reset();
      n = new IntValue(2);
      random.IntNumbers = new int[] { 4, 5 };
      parent1 = new BinaryVector(new bool[] { false, false, false, false, true, false, false, false, false });
      parent2 = new BinaryVector(new bool[] { true, true, false, true, false, false, false, false, true });
      expected = new BinaryVector(new bool[] { false, false, false, false, false, false, false, false, false });
      actual = NPointCrossover.Apply(random, parent1, parent2, n);
      Assert.IsTrue(Auxiliary.BinaryVectorIsEqualByPosition(actual, expected));

      // The following test is based on Eiben, A.E. and Smith, J.E. 2003. Introduction to Evolutionary Computation. Natural Computing Series, Springer-Verlag Berlin Heidelberg, p. 48
      random.Reset();
      n = new IntValue(2);
      random.IntNumbers = new int[] { 4, 5 };
      parent2 = new BinaryVector(new bool[] { false, false, false, false, true, false, false, false, false });
      parent1 = new BinaryVector(new bool[] { true, true, false, true, false, false, false, false, true });
      expected = new BinaryVector(new bool[] { true, true, false, true, true, false, false, false, true });
      actual = NPointCrossover.Apply(random, parent1, parent2, n);
      Assert.IsTrue(Auxiliary.BinaryVectorIsEqualByPosition(actual, expected));

      // The following test is not based on any published examples
      random.Reset();
      random.IntNumbers = new int[] { 2 };
      parent1 = new BinaryVector(new bool[] { false, true, true, false, false }); // this parent is longer
      parent2 = new BinaryVector(new bool[] { false, true, true, false });
      exceptionFired = false;
      try {
        actual = NPointCrossover.Apply(random, parent1, parent2, n);
      }
      catch (System.ArgumentException) {
        exceptionFired = true;
      }
      Assert.IsTrue(exceptionFired);
    }
        public override double Evaluate(BinaryVector individual, IRandom random)
        {
            if (individual.Length != Length)
            {
                throw new ArgumentException("The individual has not the correct length.");
            }
            int total    = 0;
            var trapSize = TrapSize;

            for (int i = 0; i < individual.Length; i += trapSize)
            {
                total += Score(individual, i, trapSize);
            }
            return((double)(total * trapSize) / (TrapMaximum * individual.Length));
        }
        public void SinglePositionBitflipManipulatorApplyTest()
        {
            TestRandom   random = new TestRandom();
            BinaryVector parent, expected;

            // The following test is based on Michalewicz, Z. 1999. Genetic Algorithms + Data Structures = Evolution Programs. Third, Revised and Extended Edition, Spring-Verlag Berlin Heidelberg, p. 21.
            random.Reset();
            random.IntNumbers = new int[] { 4 };
            parent            = new BinaryVector(new bool[] { true, true, true, false, false, false, false, false, false,
                                                              false, true, true, true, true, true, true, false, false, false, true, false, true });
            expected = new BinaryVector(new bool[] { true, true, true, false, true, false, false, false, false,
                                                     false, true, true, true, true, true, true, false, false, false, true, false, true });
            SinglePositionBitflipManipulator.Apply(random, parent);
            Assert.IsTrue(Auxiliary.BinaryVectorIsEqualByPosition(expected, parent));
        }
Example #29
0
        private void AddIfUnique(BinaryVector solution, int level)
        {
            // Don't add things you have seen
            if (seen.Contains(solution))
            {
                return;
            }
            if (level == pyramid.Count)
            {
                pyramid.Add(new Population(tracker.Length, random));
            }
            var copied = (BinaryVector)solution.Clone();

            pyramid[level].Add(copied);
            seen.Add(copied);
        }
        public sealed override IOperation InstrumentedApply()
        {
            BinaryVector v = BinaryVectorParameter.ActualValue;

            KnapsackEvaluation evaluation = Apply(BinaryVectorParameter.ActualValue,
                                                  KnapsackCapacityParameter.ActualValue,
                                                  PenaltyParameter.ActualValue,
                                                  WeightsParameter.ActualValue,
                                                  ValuesParameter.ActualValue);

            QualityParameter.ActualValue        = evaluation.Quality;
            SumWeightsParameter.ActualValue     = evaluation.SumWeights;
            SumValuesParameter.ActualValue      = evaluation.SumValues;
            AppliedPenaltyParameter.ActualValue = evaluation.AppliedPenalty;

            return(base.InstrumentedApply());
        }
Example #31
0
        public override double Evaluate(BinaryVector vector, IRandom random)
        {
            if (Evaluations >= maxEvaluations)
            {
                throw new OperationCanceledException("Maximum Evaluation Limit Reached");
            }
            Evaluations++;
            double fitness = problem.Evaluate(vector, random);

            if (double.IsNaN(BestQuality) || problem.IsBetter(fitness, BestQuality))
            {
                BestQuality           = fitness;
                BestSolution          = (BinaryVector)vector.Clone();
                BestFoundOnEvaluation = Evaluations;
            }
            return(fitness);
        }
Example #32
0
        public static bool BinaryVectorIsEqualByPosition(BinaryVector p1, BinaryVector p2)
        {
            bool equal = (p1.Length == p2.Length);

            if (equal)
            {
                for (int i = 0; i < p1.Length; i++)
                {
                    if (!p1[i].Equals(p2[i]))
                    {
                        equal = false;
                        break;
                    }
                }
            }
            return(equal);
        }
Example #33
0
        public BoolMatrix InitializeInterations(int length, int nComponents, int nInteractions, IRandom random)
        {
            Dictionary <int, int> bitInteractionCounts = new Dictionary <int, int>();

            for (int i = 0; i < length; i++)
            {
                int count = nInteractions * 2 * i / length;
                if (count > 0)
                {
                    bitInteractionCounts[i] = count;
                }
            }
            List <BinaryVector> components = new List <BinaryVector>();

            while (bitInteractionCounts.Count > 0)
            {
                BinaryVector component = new BinaryVector(length);
                for (int i = 0; i < nInteractions; i++)
                {
                    while (bitInteractionCounts.Count > 0)
                    {
                        int bit = bitInteractionCounts.ElementAt(random.Next(bitInteractionCounts.Count)).Key;
                        if (bitInteractionCounts[bit]-- <= 0)
                        {
                            bitInteractionCounts.Remove(bit);
                        }
                        if (!component[bit])
                        {
                            component[bit] = true;
                            break;
                        }
                    }
                }
                components.Add(component);
            }
            BoolMatrix m = new BoolMatrix(length, components.Count);

            foreach (var c in components.Select((v, j) => new { v, j }))
            {
                for (int i = 0; i < c.v.Length; i++)
                {
                    m[i, c.j] = c.v[i];
                }
            }
            return(m);
        }
    public void SinglePointCrossoverApplyTest() {
      TestRandom random = new TestRandom();
      BinaryVector parent1, parent2, expected, actual;
      bool exceptionFired;
      // The following test is based on Eiben, A.E. and Smith, J.E. 2003. Introduction to Evolutionary Computation. Natural Computing Series, Springer-Verlag Berlin Heidelberg, p. 49
      random.Reset();
      random.DoubleNumbers = new double[] { 0.35, 0.62, 0.18, 0.42, 0.83, 0.76, 0.39, 0.51, 0.36 };
      parent1 = new BinaryVector(new bool[] { false, false, false, false, true, false, false, false, false });
      parent2 = new BinaryVector(new bool[] { true, true, false, true, false, false, false, false, true });
      expected = new BinaryVector(new bool[] { false, true, false, false, false, false, false, false, false });
      actual = UniformCrossover.Apply(random, parent1, parent2);
      Assert.IsTrue(Auxiliary.BinaryVectorIsEqualByPosition(actual, expected));

      // The following test is based on Eiben, A.E. and Smith, J.E. 2003. Introduction to Evolutionary Computation. Natural Computing Series, Springer-Verlag Berlin Heidelberg, p. 49
      random.Reset();
      random.DoubleNumbers = new double[] { 0.35, 0.62, 0.18, 0.42, 0.83, 0.76, 0.39, 0.51, 0.36 };
      parent2 = new BinaryVector(new bool[] { false, false, false, false, true, false, false, false, false });
      parent1 = new BinaryVector(new bool[] { true, true, false, true, false, false, false, false, true });
      expected = new BinaryVector(new bool[] { true, false, false, true, true, false, false, false, true });
      actual = UniformCrossover.Apply(random, parent1, parent2);
      Assert.IsTrue(Auxiliary.BinaryVectorIsEqualByPosition(actual, expected));

      // The following test is not based on any published examples
      random.Reset();
      random.DoubleNumbers = new double[] { 0.35, 0.62, 0.18, 0.42, 0.83, 0.76, 0.39, 0.51, 0.36 };
      parent1 = new BinaryVector(new bool[] { false, true, true, false, false }); // this parent is longer
      parent2 = new BinaryVector(new bool[] { false, true, true, false });
      exceptionFired = false;
      try {
        actual = UniformCrossover.Apply(random, parent1, parent2);
      }
      catch (System.ArgumentException) {
        exceptionFired = true;
      }
      Assert.IsTrue(exceptionFired);
    }