Free cookie consent management tool by TermsFeed Policy Generator

source: branches/1614_GeneralizedQAP/HeuristicLab.Optimization/3.3/RunCollectionModification/RunCollectionDiscretizer.cs @ 16728

Last change on this file since 16728 was 16728, checked in by abeham, 6 years ago

#1614: updated to new persistence and .NET 4.6.1

File size: 8.0 KB
Line 
1#region License Information
2/* HeuristicLab
3 * Copyright (C) 2002-2019 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.Common;
26using HeuristicLab.Core;
27using HeuristicLab.Data;
28using HeuristicLab.Parameters;
29using HEAL.Attic;
30
31namespace HeuristicLab.Optimization {
32  [Item("RunCollection Discretizer",
33    "Creates several levels from the distribution of a certain result accross a run collection and " +
34    "assigns a discretized value. Non-existing numbers as well as NaN and infinities are excluded from the caluclation.")]
35  [StorableType("6EFD185F-FE23-4E23-90F0-63CB9D38E57D")]
36  public class RunCollectionDiscretizer : ParameterizedNamedItem, IRunCollectionModifier {
37
38    public override bool CanChangeName { get { return false; } }
39    public override bool CanChangeDescription { get { return false; } }
40
41    #region Parameters
42    public ValueParameter<StringValue> SourceParameter {
43      get { return (ValueParameter<StringValue>)Parameters["Source"]; }
44    }
45    public ValueParameter<StringValue> TargetParameter {
46      get { return (ValueParameter<StringValue>)Parameters["Target"]; }
47    }
48    public ValueParameter<DoubleValue> SpreadParameter {
49      get { return (ValueParameter<DoubleValue>)Parameters["Spread"]; }
50    }
51    public ValueParameter<StringValue> GroupByParameter {
52      get { return (ValueParameter<StringValue>)Parameters["GroupBy"]; }
53    }   
54    public ValueParameter<ItemList<StringValue>> LevelsParameter {
55      get { return (ValueParameter<ItemList<StringValue>>)Parameters["Levels"]; }
56    }   
57    #endregion
58
59    private string Source { get { return SourceParameter.Value.Value; } }
60    private string Target {
61      get { return TargetParameter.Value.Value; }
62      set { TargetParameter.Value.Value = value; }
63    }   
64    private double Spread { get { return SpreadParameter.Value.Value; } }
65    private string GroupBy { get { return GroupByParameter.Value.Value; } }
66    private List<string> Levels { get { return LevelsParameter.Value.Select(v => v.Value).ToList(); } }
67
68      #region Construction & Cloning
69    [StorableConstructor]
70    protected RunCollectionDiscretizer(StorableConstructorFlag _) : base(_) { }
71    protected RunCollectionDiscretizer(RunCollectionDiscretizer original, Cloner cloner)
72      : base(original, cloner) {
73      RegisterEvents();
74    }
75    public RunCollectionDiscretizer() {
76      Parameters.Add(new ValueParameter<StringValue>("Source", "Source value name to be fuzzified.", new StringValue("Value")));
77      Parameters.Add(new ValueParameter<StringValue>("Target", "Target value name. The new, fuzzified variable to be created.", new StringValue("Calc.Value")));
78      Parameters.Add(new ValueParameter<DoubleValue>("Spread", "The number of standard deviations considered one additional level. Set to zero to use empirical distribution instead.", new DoubleValue(1)));
79      Parameters.Add(new ValueParameter<StringValue>("GroupBy", "Create separate analyzes for different values of this variable.", new StringValue("")));
80      Parameters.Add(new ValueParameter<ItemList<StringValue>>("Levels", "The list of levels to be assigned.",
81        new ItemList<StringValue> {
82          new StringValue("Very Low"),
83          new StringValue("Low"),
84          new StringValue("Average"),
85          new StringValue("High"),
86          new StringValue("Very High"),
87        }));     
88      RegisterEvents();
89      UpdateName();
90    }
91    public override IDeepCloneable Clone(Cloner cloner) {
92      return new RunCollectionDiscretizer(this, cloner);
93    }
94    [StorableHook(HookType.AfterDeserialization)]
95    private void AfterDeserialization() {
96      RegisterEvents();
97    }
98    #endregion
99
100    private void RegisterEvents() {
101      SourceParameter.ToStringChanged += SourceParameter_NameChanged;
102      TargetParameter.ToStringChanged += Parameter_NameChanged;
103      GroupByParameter.ToStringChanged += Parameter_NameChanged;
104    }
105
106    private void SourceParameter_NameChanged(object sender, EventArgs e) {
107      Target = string.Format("{0}/Level", Source);
108    }
109
110    private void Parameter_NameChanged(object sender, EventArgs e) {
111      UpdateName();
112    }
113
114    private void UpdateName() {
115      name = string.Format("{0} := Discrete({1}{2})",
116        Target,
117        Source,
118        string.IsNullOrWhiteSpace(GroupBy) ? "" : string.Format("/{0}", GroupBy));       
119      OnNameChanged();
120    }
121
122    #region IRunCollectionModifier Members
123
124    public void Modify(List<IRun> runs) {
125      foreach (var group in runs
126        .Select(r => new {Run=r, Value=GetSourceValue(r)})
127        .Where(r => r.Value.HasValue && !double.IsNaN(r.Value.Value) && !double.IsInfinity(r.Value.Value))
128        .Select(r => new {r.Run, r.Value.Value, Bin=GetGroupByValue(r.Run)})
129        .GroupBy(r => r.Bin).ToList()) {
130        var values = group.Select(r => r.Value).ToList();
131        if (values.Count > 0) {
132          if (Spread > 0) {
133            var avg = values.Average();
134            var stdDev = values.StandardDeviation();
135            foreach (var r in group) {
136              r.Run.Results[Target] = new StringValue(Discretize(r.Value, avg, stdDev));
137            }
138          } else {
139            values.Sort();
140            var a = values.ToArray();
141            foreach (var r in group) {
142              r.Run.Results[Target] = new StringValue(Discretize(r.Value, a));
143            }
144          }
145        }
146      }     
147    }
148
149    private double? GetSourceValue(IRun run) {
150      return CastSourceValue(run.Results) ?? CastSourceValue(run.Parameters);
151    }
152
153    private string GetGroupByValue(IRun run) {
154      if (string.IsNullOrWhiteSpace(GroupBy))
155        return String.Empty;
156      IItem value;
157      run.Results.TryGetValue(GroupBy, out value);
158      if (value == null)
159        run.Parameters.TryGetValue(GroupBy, out value);
160      if (value != null)
161        return value.ToString();
162      else
163        return String.Empty;
164    }
165
166    private double? CastSourceValue(IDictionary<string, IItem> variables) {
167      IItem value;
168      variables.TryGetValue(Source, out value);
169      var intValue = value as IntValue;
170      if (intValue != null)
171        return intValue.Value;
172      var doubleValue = value as DoubleValue;
173      if (doubleValue != null)
174        return doubleValue.Value;
175      return null;
176    }
177
178    private string Discretize(double value, double avg, double stdDev) {
179      double dev = (value - avg)/(stdDev*Spread);
180      int index;
181      if (Levels.Count % 2 == 1) {
182        index = (int) Math.Floor(Math.Abs(dev));
183        index = (Levels.Count - 1)/2 + Math.Sign(dev) * index;
184      } else {
185        index = (int) Math.Ceiling(Math.Abs(dev));
186        if (dev > 0)
187          index = Levels.Count/2 + index;
188        else
189          index = Levels.Count/2 + 1 - index;
190      }
191      return Levels[Math.Min(Levels.Count - 1, Math.Max(0, index))];
192    }
193
194    private string Discretize(double value, double[] values) {
195      var index = Array.BinarySearch(values, value);
196      var pos = 1.0*(index < 0 ? ~index : index)/(values.Length-1);
197      return Levels[Math.Min(Levels.Count - 1, Math.Max(0, (int) Math.Round(pos*(Levels.Count-1))))];
198    }
199
200    #endregion
201  }
202}
Note: See TracBrowser for help on using the repository browser.