Esempio n. 1
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()
        {
            ItemArray <BinaryVector> binaryVectors = BinaryVectorParameter.ActualValue;
            ItemArray <DoubleValue>  qualities     = QualityParameter.ActualValue;
            ResultCollection         results       = ResultsParameter.ActualValue;
            bool        max = MaximizationParameter.ActualValue.Value;
            DoubleValue bestKnownQuality = BestKnownQualityParameter.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 = (BinaryVector)binaryVectors[i].Clone();
            }

            KnapsackSolution solution = BestSolutionParameter.ActualValue;

            if (solution == null)
            {
                solution = new KnapsackSolution((BinaryVector)binaryVectors[i].Clone(), new DoubleValue(qualities[i].Value),
                                                KnapsackCapacityParameter.ActualValue, WeightsParameter.ActualValue, ValuesParameter.ActualValue);
                BestSolutionParameter.ActualValue = solution;
                results.Add(new Result("Best Knapsack Solution", solution));
            }
            else
            {
                if (max && qualities[i].Value > solution.Quality.Value ||
                    !max && qualities[i].Value < solution.Quality.Value)
                {
                    solution.BinaryVector = (BinaryVector)binaryVectors[i].Clone();
                    solution.Quality      = new DoubleValue(qualities[i].Value);
                    solution.Capacity     = KnapsackCapacityParameter.ActualValue;
                    solution.Weights      = WeightsParameter.ActualValue;
                    solution.Values       = ValuesParameter.ActualValue;
                }
            }

            return(base.Apply());
        }
        public override IOperation Apply()
        {
            DoubleMatrix            coordinates  = CoordinatesParameter.ActualValue;
            ItemArray <Permutation> permutations = PermutationParameter.ActualValue;
            ItemArray <DoubleValue> qualities    = QualityParameter.ActualValue;
            ResultCollection        results      = ResultsParameter.ActualValue;
            bool        max = MaximizationParameter.ActualValue.Value;
            DoubleValue bestKnownQuality = BestKnownQualityParameter.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 = (Permutation)permutations[i].Clone();
            }

            PathTSPTour tour = BestSolutionParameter.ActualValue;

            if (tour == null)
            {
                tour = new PathTSPTour(coordinates, (Permutation)permutations[i].Clone(), new DoubleValue(qualities[i].Value));
                BestSolutionParameter.ActualValue = tour;
                results.Add(new Result("Best TSP Solution", tour));
            }
            else
            {
                if (max && tour.Quality.Value < qualities[i].Value ||
                    !max && tour.Quality.Value > qualities[i].Value)
                {
                    tour.Coordinates   = coordinates;
                    tour.Permutation   = (Permutation)permutations[i].Clone();
                    tour.Quality.Value = qualities[i].Value;
                }
            }

            return(base.Apply());
        }
Esempio n. 4
0
        public override IOperation Apply()
        {
            ItemArray <DoubleValue> qualities = QualityParameter.ActualValue;
            ItemArray <Schedule>    solutions = ScheduleParameter.ActualValue;
            ResultCollection        results   = ResultsParameter.ActualValue;
            bool        max = MaximizationParameter.ActualValue.Value;
            DoubleValue bestKnownQuality = BestKnownQualityParameter.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 = (Schedule)solutions[i].Clone();
            }

            Schedule bestSolution = BestSolutionParameter.ActualValue;

            if (bestSolution == null)
            {
                bestSolution         = (Schedule)solutions[i].Clone();
                bestSolution.Quality = (DoubleValue)qualities[i].Clone();
                BestSolutionParameter.ActualValue = bestSolution;
                results.Add(new Result("Best Scheduling Solution", bestSolution));
            }
            else
            {
                if (max && bestSolution.Quality.Value < qualities[i].Value ||
                    !max && bestSolution.Quality.Value > qualities[i].Value)
                {
                    bestSolution.Quality.Value = qualities[i].Value;
                    bestSolution.Resources     = (ItemList <Resource>)solutions[i].Resources.Clone();
                }
            }

            return(base.Apply());
        }
        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());
        }
    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;
    }
        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 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;
    }
