Free cookie consent management tool by TermsFeed Policy Generator

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

Last change on this file since 6017 was 6017, checked in by cneumuel, 12 years ago

#1215

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