Free cookie consent management tool by TermsFeed Policy Generator

source: branches/DataAnalysisService/HeuristicLab.Encodings.ParameterConfigurationTreeEncoding/3.3/ParameterConfigurations/ParameterConfiguration.cs @ 7938

Last change on this file since 7938 was 7938, checked in by spimming, 12 years ago

#1853:

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