Example #1
0
        protected override IScope[] Select(List <IScope> scopes)
        {
            int     count        = NumberOfSelectedSubScopesParameter.ActualValue.Value;
            bool    copy         = CopySelectedParameter.Value.Value;
            IRandom random       = RandomParameter.ActualValue;
            bool    maximization = MaximizationParameter.ActualValue.Value;
            ItemArray <DoubleValue> qualities = QualityParameter.ActualValue;

            IScope[] selected = new IScope[count];

            // create a list for each scope that contains the scope's index in the original scope list and its lots
            var temp = qualities.Where(x => IsValidQuality(x.Value)).Select((x, index) => new { index, x.Value });

            if (maximization)
            {
                temp = temp.OrderBy(x => x.Value);
            }
            else
            {
                temp = temp.OrderByDescending(x => x.Value);
            }
            var list = temp.Select((x, index) => new { x.index, lots = index + 1 }).ToList();

            //check if list with indexes is as long as the original scope list
            //otherwise invalid quality values were filtered
            if (list.Count != scopes.Count)
            {
                throw new ArgumentException("The scopes contain invalid quality values (either infinity or double.NaN) on which the selector cannot operate.");
            }

            int lotSum = list.Count * (list.Count + 1) / 2;

            for (int i = 0; i < count; i++)
            {
                int selectedLot = random.Next(lotSum) + 1;
                int j           = 0;
                int currentLot  = list[j].lots;
                while (currentLot < selectedLot)
                {
                    j++;
                    currentLot += list[j].lots;
                }
                if (copy)
                {
                    selected[i] = (IScope)scopes[list[j].index].Clone();
                }
                else
                {
                    selected[i]           = scopes[list[j].index];
                    scopes[list[j].index] = null;
                    lotSum -= list[j].lots;
                    list.RemoveAt(j);
                }
            }
            if (!copy)
            {
                scopes.RemoveAll(x => x == null);
            }
            return(selected);
        }
Example #2
0
    //[yl] 初始化
    public void Initialize()
    {
        if (matrix != null)
        {
            for (int row = 0; row < GlobalConst.RowsNum; ++row)
            {
                for (int col = 0; col < GlobalConst.ColumnsNum; ++col)
                {
                    var tempValue = matrix[row, col];
                    if (tempValue != null && tempValue.GO != null)
                    {
                        Destroy(tempValue.GO);
                        matrix[row, col] = null;
                    }
                }
            }
        }

        matrix = new ItemArray();

        CreateNewItem();
        CreateNewItem();

        GS = GameState.Playing;
    }
        public override IOperation Apply()
        {
            ItemArray <BoolValue> tabu = IsTabuParameter.ActualValue;

            if (tabu.Length > 0)
            {
                PercentValue value = PercentTabuParameter.ActualValue;
                if (value == null)
                {
                    value = new PercentValue();
                    PercentTabuParameter.ActualValue = value;
                }
                value.Value = tabu.Where(x => x.Value).Count() / (double)tabu.Length;
                ResultCollection results = ResultsParameter.ActualValue;
                if (results != null)
                {
                    IResult result = null;
                    results.TryGetValue(PercentTabuParameter.ActualName, out result);
                    if (result != null)
                    {
                        result.Value = value;
                    }
                    else
                    {
                        results.Add(new Result(PercentTabuParameter.ActualName, "Indicates how much of the neighborhood is tabu.", (IItem)value.Clone()));
                    }
                }
            }
            return(base.Apply());
        }
 public void SinglePointCrossoverCrossTest() {
   SinglePointCrossover_Accessor target = new SinglePointCrossover_Accessor(new PrivateObject(typeof(SinglePointCrossover)));
   ItemArray<BinaryVector> parents;
   TestRandom random = new TestRandom();
   bool exceptionFired;
   // The following test checks if there is an exception when there are more than 2 parents
   random.Reset();
   parents = new ItemArray<BinaryVector>(new BinaryVector[] { new BinaryVector(5), new BinaryVector(6), new BinaryVector(4) });
   exceptionFired = false;
   try {
     BinaryVector actual;
     actual = target.Cross(random, parents);
   } catch (ArgumentException) {
     exceptionFired = true;
   }
   Assert.IsTrue(exceptionFired);
   // The following test checks if there is an exception when there are less than 2 parents
   random.Reset();
   parents = new ItemArray<BinaryVector>(new BinaryVector[] { new BinaryVector(4) });
   exceptionFired = false;
   try {
     BinaryVector actual;
     actual = target.Cross(random, parents);
   } catch (ArgumentException) {
     exceptionFired = true;
   }
   Assert.IsTrue(exceptionFired);
 }
Example #5
0
        public override IOperation Apply()
        {
            IVRPProblemInstance      problemInstance = ProblemInstanceParameter.ActualValue;
            ItemArray <IVRPEncoding> solutions       = VRPToursParameter.ActualValue;
            ResultCollection         results         = ResultsParameter.ActualValue;

            ItemArray <DoubleValue> qualities        = QualityParameter.ActualValue;
            ItemArray <IntValue>    pickupViolations = PickupViolationsParameter.ActualValue;

            int i = qualities.Select((x, index) => new { index, x.Value }).OrderBy(x => x.Value).First().index;

            IVRPEncoding best     = solutions[i] as IVRPEncoding;
            VRPSolution  solution = BestSolutionParameter.ActualValue;

            if (solution != null)
            {
                if (!results.ContainsKey("Best VRP Solution PickupViolations"))
                {
                    results.Add(new Result("Best VRP Solution PickupViolations", new DoubleValue(pickupViolations[i].Value)));
                }
                else
                {
                    VRPEvaluation eval = problemInstance.Evaluate(solution.Solution);
                    if (qualities[i].Value <= eval.Quality)
                    {
                        (results["Best VRP Solution PickupViolations"].Value as DoubleValue).Value = pickupViolations[i].Value;
                    }
                }
            }

            return(base.Apply());
        }
 public void DiscreteCrossoverApplyTest() {
   TestRandom random = new TestRandom();
   RealVector parent1, parent2, expected, actual;
   ItemArray<RealVector> parents;
   bool exceptionFired;
   // The following test is not based on published examples
   random.Reset();
   random.IntNumbers = new int[] { 0, 0, 1, 0, 1 };
   parent1 = new RealVector(new double[] { 0.2, 0.2, 0.3, 0.5, 0.1 });
   parent2 = new RealVector(new double[] { 0.4, 0.1, 0.3, 0.2, 0.8 });
   parents = new ItemArray<RealVector>(new RealVector[] { parent1, parent2 });
   expected = new RealVector(new double[] { 0.2, 0.2, 0.3, 0.5, 0.8 });
   actual = DiscreteCrossover.Apply(random, parents);
   Assert.IsTrue(Auxiliary.RealVectorIsAlmostEqualByPosition(actual, expected));
   // The following test is not based on published examples
   random.Reset();
   random.IntNumbers = new int[] { 0, 0, 1, 0, 1, 0 };
   parent1 = new RealVector(new double[] { 0.2, 0.2, 0.3, 0.5, 0.1, 0.9 }); // this parent is longer
   parent2 = new RealVector(new double[] { 0.4, 0.1, 0.3, 0.2, 0.8 });
   parents = new ItemArray<RealVector>(new RealVector[] { parent1, parent2 });
   exceptionFired = false;
   try {
     actual = DiscreteCrossover.Apply(random, parents);
   }
   catch (System.ArgumentException) {
     exceptionFired = true;
   }
   Assert.IsTrue(exceptionFired);
 }
