Free cookie consent management tool by TermsFeed Policy Generator

source: branches/WebJobManager/HeuristicLab.Optimization/3.3/MetaOptimizers/Experiment.cs @ 16003

Last change on this file since 16003 was 13656, checked in by ascheibe, 9 years ago

#2582 created branch for Hive Web Job Manager

File size: 18.6 KB
Line 
1#region License Information
2/* HeuristicLab
3 * Copyright (C) 2002-2015 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 System.Threading;
27using HeuristicLab.Collections;
28using HeuristicLab.Common;
29using HeuristicLab.Core;
30using HeuristicLab.Persistence.Default.CompositeSerializers.Storable;
31
32namespace HeuristicLab.Optimization {
33  /// <summary>
34  /// An experiment which contains multiple algorithms, batch runs or other experiments.
35  /// </summary>
36  [Item("Experiment", "An experiment which contains multiple algorithms, batch runs or other experiments.")]
37  [Creatable(CreatableAttribute.Categories.TestingAndAnalysis, Priority = 100)]
38  [StorableClass]
39  public sealed class Experiment : NamedItem, IOptimizer, IStorableContent {
40    public string Filename { get; set; }
41
42    public static new Image StaticItemImage
43    {
44      get { return new Bitmap(25, 25); }
45    }
46    public override Image ItemImage
47    {
48      get
49      {
50        if (ExecutionState == ExecutionState.Prepared) return HeuristicLab.Common.Resources.VSImageLibrary.ExperimentPrepared;
51        else if (ExecutionState == ExecutionState.Started) return HeuristicLab.Common.Resources.VSImageLibrary.ExperimentStarted;
52        else if (ExecutionState == ExecutionState.Paused) return HeuristicLab.Common.Resources.VSImageLibrary.ExperimentPaused;
53        else if (ExecutionState == ExecutionState.Stopped) return HeuristicLab.Common.Resources.VSImageLibrary.ExperimentStopped;
54        else return base.ItemImage;
55      }
56    }
57
58    [Storable]
59    private ExecutionState executionState;
60    public ExecutionState ExecutionState
61    {
62      get { return executionState; }
63      private set
64      {
65        if (executionState != value) {
66          executionState = value;
67          OnExecutionStateChanged();
68          OnItemImageChanged();
69        }
70      }
71    }
72
73    [Storable]
74    private TimeSpan executionTime;
75    public TimeSpan ExecutionTime
76    {
77      get { return executionTime; }
78      private set
79      {
80        executionTime = value;
81        OnExecutionTimeChanged();
82      }
83    }
84
85    [Storable]
86    private OptimizerList optimizers;
87    public OptimizerList Optimizers
88    {
89      get { return optimizers; }
90    }
91
92    [Storable]
93    private RunCollection runs;
94    public RunCollection Runs
95    {
96      get { return runs; }
97      private set
98      {
99        if (value == null) throw new ArgumentNullException();
100        if (runs != value) {
101          if (runs != null) DeregisterRunsEvents();
102          runs = value;
103          if (runs != null) RegisterRunsEvents();
104        }
105      }
106    }
107
108    public IEnumerable<IOptimizer> NestedOptimizers
109    {
110      get
111      {
112        if (Optimizers == null) yield break;
113
114        foreach (IOptimizer opt in Optimizers) {
115          yield return opt;
116          foreach (IOptimizer nestedOpt in opt.NestedOptimizers)
117            yield return nestedOpt;
118        }
119      }
120    }
121
122    private bool experimentStarted = false;
123    private bool experimentStopped = false;
124
125    public Experiment()
126      : base() {
127      name = ItemName;
128      description = ItemDescription;
129      executionState = ExecutionState.Stopped;
130      executionTime = TimeSpan.Zero;
131      optimizers = new OptimizerList();
132      Runs = new RunCollection { OptimizerName = Name };
133      Initialize();
134    }
135    public Experiment(string name)
136      : base(name) {
137      description = ItemDescription;
138      executionState = ExecutionState.Stopped;
139      executionTime = TimeSpan.Zero;
140      optimizers = new OptimizerList();
141      Runs = new RunCollection { OptimizerName = Name };
142      Initialize();
143    }
144    public Experiment(string name, string description)
145      : base(name, description) {
146      executionState = ExecutionState.Stopped;
147      executionTime = TimeSpan.Zero;
148      optimizers = new OptimizerList();
149      Runs = new RunCollection { OptimizerName = Name };
150      Initialize();
151    }
152    [StorableConstructor]
153    private Experiment(bool deserializing) : base(deserializing) { }
154    [StorableHook(HookType.AfterDeserialization)]
155    private void AfterDeserialization() {
156      Initialize();
157    }
158    private Experiment(Experiment original, Cloner cloner)
159      : base(original, cloner) {
160      executionState = original.executionState;
161      executionTime = original.executionTime;
162      optimizers = cloner.Clone(original.optimizers);
163      runs = cloner.Clone(original.runs);
164
165      experimentStarted = original.experimentStarted;
166      experimentStopped = original.experimentStopped;
167      Initialize();
168    }
169    public override IDeepCloneable Clone(Cloner cloner) {
170      if (ExecutionState == ExecutionState.Started) throw new InvalidOperationException(string.Format("Clone not allowed in execution state \"{0}\".", ExecutionState));
171      return new Experiment(this, cloner);
172    }
173
174    private void Initialize() {
175      RegisterOptimizersEvents();
176      foreach (IOptimizer optimizer in optimizers)
177        RegisterOptimizerEvents(optimizer);
178      if (runs != null) RegisterRunsEvents();
179    }
180
181    public void Prepare() {
182      Prepare(false);
183    }
184    public void Prepare(bool clearRuns) {
185      if ((ExecutionState != ExecutionState.Prepared) && (ExecutionState != ExecutionState.Paused) && (ExecutionState != ExecutionState.Stopped))
186        throw new InvalidOperationException(string.Format("Prepare not allowed in execution state \"{0}\".", ExecutionState));
187      if (Optimizers.Count == 0) return;
188
189      if (clearRuns) runs.Clear();
190
191      experimentStarted = false;
192      experimentStopped = false;
193      foreach (IOptimizer optimizer in Optimizers.Where(x => x.ExecutionState != ExecutionState.Started)) {
194        // a race-condition may occur when the optimizer has changed the state by itself in the meantime
195        try { optimizer.Prepare(clearRuns); }
196        catch (InvalidOperationException) { }
197      }
198    }
199    public void Start() {
200      if ((ExecutionState != ExecutionState.Prepared) && (ExecutionState != ExecutionState.Paused))
201        throw new InvalidOperationException(string.Format("Start not allowed in execution state \"{0}\".", ExecutionState));
202      if (Optimizers.Count == 0) return;
203
204      experimentStarted = true;
205      experimentStopped = false;
206      IOptimizer optimizer = Optimizers.FirstOrDefault(x => (x.ExecutionState == ExecutionState.Prepared) || (x.ExecutionState == ExecutionState.Paused));
207      if (optimizer != null) {
208        // a race-condition may occur when the optimizer has changed the state by itself in the meantime
209        try { optimizer.Start(); }
210        catch (InvalidOperationException) { }
211      }
212    }
213    public void Pause() {
214      if (ExecutionState != ExecutionState.Started)
215        throw new InvalidOperationException(string.Format("Pause not allowed in execution state \"{0}\".", ExecutionState));
216      if (Optimizers.Count == 0) return;
217
218      experimentStarted = false;
219      experimentStopped = false;
220      foreach (IOptimizer optimizer in Optimizers.Where(x => x.ExecutionState == ExecutionState.Started)) {
221        // a race-condition may occur when the optimizer has changed the state by itself in the meantime
222        try { optimizer.Pause(); }
223        catch (InvalidOperationException) { }
224      }
225    }
226    public void Stop() {
227      if ((ExecutionState != ExecutionState.Started) && (ExecutionState != ExecutionState.Paused))
228        throw new InvalidOperationException(string.Format("Stop not allowed in execution state \"{0}\".", ExecutionState));
229      if (Optimizers.Count == 0) return;
230
231      experimentStarted = false;
232      experimentStopped = true;
233      if (Optimizers.Any(x => (x.ExecutionState == ExecutionState.Started) || (x.ExecutionState == ExecutionState.Paused))) {
234        foreach (var optimizer in Optimizers.Where(x => (x.ExecutionState == ExecutionState.Started) || (x.ExecutionState == ExecutionState.Paused))) {
235          // a race-condition may occur when the optimizer has changed the state by itself in the meantime
236          try { optimizer.Stop(); }
237          catch (InvalidOperationException) { }
238        }
239      } else {
240        OnStopped();
241      }
242    }
243
244    #region Events
245    protected override void OnNameChanged() {
246      base.OnNameChanged();
247      Runs.OptimizerName = Name;
248    }
249
250    public event EventHandler ExecutionStateChanged;
251    private void OnExecutionStateChanged() {
252      EventHandler handler = ExecutionStateChanged;
253      if (handler != null) handler(this, EventArgs.Empty);
254    }
255    public event EventHandler ExecutionTimeChanged;
256    private void OnExecutionTimeChanged() {
257      EventHandler handler = ExecutionTimeChanged;
258      if (handler != null) handler(this, EventArgs.Empty);
259    }
260    public event EventHandler Prepared;
261    private void OnPrepared() {
262      ExecutionState = ExecutionState.Prepared;
263      EventHandler handler = Prepared;
264      if (handler != null) handler(this, EventArgs.Empty);
265    }
266    public event EventHandler Started;
267    private void OnStarted() {
268      ExecutionState = ExecutionState.Started;
269      EventHandler handler = Started;
270      if (handler != null) handler(this, EventArgs.Empty);
271    }
272    public event EventHandler Paused;
273    private void OnPaused() {
274      ExecutionState = ExecutionState.Paused;
275      EventHandler handler = Paused;
276      if (handler != null) handler(this, EventArgs.Empty);
277    }
278    public event EventHandler Stopped;
279    private void OnStopped() {
280      ExecutionState = ExecutionState.Stopped;
281      EventHandler handler = Stopped;
282      if (handler != null) handler(this, EventArgs.Empty);
283    }
284    public event EventHandler<EventArgs<Exception>> ExceptionOccurred;
285    private void OnExceptionOccurred(Exception exception) {
286      EventHandler<EventArgs<Exception>> handler = ExceptionOccurred;
287      if (handler != null) handler(this, new EventArgs<Exception>(exception));
288    }
289
290    private void RegisterOptimizersEvents() {
291      Optimizers.CollectionReset += new CollectionItemsChangedEventHandler<IndexedItem<IOptimizer>>(Optimizers_CollectionReset);
292      Optimizers.ItemsAdded += new CollectionItemsChangedEventHandler<IndexedItem<IOptimizer>>(Optimizers_ItemsAdded);
293      Optimizers.ItemsRemoved += new CollectionItemsChangedEventHandler<IndexedItem<IOptimizer>>(Optimizers_ItemsRemoved);
294      Optimizers.ItemsReplaced += new CollectionItemsChangedEventHandler<IndexedItem<IOptimizer>>(Optimizers_ItemsReplaced);
295    }
296    private void DeregisterOptimizersEvents() {
297      Optimizers.CollectionReset -= new CollectionItemsChangedEventHandler<IndexedItem<IOptimizer>>(Optimizers_CollectionReset);
298      Optimizers.ItemsAdded -= new CollectionItemsChangedEventHandler<IndexedItem<IOptimizer>>(Optimizers_ItemsAdded);
299      Optimizers.ItemsRemoved -= new CollectionItemsChangedEventHandler<IndexedItem<IOptimizer>>(Optimizers_ItemsRemoved);
300      Optimizers.ItemsReplaced -= new CollectionItemsChangedEventHandler<IndexedItem<IOptimizer>>(Optimizers_ItemsReplaced);
301    }
302    private void Optimizers_CollectionReset(object sender, CollectionItemsChangedEventArgs<IndexedItem<IOptimizer>> e) {
303      foreach (IndexedItem<IOptimizer> item in e.OldItems)
304        RemoveOptimizer(item.Value);
305      foreach (IndexedItem<IOptimizer> item in e.Items)
306        AddOptimizer(item.Value);
307    }
308    private void Optimizers_ItemsAdded(object sender, CollectionItemsChangedEventArgs<IndexedItem<IOptimizer>> e) {
309      foreach (IndexedItem<IOptimizer> item in e.Items)
310        AddOptimizer(item.Value);
311    }
312    private void Optimizers_ItemsRemoved(object sender, CollectionItemsChangedEventArgs<IndexedItem<IOptimizer>> e) {
313      foreach (IndexedItem<IOptimizer> item in e.Items)
314        RemoveOptimizer(item.Value);
315    }
316    private void Optimizers_ItemsReplaced(object sender, CollectionItemsChangedEventArgs<IndexedItem<IOptimizer>> e) {
317      foreach (IndexedItem<IOptimizer> item in e.OldItems)
318        RemoveOptimizer(item.Value);
319      foreach (IndexedItem<IOptimizer> item in e.Items)
320        AddOptimizer(item.Value);
321    }
322    private void AddOptimizer(IOptimizer optimizer) {
323      RegisterOptimizerEvents(optimizer);
324      Runs.AddRange(optimizer.Runs);
325      optimizer.Prepare();
326      if (ExecutionState == ExecutionState.Stopped && optimizer.ExecutionState == ExecutionState.Prepared)
327        OnPrepared();
328    }
329    private void RemoveOptimizer(IOptimizer optimizer) {
330      DeregisterOptimizerEvents(optimizer);
331      Runs.RemoveRange(optimizer.Runs);
332      if (ExecutionState == ExecutionState.Prepared && !optimizers.Any(opt => opt.ExecutionState == ExecutionState.Prepared))
333        OnStopped();
334    }
335
336    private void RegisterOptimizerEvents(IOptimizer optimizer) {
337      optimizer.ExceptionOccurred += new EventHandler<EventArgs<Exception>>(optimizer_ExceptionOccurred);
338      optimizer.ExecutionTimeChanged += new EventHandler(optimizer_ExecutionTimeChanged);
339      optimizer.Paused += new EventHandler(optimizer_Paused);
340      optimizer.Prepared += new EventHandler(optimizer_Prepared);
341      optimizer.Started += new EventHandler(optimizer_Started);
342      optimizer.Stopped += new EventHandler(optimizer_Stopped);
343      optimizer.Runs.CollectionReset += new CollectionItemsChangedEventHandler<IRun>(optimizer_Runs_CollectionReset);
344      optimizer.Runs.ItemsAdded += new CollectionItemsChangedEventHandler<IRun>(optimizer_Runs_ItemsAdded);
345      optimizer.Runs.ItemsRemoved += new CollectionItemsChangedEventHandler<IRun>(optimizer_Runs_ItemsRemoved);
346    }
347    private void DeregisterOptimizerEvents(IOptimizer optimizer) {
348      optimizer.ExceptionOccurred -= new EventHandler<EventArgs<Exception>>(optimizer_ExceptionOccurred);
349      optimizer.ExecutionTimeChanged -= new EventHandler(optimizer_ExecutionTimeChanged);
350      optimizer.Paused -= new EventHandler(optimizer_Paused);
351      optimizer.Prepared -= new EventHandler(optimizer_Prepared);
352      optimizer.Started -= new EventHandler(optimizer_Started);
353      optimizer.Stopped -= new EventHandler(optimizer_Stopped);
354      optimizer.Runs.CollectionReset -= new CollectionItemsChangedEventHandler<IRun>(optimizer_Runs_CollectionReset);
355      optimizer.Runs.ItemsAdded -= new CollectionItemsChangedEventHandler<IRun>(optimizer_Runs_ItemsAdded);
356      optimizer.Runs.ItemsRemoved -= new CollectionItemsChangedEventHandler<IRun>(optimizer_Runs_ItemsRemoved);
357    }
358
359    private readonly object locker = new object();
360    private readonly object runsLocker = new object();
361    private void optimizer_ExceptionOccurred(object sender, EventArgs<Exception> e) {
362      lock (locker)
363        OnExceptionOccurred(e.Value);
364    }
365    private void optimizer_ExecutionTimeChanged(object sender, EventArgs e) {
366      // only wait for maximally 100ms to acquire lock, otherwise return and don't update the execution time
367      var success = Monitor.TryEnter(locker, 100);
368      if (!success) return;
369      try {
370        ExecutionTime = Optimizers.Aggregate(TimeSpan.Zero, (t, o) => t + o.ExecutionTime);
371      }
372      finally {
373        Monitor.Exit(locker);
374      }
375    }
376    private void optimizer_Paused(object sender, EventArgs e) {
377      lock (locker)
378        if (Optimizers.All(x => x.ExecutionState != ExecutionState.Started)) OnPaused();
379    }
380    private void optimizer_Prepared(object sender, EventArgs e) {
381      lock (locker)
382        if (Optimizers.All(x => x.ExecutionState == ExecutionState.Prepared)) OnPrepared();
383    }
384    private void optimizer_Started(object sender, EventArgs e) {
385      lock (locker)
386        if (ExecutionState != ExecutionState.Started) OnStarted();
387    }
388    private void optimizer_Stopped(object sender, EventArgs e) {
389      lock (locker) {
390        if (experimentStopped) {
391          if (Optimizers.All(x => (x.ExecutionState == ExecutionState.Stopped) || (x.ExecutionState == ExecutionState.Prepared))) OnStopped();
392        } else {
393          if (experimentStarted && Optimizers.Any(x => (x.ExecutionState == ExecutionState.Prepared) || (x.ExecutionState == ExecutionState.Paused))) {
394            Optimizers.First(x => (x.ExecutionState == ExecutionState.Prepared) || (x.ExecutionState == ExecutionState.Paused)).Start();
395          } else if (Optimizers.All(x => x.ExecutionState == ExecutionState.Stopped)) OnStopped();
396          else if (Optimizers.Any(x => (x.ExecutionState == ExecutionState.Prepared) || (x.ExecutionState == ExecutionState.Paused)) && Optimizers.All(o => o.ExecutionState != ExecutionState.Started)) OnPaused();
397        }
398      }
399    }
400    private void optimizer_Runs_CollectionReset(object sender, CollectionItemsChangedEventArgs<IRun> e) {
401      lock (runsLocker) {
402        Runs.RemoveRange(e.OldItems);
403        Runs.AddRange(e.Items);
404      }
405    }
406    private void optimizer_Runs_ItemsAdded(object sender, CollectionItemsChangedEventArgs<IRun> e) {
407      lock (runsLocker)
408        Runs.AddRange(e.Items);
409    }
410    private void optimizer_Runs_ItemsRemoved(object sender, CollectionItemsChangedEventArgs<IRun> e) {
411      lock (runsLocker)
412        Runs.RemoveRange(e.Items);
413    }
414
415    private void RegisterRunsEvents() {
416      runs.CollectionReset += new CollectionItemsChangedEventHandler<IRun>(Runs_CollectionReset);
417      runs.ItemsRemoved += new CollectionItemsChangedEventHandler<IRun>(Runs_ItemsRemoved);
418    }
419    private void DeregisterRunsEvents() {
420      runs.CollectionReset -= new CollectionItemsChangedEventHandler<IRun>(Runs_CollectionReset);
421      runs.ItemsRemoved -= new CollectionItemsChangedEventHandler<IRun>(Runs_ItemsRemoved);
422    }
423    private void Runs_CollectionReset(object sender, CollectionItemsChangedEventArgs<IRun> e) {
424      foreach (IOptimizer optimizer in Optimizers)
425        optimizer.Runs.RemoveRange(e.OldItems);
426    }
427    private void Runs_ItemsRemoved(object sender, CollectionItemsChangedEventArgs<IRun> e) {
428      foreach (IOptimizer optimizer in Optimizers)
429        optimizer.Runs.RemoveRange(e.Items);
430    }
431    #endregion
432  }
433}
Note: See TracBrowser for help on using the repository browser.