Free cookie consent management tool by TermsFeed Policy Generator

source: branches/PersistenceReintegration/HeuristicLab.Clients.OKB/3.3/RunCreation/OKBAlgorithm.cs @ 15632

Last change on this file since 15632 was 15018, checked in by gkronber, 8 years ago

#2520 introduced StorableConstructorFlag type for StorableConstructors

File size: 16.7 KB
Line 
1#region License Information
2/* HeuristicLab
3 * Copyright (C) 2002-2016 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 HeuristicLab.Clients.Access;
23using HeuristicLab.Collections;
24using HeuristicLab.Common;
25using HeuristicLab.Core;
26using HeuristicLab.Optimization;
27using HeuristicLab.Persistence;
28using HeuristicLab.Persistence.Default.Xml;
29using System;
30using System.Collections.Generic;
31using System.Drawing;
32using System.IO;
33using System.Linq;
34
35namespace HeuristicLab.Clients.OKB.RunCreation {
36  [Item("OKB Algorithm", "An algorithm which is stored in the OKB.")]
37  [Creatable(CreatableAttribute.Categories.TestingAndAnalysisOKB, Priority = 100)]
38  [StorableType("c6ea08ae-4f0e-427c-a695-3779558a3cd5")]
39  public sealed class OKBAlgorithm : Item, IAlgorithm, IStorableContent {
40    public string Filename { get; set; }
41
42    private long algorithmId;
43    public long AlgorithmId {
44      get { return algorithmId; }
45    }
46    private IAlgorithm algorithm;
47    private IAlgorithm Algorithm {
48      get { return algorithm; }
49      set {
50        if (value == null) throw new ArgumentNullException("Algorithm", "Algorithm cannot be null.");
51        if (value != algorithm) {
52          CancelEventArgs<string> e = new CancelEventArgs<string>(value.Name);
53          OnNameChanging(e);
54          if (!e.Cancel) {
55            IProblem problem = algorithm.Problem;
56            DeregisterAlgorithmEvents();
57            algorithm = value;
58            RegisterAlgorithmEvents();
59
60            OnToStringChanged();
61            OnItemImageChanged();
62            OnNameChanged();
63            OnDescriptionChanged();
64            OnAlgorithmChanged();
65            OnStoreAlgorithmInEachRunChanged();
66
67            try {
68              algorithm.Problem = problem;
69            } catch (ArgumentException) {
70              algorithm.Problem = null;
71            }
72            algorithm.Prepare(true);
73          }
74        }
75      }
76    }
77
78    public IEnumerable<IOptimizer> NestedOptimizers {
79      get {
80        // inner algorithm cannot be accessed directly
81        return Enumerable.Empty<IOptimizer>();
82      }
83    }
84
85    public override Image ItemImage {
86      get { return Algorithm.ItemImage; }
87    }
88
89    public static new Image StaticItemImage {
90      get { return HeuristicLab.Common.Resources.VSImageLibrary.Event; }
91    }
92
93    public string Name {
94      get { return Algorithm.Name; }
95      set { throw new NotSupportedException("Name cannot be changed."); }
96    }
97    public string Description {
98      get { return Algorithm.Description; }
99      set { throw new NotSupportedException("Description cannot be changed."); }
100    }
101    public bool CanChangeName {
102      get { return false; }
103    }
104    public bool CanChangeDescription {
105      get { return false; }
106    }
107
108    public IKeyedItemCollection<string, IParameter> Parameters {
109      get { return Algorithm.Parameters; }
110    }
111
112    public ExecutionState ExecutionState {
113      get { return Algorithm.ExecutionState; }
114    }
115    public TimeSpan ExecutionTime {
116      get { return Algorithm.ExecutionTime; }
117    }
118
119    public Type ProblemType {
120      get { return Algorithm.ProblemType; }
121    }
122    public IProblem Problem {
123      get { return Algorithm.Problem; }
124      set { Algorithm.Problem = value; }
125    }
126
127    public ResultCollection Results {
128      get { return Algorithm.Results; }
129    }
130
131    private RunCollection runs;
132    public RunCollection Runs {
133      get { return runs; }
134    }
135    private bool storeRunsAutomatically;
136    public bool StoreRunsAutomatically {
137      get { return storeRunsAutomatically; }
138      set {
139        if (value != storeRunsAutomatically) {
140          storeRunsAutomatically = value;
141          OnStoreRunsAutomaticallyChanged();
142        }
143      }
144    }
145    public bool StoreAlgorithmInEachRun {
146      get { return Algorithm.StoreAlgorithmInEachRun; }
147      set { Algorithm.StoreAlgorithmInEachRun = value; }
148    }
149
150    #region Persistence Properties
151    [Storable]
152    private Guid UserId;
153
154    [Storable(Name = "AlgorithmId")]
155    private long StorableAlgorithmId {
156      get { return algorithmId; }
157      set { algorithmId = value; }
158    }
159    [Storable(Name = "Algorithm")]
160    private IAlgorithm StorableAlgorithm {
161      get { return algorithm; }
162      set {
163        algorithm = value;
164        RegisterAlgorithmEvents();
165      }
166    }
167    [Storable(Name = "Runs")]
168    private RunCollection StorableRuns {
169      get { return runs; }
170      set {
171        runs = value;
172        RegisterRunsEvents();
173      }
174    }
175    [Storable(Name = "StoreRunsAutomatically")]
176    private bool StorableStoreRunsAutomatically {
177      get { return storeRunsAutomatically; }
178      set { storeRunsAutomatically = value; }
179    }
180    #endregion
181
182    [StorableConstructor]
183    private OKBAlgorithm(StorableConstructorFlag deserializing) : base(deserializing) { }
184    private OKBAlgorithm(OKBAlgorithm original, Cloner cloner)
185      : base(original, cloner) {
186      algorithmId = original.algorithmId;
187      algorithm = cloner.Clone(original.algorithm);
188      RegisterAlgorithmEvents();
189      runs = cloner.Clone(original.runs);
190      storeRunsAutomatically = original.storeRunsAutomatically;
191      UserId = original.UserId;
192      RegisterRunsEvents();
193    }
194    public OKBAlgorithm()
195      : base() {
196      algorithmId = -1;
197      algorithm = new EmptyAlgorithm("No algorithm selected. Please choose an algorithm from the OKB.");
198      RegisterAlgorithmEvents();
199      runs = new RunCollection();
200      storeRunsAutomatically = true;
201      RegisterRunsEvents();
202    }
203
204    private void CheckUserPermissions() {
205      if (UserInformation.Instance.UserExists) {
206        if (UserInformation.Instance.User.Roles.Count(x => x.Name == OKBRoles.OKBUser || x.Name == OKBRoles.OKBAdministrator) > 0) {
207          UserId = UserInformation.Instance.User.Id;
208        } else {
209          throw new Exception("You don't have the appropriate roles for executing OKB Algorithms.");
210        }
211      } else {
212        throw new Exception("You need an user account for executing OKB Algorithms.");
213      }
214    }
215
216    public override IDeepCloneable Clone(Cloner cloner) {
217      return new OKBAlgorithm(this, cloner);
218    }
219
220    public void Load(long algorithmId) {
221      if (this.algorithmId != algorithmId) {
222        IAlgorithm algorithm;
223        byte[] algorithmData = RunCreationClient.Instance.GetAlgorithmData(algorithmId);
224        using (MemoryStream stream = new MemoryStream(algorithmData)) {
225          algorithm = XmlParser.Deserialize<IAlgorithm>(stream);
226        }
227        this.algorithmId = algorithmId;
228        Algorithm = algorithm;
229      }
230    }
231
232    public IAlgorithm CloneAlgorithm() {
233      return (IAlgorithm)Algorithm.Clone();
234    }
235
236    public void CollectParameterValues(IDictionary<string, IItem> values) {
237      Algorithm.CollectParameterValues(values);
238    }
239    public void CollectResultValues(IDictionary<string, IItem> values) {
240      Algorithm.CollectResultValues(values);
241    }
242
243    public void Prepare() {
244      Algorithm.Prepare();
245    }
246    public void Prepare(bool clearRuns) {
247      if (clearRuns) runs.Clear();
248      Algorithm.Prepare(clearRuns);
249    }
250    public void Start() {
251      CheckUserPermissions();
252      if (!ClientInformation.Instance.ClientExists && storeRunsAutomatically) {
253        throw new MissingClientRegistrationException();
254      }
255      Algorithm.Start();
256    }
257    public void Pause() {
258      Algorithm.Pause();
259    }
260    public void Stop() {
261      Algorithm.Stop();
262    }
263
264    #region Events
265    public event EventHandler AlgorithmChanged;
266    private void OnAlgorithmChanged() {
267      EventHandler handler = AlgorithmChanged;
268      if (handler != null) handler(this, EventArgs.Empty);
269    }
270    public event EventHandler<CancelEventArgs<string>> NameChanging;
271    private void OnNameChanging(CancelEventArgs<string> e) {
272      var handler = NameChanging;
273      if (handler != null) handler(this, e);
274    }
275    public event EventHandler NameChanged;
276    private void OnNameChanged() {
277      var handler = NameChanged;
278      if (handler != null) handler(this, EventArgs.Empty);
279    }
280    public event EventHandler DescriptionChanged;
281    private void OnDescriptionChanged() {
282      var handler = DescriptionChanged;
283      if (handler != null) handler(this, EventArgs.Empty);
284    }
285    public event EventHandler ExecutionStateChanged;
286    private void OnExecutionStateChanged() {
287      var handler = ExecutionStateChanged;
288      if (handler != null) handler(this, EventArgs.Empty);
289    }
290    public event EventHandler ExecutionTimeChanged;
291    private void OnExecutionTimeChanged() {
292      var handler = ExecutionTimeChanged;
293      if (handler != null) handler(this, EventArgs.Empty);
294    }
295    public event EventHandler ProblemChanged;
296    private void OnProblemChanged() {
297      var handler = ProblemChanged;
298      if (handler != null) handler(this, EventArgs.Empty);
299    }
300    public event EventHandler StoreRunsAutomaticallyChanged;
301    private void OnStoreRunsAutomaticallyChanged() {
302      var handler = StoreRunsAutomaticallyChanged;
303      if (handler != null) handler(this, EventArgs.Empty);
304    }
305    public event EventHandler StoreAlgorithmInEachRunChanged;
306    private void OnStoreAlgorithmInEachRunChanged() {
307      var handler = StoreAlgorithmInEachRunChanged;
308      if (handler != null) handler(this, EventArgs.Empty);
309    }
310    public event EventHandler Prepared;
311    private void OnPrepared() {
312      var handler = Prepared;
313      if (handler != null) handler(this, EventArgs.Empty);
314    }
315    public event EventHandler Started;
316    private void OnStarted() {
317      var handler = Started;
318      if (handler != null) handler(this, EventArgs.Empty);
319    }
320    public event EventHandler Paused;
321    private void OnPaused() {
322      var handler = Paused;
323      if (handler != null) handler(this, EventArgs.Empty);
324    }
325    public event EventHandler Stopped;
326    private void OnStopped() {
327      var handler = Stopped;
328      if (handler != null) handler(this, EventArgs.Empty);
329    }
330    public event EventHandler<EventArgs<Exception>> ExceptionOccurred;
331    private void OnExceptionOccurred(Exception exception) {
332      var handler = ExceptionOccurred;
333      if (handler != null) handler(this, new EventArgs<Exception>(exception));
334    }
335
336    private void RegisterAlgorithmEvents() {
337      if (Algorithm != null) {
338        Algorithm.ToStringChanged += new EventHandler(Algorithm_ToStringChanged);
339        Algorithm.ItemImageChanged += new EventHandler(Algorithm_ItemImageChanged);
340        Algorithm.NameChanging += new EventHandler<CancelEventArgs<string>>(Algorithm_NameChanging);
341        Algorithm.NameChanged += new EventHandler(Algorithm_NameChanged);
342        Algorithm.DescriptionChanged += new EventHandler(Algorithm_DescriptionChanged);
343        Algorithm.ExecutionStateChanged += new EventHandler(Algorithm_ExecutionStateChanged);
344        Algorithm.ExecutionTimeChanged += new EventHandler(Algorithm_ExecutionTimeChanged);
345        Algorithm.ProblemChanged += new EventHandler(Algorithm_ProblemChanged);
346        Algorithm.Runs.ItemsAdded += new CollectionItemsChangedEventHandler<IRun>(Algorithm_Runs_ItemsAdded);
347        Algorithm.StoreAlgorithmInEachRunChanged += new EventHandler(Algorithm_StoreAlgorithmInEachRunChanged);
348        Algorithm.Prepared += new EventHandler(Algorithm_Prepared);
349        Algorithm.Started += new EventHandler(Algorithm_Started);
350        Algorithm.Paused += new EventHandler(Algorithm_Paused);
351        Algorithm.Stopped += new EventHandler(Algorithm_Stopped);
352        Algorithm.ExceptionOccurred += new EventHandler<EventArgs<Exception>>(Algorithm_ExceptionOccurred);
353      }
354    }
355    private void DeregisterAlgorithmEvents() {
356      if (Algorithm != null) {
357        Algorithm.ToStringChanged -= new EventHandler(Algorithm_ToStringChanged);
358        Algorithm.ItemImageChanged -= new EventHandler(Algorithm_ItemImageChanged);
359        Algorithm.NameChanging -= new EventHandler<CancelEventArgs<string>>(Algorithm_NameChanging);
360        Algorithm.NameChanged -= new EventHandler(Algorithm_NameChanged);
361        Algorithm.DescriptionChanged -= new EventHandler(Algorithm_DescriptionChanged);
362        Algorithm.ExecutionStateChanged -= new EventHandler(Algorithm_ExecutionStateChanged);
363        Algorithm.ExecutionTimeChanged -= new EventHandler(Algorithm_ExecutionTimeChanged);
364        Algorithm.ProblemChanged -= new EventHandler(Algorithm_ProblemChanged);
365        Algorithm.Runs.ItemsAdded -= new CollectionItemsChangedEventHandler<IRun>(Algorithm_Runs_ItemsAdded);
366        Algorithm.StoreAlgorithmInEachRunChanged -= new EventHandler(Algorithm_StoreAlgorithmInEachRunChanged);
367        Algorithm.Prepared -= new EventHandler(Algorithm_Prepared);
368        Algorithm.Started -= new EventHandler(Algorithm_Started);
369        Algorithm.Paused -= new EventHandler(Algorithm_Paused);
370        Algorithm.Stopped -= new EventHandler(Algorithm_Stopped);
371        Algorithm.ExceptionOccurred -= new EventHandler<EventArgs<Exception>>(Algorithm_ExceptionOccurred);
372      }
373    }
374
375    private void Algorithm_ToStringChanged(object sender, EventArgs e) {
376      OnToStringChanged();
377    }
378    private void Algorithm_ItemImageChanged(object sender, EventArgs e) {
379      OnItemImageChanged();
380    }
381    private void Algorithm_NameChanging(object sender, CancelEventArgs<string> e) {
382      OnNameChanging(e);
383    }
384    private void Algorithm_NameChanged(object sender, EventArgs e) {
385      OnNameChanged();
386    }
387    private void Algorithm_DescriptionChanged(object sender, EventArgs e) {
388      OnDescriptionChanged();
389    }
390    private void Algorithm_ExecutionStateChanged(object sender, EventArgs e) {
391      OnExecutionStateChanged();
392    }
393    private void Algorithm_ExecutionTimeChanged(object sender, EventArgs e) {
394      OnExecutionTimeChanged();
395    }
396    private void Algorithm_ProblemChanged(object sender, EventArgs e) {
397      OnProblemChanged();
398    }
399    private void Algorithm_Runs_ItemsAdded(object sender, CollectionItemsChangedEventArgs<IRun> e) {
400      OKBProblem problem = Problem as OKBProblem;
401      foreach (IRun run in e.Items) {
402        if (problem != null) {
403          OKBRun okbRun = new OKBRun(AlgorithmId, problem.ProblemId, run, UserId);
404          runs.Add(okbRun);
405          if (StoreRunsAutomatically) {
406            okbRun.Store();
407          }
408        } else {
409          runs.Add(run);
410        }
411      }
412    }
413    private void Algorithm_StoreAlgorithmInEachRunChanged(object sender, EventArgs e) {
414      OnStoreAlgorithmInEachRunChanged();
415    }
416    private void Algorithm_Prepared(object sender, EventArgs e) {
417      OnPrepared();
418    }
419    private void Algorithm_Started(object sender, EventArgs e) {
420      OnStarted();
421    }
422    private void Algorithm_Paused(object sender, EventArgs e) {
423      OnPaused();
424    }
425    private void Algorithm_Stopped(object sender, EventArgs e) {
426      OnStopped();
427    }
428    private void Algorithm_ExceptionOccurred(object sender, EventArgs<Exception> e) {
429      OnExceptionOccurred(e.Value);
430    }
431
432    private void RegisterRunsEvents() {
433      runs.ItemsRemoved += new CollectionItemsChangedEventHandler<IRun>(runs_ItemsRemoved);
434      runs.CollectionReset += new CollectionItemsChangedEventHandler<IRun>(Runs_CollectionReset);
435    }
436    private void runs_ItemsRemoved(object sender, CollectionItemsChangedEventArgs<IRun> e) {
437      foreach (IRun run in e.Items) {
438        OKBRun okbRun = run as OKBRun;
439        if (okbRun != null)
440          Algorithm.Runs.Remove(okbRun.WrappedRun);
441        else
442          Algorithm.Runs.Remove(run);
443      }
444    }
445    private void Runs_CollectionReset(object sender, CollectionItemsChangedEventArgs<IRun> e) {
446      foreach (IRun run in e.OldItems) {
447        OKBRun okbRun = run as OKBRun;
448        if (okbRun != null)
449          Algorithm.Runs.Remove(okbRun.WrappedRun);
450        else
451          Algorithm.Runs.Remove(run);
452      }
453    }
454    #endregion
455  }
456}
Note: See TracBrowser for help on using the repository browser.