Example #7
0
        public void SinglePointCrossoverCrossTest()
        {
            var target = new PrivateObject(typeof(SinglePointCrossover));
            ItemArray <IntegerVector> parents;
            TestRandom random = new TestRandom();
            bool       exceptionFired;

            // The following test checks if there is an exception when there are more than 2 parents
            random.Reset();
            parents        = new ItemArray <IntegerVector>(new IntegerVector[] { new IntegerVector(5), new IntegerVector(6), new IntegerVector(4) });
            exceptionFired = false;
            try {
                IntegerVector actual;
                actual = (IntegerVector)target.Invoke("Cross", random, parents);
            }
            catch (System.ArgumentException) {
                exceptionFired = true;
            }
            Assert.IsTrue(exceptionFired);
            // The following test checks if there is an exception when there are less than 2 parents
            random.Reset();
            parents        = new ItemArray <IntegerVector>(new IntegerVector[] { new IntegerVector(4) });
            exceptionFired = false;
            try {
                IntegerVector actual;
                actual = (IntegerVector)target.Invoke("Cross", random, parents);
            }
            catch (System.ArgumentException) {
                exceptionFired = true;
            }
            Assert.IsTrue(exceptionFired);
        }
        public void DiscreteCrossoverApplyTest()
        {
            TestRandom             random = new TestRandom();
            RealVector             parent1, parent2, expected, actual;
            ItemArray <RealVector> parents;
            bool exceptionFired;

            // The following test is not based on published examples
            random.Reset();
            random.IntNumbers = new int[] { 0, 0, 1, 0, 1 };
            parent1           = new RealVector(new double[] { 0.2, 0.2, 0.3, 0.5, 0.1 });
            parent2           = new RealVector(new double[] { 0.4, 0.1, 0.3, 0.2, 0.8 });
            parents           = new ItemArray <RealVector>(new RealVector[] { parent1, parent2 });
            expected          = new RealVector(new double[] { 0.2, 0.2, 0.3, 0.5, 0.8 });
            actual            = DiscreteCrossover.Apply(random, parents);
            Assert.IsTrue(Auxiliary.RealVectorIsAlmostEqualByPosition(actual, expected));
            // The following test is not based on published examples
            random.Reset();
            random.IntNumbers = new int[] { 0, 0, 1, 0, 1, 0 };
            parent1           = new RealVector(new double[] { 0.2, 0.2, 0.3, 0.5, 0.1, 0.9 }); // this parent is longer
            parent2           = new RealVector(new double[] { 0.4, 0.1, 0.3, 0.2, 0.8 });
            parents           = new ItemArray <RealVector>(new RealVector[] { parent1, parent2 });
            exceptionFired    = false;
            try {
                actual = DiscreteCrossover.Apply(random, parents);
            }
            catch (System.ArgumentException) {
                exceptionFired = true;
            }
            Assert.IsTrue(exceptionFired);
        }
Example #9
0
    public void Initialize()
    {
        if (matrix != null)
        {
            for (int row = 0; row < Globals.Rows; row++)
            {
                for (int column = 0; column < Globals.Columns; column++)
                {
                    if (matrix[row, column] != null && matrix[row, column].GO != null)
                    {
                        Destroy(matrix[row, column].GO);
                    }
                }
            }
        }

        matrix = new ItemArray();



        //InitArrayWithPremadeData();
        CreateNewItem();
        CreateNewItem();

        score = 0;
        UpdateScore(0);

        gameState = GameState.Playing;
    }
        public override IOperation Apply()
        {
            ItemArray <SymbolicExpressionTree> expressions = SymbolicExpressionTreeParameter.ActualValue;
            ItemArray <DoubleValue>            qualities   = QualityParameter.ActualValue;
            BoolMatrix       world        = WorldParameter.ActualValue;
            IntValue         maxTimeSteps = MaxTimeStepsParameter.ActualValue;
            ResultCollection results      = ResultsParameter.ActualValue;

            int i = qualities.Select((x, index) => new { index, x.Value }).OrderBy(x => - x.Value).First().index;

            AntTrail antTrail = BestSolutionParameter.ActualValue;

            if (antTrail == null)
            {
                var bestAntTrail = new AntTrail(world, expressions[i], maxTimeSteps);
                BestSolutionParameter.ActualValue = bestAntTrail;
                results.Add(new Result("Best Artificial Ant Solution", bestAntTrail));
            }
            else
            {
                antTrail.World = world;
                antTrail.SymbolicExpressionTree = expressions[i];
                antTrail.MaxTimeSteps           = maxTimeSteps;
                results["Best Artificial Ant Solution"].Value = antTrail;
            }
            return(base.Apply());
        }
Example #11
0
        public override IOperation InstrumentedApply()
        {
            ItemArray <IVRPEncoding> parents = new ItemArray <IVRPEncoding>(ParentsParameter.ActualValue.Length);

            for (int i = 0; i < ParentsParameter.ActualValue.Length; i++)
            {
                IVRPEncoding solution = ParentsParameter.ActualValue[i];

                if (!(solution is AlbaEncoding))
                {
                    parents[i] = AlbaEncoding.ConvertFrom(solution, ProblemInstance);
                }
                else
                {
                    parents[i] = solution;
                }
            }
            ParentsParameter.ActualValue = parents;

            ChildParameter.ActualValue =
                Crossover(RandomParameter.ActualValue, parents[0] as AlbaEncoding, parents[1] as AlbaEncoding);
            (ChildParameter.ActualValue as AlbaEncoding).Repair();

            return(base.InstrumentedApply());
        }
Example #12
0
        public override IOperation Apply()
        {
            ItemArray <DoubleValue> qualities = QualityParameter.ActualValue;
            bool        maximization          = MaximizationParameter.ActualValue.Value;
            DoubleValue best = BestQualityParameter.ActualValue;
            double      max  = (best != null) ? (best.Value) : ((maximization) ? (double.MinValue) : (double.MaxValue));

            foreach (DoubleValue quality in qualities)
            {
                if (IsBetter(maximization, quality.Value, max))
                {
                    max = quality.Value;
                }
            }

            if (best == null)
            {
                BestQualityParameter.ActualValue = new DoubleValue(max);
            }
            else
            {
                best.Value = max;
            }
            return(base.Apply());
        }
        public override IOperation Apply()
        {
            var random          = RandomParameter.ActualValue;
            var swarmSize       = SwarmSizeParameter.ActualValue.Value;
            var nrOfConnections = NrOfConnectionsParameter.ActualValue.Value;

            ItemArray <IntArray> neighbors = new ItemArray <IntArray>(swarmSize);

            for (int i = 0; i < swarmSize; i++)
            {
                var numbers = Enumerable.Range(0, swarmSize).ToList();
                numbers.RemoveAt(i);
                var selectedNumbers = new List <int>(nrOfConnections + 1);
                selectedNumbers.Add(i);
                for (int j = 0; j < nrOfConnections && numbers.Count > 0; j++)
                {
                    int index = random.Next(numbers.Count);
                    selectedNumbers.Add(numbers[index]);
                    numbers.RemoveAt(index);
                }
                neighbors[i] = new IntArray(selectedNumbers.ToArray());
            }
            NeighborsParameter.ActualValue = neighbors;
            return(base.Apply());
        }
