Free cookie consent management tool by TermsFeed Policy Generator

source: stable/HeuristicLab.Clients.OKB/3.3/RunCreation/OKBAlgorithm.cs @ 11290

Last change on this file since 11290 was 11170, checked in by ascheibe, 10 years ago

#2115 updated copyright year in stable branch

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