Free cookie consent management tool by TermsFeed Policy Generator

source: branches/OptimizationNetworks/HeuristicLab.Optimization.Networks/3.3/Nodes/AlgorithmServiceNode.cs @ 11501

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

#2205: Worked on optimization networks

File size: 7.9 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("AlgorithmServiceNode", "A node of an optimization network which provides a HeuristicLab algorithm as a service.")]
32  [StorableClass]
33  public class AlgorithmServiceNode : Node, IAlgorithmServiceNode {
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 template;
44    public IAlgorithm Template {
45      get { return template; }
46      set {
47        if (value != template) {
48          template = value;
49          OnTemplateChanged();
50        }
51      }
52    }
53
54    [Storable]
55    private RunCollection runs;
56    public RunCollection Runs {
57      get { return runs; }
58    }
59
60    [StorableConstructor]
61    protected AlgorithmServiceNode(bool deserializing) : base(deserializing) { }
62    protected AlgorithmServiceNode(AlgorithmServiceNode original, Cloner cloner)
63      : base(original, cloner) {
64      template = cloner.Clone(original.template);
65      runs = cloner.Clone(original.runs);
66    }
67    public AlgorithmServiceNode()
68      : base("AlgorithmServiceNode") {
69      runs = new RunCollection();
70    }
71    public AlgorithmServiceNode(string name)
72      : base(name) {
73      runs = new RunCollection();
74    }
75    public AlgorithmServiceNode(string name, string description)
76      : base(name, description) {
77      runs = new RunCollection();
78    }
79
80    public override IDeepCloneable Clone(Cloner cloner) {
81      return new AlgorithmServiceNode(this, cloner);
82    }
83
84    protected virtual void UpdateParameters(IMessage message, CancellationToken token) {
85      // set template parameters
86      lock (locker) {
87        if (template != null) {
88          foreach (var v in message.Values) {
89            IParameter param = null;
90            if (Template.Parameters.TryGetValue(v.Name, out param)) {
91              var vp = param as IValueParameter;
92              if (vp != null) vp.Value = v.Value;
93            }
94            if (Template.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(IMessage message, CancellationToken token) {
104      if (Template == null) throw new InvalidOperationException("Template is null");
105
106      IAlgorithm algorithm;
107      lock (locker) {
108        algorithm = (IAlgorithm)Template.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 TemplateChanged;
175    protected virtual void OnTemplateChanged() {
176      var handler = TemplateChanged;
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      IGenericPort g = port as IGenericPort;
215      if (g != null) {
216        g.MessageReceived += GenericPort_MessageReceived;
217      }
218    }
219    private void DeregisterPortEvents(IPort port) {
220      IGenericPort g = port as IGenericPort;
221      if (g != null) {
222        g.MessageReceived -= GenericPort_MessageReceived;
223      }
224    }
225    private void GenericPort_MessageReceived(object sender, EventArgs<IMessage, CancellationToken> e) {
226      var port = (IGenericPort)sender;
227      if (port.Parameters.Any(p => p.Type.HasFlag(PortParameterType.Output)))
228        Execute(e.Value, e.Value2);  // execute algorithm to compute output
229      else
230        UpdateParameters(e.Value, e.Value2);  // update template parameters
231    }
232    #endregion
233  }
234}
Note: See TracBrowser for help on using the repository browser.