Example #14
0
 public OrionChest(int chestIndex, Terraria.Chest?terrariaChest)
 {
     Index    = chestIndex;
     IsActive = terrariaChest != null;
     Wrapped  = terrariaChest ?? new Terraria.Chest();
     Items    = new ItemArray(Wrapped.item);
 }
        public static LinearLinkage Apply(IRandom random, ItemArray <LinearLinkage> parents)
        {
            var len       = parents[0].Length;
            var p         = random.Next(parents.Length);
            var child     = LinearLinkage.SingleElementGroups(len);
            var remaining = new SortedSet <int>(Enumerable.Range(0, len));

            do
            {
                var i = remaining.Min;
                foreach (var g in parents[p].GetGroupForward(i))
                {
                    if (!remaining.Contains(g))
                    {
                        continue;
                    }
                    child[i] = g;
                    i        = g;
                    remaining.Remove(g);
                }
                child[i] = i;
                remaining.Remove(i);

                p = (p + 1) % parents.Length;
            } while (remaining.Count > 0);

            return(child);
        }
        protected override IScope[] Select(List <IScope> scopes)
        {
            ItemArray <BoolValue> conditions = ConditionParameter.ActualValue;
            List <IScope>         selected   = new List <IScope>();

            if (CopySelected.Value)
            {
                for (int i = 0; i < scopes.Count; i++)
                {
                    if (conditions[i].Value)
                    {
                        selected.Add((IScope)scopes[i].Clone());
                    }
                }
            }
            else
            {
                for (int i = 0; i < scopes.Count; i++)
                {
                    if (conditions[i + selected.Count].Value)
                    {
                        selected.Add(scopes[i]);
                        scopes.RemoveAt(i);
                        i--;
                    }
                }
            }
            return(selected.ToArray());
        }
        public override IOperation Apply()
        {
            int      updateInterval = UpdateIntervalParameter.Value.Value;
            IntValue updateCounter  = UpdateCounterParameter.ActualValue;

            if (updateCounter == null)
            {
                updateCounter = new IntValue(updateInterval);
                UpdateCounterParameter.ActualValue = updateCounter;
            }

            if (updateCounter.Value == updateInterval)
            {
                var trees            = SymbolicExpressionTreeParameter.ActualValue;
                var interpreter      = SymbolicDataAnalysisTreeInterpreterParameter.ActualValue;
                var problemData      = ProblemDataParameter.ActualValue;
                var ds               = ProblemDataParameter.ActualValue.Dataset;
                var rows             = ProblemDataParameter.ActualValue.TrainingIndices;
                var modelCreator     = ModelCreatorParameter.ActualValue;
                var estimationLimits = EstimationLimitsParameter.ActualValue;
                var evaluatedValues  = new ItemArray <DoubleArray>(trees.Length);
                for (int i = 0; i < trees.Length; ++i)
                {
                    var model = (IDiscriminantFunctionClassificationModel)modelCreator.CreateSymbolicDiscriminantFunctionClassificationModel(trees[i], interpreter, estimationLimits.Lower, estimationLimits.Upper);
                    model.RecalculateModelParameters(problemData, rows);
                    var values = UseClassValues ? model.GetEstimatedClassValues(ds, rows) : model.GetEstimatedValues(ds, rows);
                    evaluatedValues[i] = new DoubleArray(values.ToArray());
                }
                EvaluatedValuesParameter.ActualValue = evaluatedValues;
            }
            return(base.Apply());
        }
Example #18
0
        /// <summary>
        /// Performs a heuristic crossover operation for two given parent integer vectors.
        /// </summary>
        /// <exception cref="ArgumentException">Thrown when the number of parents is not equal to 2.</exception>
        /// <exception cref="InvalidOperationException">
        /// Thrown when either:<br/>
        /// <list type="bullet">
        /// <item><description>Maximization parameter could not be found.</description></item>
        /// <item><description>Quality parameter could not be found or the number of quality values is not equal to the number of parents.</description></item>
        /// </list>
        /// </exception>
        /// <param name="random">A random number generator.</param>
        /// <param name="parents">An array containing the two real vectors that should be crossed.</param>
        /// /// <param name="bounds">The bounds and step size for each dimension (will be cycled in case there are less rows than elements in the parent vectors).</param>
        /// <returns>The newly created integer vector, resulting from the crossover operation.</returns>
        protected override IntegerVector CrossBounded(IRandom random, ItemArray <IntegerVector> parents, IntMatrix bounds)
        {
            if (parents.Length != 2)
            {
                throw new ArgumentException("RoundedHeuristicCrossover: The number of parents is not equal to 2");
            }

            if (MaximizationParameter.ActualValue == null)
            {
                throw new InvalidOperationException("RoundedHeuristicCrossover: Parameter " + MaximizationParameter.ActualName + " could not be found.");
            }
            if (QualityParameter.ActualValue == null || QualityParameter.ActualValue.Length != parents.Length)
            {
                throw new InvalidOperationException("RoundedHeuristicCrossover: Parameter " + QualityParameter.ActualName + " could not be found, or not in the same quantity as there are parents.");
            }

            ItemArray <DoubleValue> qualities = QualityParameter.ActualValue;
            bool maximization = MaximizationParameter.ActualValue.Value;

            if (maximization && qualities[0].Value >= qualities[1].Value || !maximization && qualities[0].Value <= qualities[1].Value)
            {
                return(Apply(random, parents[0], parents[1], bounds));
            }
            else
            {
                return(Apply(random, parents[1], parents[0], bounds));
            }
        }
Example #19
0
        /// <summary>
        /// Performs a discrete crossover operation of any number of given parents.
        /// </summary>
        /// <exception cref="ArgumentException">Thrown when the vectors of the parents are of different length or when there are less than 2 parents.</exception>
        /// <param name="random">A random number generator.</param>
        /// <param name="parents">The list of parents for the crossover operation.</param>
        /// <returns>The newly created integer vector, resulting from the crossover operation.</returns>
        public static IntegerVector Apply(IRandom random, ItemArray <IntegerVector> parents)
        {
            if (parents.Length < 2)
            {
                throw new ArgumentException("DiscreteCrossover: There are less than two parents to cross.");
            }
            int length = parents[0].Length;

            for (int i = 0; i < parents.Length; i++)
            {
                if (parents[i].Length != length)
                {
                    throw new ArgumentException("DiscreteCrossover: The parents' vectors are of different length.", "parents");
                }
            }

            var result = new IntegerVector(length);

            for (int i = 0; i < length; i++)
            {
                result[i] = parents[random.Next(parents.Length)][i];
            }

            return(result);
        }
 public void SinglePointCrossoverCrossTest() {
   var target = new PrivateObject(typeof(SinglePointCrossover));
   ItemArray<IntegerVector> parents;
   TestRandom random = new TestRandom();
   bool exceptionFired;
   // The following test checks if there is an exception when there are more than 2 parents
   random.Reset();
   parents = new ItemArray<IntegerVector>(new IntegerVector[] { new IntegerVector(5), new IntegerVector(6), new IntegerVector(4) });
   exceptionFired = false;
   try {
     IntegerVector actual;
     actual = (IntegerVector)target.Invoke("Cross", random, parents);
   }
   catch (System.ArgumentException) {
     exceptionFired = true;
   }
   Assert.IsTrue(exceptionFired);
   // The following test checks if there is an exception when there are less than 2 parents
   random.Reset();
   parents = new ItemArray<IntegerVector>(new IntegerVector[] { new IntegerVector(4) });
   exceptionFired = false;
   try {
     IntegerVector actual;
     actual = (IntegerVector)target.Invoke("Cross", random, parents);
   }
   catch (System.ArgumentException) {
     exceptionFired = true;
   }
   Assert.IsTrue(exceptionFired);
 }
