Free cookie consent management tool by TermsFeed Policy Generator

source: branches/3040_VectorBasedGP/HeuristicLab.Problems.DataAnalysis.Symbolic/3.4/SegmentOptimization/SegmentOptimizationProblem.cs @ 18096

Last change on this file since 18096 was 18096, checked in by pfleck, 3 years ago

#3040 Added instance provider for segment opt problem with WIP instances.

File size: 7.9 KB
Line 
1#region License Information
2/* HeuristicLab
3 * Copyright (C) Heuristic and Evolutionary Algorithms Laboratory (HEAL)
4 *
5 * This file is part of HeuristicLab.
6 *
7 * HeuristicLab is free software: you can redistribute it and/or modify
8 * it under the terms of the GNU General Public License as published by
9 * the Free Software Foundation, either version 3 of the License, or
10 * (at your option) any later version.
11 *
12 * HeuristicLab is distributed in the hope that it will be useful,
13 * but WITHOUT ANY WARRANTY; without even the implied warranty of
14 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
15 * GNU General Public License for more details.
16 *
17 * You should have received a copy of the GNU General Public License
18 * along with HeuristicLab. If not, see <http://www.gnu.org/licenses/>.
19 */
20#endregion
21
22using System;
23using System.Linq;
24using HEAL.Attic;
25using HeuristicLab.Common;
26using HeuristicLab.Core;
27using HeuristicLab.Data;
28using HeuristicLab.Encodings.IntegerVectorEncoding;
29using HeuristicLab.Optimization;
30using HeuristicLab.Parameters;
31using HeuristicLab.Problems.Instances;
32using HeuristicLab.Problems.Instances.Types;
33
34using DoubleVector = MathNet.Numerics.LinearAlgebra.Vector<double>;
35
36namespace HeuristicLab.Problems.DataAnalysis.Symbolic.SegmentOptimization {
37  [Item("Segment Optimization Problem (SOP)", "")]
38  [Creatable(CreatableAttribute.Categories.CombinatorialProblems, Priority = 1200)]
39  [StorableType("64107939-34A7-4530-BFAB-8EA1C321BF6F")]
40  public class SegmentOptimizationProblem : SingleObjectiveBasicProblem<IntegerVectorEncoding>, IProblemInstanceConsumer<SOPData> {
41
42    [StorableType("63243591-5A56-41A6-B079-122B83583993")]
43    public enum Aggregation {
44      Sum,
45      Mean,
46      StandardDeviation
47    }
48
49    public override bool Maximization => false;
50
51    [Storable]
52    private IValueParameter<DoubleArray> dataVectorParameter;
53    public IValueParameter<DoubleArray> DataVectorParameter {
54      get { return dataVectorParameter; }
55    }
56    [Storable]
57    private IValueParameter<IntRange> knownBoundsParameter;
58    public IValueParameter<IntRange> KnownBoundsParameter {
59      get { return knownBoundsParameter; }
60    }
61    [Storable]
62    private IValueParameter<EnumValue<Aggregation>> aggregationParameter;
63    public IValueParameter<EnumValue<Aggregation>> AggregationParameter {
64      get { return aggregationParameter; }
65    }
66   
67    public SegmentOptimizationProblem() {
68      Encoding = new IntegerVectorEncoding("bounds");
69
70      Parameters.Add(dataVectorParameter = new ValueParameter<DoubleArray>("Data Vector", ""));
71      Parameters.Add(knownBoundsParameter = new ValueParameter<IntRange>("Known Bounds", ""));
72      Parameters.Add(aggregationParameter = new ValueParameter<EnumValue<Aggregation>>("Aggregation Function", ""));
73
74      RegisterEventHandlers();
75
76      #region Default Instance
77      Load(new SOPData() {
78        Values = Enumerable.Range(1, 50).Select(x => (double)x * x).ToArray(),
79        Lower = 20, Upper = 30,
80        Aggregation = "mean"
81      });
82      #endregion
83    }
84    private SegmentOptimizationProblem(SegmentOptimizationProblem original, Cloner cloner)
85      : base(original, cloner) {
86      dataVectorParameter = cloner.Clone(original.dataVectorParameter);
87      knownBoundsParameter = cloner.Clone(original.knownBoundsParameter);
88      aggregationParameter = cloner.Clone(original.aggregationParameter);
89
90      RegisterEventHandlers();
91    }
92    public override IDeepCloneable Clone(Cloner cloner) {
93      return new SegmentOptimizationProblem(this, cloner);
94    }
95
96    [StorableConstructor]
97    private SegmentOptimizationProblem(StorableConstructorFlag _) : base(_) { }
98    [StorableHook(HookType.AfterDeserialization)]
99    private void AfterDeserialization() {
100      RegisterEventHandlers();
101    }
102   
103    private void RegisterEventHandlers() {
104      dataVectorParameter.ValueChanged += DataVectorChanged;
105      knownBoundsParameter.ValueChanged += KnownBoundsChanged;
106      aggregationParameter.Value.ValueChanged += AggregationFunctionChanged;
107    }
108    private void DataVectorChanged(object sender, EventArgs eventArgs) {
109      Encoding.Bounds = new IntMatrix(new[,] { { 0, DataVectorParameter.Value.Length } });
110    }
111    private void KnownBoundsChanged(object sender, EventArgs e) {
112    }
113    private void AggregationFunctionChanged(object sender, EventArgs eventArgs) {
114    }
115
116    public override double Evaluate(Individual individual, IRandom random) {
117      var data = DataVectorParameter.Value;
118      var knownBounds = KnownBoundsParameter.Value;
119      var aggregation = aggregationParameter.Value.Value;
120
121      var solution = individual.IntegerVector(Encoding.Name);
122      var bounds = new IntRange(solution.Min(), solution.Max());
123
124      double target = BoundedAggregation(data, knownBounds, aggregation);
125      double prediction = BoundedAggregation(data, bounds, aggregation);
126
127      return Math.Pow(target - prediction, 2);
128    }
129
130    public override void Analyze(Individual[] individuals, double[] qualities, ResultCollection results, IRandom random) {
131      var orderedIndividuals = individuals.Zip(qualities, (i, q) => new { Individual = i, Quality = q }).OrderBy(z => z.Quality);
132      var best = Maximization ? orderedIndividuals.Last().Individual.IntegerVector(Encoding.Name) : orderedIndividuals.First().Individual.IntegerVector(Encoding.Name);
133
134      var bounds = new IntRange(best.Min(), best.Max());
135
136      var data = DataVectorParameter.Value;
137      var knownBounds = KnownBoundsParameter.Value;
138      var aggregation = aggregationParameter.Value.Value;
139
140      double target = BoundedAggregation(data, knownBounds, aggregation);
141      double prediction = BoundedAggregation(data, bounds, aggregation);
142      double diff = target - prediction;
143
144      results.AddOrUpdateResult("Bounds", bounds);
145
146      results.AddOrUpdateResult("AggValue Diff", new DoubleValue(diff));
147      results.AddOrUpdateResult("AggValue Squared Diff", new DoubleValue(Math.Pow(diff, 2)));
148
149      results.AddOrUpdateResult("Lower Diff", new IntValue(knownBounds.Start - bounds.Start));
150      results.AddOrUpdateResult("Upper Diff", new IntValue(knownBounds.End - bounds.End));
151      results.AddOrUpdateResult("Length Diff", new IntValue(knownBounds.Size - bounds.Size));
152    }
153
154    private static double BoundedAggregation(DoubleArray data, IntRange bounds, Aggregation aggregation) {
155      if (bounds.Size == 0) {
156        return 0;
157      }
158
159      var vector = DoubleVector.Build.DenseOfEnumerable(data);
160      var segment = vector.SubVector(bounds.Start, bounds.Size);
161
162      switch (aggregation) {
163        case Aggregation.Sum:
164          return segment.Sum();
165        case Aggregation.Mean:
166         return segment.Average();
167          case Aggregation.StandardDeviation:
168          return segment.StandardDeviationPop();
169        default:
170          throw new NotImplementedException();
171      }
172    }
173
174    public void Load(SOPData data) {
175      DataVectorParameter.Value = new DoubleArray(data.Values);
176      KnownBoundsParameter.Value = new IntRange(data.Lower, data.Upper);
177      switch (data.Aggregation.ToLower()) {
178        case "sum":
179          AggregationParameter.Value.Value = Aggregation.Sum;
180          break;
181        case "mean":
182        case "avg":
183          AggregationParameter.Value.Value = Aggregation.Mean;
184          break;
185        case "standarddeviation":
186        case "std":
187        case "sd":
188          AggregationParameter.Value.Value = Aggregation.StandardDeviation;
189          break;
190        default:
191          throw new NotSupportedException();
192      }
193                                           
194      Encoding.Length = 2;
195      Encoding.Bounds = new IntMatrix(new[,] { { 0, DataVectorParameter.Value.Length } });
196
197      BestKnownQuality = 0;
198
199      Name = data.Name;
200      Description = data.Description;
201    }
202  }
203}
Note: See TracBrowser for help on using the repository browser.