Free cookie consent management tool by TermsFeed Policy Generator

source: branches/2521_ProblemRefactoring/HeuristicLab.Parameters/3.3/OptionalConstrainedValueParameter.cs @ 17625

Last change on this file since 17625 was 17625, checked in by abeham, 4 years ago

#2521:

  • Changed IParticleCreator to not derive from ISolutionCreator (it calls the solution creator itself, thus leading to an infinite loop)
  • Remove ForceValue method and added method to set value in constrained value parameters from valid values
  • Fix ScopeTreeLookupParameter not caching the actual value
  • Fixed single-objective test functions and removed lots of parameterize code
File size: 9.6 KB
Line 
1#region License Information
2/* HeuristicLab
3 * Copyright (C) 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.Drawing;
25using System.Linq;
26using HEAL.Attic;
27using HeuristicLab.Collections;
28using HeuristicLab.Common;
29using HeuristicLab.Core;
30
31namespace HeuristicLab.Parameters {
32  /// <summary>
33  /// A parameter whose value has to be chosen from a set of valid values or is null.
34  /// </summary>
35  [Item("OptionalConstrainedValueParameter", "A parameter whose value has to be chosen from a set of valid values or is null.")]
36  [StorableType("9B2BFAE8-CD6E-499C-83A0-401B6CEE3A08")]
37  public class OptionalConstrainedValueParameter<T> : Parameter, IConstrainedValueParameter<T> where T : class, IItem {
38    public override Image ItemImage {
39      get {
40        if (value != null) return value.ItemImage;
41        else return base.ItemImage;
42      }
43    }
44
45    [Storable]
46    private ItemSet<T> validValues;
47    public IItemSet<T> ValidValues {
48      get { return validValues; }
49    }
50
51    [Storable]
52    private T value;
53    public virtual T Value {
54      get { return this.value; }
55      set {
56        if (ReadOnly) throw new InvalidOperationException("Cannot set the value of a readonly parameter.");
57        if (value != this.value) {
58          if ((value != null) && !validValues.Contains(value)) throw new ArgumentException("Invalid value.");
59          DeregisterValueEvents();
60          this.value = value;
61          RegisterValueEvents();
62          OnValueChanged();
63        }
64      }
65    }
66
67    IItem IValueParameter.Value {
68      get { return Value; }
69      set {
70        T val = value as T;
71        if ((value != null) && (val == null))
72          throw new InvalidOperationException(
73            string.Format("Type mismatch. Value is not a \"{0}\".",
74                          typeof(T).GetPrettyName())
75          );
76        Value = val;
77      }
78    }
79
80    [Storable(DefaultValue = false)]
81    private bool readOnly;
82    public bool ReadOnly {
83      get { return readOnly; }
84      set {
85        if (value == readOnly) return;
86        readOnly = value;
87        OnReadOnlyChanged();
88      }
89    }
90
91    [Storable(DefaultValue = true)]
92    private bool getsCollected;
93    public bool GetsCollected {
94      get { return getsCollected; }
95      set {
96        if (value != getsCollected) {
97          getsCollected = value;
98          OnGetsCollectedChanged();
99        }
100      }
101    }
102
103    #region Constructors
104    [StorableConstructor]
105    protected OptionalConstrainedValueParameter(StorableConstructorFlag _) : base(_) { }
106    protected OptionalConstrainedValueParameter(OptionalConstrainedValueParameter<T> original, Cloner cloner)
107      : base(original, cloner) {
108      validValues = cloner.Clone(original.validValues);
109      value = cloner.Clone(original.value);
110      readOnly = original.readOnly;
111      getsCollected = original.getsCollected;
112      Initialize();
113    }
114    public OptionalConstrainedValueParameter()
115      : base("Anonymous", typeof(T)) {
116      this.validValues = new ItemSet<T>();
117      this.readOnly = false;
118      this.getsCollected = true;
119      Initialize();
120    }
121    public OptionalConstrainedValueParameter(string name)
122      : base(name, typeof(T)) {
123      this.validValues = new ItemSet<T>();
124      this.readOnly = false;
125      this.getsCollected = true;
126      Initialize();
127    }
128    public OptionalConstrainedValueParameter(string name, ItemSet<T> validValues)
129      : base(name, typeof(T)) {
130      this.validValues = validValues;
131      this.readOnly = false;
132      this.getsCollected = true;
133      Initialize();
134    }
135    public OptionalConstrainedValueParameter(string name, ItemSet<T> validValues, T value)
136      : base(name, typeof(T)) {
137      this.validValues = validValues;
138      this.value = value;
139      this.readOnly = false;
140      this.getsCollected = true;
141      Initialize();
142    }
143    public OptionalConstrainedValueParameter(string name, string description)
144      : base(name, description, typeof(T)) {
145      this.validValues = new ItemSet<T>();
146      this.readOnly = false;
147      this.getsCollected = true;
148      Initialize();
149    }
150    public OptionalConstrainedValueParameter(string name, string description, ItemSet<T> validValues)
151      : base(name, description, typeof(T)) {
152      this.validValues = validValues;
153      this.readOnly = false;
154      this.getsCollected = true;
155      Initialize();
156    }
157    public OptionalConstrainedValueParameter(string name, string description, ItemSet<T> validValues, T value)
158      : base(name, description, typeof(T)) {
159      this.validValues = validValues;
160      this.value = value;
161      this.readOnly = false;
162      this.getsCollected = true;
163      Initialize();
164    }
165    #endregion
166
167    public virtual void Populate(IEnumerable<IItem> items) {
168      ValidValues.Clear();
169      ValidValues.UnionWith(items.OfType<T>());
170    }
171
172    public virtual void Repopulate(IEnumerable<IItem> items) {
173      var itemsOfT = items.OfType<T>().ToList();
174      T oldItem = Value;
175      ValidValues.Clear();
176
177      foreach (T i in itemsOfT.OrderBy(x => x is INamedItem ? ((INamedItem)x).Name : x.ItemName))
178        ValidValues.Add(i);
179
180      if (oldItem != null) {
181        T item = ValidValues.FirstOrDefault(x => x.GetType() == oldItem.GetType());
182        if (item != null) Value = item;
183      }
184    }
185
186    public virtual IItem SetValueToFirstOf(Type itemType) {
187      var item = ValidValues.Where(i => itemType.IsAssignableFrom(i.GetType())).FirstOrDefault();
188      if (item != null) Value = item;
189      return item;
190    }
191
192    [StorableHook(HookType.AfterDeserialization)]
193    private void AfterDeserialization() {
194      Initialize();
195    }
196
197    private void Initialize() {
198      RegisterValidValuesEvents();
199      RegisterValueEvents();
200    }
201
202    public override IDeepCloneable Clone(Cloner cloner) {
203      return new OptionalConstrainedValueParameter<T>(this, cloner);
204    }
205
206    public override string ToString() {
207      return Name + ": " + (Value != null ? Value.ToString() : "null");
208    }
209
210    protected override IItem GetActualValue() {
211      return Value;
212    }
213    protected override void SetActualValue(IItem value) {
214      ((IValueParameter)this).Value = value;
215    }
216
217    public event EventHandler ValueChanged;
218    protected virtual void OnValueChanged() {
219      EventHandler handler = ValueChanged;
220      if (handler != null) handler(this, EventArgs.Empty);
221      OnItemImageChanged();
222      OnToStringChanged();
223    }
224    public event EventHandler ReadOnlyChanged;
225    protected virtual void OnReadOnlyChanged() {
226      EventHandler handler = ReadOnlyChanged;
227      if (handler != null) handler(this, EventArgs.Empty);
228    }
229    public event EventHandler GetsCollectedChanged;
230    protected virtual void OnGetsCollectedChanged() {
231      EventHandler handler = GetsCollectedChanged;
232      if (handler != null) handler(this, EventArgs.Empty);
233    }
234
235    private void RegisterValidValuesEvents() {
236      if (validValues != null) {
237        validValues.ItemsAdded += new CollectionItemsChangedEventHandler<T>(ValidValues_ItemsAdded);
238        validValues.ItemsRemoved += new CollectionItemsChangedEventHandler<T>(ValidValues_ItemsRemoved);
239        validValues.CollectionReset += new CollectionItemsChangedEventHandler<T>(ValidValues_CollectionReset);
240      }
241    }
242    private void DeregisterValidValuesEvents() {
243      if (validValues != null) {
244        validValues.ItemsAdded -= new CollectionItemsChangedEventHandler<T>(ValidValues_ItemsAdded);
245        validValues.ItemsRemoved -= new CollectionItemsChangedEventHandler<T>(ValidValues_ItemsRemoved);
246        validValues.CollectionReset -= new CollectionItemsChangedEventHandler<T>(ValidValues_CollectionReset);
247      }
248    }
249    protected virtual void ValidValues_ItemsAdded(object sender, CollectionItemsChangedEventArgs<T> e) { }
250    protected virtual void ValidValues_ItemsRemoved(object sender, CollectionItemsChangedEventArgs<T> e) {
251      if ((Value != null) && !validValues.Contains(Value)) Value = null;
252    }
253    protected virtual void ValidValues_CollectionReset(object sender, CollectionItemsChangedEventArgs<T> e) {
254      if ((Value != null) && !validValues.Contains(Value)) Value = null;
255    }
256
257    private void RegisterValueEvents() {
258      if (value != null) {
259        value.ItemImageChanged += new EventHandler(Value_ItemImageChanged);
260        value.ToStringChanged += new EventHandler(Value_ToStringChanged);
261      }
262    }
263    private void DeregisterValueEvents() {
264      if (value != null) {
265        value.ItemImageChanged -= new EventHandler(Value_ItemImageChanged);
266        value.ToStringChanged -= new EventHandler(Value_ToStringChanged);
267      }
268    }
269    private void Value_ItemImageChanged(object sender, EventArgs e) {
270      OnItemImageChanged();
271    }
272    private void Value_ToStringChanged(object sender, EventArgs e) {
273      OnToStringChanged();
274    }
275  }
276}
Note: See TracBrowser for help on using the repository browser.