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

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

#2615:
made minor change

File size: 10.7 KB
RevLine 
[13905]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;
[13960]24using System.Data.SqlTypes;
[13905]25using System.IO;
26using System.ServiceModel.Configuration;
27using System.Threading;
28using DistributedGA.Core.Domain;
29using DistributedGA.Core.Implementation;
30using DistributedGA.Core.Interface;
[13957]31using DistributedGA.Hive;
[13905]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]
[13965]43  public class P2PMigrationAnalyzer : SingleSuccessorOperator, IAnalyzer, ISingleObjectiveOperator, IExecutable {
[13905]44    // state: messagehandler
45    private IMessageHandler h;
46
[13960]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    }
[13905]54    public ILookupParameter<IntValue> MigrationIterationsParameter {
55      get { return (ILookupParameter<IntValue>)Parameters["MigrationIterations"]; }
56    }
[13960]57    public ILookupParameter<PercentValue> MigrationRatesParameter {
58      get { return (ILookupParameter<PercentValue>)Parameters["MigrationRate"]; }
[13957]59    }
[13960]60    public ILookupParameter<PercentValue> CommunicationRatesParameter {
61      get { return (ILookupParameter<PercentValue>)Parameters["CommunicationRate"]; }
[13957]62    }
[13959]63    public ILookupParameter<IntValue> MessageCacheCapacityParameter {
[13957]64      get { return (ILookupParameter<IntValue>)Parameters["MessageCacheCapacity"]; }
65    }
[13905]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
[13960]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    }
[13905]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"));
[13960]102      Parameters.Add(new LookupParameter<BoolValue>("Maximization"));
103      Parameters.Add(new ScopeTreeLookupParameter<DoubleValue>("Quality", 1));
[13905]104      Parameters.Add(new ValueParameter<IntValue>("MigrationInterval", "", new IntValue(1)));
[13960]105      Parameters.Add(new ValueParameter<PercentValue>("MigrationRate", "", new PercentValue(0.05)));
106      Parameters.Add(new ValueParameter<PercentValue>("CommunicationRate", "", new PercentValue(0.10)));
[13957]107      Parameters.Add(new ValueParameter<IntValue>("MessageCacheCapacity", "", new IntValue(100)));
[13905]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)));
[13960]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
[13965]120      Parameters.Add(new ConstrainedValueParameter<EnumValue<MigrationStrategy>>("MigrationStrategy", validValues, (new EnumValue<MigrationStrategy>(MigrationStrategy.TakeBestReplaceBad))));
[13905]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;
[13956]139      var problemInstance = ((StringValue)Parameters["JobGUID"].ActualValue).Value;
[13960]140      var communicationRate = ((PercentValue)Parameters["CommunicationRate"].ActualValue).Value;
[13957]141      var messageCacheCapacity = ((IntValue)Parameters["MessageCacheCapacity"].ActualValue).Value;
[13960]142      h.Init(lanIpPrefix, contactServerUri, problemInstance, (int)(100 * messageCacheCapacity), (int)(100 * communicationRate));
[13905]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
[13957]155        //define how many migrants to send
[13960]156        var migrationRate = ((PercentValue)Parameters["MigrationRate"].ActualValue).Value;
[13957]157
158        //TODO: SELECT MIGRATION STRATEGY
[13960]159        // TODO: select individuals based on quality
160        var popQualities = QualityParameter.ActualValue;
[13957]161
[13960]162        var selectedMigStrat = MigrationStrategyParameter.Value.Value;
163
[13905]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];
[13965]174              emigrantScope.ClearParentScopes();
[13960]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              HeuristicLab.Persistence.Default.Xml.XmlGenerator.Serialize(msgScope, stream);
[13905]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);
[13960]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
[13905]216              var log = LogParameter.Value;
217              double quality = 0.0;
[13960]218              quality = qImmigrant;
[13905]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; } }
[13965]230
231    #region IExecutable Members
232
233    public event EventHandler<EventArgs<Exception>> ExceptionOccurred;
234
235    public ExecutionState ExecutionState {
236      get { return ExecutionState.Prepared; }
237    }
238
239    public event EventHandler ExecutionStateChanged;
240
241    public TimeSpan ExecutionTime {
242      get { return new TimeSpan(); }
243    }
244
245    public event EventHandler ExecutionTimeChanged;
246
247    public void Pause() {
248      int i = 0;
249    }
250
251    public event EventHandler Paused;
252
253    public void Prepare() {
254      int i = 0;
255    }
256
257    public event EventHandler Prepared;
258
259    public void Start() {
260      int i = 0;
261    }
262
263    public event EventHandler Started;
264
265    public void Stop() {
266      int i = 0;
267    }
268
269    public event EventHandler Stopped;
270
271    #endregion
[13905]272  }
273}
Note: See TracBrowser for help on using the repository browser.