Free cookie consent management tool by TermsFeed Policy Generator

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

Last change on this file since 13997 was 13997, checked in by gkronber, 8 years ago

#2615 removed initState override and updated references to trunk

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