Example #21
0
        public override IOperation Apply()
        {
            ItemArray <RealVector>  realVectors = RealVectorParameter.ActualValue;
            ItemArray <DoubleValue> qualities   = QualityParameter.ActualValue;
            bool        max = MaximizationParameter.ActualValue.Value;
            DoubleValue bestKnownQuality = BestKnownQualityParameter.ActualValue;
            SingleObjectiveTestFunctionSolution solution = BestSolutionParameter.ActualValue;

            int i = -1;

            if (!max)
            {
                i = qualities.Select((x, index) => new { index, x.Value }).OrderBy(x => x.Value).First().index;
            }
            else
            {
                i = qualities.Select((x, index) => new { index, x.Value }).OrderByDescending(x => x.Value).First().index;
            }

            if (bestKnownQuality == null ||
                max && qualities[i].Value > bestKnownQuality.Value ||
                !max && qualities[i].Value < bestKnownQuality.Value)
            {
                BestKnownQualityParameter.ActualValue  = new DoubleValue(qualities[i].Value);
                BestKnownSolutionParameter.ActualValue = (RealVector)realVectors[i].Clone();
                if (solution != null)
                {
                    solution.BestKnownRealVector = BestKnownSolutionParameter.ActualValue;
                }
            }

            if (solution == null)
            {
                ResultCollection results = ResultsParameter.ActualValue;
                solution = new SingleObjectiveTestFunctionSolution((RealVector)realVectors[i].Clone(),
                                                                   (DoubleValue)qualities[i].Clone(),
                                                                   EvaluatorParameter.ActualValue);
                solution.Population = realVectors[i].Length == 2
          ? new ItemArray <RealVector>(realVectors.Select(x => x.Clone()).Cast <RealVector>())
          : null;
                solution.BestKnownRealVector = BestKnownSolutionParameter.ActualValue;
                solution.Bounds = BoundsParameter.ActualValue;
                BestSolutionParameter.ActualValue = solution;
                results.Add(new Result("Best Solution", solution));
            }
            else
            {
                if (max && qualities[i].Value > solution.BestQuality.Value ||
                    !max && qualities[i].Value < solution.BestQuality.Value)
                {
                    solution.BestRealVector = (RealVector)realVectors[i].Clone();
                    solution.BestQuality    = (DoubleValue)qualities[i].Clone();
                }
                solution.Population = realVectors[i].Length == 2
          ? new ItemArray <RealVector>(realVectors.Select(x => x.Clone()).Cast <RealVector>())
          : null;
            }

            return(base.Apply());
        }
        public override IOperation Apply()
        {
            if (CurrentIteration > 0 && CurrentIteration % RegroupingPeriod == 0)
            {
                ItemArray <IntArray> neighbors = new ItemArray <IntArray>(SwarmSize);

                var particles = Enumerable.Range(0, SwarmSize).ToList();
                for (int i = SwarmSize - 1; i > 0; i--)
                {
                    int j = Random.Next(i + 1);
                    int t = particles[j];
                    particles[j] = particles[i];
                    particles[i] = t;
                }

                for (int partitionNr = 0; partitionNr < NrOfSwarms; partitionNr++)
                {
                    int start = partitionNr * SwarmSize / NrOfSwarms;
                    int end   = (partitionNr + 1) * SwarmSize / NrOfSwarms;
                    for (int i = start; i < end; i++)
                    {
                        neighbors[particles[i]] = GetSegment(particles, start, end, i);
                    }
                }

                Neighbors = neighbors;
            }
            return(base.Apply());
        }
        public override IOperation Apply()
        {
            var random    = RandomParameter.ActualValue;
            var swarmSize = SwarmSizeParameter.ActualValue.Value;
            var k         = KParameter.ActualValue.Value;

            // SPSO: Each particle informs at most K+1 particles (at least itself and K others)
            //       it is by design that we draw from the particles with repetition
            var particlesInform = new List <HashSet <int> >(swarmSize);

            for (var i = 0; i < swarmSize; i++)
            {
                var informs = new HashSet <int>()
                {
                    i
                };
                for (var j = 0; j < k; j++)
                {
                    informs.Add(random.Next(swarmSize));
                }
                particlesInform.Add(informs);
            }

            var neighbors = new ItemArray <IntArray>(swarmSize);

            for (int i = 0; i < swarmSize; i++)
            {
                // calculate the informants for each particle
                var informants = particlesInform.Select((val, idx) => val.Contains(i) ? idx : -1).Where(x => x >= 0).ToArray();
                neighbors[i] = new IntArray(informants);
            }
            NeighborsParameter.ActualValue = neighbors;
            return(base.Apply());
        }
Example #24
0
        /// <summary>
        /// Performs the average crossover (intermediate recombination) on a list of parents.
        /// </summary>
        /// <exception cref="ArgumentException">Thrown when there is just one parent or when the parent vectors are of different length.</exception>
        /// <remarks>
        /// There can be more than two parents.
        /// </remarks>
        /// <param name="random">The random number generator.</param>
        /// <param name="parents">The list of parents.</param>
        /// <returns>The child vector (average) of the parents.</returns>
        public static RealVector Apply(IRandom random, ItemArray <RealVector> parents)
        {
            int length = parents[0].Length, parentsCount = parents.Length;

            if (parents.Length < 2)
            {
                throw new ArgumentException("AverageCrossover: The number of parents is less than 2.", "parents");
            }
            RealVector result = new RealVector(length);

            try {
                double avg;
                for (int i = 0; i < length; i++)
                {
                    avg = 0;
                    for (int j = 0; j < parentsCount; j++)
                    {
                        avg += parents[j][i];
                    }
                    result[i] = avg / (double)parentsCount;
                }
            }
            catch (IndexOutOfRangeException) {
                throw new ArgumentException("AverageCrossover: The parents' vectors are of different length.", "parents");
            }

            return(result);
        }
        /// <summary>
        /// Checks if the number of parents is equal to 2, if all parameters are available and forwards the call to <see cref="Apply(IRandom, RealVector, RealVector, DoubleValue, DoubleValue)"/>.
        /// </summary>
        /// <exception cref="ArgumentException">Thrown when the number of parents is not equal to 2.</exception>
        /// <exception cref="InvalidOperationException">
        /// Thrown when either:<br/>
        /// <list type="bullet">
        /// <item><description>Maximization parameter could not be found.</description></item>
        /// <item><description>Quality parameter could not be found or the number of quality values is not equal to the number of parents.</description></item>
        /// <item><description>Alpha parameter could not be found.</description></item>
        /// <item><description>Beta parameter could not be found.</description></item>
        /// </list>
        /// </exception>
        /// <param name="random">The random number generator to use.</param>
        /// <param name="parents">The collection of parents (must be of size 2).</param>
        /// <returns>The real vector that results from the crossover.</returns>
        protected override RealVector Cross(IRandom random, ItemArray <RealVector> parents)
        {
            if (parents.Length != 2)
            {
                throw new ArgumentException("BlendAlphaBetaCrossover: Number of parents is not equal to 2.", "parents");
            }
            if (MaximizationParameter.ActualValue == null)
            {
                throw new InvalidOperationException("BlendAlphaBetaCrossover: Parameter " + MaximizationParameter.ActualName + " could not be found.");
            }
            if (QualityParameter.ActualValue == null || QualityParameter.ActualValue.Length != parents.Length)
            {
                throw new InvalidOperationException("BlendAlphaBetaCrossover: Parameter " + QualityParameter.ActualName + " could not be found, or not in the same quantity as there are parents.");
            }
            if (AlphaParameter.ActualValue == null || BetaParameter.ActualValue == null)
            {
                throw new InvalidOperationException("BlendAlphaBetaCrossover: Parameter " + AlphaParameter.ActualName + " or paramter " + BetaParameter.ActualName + " could not be found.");
            }

            ItemArray <DoubleValue> qualities = QualityParameter.ActualValue;
            bool maximization = MaximizationParameter.ActualValue.Value;

            if (maximization && qualities[0].Value >= qualities[1].Value || !maximization && qualities[0].Value <= qualities[1].Value)
            {
                return(Apply(random, parents[0], parents[1], AlphaParameter.ActualValue, BetaParameter.ActualValue));
            }
            else
            {
                return(Apply(random, parents[1], parents[0], AlphaParameter.ActualValue, BetaParameter.ActualValue));
            }
        }
    public static LinearLinkage Apply(IRandom random, ItemArray<LinearLinkage> parents) {
      var len = parents[0].Length;

      var child = new LinearLinkage(len);
      var childGroup = new List<HashSet<int>>();
      var currentParent = random.Next(parents.Length);
      var groups = parents.Select(x => x.GetGroups().Select(y => new HashSet<int>(y)).ToList()).ToList();
      bool remaining;
      do {
        var maxGroup = groups[currentParent].Select((v, i) => Tuple.Create(i, v))
          .MaxItems(x => x.Item2.Count)
          .SampleRandom(random).Item1;
        var group = groups[currentParent][maxGroup];
        groups[currentParent].RemoveAt(maxGroup);
        childGroup.Add(group);

        remaining = false;
        for (var p = 0; p < groups.Count; p++) {
          for (var j = 0; j < groups[p].Count; j++) {
            foreach (var elem in group) groups[p][j].Remove(elem);
            if (!remaining && groups[p][j].Count > 0) remaining = true;
          }
        }

        currentParent = (currentParent + 1) % parents.Length;
      } while (remaining);

      child.SetGroups(childGroup);
      return child;
    }
