Free cookie consent management tool by TermsFeed Policy Generator

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

Last change on this file since 14379 was 14379, checked in by bburlacu, 7 years ago

#2679: Use an item list for models in the goal seeking problems instead of an item collection. Update encoding instead of creating a new one when inputs are changed.

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<ItemList<IRegressionModel>> ModelsParameter {
54      get { return (IFixedValueParameter<ItemList<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<ItemList<IRegressionModel>>(ModelsParameterName, new ItemList<IRegressionModel>()));
142      EncodingParameter.Hidden = true;
143      EvaluatorParameter.Hidden = true;
144      SolutionCreatorParameter.Hidden = true;
145      RegisterEvents();
146    }
147    #endregion
148
149    public override double Evaluate(Individual individual, IRandom random) {
150      var vector = individual.RealVector();
151      vector.ElementNames = ActiveInputs.Select(x => x.Name);
152      int i = 0;
153      // round vector according to parameter step sizes
154      foreach (var parameter in ActiveInputs) {
155        vector[i] = RoundToNearestStepMultiple(vector[i], parameter.Step);
156        ++i;
157      }
158      var estimatedValues = GetEstimatedGoalValues(vector, round: true);
159      var quality = ActiveGoals.Zip(estimatedValues, (t, v) => new { Target = t, EstimatedValue = v })
160                               .Average(x => x.Target.Weight * Math.Pow(x.EstimatedValue - x.Target.Goal, 2) / x.Target.Variance);
161      return quality;
162    }
163    #region event handlers
164
165    private void RegisterEvents() {
166      ModelsParameter.Value.ItemsAdded += ModelCollection_ItemsChanged;
167      ModelsParameter.Value.ItemsRemoved += ModelCollection_ItemsChanged;
168      GoalsParameter.Value.CheckedItemsChanged += GoalSeekingUtil.Goals_CheckedItemsChanged;
169      InputsParameter.Value.CheckedItemsChanged += GoalSeekingUtil.Inputs_CheckedItemsChanged;
170
171      foreach (var input in Inputs)
172        input.Changed += InputParameterChanged;
173
174      foreach (var goal in Goals)
175        goal.Changed += GoalParameterChanged;
176    }
177
178    private void ModelCollection_ItemsChanged(object sender, CollectionItemsChangedEventArgs<IndexedItem<IRegressionModel>> e) {
179      if (e.Items == null || !e.Items.Any()) return;
180      GoalSeekingUtil.UpdateInputs(InputsParameter.Value, Models, InputParameterChanged);
181      GoalSeekingUtil.UpdateEncoding(Encoding, ActiveInputs);
182      dataset = Inputs.Any() ? new ModifiableDataset(Inputs.Select(x => x.Name), Inputs.Select(x => new List<double> { x.Value })) : new ModifiableDataset();
183      GoalSeekingUtil.UpdateTargets(GoalsParameter.Value, Models, GoalParameterChanged);
184      GoalSeekingUtil.RaiseEvent(this, ModelsChanged);
185    }
186
187    private void InputParameterChanged(object sender, EventArgs args) {
188      var inputParameter = (InputParameter)sender;
189      var inputs = InputsParameter.Value;
190      if (inputs.ItemChecked(inputParameter) != inputParameter.Active)
191        inputs.SetItemCheckedState(inputParameter, inputParameter.Active);
192      GoalSeekingUtil.UpdateEncoding(Encoding, ActiveInputs);
193    }
194
195    private void GoalParameterChanged(object sender, EventArgs args) {
196      var goalParameter = (GoalParameter)sender;
197      var goals = GoalsParameter.Value;
198      if (goals.ItemChecked(goalParameter) != goalParameter.Active)
199        goals.SetItemCheckedState(goalParameter, goalParameter.Active);
200    }
201    #endregion
202
203    #region helper methods
204    // method which throws an exception that can be caught in the event handler if the check fails
205    private void CheckIfDatasetContainsTarget(string target) {
206      if (dataset.DoubleVariables.All(x => x != target))
207        throw new ArgumentException(string.Format("Model target \"{0}\" does not exist in the dataset.", target));
208    }
209
210    private IEnumerable<IRegressionModel> GetModels(string target) {
211      return Models.Where(x => x.TargetVariable == target);
212    }
213
214    private static double RoundToNearestStepMultiple(double value, double step) {
215      return step * (long)Math.Round(value / step);
216    }
217    #endregion
218  }
219}
Note: See TracBrowser for help on using the repository browser.