Free cookie consent management tool by TermsFeed Policy Generator

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

Last change on this file since 11463 was 11463, checked in by swagner, 10 years ago

#2205: Worked on optimization networks

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