Example #27
0
        public override IOperation Apply()
        {
            ICapacitatedProblemInstance cvrp    = ProblemInstanceParameter.ActualValue as ICapacitatedProblemInstance;
            ResultCollection            results = ResultsParameter.ActualValue;

            ItemArray <DoubleValue> qualities = QualityParameter.ActualValue;
            ItemArray <DoubleValue> overloads = OverloadParameter.ActualValue;

            double sigma      = SigmaParameter.Value.Value;
            double phi        = PhiParameter.Value.Value;
            double minPenalty = MinPenaltyFactorParameter.Value.Value;
            double maxPenalty = MaxPenaltyFactorParameter.Value.Value;

            for (int j = 0; j < qualities.Length; j++)
            {
                qualities[j].Value -= overloads[j].Value * cvrp.OverloadPenalty.Value;
            }

            int validCount = 0;

            for (int j = 0; j < qualities.Length; j++)
            {
                if (overloads[j].Value == 0)
                {
                    validCount++;
                }
            }

            double factor = 1.0 - ((double)validCount / (double)qualities.Length);

            double min = cvrp.OverloadPenalty.Value / (1 + sigma);
            double max = cvrp.OverloadPenalty.Value * (1 + phi);

            cvrp.CurrentOverloadPenalty = new DoubleValue(min + (max - min) * factor);
            if (cvrp.CurrentOverloadPenalty.Value < minPenalty)
            {
                cvrp.CurrentOverloadPenalty.Value = minPenalty;
            }
            if (cvrp.CurrentOverloadPenalty.Value > maxPenalty)
            {
                cvrp.CurrentOverloadPenalty.Value = maxPenalty;
            }

            for (int j = 0; j < qualities.Length; j++)
            {
                qualities[j].Value += overloads[j].Value * cvrp.CurrentOverloadPenalty.Value;
            }

            if (!results.ContainsKey("Current Overload Penalty"))
            {
                results.Add(new Result("Current Overload Penalty", new DoubleValue(cvrp.CurrentOverloadPenalty.Value)));
            }
            else
            {
                (results["Current Overload Penalty"].Value as DoubleValue).Value = cvrp.CurrentOverloadPenalty.Value;
            }

            return(base.Apply());
        }
Example #28
0
        public override IOperation Apply()
        {
            IPickupAndDeliveryProblemInstance pdp = ProblemInstanceParameter.ActualValue as IPickupAndDeliveryProblemInstance;
            ResultCollection results = ResultsParameter.ActualValue;

            ItemArray <DoubleValue> qualities        = QualityParameter.ActualValue;
            ItemArray <IntValue>    pickupViolations = PickupViolationsParameter.ActualValue;

            double sigma      = SigmaParameter.Value.Value;
            double phi        = PhiParameter.Value.Value;
            double minPenalty = MinPenaltyFactorParameter.Value.Value;
            double maxPenalty = MaxPenaltyFactorParameter.Value.Value;

            for (int j = 0; j < qualities.Length; j++)
            {
                qualities[j].Value -= pickupViolations[j].Value * pdp.PickupViolationPenalty.Value;
            }

            int validCount = 0;

            for (int j = 0; j < qualities.Length; j++)
            {
                if (pickupViolations[j].Value == 0)
                {
                    validCount++;
                }
            }

            double factor = 1.0 - ((double)validCount / (double)qualities.Length);

            double min = pdp.PickupViolationPenalty.Value / (1 + sigma);
            double max = pdp.PickupViolationPenalty.Value * (1 + phi);

            pdp.CurrentPickupViolationPenalty = new DoubleValue(min + (max - min) * factor);
            if (pdp.CurrentPickupViolationPenalty.Value < minPenalty)
            {
                pdp.CurrentPickupViolationPenalty.Value = minPenalty;
            }
            if (pdp.CurrentPickupViolationPenalty.Value > maxPenalty)
            {
                pdp.CurrentPickupViolationPenalty.Value = maxPenalty;
            }

            for (int j = 0; j < qualities.Length; j++)
            {
                qualities[j].Value += pickupViolations[j].Value * pdp.CurrentPickupViolationPenalty.Value;
            }

            if (!results.ContainsKey("Current Pickup Violation Penalty"))
            {
                results.Add(new Result("Current Pickup Violation Penalty", new DoubleValue(pdp.CurrentPickupViolationPenalty.Value)));
            }
            else
            {
                (results["Current Pickup Violation Penalty"].Value as DoubleValue).Value = pdp.CurrentPickupViolationPenalty.Value;
            }

            return(base.Apply());
        }
        public override IOperation Apply()
        {
            ITimeWindowedProblemInstance vrptw   = ProblemInstanceParameter.ActualValue as ITimeWindowedProblemInstance;
            ResultCollection             results = ResultsParameter.ActualValue;

            ItemArray <DoubleValue> qualities = QualityParameter.ActualValue;
            ItemArray <DoubleValue> tardiness = TardinessParameter.ActualValue;

            double sigma      = SigmaParameter.Value.Value;
            double phi        = PhiParameter.Value.Value;
            double minPenalty = MinPenaltyFactorParameter.Value.Value;
            double maxPenalty = MaxPenaltyFactorParameter.Value.Value;

            for (int j = 0; j < qualities.Length; j++)
            {
                qualities[j].Value -= tardiness[j].Value * vrptw.TardinessPenalty.Value;
            }

            int validCount = 0;

            for (int j = 0; j < qualities.Length; j++)
            {
                if (tardiness[j].Value == 0)
                {
                    validCount++;
                }
            }

            double factor = 1.0 - ((double)validCount / (double)qualities.Length);

            double min = vrptw.TardinessPenalty.Value / (1 + sigma);
            double max = vrptw.TardinessPenalty.Value * (1 + phi);

            vrptw.CurrentTardinessPenalty = new DoubleValue(min + (max - min) * factor);
            if (vrptw.CurrentTardinessPenalty.Value < minPenalty)
            {
                vrptw.CurrentTardinessPenalty.Value = minPenalty;
            }
            if (vrptw.CurrentTardinessPenalty.Value > maxPenalty)
            {
                vrptw.CurrentTardinessPenalty.Value = maxPenalty;
            }

            for (int j = 0; j < qualities.Length; j++)
            {
                qualities[j].Value += tardiness[j].Value * vrptw.CurrentTardinessPenalty.Value;
            }

            if (!results.ContainsKey("Current Tardiness Penalty"))
            {
                results.Add(new Result("Current Tardiness Penalty", new DoubleValue(vrptw.CurrentTardinessPenalty.Value)));
            }
            else
            {
                (results["Current Tardiness Penalty"].Value as DoubleValue).Value = vrptw.CurrentTardinessPenalty.Value;
            }

            return(base.Apply());
        }
 /// <summary>
 /// Performs a random convex crossover operation for two given parent real vectors.
 /// </summary>
 /// <exception cref="ArgumentException">Thrown if there are not exactly two parents.</exception>
 /// <param name="random">A random number generator.</param>
 /// <param name="parents">An array containing the two real vectors that should be crossed.</param>
 /// <returns>The newly created real vector, resulting from the crossover operation.</returns>
 protected override RealVector Cross(IRandom random, ItemArray <RealVector> parents)
 {
     if (parents.Length != 2)
     {
         throw new ArgumentException("ERROR in RandomConvexCrossover: The number of parents is not equal to 2");
     }
     return(Apply(random, parents[0], parents[1]));
 }
