Free cookie consent management tool by TermsFeed Policy Generator

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

Last change on this file since 13970 was 13970, checked in by thasling, 8 years ago

#2615:
made minor changes

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        int noOfEmigrants = Convert.ToInt32(scope.SubScopes.Count * migrationRate);
168        if (noOfEmigrants == 0 && scope.SubScopes.Count > 0) {
169          noOfEmigrants = 0;
170        }
171        var popQualities = QualityParameter.ActualValue;
172        var selectedMigStrat = MigrationStrategyParameter.Value.Value;
173
174        var rand = Random;
175        int replIdx = 0;
176        IScope emigrants = null;
177
178        for (int i = 0; i < noOfEmigrants; i++) {
179          //select emigrant depending on strategy
180          switch (selectedMigStrat) {
181            case MigrationStrategy.TakeBestReplaceBad:
182              emigrants = scope.SubScopes[i];
183              emigrantsList.Add(emigrants);
184              break;
185
186            case MigrationStrategy.TakeBestReplaceRandom:
187              emigrants = scope.SubScopes[i];
188              emigrantsList.Add(emigrants);
189              break;
190
191            case MigrationStrategy.TakeRandomReplaceBad:
192              replIdx = rand.Next(scope.SubScopes.Count);
193              emigrants = scope.SubScopes[replIdx];
194              emigrantsList.Add(emigrants);
195              break;
196
197            case MigrationStrategy.TakeRandomReplaceRandom:
198              replIdx = rand.Next(scope.SubScopes.Count);
199              emigrants = scope.SubScopes[replIdx];
200              emigrantsList.Add(emigrants);
201              break;
202
203            default:
204              break;
205          }
206        }
207        //each subscope is one emigrand
208        //IScope emigrants = scope.SubScopes[1];
209        //emigrantsList.Add(emigrants);
210
211        {
212          // send
213          var message = new byte[emigrantsList.Count][];
214          for (int ei = 0; ei < emigrantsList.Count; ei++) {
215            using (var stream = new MemoryStream()) {
216              var emigrantScope = emigrantsList[ei];
217
218              var msgScope = new Scope();
219              var cloner = new Cloner();
220              foreach (var variable in emigrantScope.Variables) {
221                msgScope.Variables.Add((IVariable)variable.Clone(cloner));
222              }
223              msgScope.ClearParentScopes();
224              HeuristicLab.Persistence.Default.Xml.XmlGenerator.Serialize(msgScope, stream);
225              message[ei] = stream.GetBuffer();
226            }
227          }
228          h.PublishDataToNetwork(message);
229        }
230
231
232        {
233          // recieve
234          var message = h.GetDataFromNetwork();
235          for (int ei = 0; ei < message.Length; ei++) {
236            using (var stream = new MemoryStream(message[ei])) {
237              var immigrantScope = HeuristicLab.Persistence.Default.Xml.XmlParser.Deserialize<IScope>(stream);
238
239              // replace individual in current population
240              switch (selectedMigStrat) {
241                case MigrationStrategy.TakeBestReplaceBad:
242                  scope.SubScopes.RemoveAt(0);
243                  break;
244
245                case MigrationStrategy.TakeRandomReplaceBad:
246                  scope.SubScopes.RemoveAt(0);
247                  break;
248
249                case MigrationStrategy.TakeBestReplaceRandom:
250                  //replace random
251                  replIdx = rand.Next(scope.SubScopes.Count);
252                  scope.SubScopes.RemoveAt(replIdx);
253                  break;
254
255                case MigrationStrategy.TakeRandomReplaceRandom:
256                  //replace random
257                  replIdx = rand.Next(scope.SubScopes.Count);
258                  scope.SubScopes.RemoveAt(replIdx);
259                  break;
260
261                default:
262                  break;
263              }
264
265              //insert individual sortet in population
266              var qualities = QualityParameter.ActualValue;
267              var qualityTranslatedName = QualityParameter.TranslatedName;
268              var qImmigrant = ((DoubleValue)immigrantScope.Variables[qualityTranslatedName].Value).Value;
269              var insertPos = scope.SubScopes.Count;
270              var maximization = Maximization.Value;
271              for (int i = 0; i < qualities.Length; i++) {
272                var qi = qualities[i].Value;
273                if ((maximization && qi < qImmigrant) || (!maximization && qi > qImmigrant)) {
274                  insertPos = i;
275                  break;
276                }
277              }
278
279              scope.SubScopes.Insert(insertPos, immigrantScope);
280
281              var log = LogParameter.Value;
282              double quality = 0.0;
283              quality = qImmigrant;
284              log.LogMessage(string.Format("Recieved individual with quality {0}", quality));
285            }
286          }
287        }
288      }
289
290      MigrationIterations.Value++;
291      return base.Apply();
292    }
293
294    private void ExceptionThrown(object sender, Exception e) {
295      var log = LogParameter.Value;
296      log.LogMessage(e.Message);
297    }
298
299  }
300}
Note: See TracBrowser for help on using the repository browser.