Free cookie consent management tool by TermsFeed Policy Generator

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

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

#2521: work in progress (removed solution creator parameter from encoding), OrienteeringProblem and test functions are broken

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        DoSetValue(value);
58      }
59    }
60    public virtual void ForceValue(T value) {
61      DoSetValue(value);
62    }
63    private void DoSetValue(T value) {
64      if (value != this.value) {
65        if ((value != null) && !validValues.Contains(value)) throw new ArgumentException("Invalid value.");
66        DeregisterValueEvents();
67        this.value = value;
68        RegisterValueEvents();
69        OnValueChanged();
70      }
71    }
72    IItem IValueParameter.Value {
73      get { return Value; }
74      set {
75        T val = value as T;
76        if ((value != null) && (val == null))
77          throw new InvalidOperationException(
78            string.Format("Type mismatch. Value is not a \"{0}\".",
79                          typeof(T).GetPrettyName())
80          );
81        Value = val;
82      }
83    }
84
85    [Storable(DefaultValue = false)]
86    private bool readOnly;
87    public bool ReadOnly {
88      get { return readOnly; }
89      set {
90        if (value == readOnly) return;
91        readOnly = value;
92        OnReadOnlyChanged();
93      }
94    }
95
96    [Storable(DefaultValue = true)]
97    private bool getsCollected;
98    public bool GetsCollected {
99      get { return getsCollected; }
100      set {
101        if (value != getsCollected) {
102          getsCollected = value;
103          OnGetsCollectedChanged();
104        }
105      }
106    }
107
108    #region Constructors
109    [StorableConstructor]
110    protected OptionalConstrainedValueParameter(StorableConstructorFlag _) : base(_) { }
111    protected OptionalConstrainedValueParameter(OptionalConstrainedValueParameter<T> original, Cloner cloner)
112      : base(original, cloner) {
113      validValues = cloner.Clone(original.validValues);
114      value = cloner.Clone(original.value);
115      readOnly = original.readOnly;
116      getsCollected = original.getsCollected;
117      Initialize();
118    }
119    public OptionalConstrainedValueParameter()
120      : base("Anonymous", typeof(T)) {
121      this.validValues = new ItemSet<T>();
122      this.readOnly = false;
123      this.getsCollected = true;
124      Initialize();
125    }
126    public OptionalConstrainedValueParameter(string name)
127      : base(name, typeof(T)) {
128      this.validValues = new ItemSet<T>();
129      this.readOnly = false;
130      this.getsCollected = true;
131      Initialize();
132    }
133    public OptionalConstrainedValueParameter(string name, ItemSet<T> validValues)
134      : base(name, typeof(T)) {
135      this.validValues = validValues;
136      this.readOnly = false;
137      this.getsCollected = true;
138      Initialize();
139    }
140    public OptionalConstrainedValueParameter(string name, ItemSet<T> validValues, T value)
141      : base(name, typeof(T)) {
142      this.validValues = validValues;
143      this.value = value;
144      this.readOnly = false;
145      this.getsCollected = true;
146      Initialize();
147    }
148    public OptionalConstrainedValueParameter(string name, string description)
149      : base(name, description, typeof(T)) {
150      this.validValues = new ItemSet<T>();
151      this.readOnly = false;
152      this.getsCollected = true;
153      Initialize();
154    }
155    public OptionalConstrainedValueParameter(string name, string description, ItemSet<T> validValues)
156      : base(name, description, typeof(T)) {
157      this.validValues = validValues;
158      this.readOnly = false;
159      this.getsCollected = true;
160      Initialize();
161    }
162    public OptionalConstrainedValueParameter(string name, string description, ItemSet<T> validValues, T value)
163      : base(name, description, typeof(T)) {
164      this.validValues = validValues;
165      this.value = value;
166      this.readOnly = false;
167      this.getsCollected = true;
168      Initialize();
169    }
170    #endregion
171
172    public void Populate(IEnumerable<IItem> items) {
173      ValidValues.Clear();
174      ValidValues.UnionWith(items.OfType<T>());
175    }
176
177    public virtual void Repopulate(IEnumerable<IItem> items) {
178      var itemsOfT = items.OfType<T>().ToList();
179      T oldItem = Value;
180      ValidValues.Clear();
181
182      foreach (T i in itemsOfT.OrderBy(x => x is INamedItem ? ((INamedItem)x).Name : x.ItemName))
183        ValidValues.Add(i);
184
185      if (oldItem != null) {
186        T item = ValidValues.FirstOrDefault(x => x.GetType() == oldItem.GetType());
187        if (item != null) Value = item;
188      }
189    }
190
191    [StorableHook(HookType.AfterDeserialization)]
192    private void AfterDeserialization() {
193      Initialize();
194    }
195
196    private void Initialize() {
197      RegisterValidValuesEvents();
198      RegisterValueEvents();
199    }
200
201    public override IDeepCloneable Clone(Cloner cloner) {
202      return new OptionalConstrainedValueParameter<T>(this, cloner);
203    }
204
205    public override string ToString() {
206      return Name + ": " + (Value != null ? Value.ToString() : "null");
207    }
208
209    protected override IItem GetActualValue() {
210      return Value;
211    }
212    protected override void SetActualValue(IItem value) {
213      ((IValueParameter)this).Value = value;
214    }
215
216    public event EventHandler ValueChanged;
217    protected virtual void OnValueChanged() {
218      EventHandler handler = ValueChanged;
219      if (handler != null) handler(this, EventArgs.Empty);
220      OnItemImageChanged();
221      OnToStringChanged();
222    }
223    public event EventHandler ReadOnlyChanged;
224    protected virtual void OnReadOnlyChanged() {
225      EventHandler handler = ReadOnlyChanged;
226      if (handler != null) handler(this, EventArgs.Empty);
227    }
228    public event EventHandler GetsCollectedChanged;
229    protected virtual void OnGetsCollectedChanged() {
230      EventHandler handler = GetsCollectedChanged;
231      if (handler != null) handler(this, EventArgs.Empty);
232    }
233
234    private void RegisterValidValuesEvents() {
235      if (validValues != null) {
236        validValues.ItemsAdded += new CollectionItemsChangedEventHandler<T>(ValidValues_ItemsAdded);
237        validValues.ItemsRemoved += new CollectionItemsChangedEventHandler<T>(ValidValues_ItemsRemoved);
238        validValues.CollectionReset += new CollectionItemsChangedEventHandler<T>(ValidValues_CollectionReset);
239      }
240    }
241    private void DeregisterValidValuesEvents() {
242      if (validValues != null) {
243        validValues.ItemsAdded -= new CollectionItemsChangedEventHandler<T>(ValidValues_ItemsAdded);
244        validValues.ItemsRemoved -= new CollectionItemsChangedEventHandler<T>(ValidValues_ItemsRemoved);
245        validValues.CollectionReset -= new CollectionItemsChangedEventHandler<T>(ValidValues_CollectionReset);
246      }
247    }
248    protected virtual void ValidValues_ItemsAdded(object sender, CollectionItemsChangedEventArgs<T> e) { }
249    protected virtual void ValidValues_ItemsRemoved(object sender, CollectionItemsChangedEventArgs<T> e) {
250      if ((Value != null) && !validValues.Contains(Value)) Value = null;
251    }
252    protected virtual void ValidValues_CollectionReset(object sender, CollectionItemsChangedEventArgs<T> e) {
253      if ((Value != null) && !validValues.Contains(Value)) Value = null;
254    }
255
256    private void RegisterValueEvents() {
257      if (value != null) {
258        value.ItemImageChanged += new EventHandler(Value_ItemImageChanged);
259        value.ToStringChanged += new EventHandler(Value_ToStringChanged);
260      }
261    }
262    private void DeregisterValueEvents() {
263      if (value != null) {
264        value.ItemImageChanged -= new EventHandler(Value_ItemImageChanged);
265        value.ToStringChanged -= new EventHandler(Value_ToStringChanged);
266      }
267    }
268    private void Value_ItemImageChanged(object sender, EventArgs e) {
269      OnItemImageChanged();
270    }
271    private void Value_ToStringChanged(object sender, EventArgs e) {
272      OnToStringChanged();
273    }
274  }
275}
Note: See TracBrowser for help on using the repository browser.