Example #31
0
 /// <summary>
 /// Checks number of parents and forwards the call to <see cref="Apply(IRandom, ItemArray<RealVector>)"/>.
 /// </summary>
 /// <exception cref="ArgumentException">Thrown when <paramref name="parents"/> contains less than 2 elements.</exception>
 /// <param name="random">The random number generator.</param>
 /// <param name="parents">The collection of parents (must be of size 2 or greater).</param>
 /// <returns>The real vector resulting from the crossover.</returns>
 protected override RealVector Cross(IRandom random, ItemArray <RealVector> parents)
 {
     if (parents.Length < 2)
     {
         throw new ArgumentException("DiscreteCrossover: The number of parents is less than 2.", "parents");
     }
     return(Apply(random, parents));
 }
 public override IOperation Apply() {
   ItemArray<IntArray> neighbors = new ItemArray<IntArray>(SwarmSize);
   for (int i = 0; i < SwarmSize; i++) {
     neighbors[i] = new IntArray(new[] { (SwarmSize + i - 1) % SwarmSize, (i + 1) % SwarmSize });
   }
   Neighbors = neighbors;
   return base.Apply();
 }
Example #33
0
 protected override LinearLinkage Cross(IRandom random, ItemArray <LinearLinkage> parents)
 {
     if (parents.Length != 2)
     {
         throw new InvalidOperationException(Name + ": Can only cross exactly two parents.");
     }
     return(Apply(random, parents[0], parents[1]));
 }
        public override IOperation Apply()
        {
            ItemArray <DoubleArray> qualities = QualitiesParameter.ActualValue;
            ResultCollection        results   = ResultsParameter.ActualValue;

            Analyze(qualities, results);
            return(base.Apply());
        }
 /// <summary>
 /// Performs a single point crossover at a randomly chosen position of two
 /// given parent integer vectors.
 /// </summary>
 /// <exception cref="ArgumentException">Thrown if there are not exactly two parents.</exception>
 /// <param name="random">A random number generator.</param>
 /// <param name="parents">An array containing the two integer vectors that should be crossed.</param>
 /// <returns>The newly created integer vector, resulting from the single point crossover.</returns>
 protected override IntegerVector Cross(IRandom random, ItemArray <IntegerVector> parents)
 {
     if (parents.Length != 2)
     {
         throw new ArgumentException("ERROR in SinglePointCrossover: The number of parents is not equal to 2");
     }
     return(Apply(random, parents[0], parents[1]));
 }
Example #36
0
        public IList<Item> GetItems(Critter critter)
        {
            var container = GetContainer (critter, false);
            if (container == null)
                return new List<Item> (0);

            var itemArray = new ItemArray ();
            container.GetItems (0, itemArray);
            return new List<Item> (itemArray);
        }
 private DoubleArray Average(IRandom random, ItemArray<DoubleArray> parents) {
   int length = parents[0].Length;
   var result = new DoubleArray(length);
   for (int i = 0; i < length; i++) {
     for (int p = 0; p < parents.Length; p++) {
       result[i] += parents[p][i];
     }
     result[i] /= parents.Length;
   }
   return result;
 }
Example #38
0
        public void PutItems(Critter critter, IList<Item> items)
        {
            var container = GetContainer (critter, true);
            if (container == null)
                return;

            var itemArray = new ItemArray ();
            itemArray.AddRange (items);

            Global.MoveItems (itemArray, container, 0);
        }
    /// <summary>
    /// Performs a discrete crossover operation on multiple parents.
    /// </summary>
    /// <exception cref="ArgumentException">Thrown when the vectors of the parents are of different length.</exception>
    /// <param name="random">A random number generator.</param>
    /// <param name="parents">An array containing the parents that should be crossed.</param>
    /// <returns>The newly created real vector, resulting from the crossover operation.</returns>
    public static RealVector Apply(IRandom random, ItemArray<RealVector> parents) {
      int length = parents[0].Length;

      for (int i = 0; i < parents.Length; i++) {
        if (parents[i].Length != length)
          throw new ArgumentException("DiscreteCrossover: The parents' vectors are of different length.", "parents");
      }

      RealVector result = new RealVector(length);
      for (int i = 0; i < length; i++) {
        result[i] = parents[random.Next(parents.Length)][i];
      }

      return result;
    }
 public override IOperation Apply() {
   ItemArray<IntArray> neighbors = new ItemArray<IntArray>(SwarmSize);
   for (int i = 0; i < SwarmSize; i++) {
     var numbers = Enumerable.Range(0, SwarmSize).ToList();
     numbers.RemoveAt(i);
     var selectedNumbers = new List<int>(NrOfConnections);
     for (int j = 0; j < NrOfConnections && numbers.Count > 0; j++) {
       int index = Random.Next(numbers.Count);
       selectedNumbers.Add(numbers[index]);
       numbers.RemoveAt(index);
     }
     neighbors[i] = new IntArray(selectedNumbers.ToArray());
   }
   Neighbors = neighbors;
   return base.Apply();
 }
    /// <summary>
    /// Performs a discrete crossover operation of any number of given parents.
    /// </summary>
    /// <exception cref="ArgumentException">Thrown when the vectors of the parents are of different length or when there are less than 2 parents.</exception>
    /// <param name="random">A random number generator.</param>
    /// <param name="parents">The list of parents for the crossover operation.</param>
    /// <returns>The newly created integer vector, resulting from the crossover operation.</returns>
    public static IntegerVector Apply(IRandom random, ItemArray<IntegerVector> parents) {
      if (parents.Length < 2) throw new ArgumentException("DiscreteCrossover: There are less than two parents to cross.");
      int length = parents[0].Length;

      for (int i = 0; i < parents.Length; i++) {
        if (parents[i].Length != length)
          throw new ArgumentException("DiscreteCrossover: The parents' vectors are of different length.", "parents");
      }

      var result = new IntegerVector(length);
      for (int i = 0; i < length; i++) {
        result[i] = parents[random.Next(parents.Length)][i];
      }

      return result;
    }
