Free cookie consent management tool by TermsFeed Policy Generator

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

Last change on this file since 11529 was 11529, checked in by swagner, 9 years ago

#2205: Implemented review comments

  • made Node and Network abstract
  • renamed GenericNode to UserDefinedNode and sealed it
  • added sealed UserDefinedNetwork
  • made Nodes in Network not changeable by default
  • made Parameters in ParameterizedPort not changeable by default
  • removed value None in PortParameterType
  • refactored call algorithm.PrepareMessage() in AlgorithmNode
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.Core.Networks;
25using HeuristicLab.Persistence.Default.CompositeSerializers.Storable;
26using System;
27using System.Collections.Generic;
28using System.Linq;
29using System.Threading;
30
31namespace HeuristicLab.Optimization.Networks {
32  [Item("AlgorithmNode", "A node of an optimization network which contains a HeuristicLab algorithm.")]
33  [StorableClass]
34  public class AlgorithmNode : Node, IAlgorithmNode {
35    private object locker = new object();
36    private Dictionary<IAlgorithm, AutoResetEvent> waitHandles = new Dictionary<IAlgorithm, AutoResetEvent>();
37    private Dictionary<IAlgorithm, Exception> exceptions = new Dictionary<IAlgorithm, Exception>();
38
39    new public PortCollection Ports {
40      get { return base.Ports; }
41    }
42
43    [Storable]
44    private IAlgorithm algorithm;
45    public IAlgorithm Algorithm {
46      get { return algorithm; }
47      set {
48        if (value != algorithm) {
49          algorithm = value;
50          OnAlgorithmChanged();
51        }
52      }
53    }
54
55    [Storable]
56    private RunCollection runs;
57    public RunCollection Runs {
58      get { return runs; }
59    }
60
61    [StorableConstructor]
62    protected AlgorithmNode(bool deserializing) : base(deserializing) { }
63    protected AlgorithmNode(AlgorithmNode original, Cloner cloner)
64      : base(original, cloner) {
65      algorithm = cloner.Clone(original.algorithm);
66      runs = cloner.Clone(original.runs);
67    }
68    public AlgorithmNode()
69      : base("AlgorithmNode") {
70      runs = new RunCollection();
71    }
72    public AlgorithmNode(string name)
73      : base(name) {
74      runs = new RunCollection();
75    }
76    public AlgorithmNode(string name, string description)
77      : base(name, description) {
78      runs = new RunCollection();
79    }
80
81    public override IDeepCloneable Clone(Cloner cloner) {
82      return new AlgorithmNode(this, cloner);
83    }
84
85    protected virtual void Configure(IConfigurationPort port, IMessage message, CancellationToken token) {
86      // set algorithm and problem parameters
87      lock (locker) {
88        if (algorithm != null) {
89          foreach (var v in message.Values) {
90            IParameter param = null;
91            if (Algorithm.Parameters.TryGetValue(v.Name, out param)) {
92              var vp = param as IValueParameter;
93              if (vp != null) vp.Value = v.Value;
94            }
95            if (Algorithm.Problem.Parameters.TryGetValue(v.Name, out param)) {
96              var vp = param as IValueParameter;
97              if (vp != null) vp.Value = v.Value;
98            }
99          }
100        }
101      }
102    }
103
104    protected virtual void Execute(IExecutionPort port, IMessage message, CancellationToken token) {
105      if (Algorithm == null) throw new InvalidOperationException("Algorithm is null");
106
107      IAlgorithm algorithm;
108      lock (locker) {
109        algorithm = (IAlgorithm)Algorithm.Clone();
110        waitHandles.Add(algorithm, new AutoResetEvent(false));
111      }
112
113      // set parameters
114      foreach (var v in message.Values) {
115        IParameter param = null;
116        if (algorithm.Parameters.TryGetValue(v.Name, out param)) {
117          var vp = param as IValueParameter;
118          if (vp != null) vp.Value = v.Value;
119        }
120        if (algorithm.Problem.Parameters.TryGetValue(v.Name, out param)) {
121          var vp = param as IValueParameter;
122          if (vp != null) vp.Value = v.Value;
123        }
124      }
125
126      algorithm.StoreAlgorithmInEachRun = false;
127      algorithm.Prepare(true);
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.