source: branches/OptimizationNetworks/HeuristicLab.Optimization.Networks/3.3/Nodes/AlgorithmNode.cs @ 11519

Last change on this file since 11519 was 11519, checked in by swagner, 8 years ago

#2205: Worked on optimization networks

File size: 8.2 KB
Line 
1#region License Information
2/* HeuristicLab
3 * Copyright (C) 2002-2014 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.Common;
23using HeuristicLab.Core;
24using HeuristicLab.Persistence.Default.CompositeSerializers.Storable;
25using System;
26using System.Collections.Generic;
27using System.Linq;
28using System.Threading;
29
30namespace HeuristicLab.Optimization.Networks {
31  [Item("AlgorithmNode", "A node of an optimization network which contains a HeuristicLab algorithm.")]
32  [StorableClass]
33  public class AlgorithmNode : Node, IAlgorithmNode {
34    private object locker = new object();
35    private Dictionary<IAlgorithm, AutoResetEvent> waitHandles = new Dictionary<IAlgorithm, AutoResetEvent>();
36    private Dictionary<IAlgorithm, Exception> exceptions = new Dictionary<IAlgorithm, Exception>();
37
38    new public PortCollection Ports {
39      get { return base.Ports; }
40    }
41
42    [Storable]
43    private IAlgorithm algorithm;
44    public IAlgorithm Algorithm {
45      get { return algorithm; }
46      set {
47        if (value != algorithm) {
48          algorithm = value;
49          OnAlgorithmChanged();
50        }
51      }
52    }
53
54    [Storable]
55    private RunCollection runs;
56    public RunCollection Runs {
57      get { return runs; }
58    }
59
60    [StorableConstructor]
61    protected AlgorithmNode(bool deserializing) : base(deserializing) { }
62    protected AlgorithmNode(AlgorithmNode original, Cloner cloner)
63      : base(original, cloner) {
64      algorithm = cloner.Clone(original.algorithm);
65      runs = cloner.Clone(original.runs);
66    }
67    public AlgorithmNode()
68      : base("AlgorithmNode") {
69      runs = new RunCollection();
70    }
71    public AlgorithmNode(string name)
72      : base(name) {
73      runs = new RunCollection();
74    }
75    public AlgorithmNode(string name, string description)
76      : base(name, description) {
77      runs = new RunCollection();
78    }
79
80    public override IDeepCloneable Clone(Cloner cloner) {
81      return new AlgorithmNode(this, cloner);
82    }
83
84    protected virtual void Configure(IConfigurationPort port, IMessage message, CancellationToken token) {
85      // set algorithm and problem parameters
86      lock (locker) {
87        if (algorithm != null) {
88          foreach (var v in message.Values) {
89            IParameter param = null;
90            if (Algorithm.Parameters.TryGetValue(v.Name, out param)) {
91              var vp = param as IValueParameter;
92              if (vp != null) vp.Value = v.Value;
93            }
94            if (Algorithm.Problem.Parameters.TryGetValue(v.Name, out param)) {
95              var vp = param as IValueParameter;
96              if (vp != null) vp.Value = v.Value;
97            }
98          }
99        }
100      }
101    }
102
103    protected virtual void Execute(IExecutionPort port, IMessage message, CancellationToken token) {
104      if (Algorithm == null) throw new InvalidOperationException("Algorithm is null");
105
106      IAlgorithm algorithm;
107      lock (locker) {
108        algorithm = (IAlgorithm)Algorithm.Clone();
109        waitHandles.Add(algorithm, new AutoResetEvent(false));
110      }
111
112      // set parameters
113      foreach (var v in message.Values) {
114        IParameter param = null;
115        if (algorithm.Parameters.TryGetValue(v.Name, out param)) {
116          var vp = param as IValueParameter;
117          if (vp != null) vp.Value = v.Value;
118        }
119        if (algorithm.Problem.Parameters.TryGetValue(v.Name, out param)) {
120          var vp = param as IValueParameter;
121          if (vp != null) vp.Value = v.Value;
122        }
123      }
124
125      algorithm.StoreAlgorithmInEachRun = false;
126      algorithm.Runs.Clear();
127      algorithm.Prepare();
128      algorithm.ExceptionOccurred += Algorithm_ExceptionOccurred;
129      algorithm.Stopped += Algorithm_Stopped;
130
131      using (token.Register(() => { algorithm.Stop(); })) {
132        algorithm.Start();
133        waitHandles[algorithm].WaitOne();
134      }
135
136      lock (locker) {
137        waitHandles[algorithm].Dispose();
138        waitHandles.Remove(algorithm);
139
140        Exception ex = null;
141        if (exceptions.TryGetValue(algorithm, out ex)) {
142          exceptions.Remove(algorithm);
143          throw ex;
144        }
145      }
146
147      // retrieve results
148      var run = algorithm.Runs.First();
149      foreach (var v in message.Values) {
150        IItem result = null;
151        if (run.Results.TryGetValue(v.Name, out result)) {
152          v.Value = result;
153        }
154      }
155
156      lock (locker) {
157        Runs.Add(run);
158      }
159    }
160
161    private void Algorithm_ExceptionOccurred(object sender, EventArgs<Exception> e) {
162      var algorithm = (IAlgorithm)sender;
163      lock (locker) {
164        exceptions.Add(algorithm, e.Value);
165      }
166      algorithm.Stop();
167    }
168    private void Algorithm_Stopped(object sender, EventArgs e) {
169      lock (locker) {
170        waitHandles[(IAlgorithm)sender].Set();
171      }
172    }
173
174    public event EventHandler AlgorithmChanged;
175    protected virtual void OnAlgorithmChanged() {
176      var handler = AlgorithmChanged;
177      if (handler != null) handler(this, EventArgs.Empty);
178    }
179
180    #region Ports Events
181    protected override void RegisterPortsEvents() {
182      base.RegisterPortsEvents();
183      foreach (var p in Ports)
184        RegisterPortEvents(p);
185    }
186    protected override void Ports_ItemsAdded(object sender, Collections.CollectionItemsChangedEventArgs<IPort> e) {
187      base.Ports_ItemsAdded(sender, e);
188      foreach (var p in e.Items)
189        RegisterPortEvents(p);
190    }
191    protected override void Ports_ItemsRemoved(object sender, Collections.CollectionItemsChangedEventArgs<IPort> e) {
192      base.Ports_ItemsRemoved(sender, e);
193      foreach (var p in e.Items)
194        DeregisterPortEvents(p);
195    }
196    protected override void Ports_ItemsReplaced(object sender, Collections.CollectionItemsChangedEventArgs<IPort> e) {
197      base.Ports_ItemsReplaced(sender, e);
198      foreach (var p in e.OldItems)
199        DeregisterPortEvents(p);
200      foreach (var p in e.Items)
201        RegisterPortEvents(p);
202    }
203    protected override void Ports_CollectionReset(object sender, Collections.CollectionItemsChangedEventArgs<IPort> e) {
204      base.Ports_CollectionReset(sender, e);
205      foreach (var p in e.OldItems)
206        DeregisterPortEvents(p);
207      foreach (var p in e.Items)
208        RegisterPortEvents(p);
209    }
210    #endregion
211
212    #region Port Events
213    private void RegisterPortEvents(IPort port) {
214      IConfigurationPort c = port as IConfigurationPort;
215      if (c != null) {
216        c.MessageReceived += ConfigurationPort_MessageReceived;
217      }
218      IExecutionPort e = port as IExecutionPort;
219      if (e != null) {
220        e.MessageReceived += ExecutionPort_MessageReceived;
221      }
222    }
223    private void DeregisterPortEvents(IPort port) {
224      IConfigurationPort c = port as IConfigurationPort;
225      if (c != null) {
226        c.MessageReceived -= ConfigurationPort_MessageReceived;
227      }
228      IExecutionPort e = port as IExecutionPort;
229      if (e != null) {
230        e.MessageReceived -= ExecutionPort_MessageReceived;
231      }
232    }
233    protected virtual void ConfigurationPort_MessageReceived(object sender, EventArgs<IMessage, CancellationToken> e) {
234      Configure((IConfigurationPort)sender, e.Value, e.Value2);
235    }
236    protected virtual void ExecutionPort_MessageReceived(object sender, EventArgs<IMessage, CancellationToken> e) {
237      Execute((IExecutionPort)sender, e.Value, e.Value2);
238    }
239    #endregion
240  }
241}
Note: See TracBrowser for help on using the repository browser.