Free cookie consent management tool by TermsFeed Policy Generator

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

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

#2615:
made minor changes,
wrong commit happende last time, so still tbd:
-sort List
-dispose of anaylzer is never called

File size: 11.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.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>> MigrationStrategySelectParameter {
75      get { return (IConstrainedValueParameter<EnumValue<MigrationStrategy>>)Parameters["MigrationStrategySelect"]; }
76    }
77
78    public IConstrainedValueParameter<EnumValue<MigrationStrategy>> MigrationStrategyReplaceParameter {
79      get { return (IConstrainedValueParameter<EnumValue<MigrationStrategy>>)Parameters["MigrationStrategyReplace"]; }
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(5)));
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(1000)));
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.Best));
118      validValues.Add(new EnumValue<MigrationStrategy>(MigrationStrategy.Worst));
119      validValues.Add(new EnumValue<MigrationStrategy>(MigrationStrategy.Random));
120      Parameters.Add(new ConstrainedValueParameter<EnumValue<MigrationStrategy>>("MigrationStrategySelect", validValues, (new EnumValue<MigrationStrategy>(MigrationStrategy.Random))));
121      Parameters.Add(new ConstrainedValueParameter<EnumValue<MigrationStrategy>>("MigrationStrategyReplace", validValues, (new EnumValue<MigrationStrategy>(MigrationStrategy.Random))));
122
123    }
124
125    public override IDeepCloneable Clone(Cloner cloner) {
126      return new P2PMigrationAnalyzer(this, cloner);
127    }
128
129    private void Init() {
130      h = new PeerNetworkMessageHandler();
131      var lanIpPrefix = ((StringValue)(Parameters["LanIpPrefix"].ActualValue)).Value;
132      var contactServerUri = ((StringValue)(Parameters["ContactServerURL"].ActualValue)).Value;
133      var problemInstance = ((StringValue)Parameters["JobGUID"].ActualValue).Value;
134      var communicationRate = ((PercentValue)Parameters["CommunicationRate"].ActualValue).Value;
135      var messageCacheCapacity = ((IntValue)Parameters["MessageCacheCapacity"].ActualValue).Value;
136      h.Init(lanIpPrefix, contactServerUri, problemInstance, (int)(100 * messageCacheCapacity), (int)(100 * communicationRate));
137      h.ExceptionOccurend += ExceptionThrown;
138    }
139
140    public override IOperation Apply() {
141      if (h == null) {
142        Init();
143        //TODO: sort population
144
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 selectedMigStratSelect = MigrationStrategySelectParameter.Value.Value;
163        var selectedMigStratReplace = MigrationStrategyReplaceParameter.Value.Value;
164
165        var rand = Random;
166        int replIdx = 0;
167        IScope emigrants = null;
168
169        for (int i = 0; i < noOfEmigrants; i++) {
170          //select emigrant depending on strategy
171          switch (selectedMigStratSelect) {
172            case MigrationStrategy.Best:
173              emigrants = scope.SubScopes[i];
174              emigrantsList.Add(emigrants);
175              break;
176
177            case MigrationStrategy.Random:
178              replIdx = rand.Next(scope.SubScopes.Count);
179              emigrants = scope.SubScopes[replIdx];
180              emigrantsList.Add(emigrants);
181              break;
182
183            case MigrationStrategy.Worst:
184              emigrants = scope.SubScopes[scope.SubScopes.Count - i];
185              emigrantsList.Add(emigrants);
186              break;
187
188
189            default:
190              break;
191          }
192        }
193
194        {
195          // send
196          for (int ei = 0; ei < emigrantsList.Count; ei++) {
197            using (var stream = new MemoryStream()) {
198              byte[] message;
199              var emigrantScope = emigrantsList[ei];
200
201              var msgScope = new Scope();
202              var cloner = new Cloner();
203              foreach (var variable in emigrantScope.Variables) {
204                msgScope.Variables.Add((IVariable)variable.Clone(cloner));
205              }
206              HeuristicLab.Persistence.Default.Xml.XmlGenerator.Serialize(msgScope, stream);
207              message = stream.GetBuffer();
208              h.PublishDataToNetwork(message);
209
210            }
211          }
212        }
213
214
215        {
216          // recieve
217          var message = h.GetDataFromNetwork();
218          //for (int ei = 0; ei < message.Length; ei++) {
219          foreach (var msg in message) {
220            using (var stream = new MemoryStream(msg.Value)) {
221              var immigrantScope = HeuristicLab.Persistence.Default.Xml.XmlParser.Deserialize<IScope>(stream);
222
223              // replace individual in current population
224              switch (selectedMigStratReplace) {
225                case MigrationStrategy.Best:
226                  scope.SubScopes.RemoveAt(0);
227                  break;
228
229                case MigrationStrategy.Random:
230                  replIdx = rand.Next(scope.SubScopes.Count);
231                  scope.SubScopes.RemoveAt(replIdx);
232                  break;
233
234                case MigrationStrategy.Worst:
235                  //replace random
236                  scope.SubScopes.RemoveAt(scope.SubScopes.Count);
237                  break;
238
239                default:
240                  break;
241              }
242
243              //insert individual sortet in population
244              var qualities = QualityParameter.ActualValue;
245              var qualityTranslatedName = QualityParameter.TranslatedName;
246              var qImmigrant = ((DoubleValue)immigrantScope.Variables[qualityTranslatedName].Value).Value;
247              var insertPos = scope.SubScopes.Count;
248              var maximization = Maximization.Value;
249              for (int i = 0; i < qualities.Length; i++) {
250                var qi = qualities[i].Value;
251                if ((maximization && qi < qImmigrant) || (!maximization && qi > qImmigrant)) {
252                  insertPos = i;
253                  break;
254                }
255              }
256
257              scope.SubScopes.Insert(insertPos, immigrantScope);
258
259              var log = LogParameter.Value;
260              double quality = 0.0;
261              quality = qImmigrant;
262              log.LogMessage(string.Format("Recieved individual with quality {0} from peer {1}:{2} ; Job: {3}",
263                                            quality, msg.Key.IpAddress, msg.Key.Port, msg.Key.ProblemInstance));
264            }
265          }
266        }
267      }
268
269      MigrationIterations.Value++;
270      return base.Apply();
271    }
272
273    private void ExceptionThrown(object sender, Exception e) {
274      var log = LogParameter.Value;
275      log.LogMessage(e.Message);
276    }
277
278  }
279}
Note: See TracBrowser for help on using the repository browser.