Free cookie consent management tool by TermsFeed Policy Generator

source: branches/HeuristicLab.MetaOptimization/HeuristicLab.Problems.MetaOptimization/3.3/Encoding/ParameterConfigurations/ParameterConfiguration.cs @ 5927

Last change on this file since 5927 was 5927, checked in by cneumuel, 13 years ago

#1215

  • worked on configurability of SymbolicExpressionGrammar
File size: 22.9 KB
Line 
1using System;
2using System.Collections;
3using System.Collections.Generic;
4using System.Drawing;
5using System.Linq;
6using System.Text;
7using HeuristicLab.Collections;
8using HeuristicLab.Common;
9using HeuristicLab.Core;
10using HeuristicLab.Data;
11using HeuristicLab.Encodings.SymbolicExpressionTreeEncoding;
12using HeuristicLab.Parameters;
13using HeuristicLab.Persistence.Default.CompositeSerializers.Storable;
14using HeuristicLab.PluginInfrastructure;
15
16namespace HeuristicLab.Problems.MetaOptimization {
17  [StorableClass]
18  public class ParameterConfiguration : Item, IParameterConfiguration, IStorableContent {
19    public bool IsOptimizable {
20      get { return true; }
21    }
22
23    [Storable]
24    public string Filename { get; set; }
25
26    [Storable]
27    protected bool optimize;
28    public virtual bool Optimize {
29      get { return optimize; }
30      set {
31        if (optimize != value) {
32          optimize = value;
33          if (optimize) {
34            PopulateValueConfigurations();
35          } else {
36            ClearValueConfigurations();
37          }
38          OnOptimizeChanged();
39          OnToStringChanged();
40        }
41      }
42    }
43
44    [Storable]
45    protected Image itemImage;
46    public override Image ItemImage {
47      get { return itemImage ?? base.ItemImage; }
48    }
49
50    [Storable]
51    protected string parameterName;
52    public string ParameterName {
53      get { return parameterName; }
54      set {
55        if (parameterName != value) {
56          parameterName = value;
57          OnToStringChanged();
58        }
59      }
60    }
61
62    [Storable]
63    protected Type parameterDataType;
64    public Type ParameterDataType {
65      get { return this.parameterDataType; }
66    }
67
68    [Storable]
69    protected Type[] validTypes;
70    public Type[] ValidTypes {
71      get { return validTypes; }
72      protected set {
73        if (this.validTypes != value) {
74          this.validTypes = value;
75        }
76      }
77    }
78
79    [Storable]
80    protected Type valueDataType;
81    public Type ValueDataType {
82      get { return valueDataType; }
83      protected set { this.valueDataType = value; }
84    }
85
86    [Storable]
87    protected ICheckedValueConfigurationList valueConfigurations;
88    public ICheckedValueConfigurationList ValueConfigurations {
89      get { return this.valueConfigurations; }
90      protected set {
91        if (this.valueConfigurations != value) {
92          if (this.valueConfigurations != null) DeregisterValueConfigurationEvents();
93          this.valueConfigurations = value;
94          if (this.valueConfigurations != null) RegisterValueConfigurationEvents();
95        }
96      }
97    }
98
99    [Storable]
100    private int actualValueConfigurationIndex = 0;
101    public int ActualValueConfigurationIndex {
102      get { return actualValueConfigurationIndex; }
103      set { actualValueConfigurationIndex = value; }
104    }
105
106    [Storable]
107    protected ConstrainedValue actualValue;
108    public ConstrainedValue ActualValue {
109      get { return actualValue; }
110      set {
111        if (actualValue != value) {
112          DeregisterActualValueEvents();
113          actualValue = value;
114          RegisterActualValueEvents();
115        }
116      }
117    }
118
119    [Storable]
120    protected bool isNullable;
121    public bool IsNullable {
122      get { return isNullable; }
123      protected set {
124        if (this.isNullable != value) {
125          this.isNullable = value;
126        }
127      }
128    }
129
130    [Storable]
131    protected bool discoverValidValues;
132    public bool DiscoverValidValues {
133      get { return discoverValidValues; }
134      set { discoverValidValues = value; }
135    }
136
137    [Storable]
138    protected IItemSet<IItem> validValues;
139
140    #region Constructors and Cloning
141    public ParameterConfiguration(string parameterName, IValueParameter valueParameter, bool discoverValidValues) {
142      this.ParameterName = parameterName;
143      this.parameterDataType = valueParameter.GetType();
144      this.valueDataType = valueParameter.DataType;
145      this.discoverValidValues = discoverValidValues;
146      this.validValues = discoverValidValues ? GetValidValues(valueParameter) : new ItemSet<IItem> { valueParameter.Value };
147      this.validTypes = GetValidTypes(valueParameter).ToArray();
148      this.IsNullable = valueParameter.ItemName.StartsWith("Optional");
149      this.itemImage = valueParameter.ItemImage;
150      if (IsNullable) {
151        validTypes = new List<Type>(validTypes) { typeof(NullValue) }.ToArray();
152      }
153      this.ValueConfigurations = new CheckedValueConfigurationList(this.validValues ?? CreateValidValues());
154      this.ActualValue = new ConstrainedValue(
155        valueParameter.Value != null ? valueParameter.Value : null, // don't clone here; otherwise settings of a non-optimized ValueParameter will not be synchronized with the ConstrainedValue
156        valueParameter.DataType,
157        this.validValues != null ? new ItemSet<IItem>(this.validValues) : CreateValidValues(),
158        this.IsNullable);
159      if (Optimize) {
160        PopulateValueConfigurations();
161      }
162    }
163    public ParameterConfiguration(string parameterName, Type type, IItem actualValue, IEnumerable<IValueConfiguration> valueConfigurations) {
164      this.ParameterName = parameterName;
165      this.parameterDataType = type;
166      this.valueDataType = type;
167      this.discoverValidValues = false;
168      this.validValues = null; // maybe use values from valueConfigurations
169      this.validTypes = new Type[] { type };
170      this.IsNullable = false;
171      this.itemImage = valueConfigurations.Count() > 0 ? valueConfigurations.FirstOrDefault().ItemImage : null;
172      this.ValueConfigurations = new CheckedValueConfigurationList(valueConfigurations);
173      this.ActualValue = new ConstrainedValue(actualValue, type, CreateValidValues(), this.IsNullable);
174    }
175    public ParameterConfiguration(string parameterName, Type type, IItem actualValue) {
176      this.ParameterName = parameterName;
177      this.parameterDataType = type;
178      this.valueDataType = type;
179      this.discoverValidValues = false;
180      this.validValues = null;
181      this.validTypes = new Type[] { type };
182      this.IsNullable = false;
183      this.itemImage = actualValue.ItemImage;
184      this.ValueConfigurations = new CheckedValueConfigurationList();
185      this.ActualValue = new ConstrainedValue(actualValue, type, CreateValidValues(), this.IsNullable);
186      if (Optimize) {
187        PopulateValueConfigurations();
188      }
189    }
190    public ParameterConfiguration() { }
191    [StorableConstructor]
192    protected ParameterConfiguration(bool deserializing) { }
193    protected ParameterConfiguration(ParameterConfiguration original, Cloner cloner)
194      : base(original, cloner) {
195      this.parameterName = original.ParameterName;
196      this.parameterDataType = original.parameterDataType;
197      this.valueDataType = original.ValueDataType;
198      this.validValues = cloner.Clone(original.validValues);
199      this.validTypes = original.validTypes.ToArray();
200      this.valueConfigurations = cloner.Clone(original.ValueConfigurations);
201      this.ActualValue = cloner.Clone(original.ActualValue);
202      this.optimize = original.optimize;
203      this.actualValueConfigurationIndex = original.actualValueConfigurationIndex;
204      this.isNullable = original.isNullable;
205      this.itemImage = original.itemImage;
206      this.discoverValidValues = original.discoverValidValues;
207      if (this.valueConfigurations != null) RegisterValueConfigurationEvents();
208    }
209
210
211    public override IDeepCloneable Clone(Cloner cloner) {
212      return new ParameterConfiguration(this, cloner);
213    }
214    [StorableHook(HookType.AfterDeserialization)]
215    private void AfterDeserialization() {
216      if (this.valueConfigurations != null) RegisterValueConfigurationEvents();
217    }
218    #endregion
219
220    private void RegisterValueConfigurationEvents() {
221      this.ValueConfigurations.CheckedItemsChanged += new CollectionItemsChangedEventHandler<IndexedItem<IValueConfiguration>>(ValueConfigurations_CheckedItemsChanged);
222      this.ValueConfigurations.ItemsAdded += new CollectionItemsChangedEventHandler<IndexedItem<IValueConfiguration>>(ValueConfigurations_ItemsAdded);
223      this.ValueConfigurations.ItemsRemoved += new CollectionItemsChangedEventHandler<IndexedItem<IValueConfiguration>>(ValueConfigurations_ItemsRemoved);
224    }
225
226    private void DeregisterValueConfigurationEvents() {
227      this.ValueConfigurations.CheckedItemsChanged -= new CollectionItemsChangedEventHandler<IndexedItem<IValueConfiguration>>(ValueConfigurations_CheckedItemsChanged);
228      this.ValueConfigurations.ItemsAdded -= new CollectionItemsChangedEventHandler<IndexedItem<IValueConfiguration>>(ValueConfigurations_ItemsAdded);
229      this.ValueConfigurations.ItemsRemoved -= new CollectionItemsChangedEventHandler<IndexedItem<IValueConfiguration>>(ValueConfigurations_ItemsRemoved);
230    }
231
232    private void RegisterActualValueEvents() {
233      if (this.ActualValue != null) this.ActualValue.ToStringChanged += new EventHandler(ActualValue_ToStringChanged);
234    }
235    private void DeregisterActualValueEvents() {
236      if (this.ActualValue != null) this.ActualValue.ToStringChanged -= new EventHandler(ActualValue_ToStringChanged);
237    }
238
239    protected virtual void PopulateValueConfigurations() {
240      foreach (Type t in this.validTypes) {
241        if (t == typeof(NullValue)) {
242          this.ValueConfigurations.Add(new NullValueConfiguration());
243        } else {
244          IItem val;
245          if (ActualValue.Value != null && ActualValue.ValueDataType == t) {
246            val = (IItem)ActualValue.Value.Clone(); // use existing value for that type (if available)
247          } else {
248            val = CreateItem(t);
249          }
250          if (val != null) { // val can be null when ValidValues does not contain the type (this can happen when discoverValidValues=false)
251            IValueConfiguration valueConfiguration;
252            if (val is IParameterizedItem) {
253              valueConfiguration = new ParameterizedValueConfiguration(val, val.GetType(), true);
254            } else {
255              if (val is ISymbolicExpressionGrammar) {
256                valueConfiguration = new SymbolicExpressionGrammarValueConfiguration((ISymbolicExpressionGrammar)val);
257              } else {
258                valueConfiguration = new RangeValueConfiguration(val, val.GetType());
259              }
260            }
261            this.ValueConfigurations.Add(valueConfiguration, true);
262          }
263        }
264      }
265    }
266
267    protected virtual void ClearValueConfigurations() {
268      this.ValueConfigurations.Clear();
269    }
270
271    private static IEnumerable<Type> GetValidTypes(IValueParameter parameter) {
272      // in case of IOperator return empty list, otherwise hundreds of types would be returned. this mostly occurs for Successor which will never be optimized
273      if (parameter.DataType == typeof(IOperator))
274        return new List<Type>();
275
276      // return only one type for ValueTypeValues<> (Int, Double, Percent, Bool). Otherwise 2 types would be returned for DoubleValue (PercentValue which is derived)
277      if (IsSubclassOfRawGeneric(typeof(ValueTypeValue<>), parameter.DataType))
278        return new List<Type> { parameter.DataType };
279
280      if (IsSubclassOfRawGeneric(typeof(OptionalConstrainedValueParameter<>), parameter.GetType())) {
281        // use existing validvalues if known
282        var parameterValidValues = (IEnumerable)parameter.GetType().GetProperty("ValidValues").GetValue(parameter, new object[] { });
283        return parameterValidValues.Cast<object>().Select(x => x.GetType());
284      } else {
285        // otherwise use all assignable types
286        return ApplicationManager.Manager.GetTypes(parameter.DataType, true);
287      }
288    }
289
290    private IItemSet<IItem> GetValidValues(IValueParameter parameter) {
291      if (IsSubclassOfRawGeneric(typeof(OptionalConstrainedValueParameter<>), parameter.GetType())) {
292        var x = (IEnumerable)parameter.GetType().GetProperty("ValidValues").GetValue(parameter, new object[] { });
293        return new ItemSet<IItem>(x.Cast<IItem>().Select(y => (IItem)y.Clone())); // cloning actually saves memory, because references to event-subscribers are removed
294      } else {
295        return null;
296      }
297    }
298
299    public IItem CreateItem(Type type) {
300      // no valid values; just instantiate
301      try {
302        if (validValues == null)
303          return (IItem)Activator.CreateInstance(type);
304      }
305      catch (MissingMemberException) {
306        return null; // can happen, when ApplicationManager.Manager.GetTypes(type, OnlyInstantiable=true) returns objects which have no default constructor
307      }
308
309      if (type == typeof(NullValue))
310        return new NullValue();
311
312      // copy value from ValidValues; this ensures that previously set ActualNames for a type are kept
313      IItem value = this.validValues.Where(v => v.GetType() == type).SingleOrDefault();
314      if (value != null)
315        return value;
316
317      return null;
318    }
319
320    private IItemSet<IItem> CreateValidValues() {
321      var validValues = new ItemSet<IItem>();
322      foreach (Type t in this.validTypes) {
323        try {
324          var val = CreateItem(t);
325          if (val != null) validValues.Add(val);
326        }
327        catch (MissingMethodException) { /* Constructor is missing, don't use those types */ }
328      }
329      return validValues;
330    }
331
332    private static bool IsSubclassOfRawGeneric(Type generic, Type toCheck) {
333      while (toCheck != typeof(object)) {
334        var cur = toCheck.IsGenericType ? toCheck.GetGenericTypeDefinition() : toCheck;
335        if (generic == cur) {
336          return true;
337        }
338        toCheck = toCheck.BaseType; // baseType is null when toCheck is an Interface
339        if (toCheck == null)
340          return false;
341      }
342      return false;
343    }
344
345    void ValueConfigurations_CheckedItemsChanged(object sender, Collections.CollectionItemsChangedEventArgs<IndexedItem<IValueConfiguration>> e) {
346      OnToStringChanged();
347    }
348    void ValueConfigurations_ItemsRemoved(object sender, Collections.CollectionItemsChangedEventArgs<IndexedItem<IValueConfiguration>> e) {
349      OnToStringChanged();
350    }
351    void ValueConfigurations_ItemsAdded(object sender, Collections.CollectionItemsChangedEventArgs<IndexedItem<IValueConfiguration>> e) {
352      OnToStringChanged();
353    }
354
355    #region INamedItem Properties
356    public virtual string Name {
357      get { return ParameterName; }
358      set { throw new NotSupportedException(); }
359    }
360    public virtual string Description {
361      get { return base.ItemDescription; }
362      set { throw new NotSupportedException(); }
363    }
364    public virtual bool CanChangeDescription {
365      get { return false; }
366    }
367    public virtual bool CanChangeName {
368      get { return false; }
369    }
370    public override string ItemDescription {
371      get { return base.ItemDescription; }
372    }
373    public override string ItemName {
374      get { return base.ItemName; }
375    }
376    #endregion
377
378    #region Events
379    void ActualValue_ToStringChanged(object sender, EventArgs e) {
380      OnToStringChanged();
381    }
382    #endregion
383
384    #region Event Handler
385    public virtual event EventHandler NameChanged;
386    protected virtual void OnNameChanged(object sender, EventArgs e) {
387      var handler = NameChanged;
388      if (handler != null) handler(sender, e);
389    }
390
391    public virtual event EventHandler<CancelEventArgs<string>> NameChanging;
392    protected virtual void OnNameChanging(object sender, CancelEventArgs<string> e) {
393      var handler = NameChanging;
394      if (handler != null) handler(sender, e);
395    }
396
397    public virtual event EventHandler DescriptionChanged;
398    protected virtual void OnDescriptionChanged(object sender, EventArgs e) {
399      var handler = DescriptionChanged;
400      if (handler != null) handler(sender, e);
401    }
402
403    public virtual event EventHandler IsOptimizableChanged;
404    private void OnIsOptimizableChanged() {
405      var handler = IsOptimizableChanged;
406      if (handler != null) handler(this, EventArgs.Empty);
407    }
408
409    public virtual event EventHandler OptimizeChanged;
410    protected virtual void OnOptimizeChanged() {
411      var handler = OptimizeChanged;
412      if (handler != null) handler(this, EventArgs.Empty);
413    }
414    #endregion
415
416    public override string ToString() {
417      if (Optimize) {
418        return string.Format("{0}: (Optimize: {1})", ParameterName, ValueConfigurations.CheckedItems.Count());
419      } else {
420        return string.Format("{0}: {1}", ParameterName, ActualValue.Value);
421      }
422    }
423
424    public string ParameterInfoString {
425      get {
426        StringBuilder sb = new StringBuilder();
427        if (this.Optimize) {
428          var vc = this.ValueConfigurations[actualValueConfigurationIndex];
429          if (vc.ActualValue == null || vc.ActualValue.Value == null) {
430            sb.Append(string.Format("{0}: null", parameterName));
431          } else if (IsSubclassOfRawGeneric(typeof(ValueTypeValue<>), vc.ActualValue.Value.GetType())) {
432            // for int, double, bool use the value directly
433            sb.Append(string.Format("{0}: {1}", parameterName, this.ActualValue.Value.ToString()));
434          } else {
435            // for other types use NumberedName (this also uses the Number-Property for otherwise ambiguous ValueConfigurations)
436            sb.Append(string.Format("{0}: {1}", parameterName, vc.NumberedName));
437          }
438
439          if (this.ActualValue.Value is IParameterizedItem) {
440            string subParams = this.ValueConfigurations[actualValueConfigurationIndex].ParameterInfoString;
441            if (!string.IsNullOrEmpty(subParams)) {
442              sb.Append(" (");
443              sb.Append(subParams);
444              sb.Append(")");
445            }
446          }
447        }
448        return sb.ToString();
449      }
450    }
451
452    public static IParameterConfiguration Create(IParameterizedNamedItem parent, IParameter parameter, bool discoverValidValues) {
453      if (parameter is IValueParameter) {
454        IValueParameter valueParameter = parameter as IValueParameter;
455        return new ParameterConfiguration(parameter.Name, valueParameter, discoverValidValues);
456      }
457      return null;
458    }
459
460    public void Parameterize(IValueParameter parameter) {
461      if (parameter is IFixedValueParameter)
462        return;
463
464      if (Optimize) {
465        if (this.ActualValue.Value is IParameterizedItem) {
466          ((ParameterizedValueConfiguration)this.ValueConfigurations[actualValueConfigurationIndex]).Parameterize((IParameterizedItem)this.ActualValue.Value);
467        }
468        if (this.ActualValue.Value is ISymbolicExpressionGrammar) {
469          ((SymbolicExpressionGrammarValueConfiguration)this.ValueConfigurations[actualValueConfigurationIndex]).Parameterize((ISymbolicExpressionGrammar)this.ActualValue.Value);
470        }
471      }
472      var clonedValue = this.ActualValue.Value != null ? (IItem)this.ActualValue.Value.Clone() : null;
473      if (clonedValue != null) AdaptValidValues(parameter, clonedValue);
474      parameter.Value = clonedValue;
475    }
476
477    /// <summary>
478    /// Adds value to the ValidValues of the parameter if they don't contain the value
479    /// </summary>
480    private void AdaptValidValues(IValueParameter parameter, IItem value) {
481      // this requires some tricky reflection, because the type is unknown at runtime so parameter.ValidValues cannot be casted to Collection<?>
482      if (IsSubclassOfRawGeneric(typeof(OptionalConstrainedValueParameter<>), parameter.GetType())) {
483        var validValues = parameter.GetType().GetProperty("ValidValues").GetValue(parameter, new object[] { });
484        Type validValuesType = validValues.GetType();
485
486        var containsMethod = validValuesType.GetMethod("Contains");
487        if (!(bool)containsMethod.Invoke(validValues, new object[] { value })) {
488          var addMethod = validValuesType.GetMethod("Add");
489          addMethod.Invoke(validValues, new object[] { value });
490        }
491      }
492    }
493
494    public void Randomize(IRandom random) {
495      if (Optimize) {
496        foreach (var vc in this.ValueConfigurations) {
497          if (this.ValueConfigurations.ItemChecked(vc)) {
498            if (vc.Optimize) vc.Randomize(random);
499          }
500        }
501        do {
502          actualValueConfigurationIndex = random.Next(ValueConfigurations.Count());
503        } while (!this.ValueConfigurations.ItemChecked(this.ValueConfigurations[actualValueConfigurationIndex]));
504        this.ActualValue = this.ValueConfigurations[actualValueConfigurationIndex].ActualValue;
505      }
506    }
507
508    public void Mutate(IRandom random, MutateDelegate mutate, IIntValueManipulator intValueManipulator, IDoubleValueManipulator doubleValueManipulator) {
509      if (Optimize) {
510        foreach (var vc in this.ValueConfigurations) {
511          if (this.ValueConfigurations.ItemChecked(vc)) {
512            if (vc.Optimize) vc.Mutate(random, mutate, intValueManipulator, doubleValueManipulator);
513          }
514        }
515        mutate(random, this, intValueManipulator, doubleValueManipulator);
516      }
517    }
518
519    public void Cross(IRandom random, IOptimizable other, CrossDelegate cross, IIntValueCrossover intValueCrossover, IDoubleValueCrossover doubleValueCrossover) {
520      if (Optimize) {
521        IParameterConfiguration otherPc = (IParameterConfiguration)other;
522        for (int i = 0; i < this.ValueConfigurations.Count; i++) {
523          if (this.ValueConfigurations.ItemChecked(this.ValueConfigurations[i])) {
524            if (this.ValueConfigurations[i].Optimize) this.ValueConfigurations[i].Cross(random, otherPc.ValueConfigurations[i], cross, intValueCrossover, doubleValueCrossover);
525          }
526        }
527        cross(random, this, other, intValueCrossover, doubleValueCrossover);
528      }
529    }
530
531    public void UpdateActualValueIndexToItem(IValueConfiguration vc) {
532      for (int i = 0; i < this.ValueConfigurations.Count(); i++) {
533        if (this.ValueConfigurations.ElementAt(i) == vc) {
534          this.actualValueConfigurationIndex = i;
535          return;
536        }
537      }
538    }
539
540    public List<IOptimizable> GetAllOptimizables() {
541      var list = new List<IOptimizable>();
542      foreach (var vc in ValueConfigurations) {
543        if (vc.Optimize) {
544          list.Add(vc);
545          list.AddRange(vc.GetAllOptimizables());
546        }
547      }
548      return list;
549    }
550
551    public void CollectOptimizedParameterNames(List<string> parameterNames, string prefix) {
552      foreach (var vc in ValueConfigurations) {
553        if (vc.Optimize) {
554          vc.CollectOptimizedParameterNames(parameterNames, prefix);
555        }
556      }
557    }
558
559    public double CalculateSimilarity(IOptimizable optimizable) {
560      var other = (IParameterConfiguration)optimizable;
561      if (this.ActualValueConfigurationIndex == other.ActualValueConfigurationIndex) {
562        return this.ValueConfigurations[this.ActualValueConfigurationIndex].CalculateSimilarity(other.ValueConfigurations[other.ActualValueConfigurationIndex]);
563      } else {
564        return 0.0;
565      }
566    }
567  }
568}
Note: See TracBrowser for help on using the repository browser.