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

Last change on this file since 13969 was 13969, checked in by thasling, 5 years ago

#2615:
implemented migration strategies
log in HL now also logs exceptions of peers

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