Free cookie consent management tool by TermsFeed Policy Generator

source: branches/HeuristicLab.GoalSeekingProblem/HeuristicLab.GoalSeekingProblem/3.4/SingleObjectiveGoalSeekingProblem.cs @ 14333

Last change on this file since 14333 was 14333, checked in by bburlacu, 8 years ago

#2679: Refactor problems and extract common functionality in static util class.

File size: 9.2 KB
Line 
1#region License Information
2/* HeuristicLab
3 * Copyright (C) 2002-2016 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.Collections.Generic;
24using System.Linq;
25using HeuristicLab.Collections;
26using HeuristicLab.Common;
27using HeuristicLab.Core;
28using HeuristicLab.Encodings.RealVectorEncoding;
29using HeuristicLab.Optimization;
30using HeuristicLab.Parameters;
31using HeuristicLab.Persistence.Default.CompositeSerializers.Storable;
32using HeuristicLab.Problems.DataAnalysis;
33
34namespace HeuristicLab.GoalSeeking {
35  [Item("Goal seeking problem (single-objective)", "Represents a single objective optimization problem which uses configurable regression solutions to evaluate targets from a given dataset.")]
36  [Creatable("Problems")]
37  [StorableClass]
38  public sealed class SingleObjectiveGoalSeekingProblem : SingleObjectiveBasicProblem<RealVectorEncoding>, IGoalSeekingProblem {
39    #region parameter names
40    private const string ModifiableDatasetParameterName = "Dataset";
41    private const string InputsParameterName = "Inputs";
42    private const string GoalsParameterName = "Goals";
43    private const string ModelsParameterName = "Models";
44    #endregion
45
46    #region parameters
47    public IValueParameter<CheckedItemList<InputParameter>> InputsParameter {
48      get { return (IValueParameter<CheckedItemList<InputParameter>>)Parameters[InputsParameterName]; }
49    }
50    public IValueParameter<CheckedItemList<GoalParameter>> GoalsParameter {
51      get { return (IValueParameter<CheckedItemList<GoalParameter>>)Parameters[GoalsParameterName]; }
52    }
53    public IFixedValueParameter<ItemCollection<IRegressionModel>> ModelsParameter {
54      get { return (IFixedValueParameter<ItemCollection<IRegressionModel>>)Parameters[ModelsParameterName]; }
55    }
56    #endregion
57
58    #region IGoalSeekingProblem implementation
59    public IEnumerable<IRegressionModel> Models {
60      get { return ModelsParameter.Value; }
61    }
62
63    public IEnumerable<GoalParameter> Goals {
64      get { return GoalsParameter.Value; }
65    }
66
67    public IEnumerable<InputParameter> Inputs {
68      get { return InputsParameter.Value; }
69    }
70
71    public void AddModel(IRegressionModel model) {
72      var models = ModelsParameter.Value;
73      models.Add(model);
74      GoalSeekingUtil.RaiseEvent(this, ModelsChanged);
75    }
76
77    public void RemoveModel(IRegressionModel model) {
78      var models = ModelsParameter.Value;
79      models.Remove(model);
80      GoalSeekingUtil.RaiseEvent(this, ModelsChanged);
81    }
82
83    public void Configure(IRegressionProblemData problemData, int row) {
84      GoalSeekingUtil.Configure(Goals, Inputs, problemData, row);
85    }
86
87    public IEnumerable<double> GetEstimatedGoalValues(IEnumerable<double> parameterValues, bool round = false) {
88      var ds = (ModifiableDataset)dataset.Clone();
89      foreach (var parameter in ActiveInputs.Zip(parameterValues, (p, v) => new { Name = p.Name, Value = v })) {
90        ds.SetVariableValue(parameter.Value, parameter.Name, 0);
91      }
92      var rows = new[] { 0 }; // actually just one row
93      var estimatedValues =
94        round ? ActiveGoals.Select(t => RoundToNearestStepMultiple(GetModels(t.Name).Average(m => m.GetEstimatedValues(ds, rows).Single()), t.Step))
95              : ActiveGoals.Select(t => GetModels(t.Name).Average(m => m.GetEstimatedValues(ds, rows).Single()));
96      return estimatedValues;
97    }
98
99    public event EventHandler ModelsChanged;
100    public event EventHandler TargetsChanged;
101    public event EventHandler ParametersChanged;
102    #endregion
103
104    private IEnumerable<GoalParameter> ActiveGoals {
105      get { return Goals.Where(x => x.Active); }
106    }
107    private IEnumerable<InputParameter> ActiveInputs {
108      get { return Inputs.Where(x => x.Active); }
109    }
110
111    [Storable]
112    private ModifiableDataset dataset; // modifiable dataset
113
114    public override bool Maximization {
115      get { return false; }
116    }
117
118    #region constructors
119    [StorableConstructor]
120    private SingleObjectiveGoalSeekingProblem(bool deserializing) : base(deserializing) { }
121
122    private SingleObjectiveGoalSeekingProblem(SingleObjectiveGoalSeekingProblem original, Cloner cloner) : base(original, cloner) {
123      this.dataset = cloner.Clone(original.dataset);
124      RegisterEvents();
125    }
126
127    public override IDeepCloneable Clone(Cloner cloner) {
128      return new SingleObjectiveGoalSeekingProblem(this, cloner);
129    }
130
131    [StorableHook(HookType.AfterDeserialization)]
132    private void AfterDeserialization() {
133      RegisterEvents();
134    }
135
136    public SingleObjectiveGoalSeekingProblem() {
137      dataset = new ModifiableDataset();
138      Parameters.Add(new ValueParameter<IDataset>(ModifiableDatasetParameterName, dataset) { Hidden = true });
139      Parameters.Add(new ValueParameter<CheckedItemList<InputParameter>>(InputsParameterName));
140      Parameters.Add(new ValueParameter<CheckedItemList<GoalParameter>>(GoalsParameterName));
141      Parameters.Add(new FixedValueParameter<ItemCollection<IRegressionModel>>(ModelsParameterName, new ItemCollection<IRegressionModel>()));
142      EncodingParameter.Hidden = true;
143      EvaluatorParameter.Hidden = true;
144      SolutionCreatorParameter.Hidden = true;
145      GoalSeekingUtil.UpdateInputs(InputsParameter.Value, Models, InputParameterChanged);
146      Encoding = GoalSeekingUtil.CreateEncoding(ActiveInputs);
147      GoalSeekingUtil.UpdateTargets(GoalsParameter.Value, Models, GoalParameterChanged);
148      RegisterEvents();
149    }
150    #endregion
151
152    public override double Evaluate(Individual individual, IRandom random) {
153      var vector = individual.RealVector();
154      vector.ElementNames = ActiveInputs.Select(x => x.Name);
155      int i = 0;
156      // round vector according to parameter step sizes
157      foreach (var parameter in ActiveInputs) {
158        vector[i] = RoundToNearestStepMultiple(vector[i], parameter.Step);
159        ++i;
160      }
161      var estimatedValues = GetEstimatedGoalValues(vector, round: true);
162      var quality = ActiveGoals.Zip(estimatedValues, (t, v) => new { Target = t, EstimatedValue = v })
163                               .Average(x => x.Target.Weight * Math.Pow(x.EstimatedValue - x.Target.Goal, 2) / x.Target.Variance);
164      return quality;
165    }
166    #region event handlers
167
168    private void RegisterEvents() {
169      ModelsParameter.Value.ItemsAdded += ModelCollection_ItemsChanged;
170      ModelsParameter.Value.ItemsRemoved += ModelCollection_ItemsChanged;
171      GoalsParameter.Value.CheckedItemsChanged += GoalSeekingUtil.Goals_CheckedItemsChanged;
172      InputsParameter.Value.CheckedItemsChanged += GoalSeekingUtil.Inputs_CheckedItemsChanged;
173    }
174
175    private void ModelCollection_ItemsChanged(object sender, CollectionItemsChangedEventArgs<IRegressionModel> e) {
176      if (e.Items == null || !e.Items.Any()) return;
177      GoalSeekingUtil.UpdateInputs(InputsParameter.Value, Models, InputParameterChanged);
178      Encoding = GoalSeekingUtil.CreateEncoding(ActiveInputs);
179      GoalSeekingUtil.UpdateTargets(GoalsParameter.Value, Models, GoalParameterChanged);
180      GoalSeekingUtil.RaiseEvent(this, ModelsChanged);
181    }
182
183    private void InputParameterChanged(object sender, EventArgs args) {
184      var inputParameter = (InputParameter)sender;
185      var inputs = InputsParameter.Value;
186      if (inputs.ItemChecked(inputParameter) != inputParameter.Active)
187        inputs.SetItemCheckedState(inputParameter, inputParameter.Active);
188      Encoding = GoalSeekingUtil.CreateEncoding(ActiveInputs);
189    }
190
191    private void GoalParameterChanged(object sender, EventArgs args) {
192      var goalParameter = (GoalParameter)sender;
193      var goals = GoalsParameter.Value;
194      if (goals.ItemChecked(goalParameter) != goalParameter.Active)
195        goals.SetItemCheckedState(goalParameter, goalParameter.Active);
196    }
197    #endregion
198
199    #region helper methods
200    // method which throws an exception that can be caught in the event handler if the check fails
201    private void CheckIfDatasetContainsTarget(string target) {
202      if (dataset.DoubleVariables.All(x => x != target))
203        throw new ArgumentException(string.Format("Model target \"{0}\" does not exist in the dataset.", target));
204    }
205
206    private IEnumerable<IRegressionModel> GetModels(string target) {
207      return Models.Where(x => x.TargetVariable == target);
208    }
209
210    private static double RoundToNearestStepMultiple(double value, double step) {
211      return step * (long)Math.Round(value / step);
212    }
213    #endregion
214  }
215}
Note: See TracBrowser for help on using the repository browser.