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

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

#2615:
made minor changes

File size: 10.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.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, IExecutable {
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, (new EnumValue<MigrationStrategy>(MigrationStrategy.TakeBestReplaceBad))));
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              emigrantScope.ClearParentScopes();
175              var msgScope = new Scope();
176              var cloner = new Cloner();
177              foreach (var variable in emigrantScope.Variables) {
178                msgScope.Variables.Add((IVariable)variable.Clone(cloner));
179              }
180              msgScope.ClearParentScopes();
181              //TODO: CLEAR EMMIGRANT SCOPES
182              HeuristicLab.Persistence.Default.Xml.XmlGenerator.Serialize(msgScope, stream);
183              message[ei] = stream.GetBuffer();
184            }
185          }
186          h.PublishDataToNetwork(message);
187        }
188
189
190        {
191          // recieve
192          var message = h.GetDataFromNetwork();
193          for (int ei = 0; ei < message.Length; ei++) {
194            using (var stream = new MemoryStream(message[ei])) {
195              var immigrantScope = HeuristicLab.Persistence.Default.Xml.XmlParser.Deserialize<IScope>(stream);
196
197              // replace random individual in current population
198              var rand = Random;
199              var replIdx = rand.Next(scope.SubScopes.Count);
200
201              scope.SubScopes.RemoveAt(replIdx);
202              var qualities = QualityParameter.ActualValue;
203
204              var qualityTranslatedName = QualityParameter.TranslatedName;
205              var qImmigrant = ((DoubleValue)immigrantScope.Variables[qualityTranslatedName].Value).Value;
206              var insertPos = scope.SubScopes.Count;
207              var maximization = Maximization.Value;
208              for (int i = 0; i < qualities.Length; i++) {
209                var qi = qualities[i].Value;
210                if ((maximization && qi < qImmigrant) || (!maximization && qi > qImmigrant)) {
211                  insertPos = i;
212                  break;
213                }
214              }
215
216              scope.SubScopes.Insert(insertPos, immigrantScope);
217
218              var log = LogParameter.Value;
219              double quality = 0.0;
220              quality = qImmigrant;
221              log.LogMessage(string.Format("Recieved individual with quality {0}", quality));
222            }
223          }
224        }
225      }
226
227      MigrationIterations.Value++;
228      return base.Apply();
229    }
230
231    public bool EnabledByDefault { get { return false; } }
232
233    #region IExecutable Members
234
235    public event EventHandler<EventArgs<Exception>> ExceptionOccurred;
236
237    public ExecutionState ExecutionState {
238      get { return ExecutionState.Prepared; }
239    }
240
241    public event EventHandler ExecutionStateChanged;
242
243    public TimeSpan ExecutionTime {
244      get { return new TimeSpan(); }
245    }
246
247    public event EventHandler ExecutionTimeChanged;
248
249    public void Pause() {
250      int i = 0;
251    }
252
253    public event EventHandler Paused;
254
255    public void Prepare() {
256      int i = 0;
257    }
258
259    public event EventHandler Prepared;
260
261    public void Start() {
262      int i = 0;
263    }
264
265    public event EventHandler Started;
266
267    public void Stop() {
268      int i = 0;
269    }
270
271    public event EventHandler Stopped;
272
273    #endregion
274  }
275}
Note: See TracBrowser for help on using the repository browser.