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
RevLine 
[11406]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;
[11526]24using HeuristicLab.Core.Networks;
[11554]25using HeuristicLab.Operators;
[11577]26using HeuristicLab.Optimization;
[11406]27using HeuristicLab.Persistence.Default.CompositeSerializers.Storable;
[11409]28using System;
[11519]29using System.Collections.Generic;
30using System.Linq;
31using System.Threading;
[11406]32
[11577]33namespace HeuristicLab.Networks {
[11406]34  [Item("AlgorithmNode", "A node of an optimization network which contains a HeuristicLab algorithm.")]
35  [StorableClass]
[11409]36  public class AlgorithmNode : Node, IAlgorithmNode {
[11519]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
[11409]41    new public PortCollection Ports {
42      get { return base.Ports; }
43    }
44
[11406]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
[11519]57    [Storable]
58    private RunCollection runs;
59    public RunCollection Runs {
60      get { return runs; }
61    }
62
[11406]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);
[11519]68      runs = cloner.Clone(original.runs);
[11406]69    }
[11519]70    public AlgorithmNode()
71      : base("AlgorithmNode") {
72      runs = new RunCollection();
[11406]73    }
[11519]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    }
[11406]82
83    public override IDeepCloneable Clone(Cloner cloner) {
84      return new AlgorithmNode(this, cloner);
85    }
86
[11519]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            }
[11406]101          }
102        }
103      }
104    }
[11519]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) {
[11554]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);
[11519]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;
[11406]126        }
[11519]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        }
[11406]131      }
[11519]132
133      algorithm.StoreAlgorithmInEachRun = false;
[11529]134      algorithm.Prepare(true);
[11519]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;
[11409]151        }
152      }
[11519]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      }
[11409]166    }
[11406]167
[11519]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
[11406]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
[11423]188    protected override void RegisterPortsEvents() {
189      base.RegisterPortsEvents();
[11409]190      foreach (var p in Ports)
191        RegisterPortEvents(p);
[11406]192    }
[11423]193    protected override void Ports_ItemsAdded(object sender, Collections.CollectionItemsChangedEventArgs<IPort> e) {
194      base.Ports_ItemsAdded(sender, e);
[11406]195      foreach (var p in e.Items)
196        RegisterPortEvents(p);
197    }
[11423]198    protected override void Ports_ItemsRemoved(object sender, Collections.CollectionItemsChangedEventArgs<IPort> e) {
199      base.Ports_ItemsRemoved(sender, e);
[11406]200      foreach (var p in e.Items)
201        DeregisterPortEvents(p);
202    }
[11423]203    protected override void Ports_ItemsReplaced(object sender, Collections.CollectionItemsChangedEventArgs<IPort> e) {
204      base.Ports_ItemsReplaced(sender, e);
[11406]205      foreach (var p in e.OldItems)
206        DeregisterPortEvents(p);
207      foreach (var p in e.Items)
208        RegisterPortEvents(p);
209    }
[11423]210    protected override void Ports_CollectionReset(object sender, Collections.CollectionItemsChangedEventArgs<IPort> e) {
211      base.Ports_CollectionReset(sender, e);
[11406]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) {
[11519]221      IConfigurationPort c = port as IConfigurationPort;
222      if (c != null) {
223        c.MessageReceived += ConfigurationPort_MessageReceived;
[11406]224      }
[11519]225      IExecutionPort e = port as IExecutionPort;
226      if (e != null) {
227        e.MessageReceived += ExecutionPort_MessageReceived;
[11409]228      }
[11406]229    }
230    private void DeregisterPortEvents(IPort port) {
[11519]231      IConfigurationPort c = port as IConfigurationPort;
232      if (c != null) {
233        c.MessageReceived -= ConfigurationPort_MessageReceived;
[11406]234      }
[11519]235      IExecutionPort e = port as IExecutionPort;
236      if (e != null) {
237        e.MessageReceived -= ExecutionPort_MessageReceived;
[11409]238      }
[11406]239    }
[11519]240    protected virtual void ConfigurationPort_MessageReceived(object sender, EventArgs<IMessage, CancellationToken> e) {
241      Configure((IConfigurationPort)sender, e.Value, e.Value2);
[11409]242    }
[11519]243    protected virtual void ExecutionPort_MessageReceived(object sender, EventArgs<IMessage, CancellationToken> e) {
244      Execute((IExecutionPort)sender, e.Value, e.Value2);
[11406]245    }
246    #endregion
247  }
248}
Note: See TracBrowser for help on using the repository browser.