Free cookie consent management tool by TermsFeed Policy Generator

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

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

#2615 debugging and changes preparing for different migration strategies

File size: 9.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.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 ILookupParameter<BoolValue> MaximizationParameter {
48      get { return (ILookupParameter<BoolValue>)Parameters["Maximization"]; }
49    }
50    // for name translation
51    public ScopeTreeLookupParameter<DoubleValue> QualityParameter {
52      get { return (ScopeTreeLookupParameter<DoubleValue>)Parameters["Quality"]; }
53    }
54    public ILookupParameter<IntValue> MigrationIterationsParameter {
55      get { return (ILookupParameter<IntValue>)Parameters["MigrationIterations"]; }
56    }
57    public ILookupParameter<PercentValue> MigrationRatesParameter {
58      get { return (ILookupParameter<PercentValue>)Parameters["MigrationRate"]; }
59    }
60    public ILookupParameter<PercentValue> CommunicationRatesParameter {
61      get { return (ILookupParameter<PercentValue>)Parameters["CommunicationRate"]; }
62    }
63    public ILookupParameter<IntValue> MessageCacheCapacityParameter {
64      get { return (ILookupParameter<IntValue>)Parameters["MessageCacheCapacity"]; }
65    }
66    public ILookupParameter<IRandom> RandomParameter {
67      get { return (ILookupParameter<IRandom>)Parameters["Random"]; }
68    }
69    public IValueParameter<IntValue> MigrationIntervalParameter {
70      get { return (IValueParameter<IntValue>)Parameters["MigrationInterval"]; }
71    }
72    public IValueParameter<ILog> LogParameter {
73      get { return (IValueParameter<ILog>)Parameters["Log"]; }
74    }
75
76    public IConstrainedValueParameter<EnumValue<MigrationStrategy>> MigrationStrategyParameter {
77      get { return (IConstrainedValueParameter<EnumValue<MigrationStrategy>>)Parameters["MigrationStrategy"]; }
78    }
79
80    public BoolValue Maximization {
81      get { return MaximizationParameter.ActualValue; }
82    }
83    public IntValue MigrationIterations {
84      get { return MigrationIterationsParameter.ActualValue; }
85    }
86
87    public IntValue MigrationInterval {
88      get { return MigrationIntervalParameter.Value; }
89    }
90
91    public IRandom Random {
92      get { return RandomParameter.ActualValue; }
93    }
94
95    [StorableConstructor]
96    protected P2PMigrationAnalyzer(bool deserializing) : base(deserializing) { }
97    protected P2PMigrationAnalyzer(P2PMigrationAnalyzer original, Cloner cloner) : base(original, cloner) { }
98
99    public P2PMigrationAnalyzer()
100      : base() {
101      Parameters.Add(new LookupParameter<IntValue>("MigrationIterations"));
102      Parameters.Add(new LookupParameter<BoolValue>("Maximization"));
103      Parameters.Add(new ScopeTreeLookupParameter<DoubleValue>("Quality", 1));
104      Parameters.Add(new ValueParameter<IntValue>("MigrationInterval", "", new IntValue(1)));
105      Parameters.Add(new ValueParameter<PercentValue>("MigrationRate", "", new PercentValue(0.05)));
106      Parameters.Add(new ValueParameter<PercentValue>("CommunicationRate", "", new PercentValue(0.10)));
107      Parameters.Add(new ValueParameter<IntValue>("MessageCacheCapacity", "", new IntValue(100)));
108      Parameters.Add(new ValueParameter<StringValue>("LanIpPrefix", "", new StringValue("10.")));
109      Parameters.Add(new LookupParameter<IRandom>("Random", "The random number generator"));
110      Parameters.Add(new ValueParameter<StringValue>("ContactServerURL", "", new StringValue("net.tcp://10.42.1.150:9090/DistributedGA.ContactServer/ContactService")));
111      Parameters.Add(new ValueParameter<StringValue>("JobGUID", "", new StringValue(Guid.NewGuid().ToString())));
112      Parameters.Add(new ValueParameter<ILog>("Log", "The log", new Log(1000)));
113
114      var validValues = new ItemSet<EnumValue<MigrationStrategy>>();
115      validValues.Add(new EnumValue<MigrationStrategy>(MigrationStrategy.TakeBestReplaceBad));
116      validValues.Add(new EnumValue<MigrationStrategy>(MigrationStrategy.TakeBestReplaceRandom));
117      validValues.Add(new EnumValue<MigrationStrategy>(MigrationStrategy.TakeRandomReplaceBad));
118      validValues.Add(new EnumValue<MigrationStrategy>(MigrationStrategy.TakeRandomReplaceRandom));
119
120      Parameters.Add(new ConstrainedValueParameter<EnumValue<MigrationStrategy>>("MigrationStrategy", validValues));
121    }
122
123    public override IDeepCloneable Clone(Cloner cloner) {
124      return new P2PMigrationAnalyzer(this, cloner);
125    }
126
127    public override void ClearState() {
128      base.ClearState();
129      h.Dispose();
130      h = null;
131    }
132
133    public override void InitializeState() {
134      base.InitializeState();
135      // init P2P
136      h = new PeerNetworkMessageHandler();
137      var lanIpPrefix = ((StringValue)(Parameters["LanIpPrefix"].ActualValue)).Value;
138      var contactServerUri = ((StringValue)(Parameters["ContactServerURL"].ActualValue)).Value;
139      var problemInstance = ((StringValue)Parameters["JobGUID"].ActualValue).Value;
140      var communicationRate = ((PercentValue)Parameters["CommunicationRate"].ActualValue).Value;
141      var messageCacheCapacity = ((IntValue)Parameters["MessageCacheCapacity"].ActualValue).Value;
142      h.Init(lanIpPrefix, contactServerUri, problemInstance, (int)(100 * messageCacheCapacity), (int)(100 * communicationRate));
143    }
144
145    public override IOperation Apply() {
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
158        //TODO: SELECT MIGRATION STRATEGY
159        // TODO: select individuals based on quality
160        var popQualities = QualityParameter.ActualValue;
161
162        var selectedMigStrat = MigrationStrategyParameter.Value.Value;
163
164        // select best as emigrant
165        IScope emigrants = scope.SubScopes[1];
166        emigrantsList.Add(emigrants);
167
168        {
169          // send
170          var message = new byte[emigrantsList.Count][];
171          for (int ei = 0; ei < emigrantsList.Count; ei++) {
172            using (var stream = new MemoryStream()) {
173              var emigrantScope = emigrantsList[ei];
174              var msgScope = new Scope();
175              var cloner = new Cloner();
176              foreach (var variable in emigrantScope.Variables) {
177                msgScope.Variables.Add((IVariable)variable.Clone(cloner));
178              }
179              // emigrantScope.ClearParentScopes();
180              HeuristicLab.Persistence.Default.Xml.XmlGenerator.Serialize(msgScope, stream);
181              message[ei] = stream.GetBuffer();
182            }
183          }
184          h.PublishDataToNetwork(message);
185        }
186
187
188        {
189          // recieve
190          var message = h.GetDataFromNetwork();
191          for (int ei = 0; ei < message.Length; ei++) {
192            using (var stream = new MemoryStream(message[ei])) {
193              var immigrantScope = HeuristicLab.Persistence.Default.Xml.XmlParser.Deserialize<IScope>(stream);
194
195              // replace random individual in current population
196              var rand = Random;
197              var replIdx = rand.Next(scope.SubScopes.Count);
198
199              scope.SubScopes.RemoveAt(replIdx);
200              var qualities = QualityParameter.ActualValue;
201
202              var qualityTranslatedName = QualityParameter.TranslatedName;
203              var qImmigrant = ((DoubleValue)immigrantScope.Variables[qualityTranslatedName].Value).Value;
204              var insertPos = scope.SubScopes.Count;
205              var maximization = Maximization.Value;
206              for (int i = 0; i < qualities.Length; i++) {
207                var qi = qualities[i].Value;
208                if ((maximization && qi < qImmigrant) || (!maximization && qi > qImmigrant)) {
209                  insertPos = i;
210                  break;
211                }
212              }
213
214              scope.SubScopes.Insert(insertPos, immigrantScope);
215
216              var log = LogParameter.Value;
217              double quality = 0.0;
218              quality = qImmigrant;
219              log.LogMessage(string.Format("Recieved individual with quality {0}", quality));
220            }
221          }
222        }
223      }
224
225      MigrationIterations.Value++;
226      return base.Apply();
227    }
228
229    public bool EnabledByDefault { get { return false; } }
230  }
231}
Note: See TracBrowser for help on using the repository browser.