Free cookie consent management tool by TermsFeed Policy Generator

source: branches/OptimizationNetworks/HeuristicLab.Networks.IntegratedOptimization/3.3/OrchestratedAlgorithmNode.cs @ 14601

Last change on this file since 14601 was 14601, checked in by jkarder, 7 years ago

#2205: worked on optimization networks

  • created separate project for ttp optimization
  • removed some unused classes
File size: 7.1 KB
Line 
1using System;
2using System.Collections.Generic;
3using System.Linq;
4using System.Threading;
5using HeuristicLab.Common;
6using HeuristicLab.Core;
7using HeuristicLab.Core.Networks;
8using HeuristicLab.Data;
9using HeuristicLab.Operators;
10using HeuristicLab.Optimization;
11using HeuristicLab.Persistence.Default.CompositeSerializers.Storable;
12
13namespace HeuristicLab.Networks.IntegratedOptimization {
14  [Item("OrchestratedAlgorithmNode", "A node of a network which contains a HeuristicLab algorithm and can be orchestrated by an orchestrator.")]
15  [StorableClass]
16  public class OrchestratedAlgorithmNode : AlgorithmNode {
17    #region Constants
18    private const string OrchestrationPortName = "OrchestrationPort";
19    private const string EvaluationPortName = "EvaluationPort";
20    #endregion
21
22    private bool sendResultMessage = true;
23
24    #region Ports
25    public IMessagePort OrchestrationPort {
26      get { return (IMessagePort)Ports[OrchestrationPortName]; }
27    }
28    public IMessagePort EvaluationPort {
29      get { return (IMessagePort)Ports[EvaluationPortName]; }
30    }
31    #endregion
32
33    [Storable]
34    private IHookOperator evalHook;
35    public IHookOperator EvalHook {
36      get { return evalHook; }
37      set {
38        if (evalHook == value) return;
39        evalHook = value;
40        evalHook.Port = EvaluationPort;
41      }
42    }
43
44    [StorableConstructor]
45    protected OrchestratedAlgorithmNode(bool deserializing) : base(deserializing) { }
46    protected OrchestratedAlgorithmNode(OrchestratedAlgorithmNode original, Cloner cloner) : base(original, cloner) {
47      EvalHook = cloner.Clone(original.EvalHook);
48      RegisterEvents();
49    }
50    public OrchestratedAlgorithmNode() : this("OrchestratedAlgorithmNode") { }
51    public OrchestratedAlgorithmNode(string name) : base(name) {
52      var orchestrationPort = new MessagePort(OrchestrationPortName);
53      Ports.Add(orchestrationPort);
54
55      var evaluationPort = new MessagePort(EvaluationPortName);
56      Ports.Add(evaluationPort);
57
58      RegisterEvents();
59    }
60
61    public override IDeepCloneable Clone(Cloner cloner) {
62      return new OrchestratedAlgorithmNode(this, cloner);
63    }
64
65    [StorableHook(HookType.AfterDeserialization)]
66    private void AfterDeserialization() {
67      RegisterEvents();
68    }
69
70    private void RegisterEvents() {
71      OrchestrationPort.MessageReceived += OrchestrationPort_MessageReceived;
72    }
73
74    #region Port Events
75    private void OrchestrationPort_MessageReceived(object sender, EventArgs<IMessage, CancellationToken> e) {
76      var message = ((EnumValue<OrchestrationMessage>)e.Value["OrchestrationMessage"]).Value;
77
78      #region Prepare
79      if (message.HasFlag(OrchestrationMessage.Prepare)) {
80        switch (Algorithm.ExecutionState) {
81          case ExecutionState.Prepared:
82          case ExecutionState.Paused:
83          case ExecutionState.Stopped:
84            IMessageValue problemMsgVal;
85            if (e.Value.Values.TryGetValue("Problem", out problemMsgVal)) {
86              var prob = (IHeuristicOptimizationProblem)problemMsgVal.Value.Clone();
87
88              if (message.HasFlag(OrchestrationMessage.QualityAdaption)) {
89                var instEval = prob.Evaluator as InstrumentedOperator;
90                if (instEval != null && EvalHook != null) instEval.AfterExecutionOperators.Add(EvalHook);
91              }
92
93              IParameter analyzerParameter = null;
94              IMultiAnalyzer multiAnalyzer = null;
95              var checkedStates = new Dictionary<Type, bool>();
96              if (Algorithm.Parameters.TryGetValue("Analyzer", out analyzerParameter)) {
97                multiAnalyzer = analyzerParameter.ActualValue as IMultiAnalyzer;
98                foreach (var item in multiAnalyzer.Operators)
99                  checkedStates.Add(item.GetType(), multiAnalyzer.Operators.ItemChecked(item));
100              }
101
102              Algorithm.Problem = prob;
103
104              if (multiAnalyzer != null) {
105                if (Algorithm.Parameters.TryGetValue("Analyzer", out analyzerParameter)) {
106                  multiAnalyzer = analyzerParameter.ActualValue as IMultiAnalyzer;
107                  if (multiAnalyzer != null && checkedStates.Any()) {
108                    foreach (var analyzer in multiAnalyzer.Operators) {
109                      bool checkedState;
110                      if (!checkedStates.TryGetValue(analyzer.GetType(), out checkedState))
111                        checkedState = analyzer.EnabledByDefault;
112                      multiAnalyzer.Operators.SetItemCheckedState(analyzer, checkedState);
113                    }
114                  }
115                }
116              }
117
118              Algorithm.Prepare();
119            }
120            break;
121        }
122      }
123      #endregion
124
125      #region Start
126      if (message.HasFlag(OrchestrationMessage.Start)) {
127        switch (Algorithm.ExecutionState) {
128          case ExecutionState.Prepared:
129          case ExecutionState.Paused:
130            var trigger = new ManualResetEvent(false);
131            Exception ex = null;
132
133            EventHandler onStopped = null;
134            EventHandler<EventArgs<Exception>> onExceptionOccurred = null;
135            Algorithm.Stopped += onStopped = (src, args) => {
136              Algorithm.Stopped -= onStopped;
137              Algorithm.ExceptionOccurred -= onExceptionOccurred;
138              trigger.Set();
139            };
140            Algorithm.ExceptionOccurred += onExceptionOccurred = (src, args) => {
141              Algorithm.Stopped -= onStopped;
142              Algorithm.ExceptionOccurred -= onExceptionOccurred;
143              ex = args.Value;
144              trigger.Set();
145            };
146
147            Algorithm.Start();
148            trigger.WaitOne();
149
150            if (ex != null) throw ex;
151
152            if (sendResultMessage) {
153              var msg = OrchestrationPort.PrepareMessage();
154              msg["Results"] = (ResultCollection)Algorithm.Results.Clone();
155              OrchestrationPort.SendMessage(msg);
156            } else sendResultMessage = true;
157            break;
158        }
159      }
160      #endregion
161
162      #region Pause
163      if (message.HasFlag(OrchestrationMessage.Pause)) {
164        if (Algorithm.ExecutionState == ExecutionState.Started) {
165          sendResultMessage = false;
166          try {
167            Algorithm.Pause();
168          } catch (InvalidOperationException) {
169            // ExecutionState might have changed since we accepted the message
170          }
171        }
172      }
173      #endregion
174
175      #region Stop
176      if (message.HasFlag(OrchestrationMessage.Stop)) {
177        switch (Algorithm.ExecutionState) {
178          case ExecutionState.Started:
179          case ExecutionState.Paused:
180            try {
181              Algorithm.Stop();
182            } catch (InvalidOperationException) {
183              // ExecutionState might have changed since we accepted the message
184            } catch (NullReferenceException) {
185              // BasicAlgorithm might have stopped since we accepted the message
186              // CancellationTokenSource is null in this case
187            }
188            break;
189        }
190      }
191      #endregion
192    }
193    #endregion
194  }
195}
Note: See TracBrowser for help on using the repository browser.