Esempio n. 9
0
        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);
        }
        public static LinearLinkage Apply(IRandom random, ItemArray <LinearLinkage> parents)
        {
            var len       = parents[0].Length;
            var child     = LinearLinkage.SingleElementGroups(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 override IOperation Apply()
        {
            IVRPProblemInstance      problemInstance = ProblemInstanceParameter.ActualValue;
            ItemArray <IVRPEncoding> solutions       = VRPToursParameter.ActualValue;
            ResultCollection         results         = ResultsParameter.ActualValue;

            ItemArray <DoubleValue> qualities            = QualityParameter.ActualValue;
            ItemArray <DoubleValue> distances            = DistanceParameter.ActualValue;
            ItemArray <DoubleValue> vehiclesUtilizations = VehiclesUtilizedParameter.ActualValue;

            int          i        = qualities.Select((x, index) => new { index, x.Value }).OrderBy(x => x.Value).First().index;
            IVRPEncoding best     = solutions[i].Clone() as IVRPEncoding;
            VRPSolution  solution = BestSolutionParameter.ActualValue;

            if (solution == null)
            {
                solution = new VRPSolution(problemInstance, best.Clone() as IVRPEncoding, new DoubleValue(qualities[i].Value));
                BestSolutionParameter.ActualValue = solution;
                results.Add(new Result("Best VRP Solution", solution));

                results.Add(new Result("Best VRP Solution Distance", new DoubleValue(distances[i].Value)));
                results.Add(new Result("Best VRP Solution VehicleUtilization", new DoubleValue(vehiclesUtilizations[i].Value)));
            }
            else
            {
                VRPEvaluation eval = problemInstance.Evaluate(solution.Solution);
                if (qualities[i].Value <= eval.Quality)
                {
                    solution.ProblemInstance = problemInstance;
                    solution.Solution        = best.Clone() as IVRPEncoding;
                    solution.Quality.Value   = qualities[i].Value;
                    (results["Best VRP Solution Distance"].Value as DoubleValue).Value           = distances[i].Value;
                    (results["Best VRP Solution VehicleUtilization"].Value as DoubleValue).Value = vehiclesUtilizations[i].Value;
                }
            }

            var idx = qualities.Select((x, index) => new { index, x.Value }).Where(index => problemInstance.Feasible(solutions[index.index])).OrderBy(x => x.Value).FirstOrDefault();

            if (idx != null)
            {
                int          j             = idx.index;
                IVRPEncoding bestFeasible  = solutions[j].Clone() as IVRPEncoding;
                VRPSolution  validSolution = BestValidSolutionParameter.ActualValue;
                if (validSolution == null)
                {
                    validSolution = new VRPSolution(problemInstance, best.Clone() as IVRPEncoding, new DoubleValue(qualities[j].Value));
                    BestValidSolutionParameter.ActualValue = validSolution;
                    if (results.ContainsKey("Best valid VRP Solution"))
                    {
                        results["Best valid VRP Solution"].Value = validSolution;
                    }
                    else
                    {
                        results.Add(new Result("Best valid VRP Solution", validSolution));
                    }

                    results.Add(new Result("Best valid VRP Solution Distance", new DoubleValue(distances[j].Value)));
                    results.Add(new Result("Best valid VRP Solution VehicleUtilization", new DoubleValue(vehiclesUtilizations[j].Value)));
                }
                else
                {
                    if (qualities[j].Value <= validSolution.Quality.Value)
                    {
                        if (ProblemInstanceParameter.ActualValue.Feasible(best))
                        {
                            validSolution.ProblemInstance = problemInstance;
                            validSolution.Solution        = best.Clone() as IVRPEncoding;
                            validSolution.Quality.Value   = qualities[j].Value;
                            (results["Best valid VRP Solution Distance"].Value as DoubleValue).Value           = distances[j].Value;
                            (results["Best valid VRP Solution VehicleUtilization"].Value as DoubleValue).Value = vehiclesUtilizations[j].Value;
                        }
                    }
                }

                DoubleValue bestKnownQuality = BestKnownQualityParameter.ActualValue;
                if (bestKnownQuality == null || qualities[j].Value < bestKnownQuality.Value)
                {
                    BestKnownQualityParameter.ActualValue  = new DoubleValue(qualities[j].Value);
                    BestKnownSolutionParameter.ActualValue = (VRPSolution)validSolution.Clone();
                }
            }

            return(base.Apply());
        }
        public override IOperation Apply()
        {
            DoubleMatrix            distances    = DistancesParameter.ActualValue;
            DoubleMatrix            weights      = WeightsParameter.ActualValue;
            ItemArray <Permutation> permutations = PermutationParameter.ActualValue;
            ItemArray <DoubleValue> qualities    = QualityParameter.ActualValue;
            ResultCollection        results      = ResultsParameter.ActualValue;
            bool        max = MaximizationParameter.ActualValue.Value;
            DoubleValue bestKnownQuality = BestKnownQualityParameter.ActualValue;

            var sorted = qualities.Select((x, index) => new { index, x.Value }).OrderBy(x => x.Value).ToArray();

            if (max)
            {
                sorted = sorted.Reverse().ToArray();
            }
            int i = sorted.First().index;

            if (bestKnownQuality == null ||
                max && qualities[i].Value > bestKnownQuality.Value ||
                !max && qualities[i].Value < bestKnownQuality.Value)
            {
                // if there isn't a best-known quality or we improved the best-known quality we'll add the current solution as best-known
                BestKnownQualityParameter.ActualValue   = new DoubleValue(qualities[i].Value);
                BestKnownSolutionParameter.ActualValue  = (Permutation)permutations[i].Clone();
                BestKnownSolutionsParameter.ActualValue = new ItemSet <Permutation>(new PermutationEqualityComparer());
                BestKnownSolutionsParameter.ActualValue.Add((Permutation)permutations[i].Clone());
            }
            else if (bestKnownQuality.Value == qualities[i].Value)
            {
                // if we matched the best-known quality we'll try to set the best-known solution if it isn't null
                // and try to add it to the pool of best solutions if it is different
                if (BestKnownSolutionParameter.ActualValue == null)
                {
                    BestKnownSolutionParameter.ActualValue = (Permutation)permutations[i].Clone();
                }
                if (BestKnownSolutionsParameter.ActualValue == null)
                {
                    BestKnownSolutionsParameter.ActualValue = new ItemSet <Permutation>(new PermutationEqualityComparer());
                }
                foreach (var k in sorted) // for each solution that we found check if it is in the pool of best-knowns
                {
                    if (!max && k.Value > qualities[i].Value ||
                        max && k.Value < qualities[i].Value)
                    {
                        break;                             // stop when we reached a solution worse than the best-known quality
                    }
                    Permutation p = permutations[k.index];
                    if (!BestKnownSolutionsParameter.ActualValue.Contains(p))
                    {
                        BestKnownSolutionsParameter.ActualValue.Add((Permutation)permutations[k.index].Clone());
                    }
                }
            }

            QAPAssignment assignment = BestSolutionParameter.ActualValue;

            if (assignment == null)
            {
                assignment           = new QAPAssignment(weights, (Permutation)permutations[i].Clone(), new DoubleValue(qualities[i].Value));
                assignment.Distances = distances;
                BestSolutionParameter.ActualValue = assignment;
                results.Add(new Result("Best QAP Solution", assignment));
            }
            else
            {
                if (max && assignment.Quality.Value < qualities[i].Value ||
                    !max && assignment.Quality.Value > qualities[i].Value)
                {
                    assignment.Distances     = distances;
                    assignment.Weights       = weights;
                    assignment.Assignment    = (Permutation)permutations[i].Clone();
                    assignment.Quality.Value = qualities[i].Value;
                }
            }

            return(base.Apply());
        }
        public override IOperation Apply()
        {
            int      updateInterval = UpdateIntervalParameter.Value.Value;
            IntValue updateCounter  = UpdateCounterParameter.ActualValue;

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

            if (updateCounter.Value == updateInterval)
            {
                updateCounter.Value = 0;

                bool          max               = MaximizationParameter.ActualValue.Value;
                ItemArray <T> solutions         = SolutionParameter.ActualValue;
                double[]      qualities         = QualityParameter.ActualValue.Select(x => x.Value).ToArray();
                T             bestKnownSolution = BestKnownSolutionParameter.ActualValue;
                bool          storeHistory      = StoreHistoryParameter.Value.Value;

                // calculate index of current best solution
                int bestIndex = -1;
                if (!max)
                {
                    bestIndex = qualities
                                .Select((x, i) => new { Index = i, Value = x })
                                .OrderBy(x => x.Value)
                                .First().Index;
                }
                else
                {
                    bestIndex = qualities
                                .Select((x, i) => new { Index = i, Value = x })
                                .OrderByDescending(x => x.Value)
                                .First().Index;
                }

                // calculate allels of current best and (if available) best known solution
                Allele[] bestAlleles      = CalculateAlleles(solutions[bestIndex]);
                Allele[] bestKnownAlleles = null;
                if (bestKnownSolution != null)
                {
                    bestKnownAlleles = CalculateAlleles(bestKnownSolution);
                }

                // calculate allele frequencies
                var frequencies = solutions.SelectMany((s, index) => CalculateAlleles(s).Select(a => new { Allele = a, Quality = qualities[index] })).
                                  GroupBy(x => x.Allele.Id).
                                  Select(x => new AlleleFrequency(x.Key,
                                                                  x.Count() / ((double)solutions.Length),
                                                                  x.Average(a => a.Allele.Impact),
                                                                  x.Average(a => a.Quality),
                                                                  bestKnownAlleles == null ? false : bestKnownAlleles.Any(a => a.Id == x.Key),
                                                                  bestAlleles.Any(a => a.Id == x.Key)));

                // calculate dummy allele frequencies of alleles of best known solution which did not occur
                if (bestKnownAlleles != null)
                {
                    var bestKnownFrequencies = bestKnownAlleles.Select(x => new AlleleFrequency(x.Id, 0, x.Impact, 0, true, false)).Except(frequencies, new AlleleFrequencyIdEqualityComparer());
                    frequencies = frequencies.Concat(bestKnownFrequencies);
                }

                // fetch results collection
                ResultCollection results;
                if (!ResultsParameter.ActualValue.ContainsKey(Name + " Results"))
                {
                    results = new ResultCollection();
                    ResultsParameter.ActualValue.Add(new Result(Name + " Results", results));
                }
                else
                {
                    results = (ResultCollection)ResultsParameter.ActualValue[Name + " Results"].Value;
                }

                // store allele frequencies
                AlleleFrequencyCollection frequenciesCollection = new AlleleFrequencyCollection(frequencies);
                if (!results.ContainsKey("Allele Frequencies"))
                {
                    results.Add(new Result("Allele Frequencies", frequenciesCollection));
                }
                else
                {
                    results["Allele Frequencies"].Value = frequenciesCollection;
                }

                // store allele frequencies history
                if (storeHistory)
                {
                    if (!results.ContainsKey("Allele Frequencies History"))
                    {
                        AlleleFrequencyCollectionHistory history = new AlleleFrequencyCollectionHistory();
                        history.Add(frequenciesCollection);
                        results.Add(new Result("Allele Frequencies History", history));
                    }
                    else
                    {
                        ((AlleleFrequencyCollectionHistory)results["Allele Frequencies History"].Value).Add(frequenciesCollection);
                    }
                }

                // store alleles data table
                DataTable allelesTable;
                if (!results.ContainsKey("Alleles"))
                {
                    allelesTable = new DataTable("Alleles");
                    allelesTable.VisualProperties.XAxisTitle       = "Iteration";
                    allelesTable.VisualProperties.YAxisTitle       = "Number of Alleles";
                    allelesTable.VisualProperties.SecondYAxisTitle = "Number of Alleles";

                    allelesTable.Rows.Add(new DataRow("Unique Alleles"));
                    allelesTable.Rows["Unique Alleles"].VisualProperties.StartIndexZero = true;

                    allelesTable.Rows.Add(new DataRow("Unique Alleles of Best Known Solution", null));
                    allelesTable.Rows["Unique Alleles of Best Known Solution"].VisualProperties.SecondYAxis    = true;
                    allelesTable.Rows["Unique Alleles of Best Known Solution"].VisualProperties.StartIndexZero = true;

                    allelesTable.Rows.Add(new DataRow("Fixed Alleles", null));
                    allelesTable.Rows["Fixed Alleles"].VisualProperties.SecondYAxis    = true;
                    allelesTable.Rows["Fixed Alleles"].VisualProperties.StartIndexZero = true;

                    allelesTable.Rows.Add(new DataRow("Fixed Alleles of Best Known Solution", null));
                    allelesTable.Rows["Fixed Alleles of Best Known Solution"].VisualProperties.SecondYAxis    = true;
                    allelesTable.Rows["Fixed Alleles of Best Known Solution"].VisualProperties.StartIndexZero = true;

                    allelesTable.Rows.Add(new DataRow("Lost Alleles of Best Known Solution", null));
                    allelesTable.Rows["Lost Alleles of Best Known Solution"].VisualProperties.SecondYAxis    = true;
                    allelesTable.Rows["Lost Alleles of Best Known Solution"].VisualProperties.StartIndexZero = true;

                    results.Add(new Result("Alleles", allelesTable));
                }
                else
                {
                    allelesTable = (DataTable)results["Alleles"].Value;
                }

                int fixedAllelesCount          = frequenciesCollection.Where(x => x.Frequency == 1).Count();
                var relevantAlleles            = frequenciesCollection.Where(x => x.ContainedInBestKnownSolution);
                int relevantAllelesCount       = relevantAlleles.Count();
                int fixedRelevantAllelesCount  = relevantAlleles.Where(x => x.Frequency == 1).Count();
                int lostRelevantAllelesCount   = relevantAlleles.Where(x => x.Frequency == 0).Count();
                int uniqueRelevantAllelesCount = relevantAllelesCount - lostRelevantAllelesCount;
                allelesTable.Rows["Unique Alleles"].Values.Add(frequenciesCollection.Count);
                allelesTable.Rows["Unique Alleles of Best Known Solution"].Values.Add(uniqueRelevantAllelesCount);
                allelesTable.Rows["Fixed Alleles"].Values.Add(fixedAllelesCount);
                allelesTable.Rows["Fixed Alleles of Best Known Solution"].Values.Add(fixedRelevantAllelesCount);
                allelesTable.Rows["Lost Alleles of Best Known Solution"].Values.Add(lostRelevantAllelesCount);

                // store alleles values
                if (!results.ContainsKey("Unique Alleles"))
                {
                    results.Add(new Result("Unique Alleles", new DoubleValue(frequenciesCollection.Count)));
                }
                else
                {
                    ((DoubleValue)results["Unique Alleles"].Value).Value = frequenciesCollection.Count;
                }

                if (!results.ContainsKey("Unique Alleles of Best Known Solution"))
                {
                    results.Add(new Result("Unique Alleles of Best Known Solution", new DoubleValue(uniqueRelevantAllelesCount)));
                }
                else
                {
                    ((DoubleValue)results["Unique Alleles of Best Known Solution"].Value).Value = uniqueRelevantAllelesCount;
                }

                if (!results.ContainsKey("Fixed Alleles"))
                {
                    results.Add(new Result("Fixed Alleles", new DoubleValue(fixedAllelesCount)));
                }
                else
                {
                    ((DoubleValue)results["Fixed Alleles"].Value).Value = fixedAllelesCount;
                }

                if (!results.ContainsKey("Fixed Alleles of Best Known Solution"))
                {
                    results.Add(new Result("Fixed Alleles of Best Known Solution", new DoubleValue(fixedRelevantAllelesCount)));
                }
                else
                {
                    ((DoubleValue)results["Fixed Alleles of Best Known Solution"].Value).Value = fixedRelevantAllelesCount;
                }

                if (!results.ContainsKey("Lost Alleles of Best Known Solution"))
                {
                    results.Add(new Result("Lost Alleles of Best Known Solution", new DoubleValue(lostRelevantAllelesCount)));
                }
                else
                {
                    ((DoubleValue)results["Lost Alleles of Best Known Solution"].Value).Value = lostRelevantAllelesCount;
                }

                // calculate contained alleles of best known solution and relative quality
                if (bestKnownAlleles != null)
                {
                    double qualityRange = Math.Abs(qualities.Max() - qualities.Min());
                    var    points       = solutions.Select((s, index) => new Point2D <double>(CalculateAlleles(s).Intersect(bestKnownAlleles, new AlleleIdEqualityComparer()).Count(),
                                                                                              Math.Abs(qualities[index] - qualities[bestIndex]) / qualityRange));
                    var avgContainedReleventAlleles = points.Select(x => x.X).Average();

                    var plot = new ScatterPlot("Contained Alleles of Best Known Solution and Relative Solution Qualtiy", null);
                    plot.VisualProperties.XAxisTitle             = "Contained Alleles of Best Known Solution";
                    plot.VisualProperties.YAxisTitle             = "Relative Solution Quality";
                    plot.VisualProperties.XAxisMinimumAuto       = false;
                    plot.VisualProperties.XAxisMinimumFixedValue = 0.0;
                    plot.VisualProperties.XAxisMaximumAuto       = false;
                    plot.VisualProperties.XAxisMaximumFixedValue = bestKnownAlleles.Length;
                    plot.VisualProperties.YAxisMinimumAuto       = false;
                    plot.VisualProperties.YAxisMinimumFixedValue = 0.0;
                    plot.VisualProperties.YAxisMaximumAuto       = false;
                    plot.VisualProperties.YAxisMaximumFixedValue = 1.0;
                    var row = new ScatterPlotDataRow("Solutions of Current Generation", null, points);
                    row.VisualProperties.PointStyle = ScatterPlotDataRowVisualProperties.ScatterPlotDataRowPointStyle.Circle;
                    row.VisualProperties.PointSize  = 5;
                    plot.Rows.Add(row);

                    if (!results.ContainsKey("Scatter Plot"))
                    {
                        results.Add(new Result("Scatter Plot", plot));
                    }
                    else
                    {
                        results["Scatter Plot"].Value = plot;
                    }
                    if (storeHistory)
                    {
                        if (!results.ContainsKey("Scatter Plot History"))
                        {
                            results.Add(new Result("Scatter Plot History", new ScatterPlotHistory()));
                        }
                        ((ScatterPlotHistory)results["Scatter Plot History"].Value).Add(plot);
                    }

                    if (!allelesTable.Rows.ContainsKey("Average Contained Alleles of Best Known Solution"))
                    {
                        allelesTable.Rows.Add(new DataRow("Average Contained Alleles of Best Known Solution", null));
                        allelesTable.Rows["Average Contained Alleles of Best Known Solution"].VisualProperties.SecondYAxis    = true;
                        allelesTable.Rows["Average Contained Alleles of Best Known Solution"].VisualProperties.StartIndexZero = true;
                    }
                    allelesTable.Rows["Average Contained Alleles of Best Known Solution"].Values.Add(avgContainedReleventAlleles);

                    if (!results.ContainsKey("Average Contained Alleles of Best Known Solution"))
                    {
                        results.Add(new Result("Average Contained Alleles of Best Known Solution", new DoubleValue(avgContainedReleventAlleles)));
                    }
                    else
                    {
                        ((DoubleValue)results["Average Contained Alleles of Best Known Solution"].Value).Value = avgContainedReleventAlleles;
                    }
                }
            }
            return(base.Apply());
        }
        public override IOperation Apply()
        {
            ItemArray <DoubleValue> rightQualities = RightSideParameter.ActualValue;

            if (rightQualities.Length < 1)
            {
                throw new InvalidOperationException(Name + ": No subscopes found.");
            }
            double compFact     = ComparisonFactorParameter.ActualValue.Value;
            bool   maximization = MaximizationParameter.ActualValue.Value;
            double leftQuality  = LeftSideParameter.ActualValue.Value;

            double threshold = 0;

            #region Calculate threshold
            if (rightQualities.Length == 2) // this case will probably be used most often
            {
                double minQuality = Math.Min(rightQualities[0].Value, rightQualities[1].Value);
                double maxQuality = Math.Max(rightQualities[0].Value, rightQualities[1].Value);
                if (maximization)
                {
                    threshold = minQuality + (maxQuality - minQuality) * compFact;
                }
                else
                {
                    threshold = maxQuality - (maxQuality - minQuality) * compFact;
                }
            }
            else if (rightQualities.Length == 1) // case for just one parent
            {
                threshold = rightQualities[0].Value;
            }
            else // general case extended to 3 or more parents
            {
                List <double> sortedQualities = rightQualities.Select(x => x.Value).ToList();
                sortedQualities.Sort();
                double minimumQuality = sortedQualities.First();

                double integral = 0;
                for (int i = 0; i < sortedQualities.Count - 1; i++)
                {
                    integral += (sortedQualities[i] + sortedQualities[i + 1]) / 2.0; // sum of the trapezoid
                }
                integral -= minimumQuality * sortedQualities.Count;
                if (integral == 0)
                {
                    threshold = sortedQualities[0];        // all qualities are equal
                }
                else
                {
                    double selectedArea = integral * (maximization ? compFact : (1 - compFact));
                    integral = 0;
                    for (int i = 0; i < sortedQualities.Count - 1; i++)
                    {
                        double currentSliceArea  = (sortedQualities[i] + sortedQualities[i + 1]) / 2.0;
                        double windowedSliceArea = currentSliceArea - minimumQuality;
                        if (windowedSliceArea == 0)
                        {
                            continue;
                        }
                        integral += windowedSliceArea;
                        if (integral >= selectedArea)
                        {
                            double factor = 1 - ((integral - selectedArea) / (windowedSliceArea));
                            threshold = sortedQualities[i] + (sortedQualities[i + 1] - sortedQualities[i]) * factor;
                            break;
                        }
                    }
                }
            }
            #endregion

            bool      result      = maximization && leftQuality > threshold || !maximization && leftQuality < threshold;
            BoolValue resultValue = ResultParameter.ActualValue;
            if (resultValue == null)
            {
                ResultParameter.ActualValue = new BoolValue(result);
            }
            else
            {
                resultValue.Value = result;
            }

            return(base.Apply());
        }
        public override IOperation Apply()
        {
            int      updateInterval = UpdateIntervalParameter.Value.Value;
            IntValue updateCounter  = UpdateCounterParameter.ActualValue;

            // if counter does not yet exist then initialize it with update interval
            // to make sure the solutions are analyzed on the first application of this operator
            if (updateCounter == null)
            {
                updateCounter = new IntValue(updateInterval);
                UpdateCounterParameter.ActualValue = updateCounter;
            }
            else
            {
                updateCounter.Value++;
            }

            //analyze solutions only every 'updateInterval' times
            if (updateCounter.Value == updateInterval)
            {
                updateCounter.Value = 0;

                bool                    max          = MaximizationParameter.ActualValue.Value;
                ItemArray <T>           solutions    = SolutionParameter.ActualValue;
                ItemArray <DoubleValue> qualities    = QualityParameter.ActualValue;
                bool                    storeHistory = StoreHistoryParameter.Value.Value;
                int count = solutions.Length;

                if (count > 1)
                {
                    // sort solutions by quality
                    T[] sortedSolutions = null;
                    if (max)
                    {
                        sortedSolutions = solutions
                                          .Select((x, index) => new { Solution = x, Quality = qualities[index] })
                                          .OrderByDescending(x => x.Quality)
                                          .Select(x => x.Solution)
                                          .ToArray();
                    }
                    else
                    {
                        sortedSolutions = solutions
                                          .Select((x, index) => new { Solution = x, Quality = qualities[index] })
                                          .OrderBy(x => x.Quality)
                                          .Select(x => x.Solution)
                                          .ToArray();
                    }

                    // calculate solution similarities
                    double[,] similarities = CalculateSimilarities(sortedSolutions);

                    // calculate minimum, average and maximum similarities
                    double   similarity;
                    double[] minSimilarities = new double[count];
                    double[] avgSimilarities = new double[count];
                    double[] maxSimilarities = new double[count];
                    for (int i = 0; i < count; i++)
                    {
                        minSimilarities[i] = 1;
                        avgSimilarities[i] = 0;
                        maxSimilarities[i] = 0;
                        for (int j = 0; j < count; j++)
                        {
                            if (i != j)
                            {
                                similarity = similarities[i, j];

                                if ((similarity < 0) || (similarity > 1))
                                {
                                    throw new InvalidOperationException("Solution similarities have to be in the interval [0;1].");
                                }

                                if (minSimilarities[i] > similarity)
                                {
                                    minSimilarities[i] = similarity;
                                }
                                avgSimilarities[i] += similarity;
                                if (maxSimilarities[i] < similarity)
                                {
                                    maxSimilarities[i] = similarity;
                                }
                            }
                        }
                        avgSimilarities[i] = avgSimilarities[i] / (count - 1);
                    }
                    double avgMinSimilarity = minSimilarities.Average();
                    double avgAvgSimilarity = avgSimilarities.Average();
                    double avgMaxSimilarity = maxSimilarities.Average();

                    // fetch results collection
                    ResultCollection results;
                    if (!ResultsParameter.ActualValue.ContainsKey(Name + " Results"))
                    {
                        results = new ResultCollection();
                        ResultsParameter.ActualValue.Add(new Result(Name + " Results", results));
                    }
                    else
                    {
                        results = (ResultCollection)ResultsParameter.ActualValue[Name + " Results"].Value;
                    }

                    // store similarities
                    HeatMap similaritiesHeatMap = new HeatMap(similarities, "Solution Similarities", 0.0, 1.0);
                    if (!results.ContainsKey("Solution Similarities"))
                    {
                        results.Add(new Result("Solution Similarities", similaritiesHeatMap));
                    }
                    else
                    {
                        results["Solution Similarities"].Value = similaritiesHeatMap;
                    }

                    // store similarities history
                    if (storeHistory)
                    {
                        if (!results.ContainsKey("Solution Similarities History"))
                        {
                            HeatMapHistory history = new HeatMapHistory();
                            history.Add(similaritiesHeatMap);
                            results.Add(new Result("Solution Similarities History", history));
                        }
                        else
                        {
                            ((HeatMapHistory)results["Solution Similarities History"].Value).Add(similaritiesHeatMap);
                        }
                    }

                    // store average minimum, average and maximum similarity
                    if (!results.ContainsKey("Average Minimum Solution Similarity"))
                    {
                        results.Add(new Result("Average Minimum Solution Similarity", new DoubleValue(avgMinSimilarity)));
                    }
                    else
                    {
                        ((DoubleValue)results["Average Minimum Solution Similarity"].Value).Value = avgMinSimilarity;
                    }

                    if (!results.ContainsKey("Average Average Solution Similarity"))
                    {
                        results.Add(new Result("Average Average Solution Similarity", new DoubleValue(avgAvgSimilarity)));
                    }
                    else
                    {
                        ((DoubleValue)results["Average Average Solution Similarity"].Value).Value = avgAvgSimilarity;
                    }

                    if (!results.ContainsKey("Average Maximum Solution Similarity"))
                    {
                        results.Add(new Result("Average Maximum Solution Similarity", new DoubleValue(avgMaxSimilarity)));
                    }
                    else
                    {
                        ((DoubleValue)results["Average Maximum Solution Similarity"].Value).Value = avgMaxSimilarity;
                    }

                    // store average minimum, average and maximum solution similarity data table
                    DataTable minAvgMaxSimilarityDataTable;
                    if (!results.ContainsKey("Average Minimum/Average/Maximum Solution Similarity"))
                    {
                        minAvgMaxSimilarityDataTable = new DataTable("Average Minimum/Average/Maximum Solution Similarity");
                        minAvgMaxSimilarityDataTable.VisualProperties.XAxisTitle = "Iteration";
                        minAvgMaxSimilarityDataTable.VisualProperties.YAxisTitle = "Solution Similarity";
                        minAvgMaxSimilarityDataTable.Rows.Add(new DataRow("Average Minimum Solution Similarity", null));
                        minAvgMaxSimilarityDataTable.Rows["Average Minimum Solution Similarity"].VisualProperties.StartIndexZero = true;
                        minAvgMaxSimilarityDataTable.Rows.Add(new DataRow("Average Average Solution Similarity", null));
                        minAvgMaxSimilarityDataTable.Rows["Average Average Solution Similarity"].VisualProperties.StartIndexZero = true;
                        minAvgMaxSimilarityDataTable.Rows.Add(new DataRow("Average Maximum Solution Similarity", null));
                        minAvgMaxSimilarityDataTable.Rows["Average Maximum Solution Similarity"].VisualProperties.StartIndexZero = true;
                        results.Add(new Result("Average Minimum/Average/Maximum Solution Similarity", minAvgMaxSimilarityDataTable));
                    }
                    else
                    {
                        minAvgMaxSimilarityDataTable = (DataTable)results["Average Minimum/Average/Maximum Solution Similarity"].Value;
                    }
                    minAvgMaxSimilarityDataTable.Rows["Average Minimum Solution Similarity"].Values.Add(avgMinSimilarity);
                    minAvgMaxSimilarityDataTable.Rows["Average Average Solution Similarity"].Values.Add(avgAvgSimilarity);
                    minAvgMaxSimilarityDataTable.Rows["Average Maximum Solution Similarity"].Values.Add(avgMaxSimilarity);

                    // store minimum, average, maximum similarities data table
                    DataTable minAvgMaxSimilaritiesDataTable = new DataTable("Minimum/Average/Maximum Solution Similarities");
                    minAvgMaxSimilaritiesDataTable.VisualProperties.XAxisTitle = "Solution Index";
                    minAvgMaxSimilaritiesDataTable.VisualProperties.YAxisTitle = "Solution Similarity";
                    minAvgMaxSimilaritiesDataTable.Rows.Add(new DataRow("Minimum Solution Similarity", null, minSimilarities));
                    minAvgMaxSimilaritiesDataTable.Rows["Minimum Solution Similarity"].VisualProperties.ChartType = DataRowVisualProperties.DataRowChartType.Points;
                    minAvgMaxSimilaritiesDataTable.Rows.Add(new DataRow("Average Solution Similarity", null, avgSimilarities));
                    minAvgMaxSimilaritiesDataTable.Rows["Average Solution Similarity"].VisualProperties.ChartType = DataRowVisualProperties.DataRowChartType.Points;
                    minAvgMaxSimilaritiesDataTable.Rows.Add(new DataRow("Maximum Solution Similarity", null, maxSimilarities));
                    minAvgMaxSimilaritiesDataTable.Rows["Maximum Solution Similarity"].VisualProperties.ChartType = DataRowVisualProperties.DataRowChartType.Points;
                    if (!results.ContainsKey("Minimum/Average/Maximum Solution Similarities"))
                    {
                        results.Add(new Result("Minimum/Average/Maximum Solution Similarities", minAvgMaxSimilaritiesDataTable));
                    }
                    else
                    {
                        results["Minimum/Average/Maximum Solution Similarities"].Value = minAvgMaxSimilaritiesDataTable;
                    }

                    // store minimum, average, maximum similarities history
                    if (storeHistory)
                    {
                        if (!results.ContainsKey("Minimum/Average/Maximum Solution Similarities History"))
                        {
                            DataTableHistory history = new DataTableHistory();
                            history.Add(minAvgMaxSimilaritiesDataTable);
                            results.Add(new Result("Minimum/Average/Maximum Solution Similarities History", history));
                        }
                        else
                        {
                            ((DataTableHistory)results["Minimum/Average/Maximum Solution Similarities History"].Value).Add(minAvgMaxSimilaritiesDataTable);
                        }
                    }
                }
            }
            return(base.Apply());
        }
Esempio n. 16
0
        /// <summary>
        /// Packs a collection of items into a single image.
        /// </summary>
        /// <param name="items">The list of file paths of the images to be combined.</param>
        /// <param name="requirePowerOfTwo">Whether or not the output image must have a power of two size.</param>
        /// <param name="requireSquareImage">Whether or not the output image must be a square.</param>
        /// <param name="maximumWidth">The maximum width of the output image.</param>
        /// <param name="maximumHeight">The maximum height of the output image.</param>
        /// <param name="imagePadding">The amount of blank space to insert in between individual images.</param>
        /// <param name="outputImage">The resulting output image.</param>
        /// <param name="outputMap">The resulting output map of placement rectangles for the images.</param>
        /// <param name="imageHeight">Output the merged image height</param>
        /// <param name="imageWidth">Output the merged image width</param>
        /// <returns>0 if the packing was successful, error code otherwise.</returns>
        public ImagePackReturnCode Pack(
            IEnumerable <T> items,
            bool requirePowerOfTwo,
            bool requireSquareImage,
            int maximumWidth,
            int maximumHeight,
            int imagePadding,
            out Bitmap outputImage, out int imageWidth, out int imageHeight,
            out RectangleF[] outputMap)
        {
            imageWidth  = 0;
            imageHeight = 0;
            if (deviceRes2D.Device2D == null || deviceRes2D.Device2D.IsDisposed)
            {
                outputImage = null;
                outputMap   = null;
                return(ImagePackReturnCode.DeviceFailed);
            }
            ItemArray = GetArray(items);

            requirePow2   = requirePowerOfTwo;
            requireSquare = requireSquareImage;
            OutputWidth   = maximumWidth;
            OutputHeight  = maximumHeight;
            padding       = imagePadding;

            outputImage = null;
            outputMap   = null;

            ImageSizes     = ItemArray.Select(x => GetSize(x.Value)).ToArray();
            ImagePlacement = new RectangleF[ItemArray.Length];
            // sort our files by file size so we place large sprites first
            Array.Sort(ItemArray,
                       (f1, f2) =>
            {
                var b1 = GetSize(f1.Value);
                var b2 = GetSize(f2.Value);

                int c = -b1.Width.CompareTo(b2.Width);
                if (c != 0)
                {
                    return(c);
                }

                c = -b1.Height.CompareTo(b2.Height);
                if (c != 0)
                {
                    return(c);
                }

                return(0);
            });

            // try to pack the images
            if (!PackImageRectangles())
            {
                return(ImagePackReturnCode.FailedToPackImage);
            }

            // make our output image
            outputImage = CreateOutputImage(DrawOntoOutputTarget);
            if (outputImage == null)
            {
                return(ImagePackReturnCode.FailedToCreateImage);
            }

            // copy the placement dictionary to the output
            outputMap   = ImagePlacement;
            imageWidth  = OutputWidth;
            imageHeight = OutputHeight;
            return(ImagePackReturnCode.Succeed);
        }
        public override IOperation Apply()
        {
            ItemArray <RealVector>  parameterVectors = ParameterVectorParameter.ActualValue;
            ItemArray <DoubleValue> qualities        = QualityParameter.ActualValue;
            bool        max = MaximizationParameter.ActualValue.Value;
            DoubleValue bestKnownQuality = BestKnownQualityParameter.ActualValue;

            int indexOfBest = -1;

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

            var bestQuality          = qualities[indexOfBest].Value;
            var bestParameterVector  = (RealVector)parameterVectors[indexOfBest].Clone();
            ResultCollection results = ResultsParameter.ActualValue;

            if (BestQualityParameter.ActualValue == null)
            {
                if (max)
                {
                    BestQualityParameter.ActualValue = new DoubleValue(double.MinValue);
                }
                else
                {
                    BestQualityParameter.ActualValue = new DoubleValue(double.MaxValue);
                }
            }

            if (!results.ContainsKey(BestSolutionResultName))
            {
                results.Add(new Result(BestSolutionResultName, new DoubleArray(bestParameterVector.ToArray())));
                var bestSolution = (DoubleArray)results[BestSolutionResultName].Value;
                bestSolution.ElementNames = ParameterNamesParameter.ActualValue;
                BestQualityParameter.ActualValue.Value = bestQuality;
            }
            else if (max && bestQuality > BestQualityParameter.ActualValue.Value ||
                     !max && bestQuality < BestQualityParameter.ActualValue.Value)
            {
                var bestSolution = (DoubleArray)results[BestSolutionResultName].Value;
                bestSolution.ElementNames = ParameterNamesParameter.ActualValue;
                for (int i = 0; i < bestParameterVector.Length; i++)
                {
                    bestSolution[i] = bestParameterVector[i];
                }
                BestQualityParameter.ActualValue.Value = bestQuality;
            }

            //update best known quality
            if (bestKnownQuality == null ||
                max && bestQuality > bestKnownQuality.Value ||
                !max && bestQuality < bestKnownQuality.Value)
            {
                BestKnownQualityParameter.ActualValue = new DoubleValue(bestQuality);
            }

            return(base.Apply());
        }
Esempio n. 18
0
        public override IOperation Apply()
        {
            ItemArray <DoubleValue> qualities = QualityParameter.ActualValue;
            ResultCollection        results   = ResultsParameter.ActualValue;
            bool        max = MaximizationParameter.ActualValue.Value;
            DoubleValue bestKnownQuality = BestKnownQualityParameter.ActualValue;

            if (results.ContainsKey(BestSolutionResultName) && !typeof(IScope).IsAssignableFrom(results[BestSolutionResultName].DataType))
            {
                throw new InvalidOperationException(string.Format("Could not add best solution result, because there is already a result with the name \"{0}\" present in the result collection.", BestSolutionResultName));
            }

            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;
            }

            IEnumerable <IScope> scopes = new IScope[] { ExecutionContext.Scope };

            for (int j = 0; j < QualityParameter.Depth; j++)
            {
                scopes = scopes.SelectMany(x => x.SubScopes);
            }
            IScope currentBestScope = scopes.ToList()[i];

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

            if (!results.ContainsKey(BestSolutionResultName))
            {
                var cloner = new Cloner();
                //avoid cloning of subscopes and the results collection that the solution is put in
                cloner.RegisterClonedObject(results, new ResultCollection());
                cloner.RegisterClonedObject(currentBestScope.SubScopes, new ScopeList());
                var solution = cloner.Clone(currentBestScope);

                results.Add(new Result(BestSolutionResultName, solution));
            }
            else
            {
                var    bestSolution = (IScope)results[BestSolutionResultName].Value;
                string qualityName  = QualityParameter.TranslatedName;
                if (bestSolution.Variables.ContainsKey(qualityName))
                {
                    double bestQuality = ((DoubleValue)bestSolution.Variables[qualityName].Value).Value;
                    if (max && qualities[i].Value > bestQuality ||
                        !max && qualities[i].Value < bestQuality)
                    {
                        var cloner = new Cloner();
                        //avoid cloning of subscopes and the results collection that the solution is put in
                        cloner.RegisterClonedObject(results, new ResultCollection());
                        cloner.RegisterClonedObject(currentBestScope.SubScopes, new ScopeList());
                        var solution = cloner.Clone(currentBestScope);

                        results[BestSolutionResultName].Value = solution;
                    }
                }
            }
            return(base.Apply());
        }