Example #42
0
    public override IOperation InstrumentedApply() {
      ItemArray<IVRPEncoding> parents = new ItemArray<IVRPEncoding>(ParentsParameter.ActualValue.Length);
      for (int i = 0; i < ParentsParameter.ActualValue.Length; i++) {
        IVRPEncoding solution = ParentsParameter.ActualValue[i];

        if (!(solution is PrinsEncoding)) {
          parents[i] = PrinsEncoding.ConvertFrom(solution, ProblemInstance);
        } else {
          parents[i] = solution;
        }
      }
      ParentsParameter.ActualValue = parents;

      ChildParameter.ActualValue =
        Crossover(RandomParameter.ActualValue, parents[0] as PrinsEncoding, parents[1] as PrinsEncoding);

      return base.InstrumentedApply();
    }
    /// <summary>
    /// Performs the average crossover (intermediate recombination) on a list of parents.
    /// </summary>
    /// <exception cref="ArgumentException">Thrown when there is just one parent or when the parent vectors are of different length.</exception>
    /// <remarks>
    /// There can be more than two parents.
    /// </remarks>
    /// <param name="random">The random number generator.</param>
    /// <param name="parents">The list of parents.</param>
    /// <returns>The child vector (average) of the parents.</returns>
    public static RealVector Apply(IRandom random, ItemArray<RealVector> parents) {
      int length = parents[0].Length, parentsCount = parents.Length;
      if (parents.Length < 2) throw new ArgumentException("AverageCrossover: The number of parents is less than 2.", "parents");
      RealVector result = new RealVector(length);
      try {
        double avg;
        for (int i = 0; i < length; i++) {
          avg = 0;
          for (int j = 0; j < parentsCount; j++)
            avg += parents[j][i];
          result[i] = avg / (double)parentsCount;
        }
      }
      catch (IndexOutOfRangeException) {
        throw new ArgumentException("AverageCrossover: The parents' vectors are of different length.", "parents");
      }

      return result;
    }
    public static LinearLinkage Apply(IRandom random, ItemArray<LinearLinkage> parents) {
      var len = parents[0].Length;
      var child = new LinearLinkage(len);
      var remaining = new SortedSet<int>(Enumerable.Range(0, len));
      do {
        var groups = parents.Select(x => x.GetGroupForward(remaining.Min).Where(y => remaining.Contains(y)).ToList()).ToList();
        var max = groups.Select((v, idx) => Tuple.Create(idx, v.Count)).MaxItems(x => x.Item2).SampleRandom(random).Item1;
        var i = groups[max][0];
        for (var k = 1; k < groups[max].Count; k++) {
          child[i] = groups[max][k];
          remaining.Remove(i);
          i = child[i];
        }
        child[i] = i;
        remaining.Remove(i);
      } while (remaining.Count > 0);

      return child;
    }
    public static LinearLinkage Apply(IRandom random, ItemArray<LinearLinkage> parents) {
      var len = parents[0].Length;
      var p = random.Next(parents.Length);
      var child = new LinearLinkage(len);
      var remaining = new SortedSet<int>(Enumerable.Range(0, len));
      do {
        var i = remaining.Min;
        foreach (var g in parents[p].GetGroupForward(i)) {
          if (!remaining.Contains(g)) continue;
          child[i] = g;
          i = g;
          remaining.Remove(g);
        }
        child[i] = i;
        remaining.Remove(i);

        p = (p + 1) % parents.Length;
      } while (remaining.Count > 0);

      return child;
    }
Example #46
0
 public static string ShowMatrixOnConsole(ItemArray matrix)
 {
     string x = string.Empty;
     for (int row = Globals.Rows - 1; row >= 0; row--)
     {
         for (int column = 0; column < Globals.Columns; column++)
         {
             if (matrix[row, column] != null)
             {
                 x += matrix[row, column].Value + "|";
             }
             else
             {
                 x += "X" + "|";
             }
         }
         x += Environment.NewLine;
     }
     Debug.Log(x);
     return x;
 }
