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

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

#2205: Worked on optimization networks

File size: 7.7 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.Threading;
28using System.Linq;
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
37    new public PortCollection Ports {
38      get { return base.Ports; }
39    }
40
41    [Storable]
42    private IAlgorithm template;
43    public IAlgorithm Template {
44      get { return template; }
45      set {
46        if (value != template) {
47          template = value;
48          OnTemplateChanged();
49        }
50      }
51    }
52
53    [Storable]
54    private RunCollection runs;
55    public RunCollection Runs {
56      get { return runs; }
57    }
58
59    [StorableConstructor]
60    protected AlgorithmServiceNode(bool deserializing) : base(deserializing) { }
61    protected AlgorithmServiceNode(AlgorithmServiceNode original, Cloner cloner)
62      : base(original, cloner) {
63      template = cloner.Clone(original.template);
64      runs = cloner.Clone(original.runs);
65    }
66    public AlgorithmServiceNode()
67      : base("AlgorithmServiceNode") {
68      runs = new RunCollection();
69    }
70    public AlgorithmServiceNode(string name)
71      : base(name) {
72      runs = new RunCollection();
73    }
74    public AlgorithmServiceNode(string name, string description)
75      : base(name, description) {
76      runs = new RunCollection();
77    }
78
79    public override IDeepCloneable Clone(Cloner cloner) {
80      return new AlgorithmServiceNode(this, cloner);
81    }
82
83    private void UpdateParameter(IInputPort port) {
84      if (template != null) {
85        IParameter param = null;
86        if (template.Parameters.TryGetValue(port.Name, out param)) {
87          IValueParameter p = param as IValueParameter;
88          if ((p != null) && (port.Value != null)) {
89            p.Value = (IItem)port.Value;
90          }
91        }
92      }
93    }
94
95    protected virtual void Execute(ServiceParameterCollection parameters, CancellationToken token) {
96      if (Template == null) throw new InvalidOperationException("Template is null");
97
98      IAlgorithm algorithm;
99      lock (locker) {
100        algorithm = (IAlgorithm)Template.Clone();
101        waitHandles.Add(algorithm, new AutoResetEvent(false));
102      }
103
104      // set parameters
105      foreach (var p in parameters.Where(x => x.Type == ServiceParameterType.Input)) {
106        IParameter param = null;
107        if (algorithm.Parameters.TryGetValue(p.Name, out param)) {
108          var v = param as IValueParameter;
109          if (v != null) v.Value = p.Value;
110        }
111        if (algorithm.Problem.Parameters.TryGetValue(p.Name, out param)) {
112          var v = param as IValueParameter;
113          if (v != null) v.Value = p.Value;
114        }
115      }
116
117      algorithm.StoreAlgorithmInEachRun = false;
118      algorithm.Runs.Clear();
119      algorithm.Prepare();
120      algorithm.Stopped += Algorithm_Stopped;
121      algorithm.Start();
122      if (WaitHandle.WaitAny(new WaitHandle[] { waitHandles[algorithm], token.WaitHandle }) == 1) {
123        // retrieve results
124        foreach (var p in parameters.Where(x => x.Type == ServiceParameterType.Output)) {
125          IResult result = null;
126          if (algorithm.Results.TryGetValue(p.Name, out result)) {
127            p.Value = result.Value;
128          }
129        }
130
131        lock (locker) {
132          waitHandles[algorithm].Dispose();
133          waitHandles.Remove(algorithm);
134          Runs.Add(algorithm.Runs.ToArray()[0]);
135        }
136      } else {  // cancellation
137        algorithm.Stop();
138        lock (locker) {
139          waitHandles[algorithm].Dispose();
140          waitHandles.Remove(algorithm);
141        }
142      }
143    }
144
145    private void Algorithm_Stopped(object sender, EventArgs e) {
146      lock (locker) {
147        waitHandles[(IAlgorithm)sender].Set();
148      }
149    }
150
151    public event EventHandler TemplateChanged;
152    protected virtual void OnTemplateChanged() {
153      var handler = TemplateChanged;
154      if (handler != null) handler(this, EventArgs.Empty);
155    }
156
157    #region Ports Events
158    protected override void RegisterPortsEvents() {
159      base.RegisterPortsEvents();
160      foreach (var p in Ports)
161        RegisterPortEvents(p);
162    }
163    protected override void Ports_ItemsAdded(object sender, Collections.CollectionItemsChangedEventArgs<IPort> e) {
164      base.Ports_ItemsAdded(sender, e);
165      foreach (var p in e.Items)
166        RegisterPortEvents(p);
167    }
168    protected override void Ports_ItemsRemoved(object sender, Collections.CollectionItemsChangedEventArgs<IPort> e) {
169      base.Ports_ItemsRemoved(sender, e);
170      foreach (var p in e.Items)
171        DeregisterPortEvents(p);
172    }
173    protected override void Ports_ItemsReplaced(object sender, Collections.CollectionItemsChangedEventArgs<IPort> e) {
174      base.Ports_ItemsReplaced(sender, e);
175      foreach (var p in e.OldItems)
176        DeregisterPortEvents(p);
177      foreach (var p in e.Items)
178        RegisterPortEvents(p);
179    }
180    protected override void Ports_CollectionReset(object sender, Collections.CollectionItemsChangedEventArgs<IPort> e) {
181      base.Ports_CollectionReset(sender, e);
182      foreach (var p in e.OldItems)
183        DeregisterPortEvents(p);
184      foreach (var p in e.Items)
185        RegisterPortEvents(p);
186    }
187    #endregion
188
189    #region Port Events
190    private void RegisterPortEvents(IPort port) {
191      IInputPort i = port as IInputPort;
192      if (i != null) {
193        i.NameChanged += InputPort_NameChanged;
194        i.ValueChanged += InputPort_ValueChanged;
195        UpdateParameter(i);
196      }
197      IServicePort s = port as IServicePort;
198      if (s != null) {
199        s.ProcessParameters += ServicePort_ProcessParameters;
200      }
201    }
202
203    private void DeregisterPortEvents(IPort port) {
204      IInputPort i = port as IInputPort;
205      if (i != null) {
206        i.NameChanged -= InputPort_NameChanged;
207        i.ValueChanged -= InputPort_ValueChanged;
208      }
209      IServicePort s = port as IServicePort;
210      if (s != null) {
211        s.ProcessParameters -= ServicePort_ProcessParameters;
212      }
213    }
214    private void InputPort_NameChanged(object sender, EventArgs e) {
215      UpdateParameter((IInputPort)sender);
216    }
217    private void InputPort_ValueChanged(object sender, EventArgs e) {
218      UpdateParameter((IInputPort)sender);
219    }
220    private void ServicePort_ProcessParameters(object sender, EventArgs<ServiceParameterCollection, CancellationToken> e) {
221      Execute(e.Value, e.Value2);
222    }
223    #endregion
224  }
225}
Note: See TracBrowser for help on using the repository browser.