Free cookie consent management tool by TermsFeed Policy Generator

source: trunk/sources/HeuristicLab.Encodings.RealVectorEncoding/3.3/ParticleOperators/RealVectorSwarmUpdater.cs @ 15071

Last change on this file since 15071 was 15071, checked in by abeham, 7 years ago

#2748: fixed personal best tracking in RealVectorSwarmUpdater

File size: 15.8 KB
RevLine 
[5560]1#region License Information
2/* HeuristicLab
[14185]3 * Copyright (C) 2002-2016 Heuristic and Evolutionary Algorithms Laboratory (HEAL)
[5560]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
[5905]22using System;
[15071]23using System.Collections.Generic;
[5561]24using System.Linq;
[5560]25using HeuristicLab.Common;
26using HeuristicLab.Core;
27using HeuristicLab.Data;
28using HeuristicLab.Operators;
[5568]29using HeuristicLab.Optimization;
[5866]30using HeuristicLab.Optimization.Operators;
[5560]31using HeuristicLab.Parameters;
32using HeuristicLab.Persistence.Default.CompositeSerializers.Storable;
[5866]33using HeuristicLab.PluginInfrastructure;
[5560]34
35namespace HeuristicLab.Encodings.RealVectorEncoding {
[5911]36  [Item("RealVectorSwarmUpdater", "Updates personal best point and quality as well as global best point and quality.")]
[5560]37  [StorableClass]
[11970]38  public sealed class RealVectorSwarmUpdater : SingleSuccessorOperator, IRealVectorSwarmUpdater, ISingleObjectiveOperator {
[5592]39
[5866]40    [Storable]
41    private ResultsCollector ResultsCollector;
42
[5560]43    public override bool CanChangeName {
44      get { return false; }
45    }
46
47    #region Parameter properties
[5561]48    public IScopeTreeLookupParameter<DoubleValue> QualityParameter {
49      get { return (IScopeTreeLookupParameter<DoubleValue>)Parameters["Quality"]; }
[5560]50    }
[5561]51    public IScopeTreeLookupParameter<DoubleValue> PersonalBestQualityParameter {
52      get { return (IScopeTreeLookupParameter<DoubleValue>)Parameters["PersonalBestQuality"]; }
[5560]53    }
[5568]54    public IScopeTreeLookupParameter<DoubleValue> NeighborBestQualityParameter {
55      get { return (IScopeTreeLookupParameter<DoubleValue>)Parameters["NeighborBestQuality"]; }
[5560]56    }
[5561]57    public IScopeTreeLookupParameter<RealVector> RealVectorParameter {
58      get { return (IScopeTreeLookupParameter<RealVector>)Parameters["RealVector"]; }
[5560]59    }
[5561]60    public IScopeTreeLookupParameter<RealVector> PersonalBestParameter {
61      get { return (IScopeTreeLookupParameter<RealVector>)Parameters["PersonalBest"]; }
[5560]62    }
[5568]63    public IScopeTreeLookupParameter<RealVector> NeighborBestParameter {
64      get { return (IScopeTreeLookupParameter<RealVector>)Parameters["NeighborBest"]; }
[5560]65    }
[5568]66    public ILookupParameter<BoolValue> MaximizationParameter {
67      get { return (ILookupParameter<BoolValue>)Parameters["Maximization"]; }
[5560]68    }
[7073]69    public ILookupParameter<DoubleValue> SwarmBestQualityParameter {
70      get { return (ILookupParameter<DoubleValue>)Parameters["SwarmBestQuality"]; }
[5561]71    }
[5643]72    public ILookupParameter<RealVector> BestRealVectorParameter {
73      get { return (ILookupParameter<RealVector>)Parameters["BestRealVector"]; }
[5561]74    }
75    public IScopeTreeLookupParameter<IntArray> NeighborsParameter {
76      get { return (IScopeTreeLookupParameter<IntArray>)Parameters["Neighbors"]; }
77    }
[5866]78    public IValueLookupParameter<DoubleMatrix> VelocityBoundsParameter {
79      get { return (ValueLookupParameter<DoubleMatrix>)Parameters["VelocityBounds"]; }
[5568]80    }
[5866]81    public ILookupParameter<DoubleMatrix> CurrentVelocityBoundsParameter {
82      get { return (ILookupParameter<DoubleMatrix>)Parameters["CurrentVelocityBounds"]; }
[5568]83    }
[5866]84    public LookupParameter<ResultCollection> ResultsParameter {
85      get { return (LookupParameter<ResultCollection>)Parameters["Results"]; }
86    }
87
88    #region Velocity Bounds Updating
89    public ILookupParameter<DoubleValue> VelocityBoundsScaleParameter {
90      get { return (ILookupParameter<DoubleValue>)Parameters["VelocityBoundsScale"]; }
91    }
[8121]92    public IConstrainedValueParameter<IDiscreteDoubleValueModifier> VelocityBoundsScalingOperatorParameter {
93      get { return (IConstrainedValueParameter<IDiscreteDoubleValueModifier>)Parameters["VelocityBoundsScalingOperator"]; }
[5866]94    }
95    public IValueLookupParameter<DoubleValue> VelocityBoundsStartValueParameter {
96      get { return (IValueLookupParameter<DoubleValue>)Parameters["VelocityBoundsStartValue"]; }
97    }
98    public IValueLookupParameter<DoubleValue> VelocityBoundsEndValueParameter {
99      get { return (IValueLookupParameter<DoubleValue>)Parameters["VelocityBoundsEndValue"]; }
100    }
101    public ILookupParameter<IntValue> VelocityBoundsIndexParameter {
102      get { return (ILookupParameter<IntValue>)Parameters["VelocityBoundsIndex"]; }
103    }
104    public IValueLookupParameter<IntValue> VelocityBoundsStartIndexParameter {
105      get { return (IValueLookupParameter<IntValue>)Parameters["VelocityBoundsStartIndex"]; }
106    }
107    public IValueLookupParameter<IntValue> VelocityBoundsEndIndexParameter {
108      get { return (IValueLookupParameter<IntValue>)Parameters["VelocityBoundsEndIndex"]; }
109    }
[5560]110    #endregion
111
[5866]112    #endregion
[15071]113   
[5560]114    #region Construction & Cloning
115
116    [StorableConstructor]
117    private RealVectorSwarmUpdater(bool deserializing) : base(deserializing) { }
[5866]118    private RealVectorSwarmUpdater(RealVectorSwarmUpdater original, Cloner cloner)
119      : base(original, cloner) {
120      ResultsCollector = cloner.Clone(original.ResultsCollector);
121    }
[5560]122    public RealVectorSwarmUpdater()
123      : base() {
[7073]124      Parameters.Add(new LookupParameter<DoubleValue>("SwarmBestQuality", "Swarm's best quality."));
125      Parameters.Add(new LookupParameter<RealVector>("BestRealVector", "Global best particle position."));
126      Parameters.Add(new ScopeTreeLookupParameter<DoubleValue>("Quality", "Particles' qualities."));
127      Parameters.Add(new ScopeTreeLookupParameter<DoubleValue>("PersonalBestQuality", "Particles' personal best qualities."));
128      Parameters.Add(new ScopeTreeLookupParameter<DoubleValue>("NeighborBestQuality", "Best neighbor particles' qualities."));
129      Parameters.Add(new ScopeTreeLookupParameter<RealVector>("RealVector", "Particles' positions."));
130      Parameters.Add(new ScopeTreeLookupParameter<RealVector>("PersonalBest", "Particles' personal best positions."));
131      Parameters.Add(new ScopeTreeLookupParameter<RealVector>("NeighborBest", "Neighborhood (or global in case of totally connected neighborhood) best particle positions."));
[5561]132      Parameters.Add(new ScopeTreeLookupParameter<IntArray>("Neighbors", "The list of neighbors for each particle."));
[5568]133      Parameters.Add(new LookupParameter<BoolValue>("Maximization", "True if the problem is a maximization problem, otherwise false."));
[5866]134      Parameters.Add(new ValueLookupParameter<DoubleMatrix>("VelocityBounds", "Maximum velocity for each dimension.", new DoubleMatrix(new double[,] { { -1, 1 } })));
135      Parameters.Add(new LookupParameter<DoubleMatrix>("CurrentVelocityBounds", "Current value of velocity bounds."));
136      Parameters.Add(new LookupParameter<ResultCollection>("Results", "Results"));
137
138      #region Velocity Bounds Updating
139      Parameters.Add(new LookupParameter<DoubleValue>("VelocityBoundsScale", "Scale parameter."));
140      Parameters.Add(new OptionalConstrainedValueParameter<IDiscreteDoubleValueModifier>("VelocityBoundsScalingOperator", "Modifies the value"));
141      Parameters.Add(new ValueLookupParameter<DoubleValue>("VelocityBoundsStartValue", "The start value of 'Value'.", new DoubleValue(1)));
142      Parameters.Add(new ValueLookupParameter<DoubleValue>("VelocityBoundsEndValue", "The end value of 'Value'.", new DoubleValue(1E-10)));
[7745]143      Parameters.Add(new LookupParameter<IntValue>("VelocityBoundsIndex", "The current index.", "Iterations"));
[5866]144      Parameters.Add(new ValueLookupParameter<IntValue>("VelocityBoundsStartIndex", "The start index at which to start modifying 'Value'.", new IntValue(0)));
145      Parameters.Add(new ValueLookupParameter<IntValue>("VelocityBoundsEndIndex", "The end index by which 'Value' should have reached 'EndValue'.", "MaxIterations"));
146      VelocityBoundsStartIndexParameter.Hidden = true;
147      VelocityBoundsEndIndexParameter.Hidden = true;
148      #endregion
149
150      Initialize();
[5905]151      RegisterEvents();
[5560]152    }
153
154    public override IDeepCloneable Clone(Cloner cloner) {
155      return new RealVectorSwarmUpdater(this, cloner);
156    }
157
158    #endregion
159
[5905]160    [StorableHook(HookType.AfterDeserialization)]
[7073]161    private void AfterDeserialization() {
162      if (!Parameters.ContainsKey("SwarmBestQuality")) {
[7074]163        ILookupParameter<DoubleValue> oldBestQualityParameter = Parameters["BestQuality"] as ILookupParameter<DoubleValue>;
[7073]164        Parameters.Add(new LookupParameter<DoubleValue>("SwarmBestQuality", "Swarm's best quality."));
[7074]165        if (oldBestQualityParameter.ActualName != oldBestQualityParameter.Name)
166          SwarmBestQualityParameter.ActualName = oldBestQualityParameter.ActualName;
[7073]167        Parameters.Remove("BestQuality");
168      }
169      RegisterEvents();
170    }
171
[5905]172    private void RegisterEvents() {
173      VelocityBoundsStartValueParameter.ValueChanged += new EventHandler(VelocityBoundsStartValueParameter_ValueChanged);
174      VelocityBoundsStartValueParameter.Value.ValueChanged += new EventHandler(VelocityBoundsStartValueParameter_Value_ValueChanged);
175    }
176
177    void VelocityBoundsStartValueParameter_Value_ValueChanged(object sender, EventArgs e) {
[11970]178      UpdateVelocityBoundsParamater();
[5911]179    }
180
181    void UpdateVelocityBoundsParamater() {
[5905]182      if (VelocityBoundsParameter.Value == null) {
183        VelocityBoundsParameter.Value = new DoubleMatrix(1, 2);
184      } else if (VelocityBoundsParameter.Value.Columns != 2) {
185        VelocityBoundsParameter.Value = new DoubleMatrix(VelocityBoundsParameter.Value.Rows, 2);
186      }
187      if (VelocityBoundsStartValueParameter.Value != null) {
188        DoubleMatrix matrix = VelocityBoundsParameter.Value;
189        for (int i = 0; i < matrix.Rows; i++) {
190          matrix[i, 0] = (-1) * VelocityBoundsStartValueParameter.Value.Value;
191          matrix[i, 1] = VelocityBoundsStartValueParameter.Value.Value;
192        }
193      }
194    }
195
196    void VelocityBoundsStartValueParameter_ValueChanged(object sender, EventArgs e) {
197      if (VelocityBoundsStartValueParameter.Value != null) {
198        VelocityBoundsStartValueParameter.Value.ValueChanged += new EventHandler(VelocityBoundsStartValueParameter_Value_ValueChanged);
199      }
[11970]200      UpdateVelocityBoundsParamater();
[5905]201    }
202
[5866]203    private void Initialize() {
204      ResultsCollector = new ResultsCollector();
205      ResultsCollector.CollectedValues.Add(CurrentVelocityBoundsParameter);
206      ResultsCollector.CollectedValues.Add(VelocityBoundsParameter);
207
208      foreach (IDiscreteDoubleValueModifier op in ApplicationManager.Manager.GetInstances<IDiscreteDoubleValueModifier>()) {
209        VelocityBoundsScalingOperatorParameter.ValidValues.Add(op);
210        op.ValueParameter.ActualName = VelocityBoundsScaleParameter.Name;
211        op.StartValueParameter.ActualName = VelocityBoundsStartValueParameter.Name;
212        op.EndValueParameter.ActualName = VelocityBoundsEndValueParameter.Name;
213        op.IndexParameter.ActualName = VelocityBoundsIndexParameter.Name;
214        op.StartIndexParameter.ActualName = VelocityBoundsStartIndexParameter.Name;
215        op.EndIndexParameter.ActualName = VelocityBoundsEndIndexParameter.Name;
216      }
217      VelocityBoundsScalingOperatorParameter.Value = null;
218    }
219
[5560]220    public override IOperation Apply() {
[15071]221      var max = MaximizationParameter.ActualValue.Value;
222      var points = RealVectorParameter.ActualValue;
223      var qualities = QualityParameter.ActualValue;
224      var particles = points.Select((p, i) => new { Particle = p, Index = i })
225        .Zip(qualities, (p, q) => Tuple.Create(p.Index, p.Particle, q.Value)).ToList();
226      UpdateGlobalBest(max, particles);
227      UpdateNeighborBest(max, particles);
228      UpdatePersonalBest(max, particles);
[5592]229      return UpdateVelocityBounds();
[5561]230    }
231
[15071]232    private void UpdateGlobalBest(bool maximization, IList<Tuple<int, RealVector, double>> particles) {
233      var best = maximization ? particles.MaxItems(x => x.Item3).First() : particles.MinItems(x => x.Item3).First();
234      var bestQuality = SwarmBestQualityParameter.ActualValue;
235      if (bestQuality == null) {
236        SwarmBestQualityParameter.ActualValue = new DoubleValue(best.Item3);
237      } else bestQuality.Value = best.Item3;
238      BestRealVectorParameter.ActualValue = (RealVector)best.Item2.Clone();
[5561]239    }
240
[15071]241    private void UpdateNeighborBest(bool maximization, IList<Tuple<int, RealVector, double>> particles) {
242      var neighbors = NeighborsParameter.ActualValue;
243      if (neighbors.Length > 0) {
244        var neighborBest = new ItemArray<RealVector>(neighbors.Length);
245        var neighborBestQuality = new ItemArray<DoubleValue>(neighbors.Length);
246        for (int n = 0; n < neighbors.Length; n++) {
247          var pairs = particles.Where(x => x.Item1 == n || neighbors[n].Contains(x.Item1));
248          var bestNeighbor = (maximization ? pairs.MaxItems(p => p.Item3)
249                                           : pairs.MinItems(p => p.Item3)).First();
250          neighborBest[n] = bestNeighbor.Item2;
251          neighborBestQuality[n] = new DoubleValue(bestNeighbor.Item3);
[5560]252        }
[15071]253        NeighborBestParameter.ActualValue = neighborBest;
254        NeighborBestQualityParameter.ActualValue = neighborBestQuality;
[5560]255      }
256    }
257
[15071]258    private void UpdatePersonalBest(bool maximization, IList<Tuple<int, RealVector, double>> particles) {
259      var personalBest = PersonalBestParameter.ActualValue;
260      var personalBestQuality = PersonalBestQualityParameter.ActualValue;
261
262      if (personalBestQuality.Length == 0) {
263        personalBestQuality = new ItemArray<DoubleValue>(particles.Select(x => new DoubleValue(x.Item3)));
264        PersonalBestQualityParameter.ActualValue = personalBestQuality;
265      }
266      foreach (var p in particles) {
267        if (maximization && p.Item3 > personalBestQuality[p.Item1].Value ||
268          !maximization && p.Item3 < personalBestQuality[p.Item1].Value) {
269          personalBestQuality[p.Item1].Value = p.Item3;
270          personalBest[p.Item1] = p.Item2;
[5568]271        }
272      }
[15071]273      PersonalBestParameter.ActualValue = personalBest;
[5561]274    }
[5592]275
276    private IOperation UpdateVelocityBounds() {
[15071]277      var currentVelocityBounds = CurrentVelocityBoundsParameter.ActualValue;
[5866]278
[15071]279      if (currentVelocityBounds == null) {
280        currentVelocityBounds = (DoubleMatrix)VelocityBoundsParameter.ActualValue.Clone();
281        CurrentVelocityBoundsParameter.ActualValue = currentVelocityBounds;
282      }
283      if (VelocityBoundsScalingOperatorParameter.Value == null)
[5866]284        return new OperationCollection() {
285          ExecutionContext.CreateChildOperation(ResultsCollector),       
286          base.Apply()
[5592]287        };
[5866]288
[15071]289      var velocityBoundsScale = VelocityBoundsScaleParameter.ActualValue;
290      var velocityBoundsStartValue = VelocityBoundsStartValueParameter.ActualValue;
291
292      if (velocityBoundsScale == null && velocityBoundsStartValue != null) {
293        velocityBoundsScale = new DoubleValue(velocityBoundsStartValue.Value);
294        VelocityBoundsScaleParameter.ActualValue = velocityBoundsScale;
[5866]295      }
[15071]296      for (int i = 0; i < currentVelocityBounds.Rows; i++) {
297        for (int j = 0; j < currentVelocityBounds.Columns; j++) {
298          if (currentVelocityBounds[i, j] >= 0) {
299            currentVelocityBounds[i, j] = velocityBoundsScale.Value;
[5866]300          } else {
[15071]301            currentVelocityBounds[i, j] = (-1) * velocityBoundsScale.Value;
[5866]302          }
303        }
304      }
305
306      return new OperationCollection() {
307        ExecutionContext.CreateChildOperation(ResultsCollector),
[15071]308        ExecutionContext.CreateChildOperation(VelocityBoundsScalingOperatorParameter.Value),
[5866]309        base.Apply()
310      };
[5592]311    }
[5560]312  }
313}
Note: See TracBrowser for help on using the repository browser.