Example #47
0
    public void Initialize()
    {
        if (matrix != null)
            for (int row = 0; row < Globals.Rows; row++)
                for (int column = 0; column < Globals.Columns; column++)
                {
                    if (matrix[row, column] != null && matrix[row, column].GO != null)
                        Destroy(matrix[row, column].GO);
                }

        matrix = new ItemArray();



        //InitArrayWithPremadeData();
        CreateNewItem();
        CreateNewItem();

        score = 0;
        UpdateScore(0);

        gameState = GameState.Playing;
    }
    protected override void Analyze(ItemArray<DoubleArray> qualities, ResultCollection results) {
      ItemArray<IntValue> ranks = RankParameter.ActualValue;

      bool populationLevel = RankParameter.Depth == 1;

      int objectives = qualities[0].Length;
      int frontSize = ranks.Count(x => x.Value == 0);
      ItemArray<IScope> paretoArchive = null;
      if (populationLevel) paretoArchive = new ItemArray<IScope>(frontSize);

      DoubleMatrix front = new DoubleMatrix(frontSize, objectives);
      int counter = 0;
      for (int i = 0; i < ranks.Length; i++) {
        if (ranks[i].Value == 0) {
          for (int k = 0; k < objectives; k++)
            front[counter, k] = qualities[i][k];
          if (populationLevel) {
            paretoArchive[counter] = (IScope)ExecutionContext.Scope.SubScopes[i].Clone();
          }
          counter++;
        }
      }

      front.RowNames = GetRowNames(front);
      front.ColumnNames = GetColumnNames(front);

      if (results.ContainsKey("Pareto Front"))
        results["Pareto Front"].Value = front;
      else results.Add(new Result("Pareto Front", front));

      if (populationLevel) {
        if (results.ContainsKey("Pareto Archive"))
          results["Pareto Archive"].Value = paretoArchive;
        else results.Add(new Result("Pareto Archive", paretoArchive));
      }
    }
    /// <summary>
    /// Performs an average crossover of the two given parent integer vectors.
    /// The average is rounded and mapped to the nearest valid value (e.g. if step size is > 1)
    /// </summary>
    /// <param name="random">A random number generator.</param>
    /// <param name="parents">The parents for crossover.</param>
    /// <param name="bounds">The bounds matrix that contains for each dimension one row with minimum (inclusive), maximum (exclusive), and step size columns.
    /// If the number of rows is smaller than the number of dimensions the matrix is cycled.</param>
    /// <returns>The newly created integer vector, resulting from the single point crossover.</returns>
    public static IntegerVector Apply(IRandom random, ItemArray<IntegerVector> parents, IntMatrix bounds) {
      int length = parents[0].Length, parentsCount = parents.Length;
      if (parents.Length < 2) throw new ArgumentException("RoundedAverageCrossover: The number of parents is less than 2.", "parents");
      if (bounds == null || bounds.Rows < 1 || bounds.Columns < 2) throw new ArgumentException("AverageCrossover: Invalid bounds specified.", "bounds");

      var result = new IntegerVector(length);
      try {
        double avg;
        for (int i = 0; i < length; i++) {
          avg = 0;
          for (int j = 0; j < parentsCount; j++)
            avg += parents[j][i];
          avg /= parentsCount;
          int min = bounds[i % bounds.Rows, 0], max = bounds[i % bounds.Rows, 1], step = 1;
          if (bounds.Columns > 2) step = bounds[i % bounds.Rows, 2];
          max = FloorFeasible(min, max, step, max - 1);
          result[i] = RoundFeasible(min, max, step, avg);
        }
      } catch (IndexOutOfRangeException) {
        throw new ArgumentException("RoundedAverageCrossover: The parents' vectors are of different length.", "parents");
      }

      return result;
    }
 protected abstract RealVector Cross(IRandom random, ItemArray<RealVector> parents);
 protected abstract IntegerVector Cross(IRandom random, ItemArray<IntegerVector> parents);
    /// <summary>
    /// Checks if the number of parents is equal to 2, if all parameters are available and forwards the call to <see cref="Apply(IRandom, IntegerVector, IntegerVector, IntMatrix, DoubleValue, DoubleValue)"/>.
    /// </summary>
    /// <exception cref="ArgumentException">Thrown when the number of parents is not equal to 2.</exception>
    /// <exception cref="InvalidOperationException">
    /// Thrown when either:<br/>
    /// <list type="bullet">
    /// <item><description>Maximization parameter could not be found.</description></item>
    /// <item><description>Quality parameter could not be found or the number of quality values is not equal to the number of parents.</description></item>
    /// <item><description>Alpha parameter could not be found.</description></item>
    /// <item><description>Beta parameter could not be found.</description></item>
    /// </list>
    /// </exception>
    /// <param name="random">The random number generator to use.</param>
    /// <param name="parents">The collection of parents (must be of size 2).</param>
    /// <param name="bounds">The bounds and step size for each dimension (will be cycled in case there are less rows than elements in the parent vectors).</param>
    /// <returns>The integer vector that results from the crossover.</returns>
    protected override IntegerVector CrossBounded(IRandom random, ItemArray<IntegerVector> parents, IntMatrix bounds) {
      if (parents.Length != 2) throw new ArgumentException("RoundedBlendAlphaBetaCrossover: Number of parents is not equal to 2.", "parents");
      if (MaximizationParameter.ActualValue == null) throw new InvalidOperationException("RoundedBlendAlphaBetaCrossover: Parameter " + MaximizationParameter.ActualName + " could not be found.");
      if (QualityParameter.ActualValue == null || QualityParameter.ActualValue.Length != parents.Length) throw new InvalidOperationException("RoundedBlendAlphaBetaCrossover: Parameter " + QualityParameter.ActualName + " could not be found, or not in the same quantity as there are parents.");
      if (AlphaParameter.ActualValue == null || BetaParameter.ActualValue == null) throw new InvalidOperationException("RoundedBlendAlphaBetaCrossover: Parameter " + AlphaParameter.ActualName + " or paramter " + BetaParameter.ActualName + " could not be found.");

      ItemArray<DoubleValue> qualities = QualityParameter.ActualValue;
      bool maximization = MaximizationParameter.ActualValue.Value;
      if (maximization && qualities[0].Value >= qualities[1].Value || !maximization && qualities[0].Value <= qualities[1].Value)
        return Apply(random, parents[0], parents[1], bounds, AlphaParameter.ActualValue, BetaParameter.ActualValue);
      else {
        return Apply(random, parents[1], parents[0], bounds, AlphaParameter.ActualValue, BetaParameter.ActualValue);
      }
    }
 /// <summary>
 /// Checks number of parents and calls <see cref="Apply(IRandom, Permutation, Permutation)"/>.
 /// </summary>
 /// <exception cref="InvalidOperationException">Thrown if there are not exactly two parents.</exception>
 /// <param name="random">A random number generator.</param>
 /// <param name="parents">An array containing the two permutations that should be crossed.</param>
 /// <returns>The new permutation resulting from the crossover.</returns>
 protected override Permutation Cross(IRandom random, ItemArray<Permutation> parents) {
   if (parents.Length != 2) throw new InvalidOperationException("OrderCrossover2: Number of parents is not equal to 2.");
   return Apply(random, parents[0], parents[1]);
 }
 /// <summary>
 /// Checks that the number of parents is equal to 2 and forwards the call to <see cref="Apply(IRandom, RealVector, RealVector, DoubleValue)"/>.
 /// </summary>
 /// <exception cref="ArgumentException">Thrown when the number of parents is not equal to 2.</exception>
 /// <exception cref="InvalidOperationException">Thrown when the parameter alpha could not be found.</exception>
 /// <param name="random">The random number generator to use.</param>
 /// <param name="parents">The collection of parents (must be of size 2).</param>
 /// <param name="bounds">The bounds and step size for each dimension (will be cycled in case there are less rows than elements in the parent vectors).</param>
 /// <returns>The integer vector resulting from the crossover operation.</returns>
 protected override IntegerVector CrossBounded(IRandom random, ItemArray<IntegerVector> parents, IntMatrix bounds) {
   if (parents.Length != 2) throw new ArgumentException("RoundedBlendAlphaCrossover: The number of parents is not equal to 2", "parents");
   if (AlphaParameter.ActualValue == null) throw new InvalidOperationException("RoundedBlendAlphaCrossover: Parameter " + AlphaParameter.ActualName + " could not be found.");
   return Apply(random, parents[0], parents[1], bounds, AlphaParameter.ActualValue);
 }
Example #55
0
    /// <summary>
    /// Performs a N point crossover at a randomly chosen position of two 
    /// given parent binary vectors.
    /// </summary>
    /// <exception cref="ArgumentException">Thrown if there are not exactly two parents.</exception>
    /// <exception cref="InvalidOperationException">
    /// Thrown when the N parameter could not be found.</description></item>
    /// </exception>
    /// <param name="random">A random number generator.</param>
    /// <param name="parents">An array containing the two binary vectors that should be crossed.</param>
    /// <returns>The newly created binary vector, resulting from the N point crossover.</returns>
    protected override BinaryVector Cross(IRandom random, ItemArray<BinaryVector> parents) {
      if (parents.Length != 2) throw new ArgumentException("ERROR in NPointCrossover: The number of parents is not equal to 2");

      if (NParameter.ActualValue == null) throw new InvalidOperationException("NPointCrossover: Parameter " + NParameter.ActualName + " could not be found.");

      return Apply(random, parents[0], parents[1], NParameter.ActualValue);
    }
 /// <summary>
 /// Performs a random convex crossover operation for two given parent real vectors.
 /// </summary>
 /// <exception cref="ArgumentException">Thrown if there are not exactly two parents.</exception>
 /// <param name="random">A random number generator.</param>
 /// <param name="parents">An array containing the two real vectors that should be crossed.</param>
 /// <returns>The newly created real vector, resulting from the crossover operation.</returns>
 protected override RealVector Cross(IRandom random, ItemArray<RealVector> parents) {
   if (parents.Length != 2) throw new ArgumentException("ERROR in RandomConvexCrossover: The number of parents is not equal to 2");
   return Apply(random, parents[0], parents[1]);
 }
 protected override LinearLinkage Cross(IRandom random, ItemArray<LinearLinkage> parents) {
   return Apply(random, parents);
 }
 protected override ItemArray<IItem> Relink(ItemArray<IItem> parents, PercentValue n) {
   if (parents.Length != 2)
     throw new ArgumentException("The number of parents is not equal to 2.");
   return Apply(parents[0], parents[1], RelinkingIntensity, n);
 }
 protected override LinearLinkage Cross(IRandom random, ItemArray<LinearLinkage> parents) {
   if (parents.Length != 2) throw new InvalidOperationException(Name + ": Can only cross exactly two parents.");
   return Apply(random, parents[0], parents[1]);
 }
 /// <summary>
 /// Checks number of parents and calls <see cref="Apply(IRandom, Permutation, Permutation)"/>.
 /// </summary>
 /// <exception cref="InvalidOperationException">Thrown if there are not exactly two parents.</exception>
 /// <param name="random">A random number generator.</param>
 /// <param name="parents">An array containing the two permutations that should be crossed.</param>
 /// <returns>The newly created permutation, resulting from the crossover operation.</returns>
 protected override Permutation Cross(IRandom random, ItemArray<Permutation> parents) {
   if (parents.Length != 2) throw new InvalidOperationException("ERROR in PositionBasedCrossover: The number of parents is not equal to 2");
   return Apply(random, parents[0], parents[1]);
 }