Free cookie consent management tool by TermsFeed Policy Generator

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

Last change on this file since 14019 was 14019, checked in by thasling, 7 years ago

#2615:
added jobguid as parameter, so it can be accesed from outside the analyzer

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