source: branches/thasling/DistributedGA/DistributedGA.Hive/P2PMigrationAnalyzer.cs @ 14033

Last change on this file since 14033 was 14033, checked in by gkronber, 5 years ago

#2615: fixed the problem where an exception occurred in object graph traversal when an algorithm is stopped

File size: 12.8 KB
Line 
1#region License Information
2/* HeuristicLab
3 * Copyright (C) 2002-2015 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 System;
23using System.Collections;
24using System.Collections.Generic;
25using System.IO;
26using System.Linq;
27using DistributedGA.Core.Domain;
28using DistributedGA.Core.Implementation;
29using DistributedGA.Core.Interface;
30using DistributedGA.Hive;
31using HeuristicLab.Common;
32using HeuristicLab.Core;
33using HeuristicLab.Data;
34using HeuristicLab.Operators;
35using HeuristicLab.Parameters;
36using HeuristicLab.Persistence.Default.CompositeSerializers.Storable;
37
38namespace HeuristicLab.Optimization.Operators {
39  [Item("P2PMigrationAnalyzer", "Migrates individuals using a P2P network.")]
40  [StorableClass]
41  public class P2PMigrationAnalyzer : SingleSuccessorOperator, IAnalyzer, ISingleObjectiveOperator {
42    // state: messagehandler
43    [ExcludeFromObjectGraphTraversalAttribute]
44    private IMessageHandler h;
45
46    public bool EnabledByDefault { get { return false; } }
47
48    public ILookupParameter<BoolValue> MaximizationParameter {
49      get { return (ILookupParameter<BoolValue>)Parameters["Maximization"]; }
50    }
51    // for name translation
52    public ScopeTreeLookupParameter<DoubleValue> QualityParameter {
53      get { return (ScopeTreeLookupParameter<DoubleValue>)Parameters["Quality"]; }
54    }
55    public ILookupParameter<IntValue> MigrationIterationsParameter {
56      get { return (ILookupParameter<IntValue>)Parameters["MigrationIterations"]; }
57    }
58    public ILookupParameter<PercentValue> MigrationRatesParameter {
59      get { return (ILookupParameter<PercentValue>)Parameters["MigrationRate"]; }
60    }
61    public ILookupParameter<PercentValue> CommunicationRatesParameter {
62      get { return (ILookupParameter<PercentValue>)Parameters["CommunicationRate"]; }
63    }
64    public ILookupParameter<IntValue> MessageCacheCapacityParameter {
65      get { return (ILookupParameter<IntValue>)Parameters["MessageCacheCapacity"]; }
66    }
67    public ILookupParameter<IRandom> RandomParameter {
68      get { return (ILookupParameter<IRandom>)Parameters["Random"]; }
69    }
70    public IValueParameter<IntValue> MigrationIntervalParameter {
71      get { return (IValueParameter<IntValue>)Parameters["MigrationInterval"]; }
72    }
73    public IValueParameter<ILog> LogParameter {
74      get { return (IValueParameter<ILog>)Parameters["Log"]; }
75    }
76    public ILookupParameter<StringValue> JobGuidParameter {
77      get { return (ILookupParameter<StringValue>)Parameters["JobGUID"]; }
78    }
79
80    public IConstrainedValueParameter<EnumValue<MigrationStrategy>> MigrationStrategySelectParameter {
81      get { return (IConstrainedValueParameter<EnumValue<MigrationStrategy>>)Parameters["MigrationStrategySelect"]; }
82    }
83
84    public IConstrainedValueParameter<EnumValue<MigrationStrategy>> MigrationStrategyReplaceParameter {
85      get { return (IConstrainedValueParameter<EnumValue<MigrationStrategy>>)Parameters["MigrationStrategyReplace"]; }
86    }
87
88    public BoolValue Maximization {
89      get { return MaximizationParameter.ActualValue; }
90    }
91    public IntValue MigrationIterations {
92      get { return MigrationIterationsParameter.ActualValue; }
93    }
94
95    public IntValue MigrationInterval {
96      get { return MigrationIntervalParameter.Value; }
97    }
98
99    public IRandom Random {
100      get { return RandomParameter.ActualValue; }
101    }
102
103    [StorableConstructor]
104    protected P2PMigrationAnalyzer(bool deserializing) : base(deserializing) { }
105    protected P2PMigrationAnalyzer(P2PMigrationAnalyzer original, Cloner cloner) : base(original, cloner) { }
106
107    public P2PMigrationAnalyzer()
108      : base() {
109      Parameters.Add(new LookupParameter<IntValue>("MigrationIterations"));
110      Parameters.Add(new LookupParameter<BoolValue>("Maximization"));
111      Parameters.Add(new ScopeTreeLookupParameter<DoubleValue>("Quality", 1));
112      Parameters.Add(new ValueParameter<IntValue>("MigrationInterval", "", new IntValue(5)));
113      Parameters.Add(new ValueParameter<PercentValue>("MigrationRate", "", new PercentValue(0.05)));
114      Parameters.Add(new ValueParameter<PercentValue>("CommunicationRate", "", new PercentValue(0.10)));
115      Parameters.Add(new ValueParameter<IntValue>("MessageCacheCapacity", "", new IntValue(1000)));
116      Parameters.Add(new ValueParameter<StringValue>("LanIpPrefix", "", new StringValue("10.")));
117      Parameters.Add(new LookupParameter<IRandom>("Random", "The random number generator"));
118      Parameters.Add(new ValueParameter<StringValue>("ContactServerURL", "", new StringValue("net.tcp://10.42.1.150:9090/DistributedGA.ContactServer/ContactService")));
119      Parameters.Add(new ValueParameter<StringValue>("JobGUID", "", new StringValue(Guid.NewGuid().ToString())));
120      Parameters.Add(new ValueParameter<ILog>("Log", "The log", new Log(1000)));
121
122      var validValues = new ItemSet<EnumValue<MigrationStrategy>>();
123      validValues.Add(new EnumValue<MigrationStrategy>(MigrationStrategy.Best));
124      validValues.Add(new EnumValue<MigrationStrategy>(MigrationStrategy.Worst));
125      validValues.Add(new EnumValue<MigrationStrategy>(MigrationStrategy.Random));
126      Parameters.Add(new ConstrainedValueParameter<EnumValue<MigrationStrategy>>("MigrationStrategySelect", validValues, (new EnumValue<MigrationStrategy>(MigrationStrategy.Random))));
127      Parameters.Add(new ConstrainedValueParameter<EnumValue<MigrationStrategy>>("MigrationStrategyReplace", validValues, (new EnumValue<MigrationStrategy>(MigrationStrategy.Random))));
128
129    }
130
131    public override IDeepCloneable Clone(Cloner cloner) {
132      return new P2PMigrationAnalyzer(this, cloner);
133    }
134
135    public override void ClearState() {
136      base.ClearState();
137      h.Dispose();
138      h = null;
139    }
140
141    private void Init() {
142      h = new PeerNetworkMessageHandler();
143      var lanIpPrefix = ((StringValue)(Parameters["LanIpPrefix"].ActualValue)).Value;
144      var contactServerUri = ((StringValue)(Parameters["ContactServerURL"].ActualValue)).Value;
145      var problemInstance = ((StringValue)Parameters["JobGUID"].ActualValue).Value;
146      var communicationRate = ((PercentValue)Parameters["CommunicationRate"].ActualValue).Value;
147      var messageCacheCapacity = ((IntValue)Parameters["MessageCacheCapacity"].ActualValue).Value;
148      h.Init(lanIpPrefix, contactServerUri, problemInstance, (int)(100 * messageCacheCapacity), (int)(100 * communicationRate));
149      h.ExceptionOccurend += ExceptionThrown;
150    }
151
152    public override IOperation Apply() {
153      if (h == null) {
154        Init();
155      }
156
157      if (MigrationIterationsParameter.ActualValue == null) {
158        MigrationIterationsParameter.ActualValue = new IntValue(0);
159      }
160
161      if (MigrationIterations.Value % MigrationInterval.Value == 0) {
162
163        IScope scope = ExecutionContext.Scope;
164        List<IScope> emigrantsList = new List<IScope>();
165
166        //define how many migrants to send
167        var migrationRate = ((PercentValue)Parameters["MigrationRate"].ActualValue).Value;
168        int noOfEmigrants = Convert.ToInt32(scope.SubScopes.Count * migrationRate);
169        if (noOfEmigrants == 0 && scope.SubScopes.Count > 0) {
170          noOfEmigrants = 1;
171        }
172        var popQualities = QualityParameter.ActualValue;
173        var pop = new List<IScope>(scope.SubScopes);
174
175        List<IScope> sortedPop;
176        if (Maximization.Value) {
177          sortedPop = pop.Zip(popQualities, Tuple.Create).OrderByDescending(t => t.Item2).Select(t => t.Item1).ToList();
178        } else {
179          sortedPop = pop.Zip(popQualities, Tuple.Create).OrderBy(t => t.Item2).Select(t => t.Item1).ToList();
180        }
181
182        var selectedMigStratSelect = MigrationStrategySelectParameter.Value.Value;
183        var selectedMigStratReplace = MigrationStrategyReplaceParameter.Value.Value;
184
185        var rand = Random;
186        int replIdx = 0;
187        IScope emigrants = null;
188
189        for (int i = 0; i < noOfEmigrants; i++) {
190          //select emigrant depending on strategy
191          switch (selectedMigStratSelect) {
192            case MigrationStrategy.Best:
193              emigrants = sortedPop[i];
194              emigrantsList.Add(emigrants);
195              break;
196
197            case MigrationStrategy.Random:
198              replIdx = rand.Next(sortedPop.Count);
199              emigrants = sortedPop[replIdx];
200              emigrantsList.Add(emigrants);
201              break;
202
203            case MigrationStrategy.Worst:
204              emigrants = sortedPop[scope.SubScopes.Count - i - 1];
205              emigrantsList.Add(emigrants);
206              break;
207          }
208        }
209
210        {
211          // send
212          for (int ei = 0; ei < emigrantsList.Count; ei++) {
213            using (var stream = new MemoryStream()) {
214              byte[] message;
215              var emigrantScope = emigrantsList[ei];
216
217              var msgScope = new Scope();
218              var cloner = new Cloner();
219              foreach (var variable in emigrantScope.Variables) {
220                msgScope.Variables.Add((IVariable)variable.Clone(cloner));
221              }
222              HeuristicLab.Persistence.Default.Xml.XmlGenerator.Serialize(msgScope, stream);
223              message = stream.GetBuffer();
224              h.PublishDataToNetwork(message);
225            }
226          }
227        }
228
229
230        {
231          // recieve
232          var message = h.GetDataFromNetwork();
233          List<KeyValuePair<PeerInfo, byte[]>> immigrants = new List<KeyValuePair<PeerInfo, byte[]>>();
234          //limit number of immigrants to use
235          if(noOfEmigrants < message.Count)
236          {
237            immigrants = message.Skip(Math.Max(0, message.Count() - noOfEmigrants)).ToList();
238          } else {
239            immigrants = message;
240          }
241         
242          // remove individuals from population to make place for immigrants
243          for (int i = 0; i < immigrants.Count; i++) {
244            switch (selectedMigStratReplace) {
245              case MigrationStrategy.Best:
246                scope.SubScopes.Remove(sortedPop[0]);
247                sortedPop.RemoveAt(0);
248                break;
249
250              case MigrationStrategy.Random:
251                replIdx = rand.Next(sortedPop.Count);
252                scope.SubScopes.Remove(sortedPop[replIdx]);
253                sortedPop.RemoveAt(replIdx);
254                break;
255
256              case MigrationStrategy.Worst:
257                //replace random
258                scope.SubScopes.Remove(sortedPop[sortedPop.Count - 1]);
259                sortedPop.RemoveAt(sortedPop.Count - 1);
260                break;
261            }
262          }
263
264          //insert individual sorted in population
265          var qualities = QualityParameter.ActualValue;
266          var qualityTranslatedName = QualityParameter.TranslatedName;
267          foreach (var msg in immigrants) {
268            using (var stream = new MemoryStream(msg.Value)) {
269              var immigrantScope = HeuristicLab.Persistence.Default.Xml.XmlParser.Deserialize<IScope>(stream);
270
271              var qImmigrant = ((DoubleValue)immigrantScope.Variables[qualityTranslatedName].Value).Value;
272              var insertPos = scope.SubScopes.Count;
273              var maximization = Maximization.Value;
274              for (int i = 0; i < qualities.Length; i++) {
275                var qi = qualities[i].Value;
276                if ((maximization && qi < qImmigrant) || (!maximization && qi > qImmigrant)) {
277                  insertPos = i;
278                  break;
279                }
280              }
281
282              scope.SubScopes.Insert(insertPos, immigrantScope);
283
284              var log = LogParameter.Value;
285              double quality = qImmigrant;
286              log.LogMessage(string.Format("Recieved individual with quality {0} from peer {1}:{2} ; Job: {3}",
287                                            quality, msg.Key.IpAddress, msg.Key.Port, msg.Key.ProblemInstance));
288            }
289          }
290        }
291      }
292
293      MigrationIterations.Value++;
294      return base.Apply();
295    }
296
297    private void ExceptionThrown(object sender, Exception e) {
298      var log = LogParameter.Value;
299      log.LogMessage(e.Message);
300    }
301
302  }
303}
Note: See TracBrowser for help on using the repository browser.