Free cookie consent management tool by TermsFeed Policy Generator

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

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

#2205: Restructured solution and projects and switched all projects to .NET 4.5

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