Free cookie consent management tool by TermsFeed Policy Generator

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

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

#2205: Worked on optimization networks

File size: 7.3 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) {
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      waitHandles[algorithm].WaitOne();
123
124      // retrieve results
125      foreach (var p in parameters.Where(x => x.Type == ServiceParameterType.Output)) {
126        IResult result = null;
127        if (algorithm.Results.TryGetValue(p.Name, out result)) {
128          p.Value = result.Value;
129        }
130      }
131
132      lock (locker) {
133        waitHandles[algorithm].Dispose();
134        waitHandles.Remove(algorithm);
135        Runs.Add(algorithm.Runs.ToArray()[0]);
136      }
137    }
138
139    private void Algorithm_Stopped(object sender, EventArgs e) {
140      lock (locker) {
141        waitHandles[(IAlgorithm)sender].Set();
142      }
143    }
144
145    public event EventHandler TemplateChanged;
146    protected virtual void OnTemplateChanged() {
147      var handler = TemplateChanged;
148      if (handler != null) handler(this, EventArgs.Empty);
149    }
150
151    #region Ports Events
152    protected override void RegisterPortsEvents() {
153      base.RegisterPortsEvents();
154      foreach (var p in Ports)
155        RegisterPortEvents(p);
156    }
157    protected override void Ports_ItemsAdded(object sender, Collections.CollectionItemsChangedEventArgs<IPort> e) {
158      base.Ports_ItemsAdded(sender, e);
159      foreach (var p in e.Items)
160        RegisterPortEvents(p);
161    }
162    protected override void Ports_ItemsRemoved(object sender, Collections.CollectionItemsChangedEventArgs<IPort> e) {
163      base.Ports_ItemsRemoved(sender, e);
164      foreach (var p in e.Items)
165        DeregisterPortEvents(p);
166    }
167    protected override void Ports_ItemsReplaced(object sender, Collections.CollectionItemsChangedEventArgs<IPort> e) {
168      base.Ports_ItemsReplaced(sender, e);
169      foreach (var p in e.OldItems)
170        DeregisterPortEvents(p);
171      foreach (var p in e.Items)
172        RegisterPortEvents(p);
173    }
174    protected override void Ports_CollectionReset(object sender, Collections.CollectionItemsChangedEventArgs<IPort> e) {
175      base.Ports_CollectionReset(sender, e);
176      foreach (var p in e.OldItems)
177        DeregisterPortEvents(p);
178      foreach (var p in e.Items)
179        RegisterPortEvents(p);
180    }
181    #endregion
182
183    #region Port Events
184    private void RegisterPortEvents(IPort port) {
185      IInputPort i = port as IInputPort;
186      if (i != null) {
187        i.NameChanged += InputPort_NameChanged;
188        i.ValueChanged += InputPort_ValueChanged;
189        UpdateParameter(i);
190      }
191      IServicePort s = port as IServicePort;
192      if (s != null) {
193        s.Called += ServicePort_Called;
194      }
195    }
196
197    private void DeregisterPortEvents(IPort port) {
198      IInputPort i = port as IInputPort;
199      if (i != null) {
200        i.NameChanged -= InputPort_NameChanged;
201        i.ValueChanged -= InputPort_ValueChanged;
202      }
203      IServicePort s = port as IServicePort;
204      if (s != null) {
205        s.Called -= ServicePort_Called;
206      }
207    }
208    private void InputPort_NameChanged(object sender, EventArgs e) {
209      UpdateParameter((IInputPort)sender);
210    }
211    private void InputPort_ValueChanged(object sender, EventArgs e) {
212      UpdateParameter((IInputPort)sender);
213    }
214    private void ServicePort_Called(object sender, EventArgs<ServiceParameterCollection> e) {
215      Execute(e.Value);
216    }
217    #endregion
218  }
219}
Note: See TracBrowser for help on using the repository browser.