Free cookie consent management tool by TermsFeed Policy Generator

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

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

#2615:
added IDisposable to classes with Dispose()-Method

File size: 12.8 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, IDisposable {
42    // state: messagehandler
43    [ExcludeFromObjectGraphTraversalAttribute]
44    private IMessageHandler h;
45
46    public bool EnabledByDefault { get { return false; } }
47
48    public ILookupParameter<BoolValue> MaximizationParameter {
49      get { return (ILookupParameter<BoolValue>)Parameters["Maximization"]; }
50    }
51    // for name translation
52    public ScopeTreeLookupParameter<DoubleValue> QualityParameter {
53      get { return (ScopeTreeLookupParameter<DoubleValue>)Parameters["Quality"]; }
54    }
55    public ILookupParameter<IntValue> MigrationIterationsParameter {
56      get { return (ILookupParameter<IntValue>)Parameters["MigrationIterations"]; }
57    }
58    public IValueParameter<PercentValue> MigrationRatesParameter {
59      get { return (IValueParameter<PercentValue>)Parameters["MigrationRate"]; }
60    }
61    public IValueParameter<PercentValue> CommunicationRatesParameter {
62      get { return (IValueParameter<PercentValue>)Parameters["CommunicationRate"]; }
63    }
64    public IValueParameter<IntValue> MessageCacheCapacityParameter {
65      get { return (IValueParameter<IntValue>)Parameters["MessageCacheCapacity"]; }
66    }
67    public ILookupParameter<IRandom> RandomParameter {
68      get { return (ILookupParameter<IRandom>)Parameters["Random"]; }
69    }
70    public IValueParameter<IntValue> MigrationIntervalParameter {
71      get { return (IValueParameter<IntValue>)Parameters["MigrationInterval"]; }
72    }
73    public IValueParameter<ILog> LogParameter {
74      get { return (IValueParameter<ILog>)Parameters["Log"]; }
75    }
76    public IValueParameter<StringValue> JobGuidParameter {
77      get { return (IValueParameter<StringValue>)Parameters["JobGUID"]; }
78    }
79
80    public IConstrainedValueParameter<EnumValue<MigrationStrategy>> MigrationStrategySelectParameter {
81      get { return (IConstrainedValueParameter<EnumValue<MigrationStrategy>>)Parameters["MigrationStrategySelect"]; }
82    }
83
84    public IConstrainedValueParameter<EnumValue<MigrationStrategy>> MigrationStrategyReplaceParameter {
85      get { return (IConstrainedValueParameter<EnumValue<MigrationStrategy>>)Parameters["MigrationStrategyReplace"]; }
86    }
87
88    public BoolValue Maximization {
89      get { return MaximizationParameter.ActualValue; }
90    }
91    public IntValue MigrationIterations {
92      get { return MigrationIterationsParameter.ActualValue; }
93    }
94
95    public IntValue MigrationInterval {
96      get { return MigrationIntervalParameter.Value; }
97    }
98
99    public IRandom Random {
100      get { return RandomParameter.ActualValue; }
101    }
102
103    [StorableConstructor]
104    protected P2PMigrationAnalyzer(bool deserializing) : base(deserializing) { }
105    protected P2PMigrationAnalyzer(P2PMigrationAnalyzer original, Cloner cloner) : base(original, cloner) { }
106
107    public P2PMigrationAnalyzer()
108      : base() {
109      Parameters.Add(new LookupParameter<IntValue>("MigrationIterations"));
110      Parameters.Add(new LookupParameter<BoolValue>("Maximization"));
111      Parameters.Add(new ScopeTreeLookupParameter<DoubleValue>("Quality", 1));
112      Parameters.Add(new ValueParameter<IntValue>("MigrationInterval", "", new IntValue(5)));
113      Parameters.Add(new ValueParameter<PercentValue>("MigrationRate", "", new PercentValue(0.05)));
114      Parameters.Add(new ValueParameter<PercentValue>("CommunicationRate", "", new PercentValue(0.10)));
115      Parameters.Add(new ValueParameter<IntValue>("MessageCacheCapacity", "", new IntValue(1000)));
116      Parameters.Add(new ValueParameter<StringValue>("LanIpPrefix", "", new StringValue("10.")));
117      Parameters.Add(new LookupParameter<IRandom>("Random", "The random number generator"));
118      Parameters.Add(new ValueParameter<StringValue>("ContactServerURL", "", new StringValue("net.tcp://10.42.1.150:9090/DistributedGA.ContactServer/ContactService")));
119      Parameters.Add(new ValueParameter<StringValue>("JobGUID", "", new StringValue(Guid.NewGuid().ToString())));
120      Parameters.Add(new ValueParameter<ILog>("Log", "The log", new Log(1000)));
121
122      var validValues = new ItemSet<EnumValue<MigrationStrategy>>();
123      validValues.Add(new EnumValue<MigrationStrategy>(MigrationStrategy.Best));
124      validValues.Add(new EnumValue<MigrationStrategy>(MigrationStrategy.Worst));
125      validValues.Add(new EnumValue<MigrationStrategy>(MigrationStrategy.Random));
126      Parameters.Add(new ConstrainedValueParameter<EnumValue<MigrationStrategy>>("MigrationStrategySelect", validValues, (new EnumValue<MigrationStrategy>(MigrationStrategy.Random))));
127      Parameters.Add(new ConstrainedValueParameter<EnumValue<MigrationStrategy>>("MigrationStrategyReplace", validValues, (new EnumValue<MigrationStrategy>(MigrationStrategy.Random))));
128
129    }
130
131    public override IDeepCloneable Clone(Cloner cloner) {
132      return new P2PMigrationAnalyzer(this, cloner);
133    }
134
135    public override void ClearState() {
136      base.ClearState();
137      Dispose();
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            immigrants = message.Skip(Math.Max(0, message.Count() - noOfEmigrants)).ToList();
236          } else {
237            immigrants = message;
238          }
239
240          // remove individuals from population to make place for immigrants
241          for (int i = 0; i < immigrants.Count; i++) {
242            switch (selectedMigStratReplace) {
243              case MigrationStrategy.Best:
244                scope.SubScopes.Remove(sortedPop[0]);
245                sortedPop.RemoveAt(0);
246                break;
247
248              case MigrationStrategy.Random:
249                replIdx = rand.Next(sortedPop.Count);
250                scope.SubScopes.Remove(sortedPop[replIdx]);
251                sortedPop.RemoveAt(replIdx);
252                break;
253
254              case MigrationStrategy.Worst:
255                //replace random
256                scope.SubScopes.Remove(sortedPop[sortedPop.Count - 1]);
257                sortedPop.RemoveAt(sortedPop.Count - 1);
258                break;
259            }
260          }
261
262          //insert individual sorted in population
263          var qualities = QualityParameter.ActualValue;
264          var qualityTranslatedName = QualityParameter.TranslatedName;
265          foreach (var msg in immigrants) {
266            using (var stream = new MemoryStream(msg.Value)) {
267              var immigrantScope = HeuristicLab.Persistence.Default.Xml.XmlParser.Deserialize<IScope>(stream);
268
269              var qImmigrant = ((DoubleValue)immigrantScope.Variables[qualityTranslatedName].Value).Value;
270              var insertPos = scope.SubScopes.Count;
271              var maximization = Maximization.Value;
272              for (int i = 0; i < qualities.Length; i++) {
273                var qi = qualities[i].Value;
274                if ((maximization && qi < qImmigrant) || (!maximization && qi > qImmigrant)) {
275                  insertPos = i;
276                  break;
277                }
278              }
279
280              scope.SubScopes.Insert(insertPos, immigrantScope);
281
282              var log = LogParameter.Value;
283              double quality = qImmigrant;
284              log.LogMessage(string.Format("Recieved individual with quality {0} from peer {1}:{2} ; Job: {3}",
285                                            quality, msg.Key.IpAddress, msg.Key.Port, msg.Key.ProblemInstance));
286            }
287          }
288        }
289      }
290
291      MigrationIterations.Value++;
292      return base.Apply();
293    }
294
295    private void ExceptionThrown(object sender, Exception e) {
296      var log = LogParameter.Value;
297      log.LogMessage(e.Message);
298    }
299
300    public void Dispose() {
301      h.Dispose();
302      h = null;
303    }
304
305  }
306}
Note: See TracBrowser for help on using the repository browser.