Free cookie consent management tool by TermsFeed Policy Generator

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

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

#2797:

  • Updated PSO to make it more compatible with SPSO 2011
  • Removed truncation of velocity vector and instead rescaled it given the maximum velocity
  • Added non-zero initial velocity according to SPSO 2011
  • Removed complicated bouncing code due to box constraints and instead implemented as described in SPSO 2011
  • Calculating neighbor best has been changed to use personal best
  • Avoiding local and global particle update and instead relying on neighborbest
  • More randomization during velocity update by using a separate random numbers per dimension
  • Reusing problem specific solution creator in RealVectorParticleCreator instead of always using UniformRandomRealVectorCreator
File size: 12.8 KB
Line 
1#region License Information
2/* HeuristicLab
3 * Copyright (C) 2002-2016 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.Linq;
25using HeuristicLab.Common;
26using HeuristicLab.Core;
27using HeuristicLab.Data;
28using HeuristicLab.Operators;
29using HeuristicLab.Optimization;
30using HeuristicLab.Optimization.Operators;
31using HeuristicLab.Parameters;
32using HeuristicLab.Persistence.Default.CompositeSerializers.Storable;
33using HeuristicLab.PluginInfrastructure;
34
35namespace HeuristicLab.Encodings.RealVectorEncoding {
36  [Item("RealVectorSwarmUpdater", "Updates personal best point and quality as well as global best point and quality.")]
37  [StorableClass]
38  public sealed class RealVectorSwarmUpdater : SingleSuccessorOperator, IRealVectorSwarmUpdater, ISingleObjectiveOperator {
39
40    [Storable]
41    private ResultsCollector ResultsCollector;
42
43    public override bool CanChangeName {
44      get { return false; }
45    }
46
47    #region Parameter properties
48    public IScopeTreeLookupParameter<DoubleValue> QualityParameter {
49      get { return (IScopeTreeLookupParameter<DoubleValue>)Parameters["Quality"]; }
50    }
51    public IScopeTreeLookupParameter<DoubleValue> PersonalBestQualityParameter {
52      get { return (IScopeTreeLookupParameter<DoubleValue>)Parameters["PersonalBestQuality"]; }
53    }
54    public IScopeTreeLookupParameter<DoubleValue> NeighborBestQualityParameter {
55      get { return (IScopeTreeLookupParameter<DoubleValue>)Parameters["NeighborBestQuality"]; }
56    }
57    public IScopeTreeLookupParameter<RealVector> RealVectorParameter {
58      get { return (IScopeTreeLookupParameter<RealVector>)Parameters["RealVector"]; }
59    }
60    public IScopeTreeLookupParameter<RealVector> PersonalBestParameter {
61      get { return (IScopeTreeLookupParameter<RealVector>)Parameters["PersonalBest"]; }
62    }
63    public IScopeTreeLookupParameter<RealVector> NeighborBestParameter {
64      get { return (IScopeTreeLookupParameter<RealVector>)Parameters["NeighborBest"]; }
65    }
66    public ILookupParameter<BoolValue> MaximizationParameter {
67      get { return (ILookupParameter<BoolValue>)Parameters["Maximization"]; }
68    }
69    public ILookupParameter<DoubleValue> SwarmBestQualityParameter {
70      get { return (ILookupParameter<DoubleValue>)Parameters["SwarmBestQuality"]; }
71    }
72    public ILookupParameter<RealVector> BestRealVectorParameter {
73      get { return (ILookupParameter<RealVector>)Parameters["BestRealVector"]; }
74    }
75    public IScopeTreeLookupParameter<IntArray> NeighborsParameter {
76      get { return (IScopeTreeLookupParameter<IntArray>)Parameters["Neighbors"]; }
77    }
78    public IValueLookupParameter<DoubleValue> MaxVelocityParameter {
79      get { return (ValueLookupParameter<DoubleValue>)Parameters["MaxVelocity"]; }
80    }
81    public ILookupParameter<DoubleValue> CurrentMaxVelocityParameter {
82      get { return (ILookupParameter<DoubleValue>)Parameters["CurrentMaxVelocity"]; }
83    }
84    public LookupParameter<ResultCollection> ResultsParameter {
85      get { return (LookupParameter<ResultCollection>)Parameters["Results"]; }
86    }
87
88    #region Max Velocity Updating
89    public IConstrainedValueParameter<IDiscreteDoubleValueModifier> MaxVelocityScalingOperatorParameter {
90      get { return (IConstrainedValueParameter<IDiscreteDoubleValueModifier>)Parameters["MaxVelocityScalingOperator"]; }
91    }
92    public IValueLookupParameter<DoubleValue> FinalMaxVelocityParameter {
93      get { return (IValueLookupParameter<DoubleValue>)Parameters["FinalMaxVelocity"]; }
94    }
95    public ILookupParameter<IntValue> MaxVelocityIndexParameter {
96      get { return (ILookupParameter<IntValue>)Parameters["MaxVelocityIndex"]; }
97    }
98    public IValueLookupParameter<IntValue> MaxVelocityStartIndexParameter {
99      get { return (IValueLookupParameter<IntValue>)Parameters["MaxVelocityStartIndex"]; }
100    }
101    public IValueLookupParameter<IntValue> MaxVelocityEndIndexParameter {
102      get { return (IValueLookupParameter<IntValue>)Parameters["MaxVelocityEndIndex"]; }
103    }
104    #endregion
105
106    #endregion
107   
108    #region Construction & Cloning
109
110    [StorableConstructor]
111    private RealVectorSwarmUpdater(bool deserializing) : base(deserializing) { }
112    private RealVectorSwarmUpdater(RealVectorSwarmUpdater original, Cloner cloner)
113      : base(original, cloner) {
114      ResultsCollector = cloner.Clone(original.ResultsCollector);
115    }
116    public RealVectorSwarmUpdater()
117      : base() {
118      Parameters.Add(new LookupParameter<DoubleValue>("SwarmBestQuality", "Swarm's best quality."));
119      Parameters.Add(new LookupParameter<RealVector>("BestRealVector", "Global best particle position."));
120      Parameters.Add(new ScopeTreeLookupParameter<DoubleValue>("Quality", "Particles' qualities."));
121      Parameters.Add(new ScopeTreeLookupParameter<DoubleValue>("PersonalBestQuality", "Particles' personal best qualities."));
122      Parameters.Add(new ScopeTreeLookupParameter<DoubleValue>("NeighborBestQuality", "Best neighbor particles' qualities."));
123      Parameters.Add(new ScopeTreeLookupParameter<RealVector>("RealVector", "Particles' positions."));
124      Parameters.Add(new ScopeTreeLookupParameter<RealVector>("PersonalBest", "Particles' personal best positions."));
125      Parameters.Add(new ScopeTreeLookupParameter<RealVector>("NeighborBest", "Neighborhood (or global in case of totally connected neighborhood) best particle positions."));
126      Parameters.Add(new ScopeTreeLookupParameter<IntArray>("Neighbors", "The list of neighbors for each particle."));
127      Parameters.Add(new LookupParameter<BoolValue>("Maximization", "True if the problem is a maximization problem, otherwise false."));
128      Parameters.Add(new ValueLookupParameter<DoubleValue>("MaxVelocity", "Speed limit for each particle.", new DoubleValue(1)));
129      Parameters.Add(new LookupParameter<DoubleValue>("CurrentMaxVelocity", "Current value of the speed limit."));
130      Parameters.Add(new LookupParameter<ResultCollection>("Results", "Results"));
131
132      #region Velocity Bounds Updating
133      Parameters.Add(new OptionalConstrainedValueParameter<IDiscreteDoubleValueModifier>("MaxVelocityScalingOperator", "Modifies the value"));
134      Parameters.Add(new ValueLookupParameter<DoubleValue>("FinalMaxVelocity", "The value of maximum velocity if PSO has reached maximum iterations.", new DoubleValue(1E-10)));
135      Parameters.Add(new LookupParameter<IntValue>("MaxVelocityIndex", "The current index.", "Iterations"));
136      Parameters.Add(new ValueLookupParameter<IntValue>("MaxVelocityStartIndex", "The start index at which to start modifying 'Value'.", new IntValue(0)));
137      Parameters.Add(new ValueLookupParameter<IntValue>("MaxVelocityEndIndex", "The end index by which 'Value' should have reached 'EndValue'.", "MaxIterations"));
138      MaxVelocityStartIndexParameter.Hidden = true;
139      MaxVelocityEndIndexParameter.Hidden = true;
140      #endregion
141
142      Initialize();
143    }
144
145    public override IDeepCloneable Clone(Cloner cloner) {
146      return new RealVectorSwarmUpdater(this, cloner);
147    }
148
149    #endregion
150
151    [StorableHook(HookType.AfterDeserialization)]
152    private void AfterDeserialization() {
153      if (!Parameters.ContainsKey("SwarmBestQuality")) {
154        ILookupParameter<DoubleValue> oldBestQualityParameter = Parameters["BestQuality"] as ILookupParameter<DoubleValue>;
155        Parameters.Add(new LookupParameter<DoubleValue>("SwarmBestQuality", "Swarm's best quality."));
156        if (oldBestQualityParameter.ActualName != oldBestQualityParameter.Name)
157          SwarmBestQualityParameter.ActualName = oldBestQualityParameter.ActualName;
158        Parameters.Remove("BestQuality");
159      }
160    }
161    private void Initialize() {
162      ResultsCollector = new ResultsCollector();
163      ResultsCollector.CollectedValues.Add(CurrentMaxVelocityParameter);
164      ResultsCollector.CollectedValues.Add(MaxVelocityParameter);
165
166      foreach (IDiscreteDoubleValueModifier op in ApplicationManager.Manager.GetInstances<IDiscreteDoubleValueModifier>()) {
167        MaxVelocityScalingOperatorParameter.ValidValues.Add(op);
168        op.ValueParameter.ActualName = CurrentMaxVelocityParameter.Name;
169        op.StartValueParameter.ActualName = MaxVelocityParameter.Name;
170        op.EndValueParameter.ActualName = FinalMaxVelocityParameter.Name;
171        op.IndexParameter.ActualName = MaxVelocityIndexParameter.Name;
172        op.StartIndexParameter.ActualName = MaxVelocityStartIndexParameter.Name;
173        op.EndIndexParameter.ActualName = MaxVelocityEndIndexParameter.Name;
174      }
175      MaxVelocityScalingOperatorParameter.Value = null;
176    }
177
178    public override IOperation Apply() {
179      var max = MaximizationParameter.ActualValue.Value;
180      // Update of the personal bests
181      var points = RealVectorParameter.ActualValue;
182      var qualities = QualityParameter.ActualValue;
183      var particles = points.Select((p, i) => new { Particle = p, Index = i })
184        .Zip(qualities, (p, q) => Tuple.Create(p.Index, p.Particle, q.Value)).ToList();
185      UpdatePersonalBest(max, particles);
186
187      // SPSO: update of the neighbor bests from the personal bests
188      var personalBestPoints = PersonalBestParameter.ActualValue;
189      var personalBestQualities = PersonalBestQualityParameter.ActualValue;
190      particles = personalBestPoints.Select((p, i) => new { Particle = p, Index = i })
191        .Zip(personalBestQualities, (p, q) => Tuple.Create(p.Index, p.Particle, q.Value)).ToList();
192      UpdateNeighborBest(max, particles);
193
194      var next = new OperationCollection() { base.Apply() };
195      next.Insert(0, ExecutionContext.CreateChildOperation(ResultsCollector));
196      if (MaxVelocityScalingOperatorParameter.Value != null) {
197        next.Insert(0, ExecutionContext.CreateChildOperation(MaxVelocityScalingOperatorParameter.Value));
198      } else CurrentMaxVelocityParameter.ActualValue = new DoubleValue(MaxVelocityParameter.ActualValue.Value);
199      return next;
200    }
201
202    private void UpdateNeighborBest(bool maximization, IList<Tuple<int, RealVector, double>> particles) {
203      var neighbors = NeighborsParameter.ActualValue;
204      if (neighbors.Length > 0) {
205        var neighborBest = new ItemArray<RealVector>(neighbors.Length);
206        var neighborBestQuality = new ItemArray<DoubleValue>(neighbors.Length);
207        for (int n = 0; n < neighbors.Length; n++) {
208          var pairs = particles.Where(x => x.Item1 == n || neighbors[n].Contains(x.Item1));
209          var bestNeighbor = (maximization ? pairs.MaxItems(p => p.Item3)
210                                           : pairs.MinItems(p => p.Item3)).First();
211          neighborBest[n] = bestNeighbor.Item2;
212          neighborBestQuality[n] = new DoubleValue(bestNeighbor.Item3);
213        }
214        NeighborBestParameter.ActualValue = neighborBest;
215        NeighborBestQualityParameter.ActualValue = neighborBestQuality;
216      } else {
217        // Neighbor best = Global best
218        var best = maximization ? particles.MaxItems(x => x.Item3).First() : particles.MinItems(x => x.Item3).First();
219        NeighborBestParameter.ActualValue = new ItemArray<RealVector>(particles.Select(x => best.Item2));
220        NeighborBestQualityParameter.ActualValue = new ItemArray<DoubleValue>(particles.Select(x => new DoubleValue(best.Item3)));
221      }
222    }
223
224    private void UpdatePersonalBest(bool maximization, IList<Tuple<int, RealVector, double>> particles) {
225      var personalBest = PersonalBestParameter.ActualValue;
226      var personalBestQuality = PersonalBestQualityParameter.ActualValue;
227
228      if (personalBestQuality.Length == 0) {
229        personalBestQuality = new ItemArray<DoubleValue>(particles.Select(x => new DoubleValue(x.Item3)));
230        PersonalBestQualityParameter.ActualValue = personalBestQuality;
231      }
232      foreach (var p in particles) {
233        if (maximization && p.Item3 > personalBestQuality[p.Item1].Value ||
234          !maximization && p.Item3 < personalBestQuality[p.Item1].Value) {
235          personalBestQuality[p.Item1].Value = p.Item3;
236          personalBest[p.Item1] = (RealVector)p.Item2.Clone();
237        }
238      }
239      PersonalBestParameter.ActualValue = personalBest;
240    }
241  }
242}
Note: See TracBrowser for help on using the repository browser.