Free cookie consent management tool by TermsFeed Policy Generator

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

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

#2615:
it works

File size: 7.5 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;
25using System.ServiceModel.Configuration;
26using System.Threading;
27using DistributedGA.Core.Domain;
28using DistributedGA.Core.Implementation;
29using DistributedGA.Core.Interface;
30using DistributedGA.Hive;
31using HeuristicLab.Clients.Hive;
32using HeuristicLab.Common;
33using HeuristicLab.Core;
34using HeuristicLab.Data;
35using HeuristicLab.Operators;
36using HeuristicLab.Parameters;
37using HeuristicLab.Persistence.Default.CompositeSerializers.Storable;
38
39namespace HeuristicLab.Optimization.Operators {
40  [Item("P2PMigrationAnalyzer", "Migrates individuals using a P2P network.")]
41  [StorableClass]
42  public class P2PMigrationAnalyzer : SingleSuccessorOperator, IAnalyzer {
43    // state: messagehandler
44    private IMessageHandler h;
45
46    public ILookupParameter<IntValue> MigrationIterationsParameter {
47      get { return (ILookupParameter<IntValue>)Parameters["MigrationIterations"]; }
48    }
49    public ILookupParameter<IntValue> MigrationRatesParameter {
50      get { return (ILookupParameter<IntValue>)Parameters["MigrationRate"]; }
51    }
52    public ILookupParameter<IntValue> CommunicationRatesParameter {
53      get { return (ILookupParameter<IntValue>)Parameters["CommunicationRate"]; }
54    }
55    public ILookupParameter<IntValue> MessageCacheCapacityParameter {
56      get { return (ILookupParameter<IntValue>)Parameters["MessageCacheCapacity"]; }
57    }
58    public ILookupParameter<IRandom> RandomParameter {
59      get { return (ILookupParameter<IRandom>)Parameters["Random"]; }
60    }
61    public IValueParameter<IntValue> MigrationIntervalParameter {
62      get { return (IValueParameter<IntValue>)Parameters["MigrationInterval"]; }
63    }
64    public IValueParameter<ILog> LogParameter {
65      get { return (IValueParameter<ILog>)Parameters["Log"]; }
66    }
67
68    public IntValue MigrationIterations {
69      get { return MigrationIterationsParameter.ActualValue; }
70    }
71
72    public IntValue MigrationInterval {
73      get { return MigrationIntervalParameter.Value; }
74    }
75
76    public IRandom Random {
77      get { return RandomParameter.ActualValue; }
78    }
79
80    [StorableConstructor]
81    protected P2PMigrationAnalyzer(bool deserializing) : base(deserializing) { }
82    protected P2PMigrationAnalyzer(P2PMigrationAnalyzer original, Cloner cloner) : base(original, cloner) { }
83
84    public P2PMigrationAnalyzer()
85      : base() {
86      Parameters.Add(new LookupParameter<IntValue>("MigrationIterations"));
87      Parameters.Add(new ValueParameter<IntValue>("MigrationInterval", "", new IntValue(1)));
88      Parameters.Add(new ValueParameter<IntValue>("MigrationRate", "", new IntValue(5)));
89      Parameters.Add(new ValueParameter<IntValue>("CommunicationRate", "", new IntValue(10)));
90      Parameters.Add(new ValueParameter<IntValue>("MessageCacheCapacity", "", new IntValue(100)));
91      Parameters.Add(new ValueParameter<StringValue>("LanIpPrefix", "", new StringValue("10.")));
92      Parameters.Add(new LookupParameter<IRandom>("Random", "The random number generator"));
93      Parameters.Add(new ValueParameter<StringValue>("ContactServerURL", "", new StringValue("net.tcp://10.42.1.150:9090/DistributedGA.ContactServer/ContactService")));
94      Parameters.Add(new ValueParameter<StringValue>("JobGUID", "", new StringValue(Guid.NewGuid().ToString())));
95      Parameters.Add(new ValueParameter<ILog>("Log", "The log", new Log(1000)));
96    }
97
98    public override IDeepCloneable Clone(Cloner cloner) {
99      return new P2PMigrationAnalyzer(this, cloner);
100    }
101
102    public override void ClearState() {
103      base.ClearState();
104      h.Dispose();
105      h = null;
106    }
107
108    public override void InitializeState() {
109      base.InitializeState();
110      // init P2P
111      h = new PeerNetworkMessageHandler();
112      var lanIpPrefix = ((StringValue)(Parameters["LanIpPrefix"].ActualValue)).Value;
113      var contactServerUri = ((StringValue)(Parameters["ContactServerURL"].ActualValue)).Value;
114      var problemInstance = ((StringValue)Parameters["JobGUID"].ActualValue).Value;
115      var communicationRate = ((IntValue)Parameters["CommunicationRate"].ActualValue).Value;
116      var messageCacheCapacity = ((IntValue)Parameters["MessageCacheCapacity"].ActualValue).Value;
117      h.Init(lanIpPrefix, contactServerUri, problemInstance, messageCacheCapacity, communicationRate);
118      var peer = h.GetPeerInfo();
119    }
120
121    public override IOperation Apply() {
122      if (MigrationIterationsParameter.ActualValue == null) {
123        MigrationIterationsParameter.ActualValue = new IntValue(0);
124      }
125
126      if (MigrationIterations.Value % MigrationInterval.Value == 0) {
127
128        IScope scope = ExecutionContext.Scope;
129        List<IScope> emigrantsList = new List<IScope>();
130
131        //define how many migrants to send
132        var migrationRate = ((IntValue)Parameters["MigrationRate"].ActualValue).Value;
133
134        //TODO: SELECT MIGRATION STRATEGY
135
136        // select best as emigrant
137        IScope emigrants = scope.SubScopes[1];
138        emigrantsList.Add(emigrants);
139
140        {
141          // send
142          var message = new byte[emigrantsList.Count][];
143          for (int ei = 0; ei < emigrantsList.Count; ei++) {
144            using (var stream = new MemoryStream()) {
145              var emigrantScope = emigrantsList[ei];
146              emigrantScope.ClearParentScopes();
147              HeuristicLab.Persistence.Default.Xml.XmlGenerator.Serialize(emigrantScope, stream);
148              message[ei] = stream.GetBuffer();
149            }
150          }
151          h.PublishDataToNetwork(message);
152        }
153
154
155        {
156          // recieve
157          var message = h.GetDataFromNetwork();
158          for (int ei = 0; ei < message.Length; ei++) {
159            using (var stream = new MemoryStream(message[ei])) {
160              var immigrantScope = HeuristicLab.Persistence.Default.Xml.XmlParser.Deserialize<IScope>(stream);
161
162              // replace random individual in current population
163              var rand = Random;
164              var replIdx = rand.Next(scope.SubScopes.Count);
165
166              scope.SubScopes.RemoveAt(replIdx);
167              scope.SubScopes.Insert(replIdx, immigrantScope);
168              var log = LogParameter.Value;
169              double quality = 0.0;
170              if (immigrantScope.Variables.ContainsKey("Quality")) quality = ((DoubleValue)immigrantScope.Variables["Quality"].Value).Value;
171              log.LogMessage(string.Format("Recieved individual with quality {0}", quality));
172            }
173          }
174        }
175      }
176
177      MigrationIterations.Value++;
178      return base.Apply();
179    }
180
181    public bool EnabledByDefault { get { return false; } }
182  }
183}
Note: See TracBrowser for help on using the repository browser.