Free cookie consent management tool by TermsFeed Policy Generator

source: branches/PSO/HeuristicLab.Algorithms.ParticleSwarmOptimization/3.3/ParticleSwarmOptimization.cs @ 5299

Last change on this file since 5299 was 5225, checked in by mkofler, 14 years ago

#852: Added two parameter updaters (for omega and the velocity bounds)

File size: 17.6 KB
Line 
1#region License Information
2/* HeuristicLab
3 * Copyright (C) 2002-2010 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.Linq;
24using HeuristicLab.Analysis;
25using HeuristicLab.Common;
26using HeuristicLab.Core;
27using HeuristicLab.Data;
28using HeuristicLab.Encodings.RealVectorEncoding;
29using HeuristicLab.Operators;
30using HeuristicLab.Optimization;
31using HeuristicLab.Optimization.Operators;
32using HeuristicLab.Parameters;
33using HeuristicLab.Persistence.Default.CompositeSerializers.Storable;
34using HeuristicLab.PluginInfrastructure;
35using HeuristicLab.Random;
36
37namespace HeuristicLab.Algorithms.ParticleSwarmOptimization {
38
39  [Item("Particle Swarm Optimization", "A particle swarm optimization algorithm based on the description in Pedersen, M.E.H. (2010). PhD thesis. University of Southampton.")]
40  [Creatable("Algorithms")]
41  [StorableClass]
42  public class ParticleSwarmOptimization : EngineAlgorithm {
43
44    #region Problem Properties
45    public override Type ProblemType {
46      get { return typeof(ISingleObjectiveProblem); }
47    }
48    public new ISingleObjectiveProblem Problem {
49      get { return (ISingleObjectiveProblem)base.Problem; }
50      set { base.Problem = value; }
51    }
52    public MultiAnalyzer Analyzer {
53      get { return AnalyzerParameter.Value; }
54      set { AnalyzerParameter.Value = value; }
55    }
56    public ValueModifierSelector OmegaUpdater {
57      get { return OmegaUpdaterParameter.Value; }
58      set { OmegaUpdaterParameter.Value = value; }
59    }
60    public WeightedValueModifierSelector VelocityBoundsUpdater {
61      get { return VelocityBoundsUpdaterParameter.Value; }
62      set { VelocityBoundsUpdaterParameter.Value = value; }
63    }
64    #endregion
65
66    #region Parameter Properties
67    public ValueParameter<IntValue> SeedParameter {
68      get { return (ValueParameter<IntValue>)Parameters["Seed"]; }
69    }
70    public ValueParameter<BoolValue> SetSeedRandomlyParameter {
71      get { return (ValueParameter<BoolValue>)Parameters["SetSeedRandomly"]; }
72    }
73    public ValueParameter<IntValue> SwarmSizeParameter {
74      get { return (ValueParameter<IntValue>)Parameters["SwarmSize"]; }
75    }
76    public ValueParameter<IntValue> MaxIterationsParameter {
77      get { return (ValueParameter<IntValue>)Parameters["MaxIterations"]; }
78    }
79    public ValueParameter<DoubleValue> OmegaParameter {
80      get { return (ValueParameter<DoubleValue>)Parameters["Omega"]; }
81    }
82    public ValueParameter<DoubleValue> Phi_PParameter {
83      get { return (ValueParameter<DoubleValue>)Parameters["Phi_P"]; }
84    }
85    public ValueParameter<DoubleValue> Phi_GParameter {
86      get { return (ValueParameter<DoubleValue>)Parameters["Phi_G"]; }
87    }
88    public ValueParameter<MultiAnalyzer> AnalyzerParameter {
89      get { return (ValueParameter<MultiAnalyzer>)Parameters["Analyzer"]; }
90    }
91    public ValueLookupParameter<DoubleMatrix> VelocityBoundsParameter {
92      get { return (ValueLookupParameter<DoubleMatrix>)Parameters["VelocityBounds"]; }
93    }
94    public ConstrainedValueParameter<IParticleUpdater> ParticleUpdaterParameter {
95      get { return (ConstrainedValueParameter<IParticleUpdater>)Parameters["ParticleUpdater"]; }
96    }
97    public ConstrainedValueParameter<ITopologyInitializer> TopologyInitializerParameter {
98      get { return (ConstrainedValueParameter<ITopologyInitializer>)Parameters["TopologyInitializer"]; }
99    }
100    public ConstrainedValueParameter<ITopologyUpdater> TopologyUpdaterParameter {
101      get { return (ConstrainedValueParameter<ITopologyUpdater>)Parameters["TopologyUpdater"]; }
102    }
103    public ValueParameter<WeightedValueModifierSelector> VelocityBoundsUpdaterParameter {
104      get { return (ValueParameter<WeightedValueModifierSelector>)Parameters["VelocityBoundsUpdater"]; }
105    }
106    public ValueParameter<ValueModifierSelector> OmegaUpdaterParameter {
107      get { return (ValueParameter<ValueModifierSelector>)Parameters["OmegaUpdater"]; }
108    }
109    #endregion
110
111    #region Properties
112    [Storable]
113    private BestAverageWorstQualityAnalyzer qualityAnalyzer;
114
115    //[Storable]
116    //private IDiscreteDoubleValueModifier omegaModifier;
117    #endregion
118
119    [StorableConstructor]
120    protected ParticleSwarmOptimization(bool deserializing) : base(deserializing) { }
121    protected ParticleSwarmOptimization(ParticleSwarmOptimization original, Cloner cloner)
122      : base(original, cloner) {
123      qualityAnalyzer = cloner.Clone(original.qualityAnalyzer);
124      //omegaModifier = cloner.Clone(original.omegaModifier);
125    }
126
127    public ParticleSwarmOptimization()
128      : base() {
129      Parameters.Add(new ValueParameter<IntValue>("Seed", "The random seed used to initialize the new pseudo random number generator.", new IntValue(0)));
130      Parameters.Add(new ValueParameter<BoolValue>("SetSeedRandomly", "True if the random seed should be set to a random value, otherwise false.", new BoolValue(true)));
131      Parameters.Add(new ValueParameter<IntValue>("SwarmSize", "Size of the particle swarm.", new IntValue(10)));
132      Parameters.Add(new ValueParameter<IntValue>("MaxIterations", "Maximal number of iterations.", new IntValue(1000)));
133      Parameters.Add(new ValueParameter<MultiAnalyzer>("Analyzer", "The operator used to analyze each generation.", new MultiAnalyzer()));
134      Parameters.Add(new ValueParameter<DoubleValue>("Omega", "Weight for particle's velocity vector.", new DoubleValue(-0.2)));
135      Parameters.Add(new ValueParameter<DoubleValue>("Phi_P", "Weight for particle's personal best position.", new DoubleValue(-0.01)));
136      Parameters.Add(new ValueParameter<DoubleValue>("Phi_G", "Weight for global best position.", new DoubleValue(3.7)));
137      Parameters.Add(new ValueLookupParameter<DoubleMatrix>("VelocityBounds", "Maximum Velocity in every dimension", new DoubleMatrix(new double[,] { { -1, 1 } })));
138      Parameters.Add(new ConstrainedValueParameter<IParticleUpdater>("ParticleUpdater", "Operator that calculates new position and velocity of a particle",
139        new ItemSet<IParticleUpdater>(ApplicationManager.Manager.GetInstances<IParticleUpdater>())));
140      Parameters.Add(new ConstrainedValueParameter<ITopologyInitializer>("TopologyInitializer", "Creates neighborhood description vectors",
141        new ItemSet<ITopologyInitializer>(ApplicationManager.Manager.GetInstances<ITopologyInitializer>())));
142      Parameters.Add(new ConstrainedValueParameter<ITopologyUpdater>("TopologyUpdater", "Updates the neighborhood description vectors",
143        new ItemSet<ITopologyUpdater>(ApplicationManager.Manager.GetInstances<ITopologyUpdater>())));
144      //Parameters.Add(new ValueParameter<MultiParameterUpdater>("ParameterUpdater", "Updates the algorithm parameters according to some strategy",
145      //  new MultiParameterUpdater()));
146      Parameters.Add(new ValueParameter<ValueModifierSelector>("OmegaUpdater", "Updates the omega parameter", new ValueModifierSelector()));
147      Parameters.Add(new ValueParameter<WeightedValueModifierSelector>("VelocityBoundsUpdater", "Adjusts the velocity bounds", new WeightedValueModifierSelector()));
148      ParticleUpdaterParameter.ActualValue = ParticleUpdaterParameter.ValidValues.SingleOrDefault(v => v.GetType() == typeof(TotallyConnectedParticleUpdater));
149      TopologyInitializerParameter.ActualValue = TopologyInitializerParameter.ValidValues.SingleOrDefault(v => v.GetType() == typeof(EmptyTopologyInitializer));
150
151      RandomCreator randomCreator = new RandomCreator();
152      VariableCreator variableCreator = new VariableCreator();
153      SolutionsCreator solutionsCreator = new SolutionsCreator();
154      CombinedOperator particleCreator = new CombinedOperator();
155      Placeholder evaluatorPlaceholder = new Placeholder();
156      Assigner bestPersonalQualityAssigner = new Assigner();
157      BestPointInitializer bestPositionInitializer = new BestPointInitializer();
158      Placeholder topologyInitializerPlaceholder = new Placeholder();
159      NeighborUpdater neighborUpdater = new NeighborUpdater();
160      Placeholder analyzerPlaceholder = new Placeholder();
161      UniformSubScopesProcessor uniformSubScopeProcessor = new UniformSubScopesProcessor();
162      Placeholder particleUpdaterPlaceholder = new Placeholder();
163      Placeholder topologyUpdaterPlaceholder = new Placeholder();
164      UniformSubScopesProcessor uniformSubscopesProcessor2 = new UniformSubScopesProcessor();
165      NeighborUpdater neighborUpdater2 = new NeighborUpdater();
166      Placeholder evaluatorPlaceholder2 = new Placeholder();
167      SwarmUpdater swarmUpdater = new SwarmUpdater();
168      Placeholder analyzerPlaceholder2 = new Placeholder();
169      IntCounter currentIterationCounter = new IntCounter();
170      Comparator currentIterationComparator = new Comparator();
171      ConditionalBranch conditionalBranch = new ConditionalBranch();
172      Placeholder velocityBoundsUpdaterPlaceholder = new Placeholder();
173      Placeholder omegaUpdaterPlaceholder = new Placeholder();
174
175      OperatorGraph.InitialOperator = randomCreator;
176
177      randomCreator.SetSeedRandomlyParameter.Value = null;
178      randomCreator.SeedParameter.Value = null;
179      randomCreator.Successor = variableCreator;
180
181      variableCreator.CollectedValues.Add(new ValueParameter<IntValue>("CurrentIteration", new IntValue(0)));
182      variableCreator.Successor = solutionsCreator;
183
184      solutionsCreator.NumberOfSolutionsParameter.ActualName = "SwarmSize";
185      solutionsCreator.EvaluatorParameter.Value = evaluatorPlaceholder;
186      solutionsCreator.SolutionCreatorParameter.Value = particleCreator;
187      solutionsCreator.Successor = bestPositionInitializer;
188
189      InitializeParticleCreator(particleCreator);
190
191      evaluatorPlaceholder.Name = "(Evaluator)";
192      evaluatorPlaceholder.OperatorParameter.ActualName = "Evaluator";
193      evaluatorPlaceholder.Successor = bestPersonalQualityAssigner;
194
195      bestPersonalQualityAssigner.LeftSideParameter.ActualName = "PersonalBestQuality";
196      bestPersonalQualityAssigner.RightSideParameter.ActualName = "Quality";
197
198      bestPositionInitializer.Successor = topologyInitializerPlaceholder;
199
200      topologyInitializerPlaceholder.Name = "(TopologyInitializer)";
201      topologyInitializerPlaceholder.OperatorParameter.ActualName = "TopologyInitializer";
202      topologyInitializerPlaceholder.Successor = neighborUpdater;
203
204      neighborUpdater.Successor = analyzerPlaceholder;
205
206      analyzerPlaceholder.Name = "(Analyzer)";
207      analyzerPlaceholder.OperatorParameter.ActualName = "Analyzer";
208      analyzerPlaceholder.Successor = uniformSubScopeProcessor;
209
210      uniformSubScopeProcessor.Operator = particleUpdaterPlaceholder;
211      uniformSubScopeProcessor.Successor = topologyUpdaterPlaceholder;
212
213      particleUpdaterPlaceholder.Name = "(ParticleUpdater)";
214      particleUpdaterPlaceholder.OperatorParameter.ActualName = "ParticleUpdater";
215      particleUpdaterPlaceholder.Successor = evaluatorPlaceholder2;
216
217      evaluatorPlaceholder2.Name = "(Evaluator)";
218      evaluatorPlaceholder2.OperatorParameter.ActualName = "Evaluator";
219
220      topologyUpdaterPlaceholder.Name = "(TopologyUpdater)";
221      topologyUpdaterPlaceholder.OperatorParameter.ActualName = "TopologyUpdater";
222      topologyUpdaterPlaceholder.Successor = neighborUpdater2;
223
224      neighborUpdater2.Successor = uniformSubscopesProcessor2;
225
226      uniformSubscopesProcessor2.Operator = swarmUpdater;
227      uniformSubscopesProcessor2.Successor = analyzerPlaceholder2;
228
229      analyzerPlaceholder2.Name = "(Analyzer)";
230      analyzerPlaceholder2.OperatorParameter.ActualName = "Analyzer";
231      analyzerPlaceholder2.Successor = currentIterationCounter;
232
233      currentIterationCounter.Name = "CurrentIteration++";
234      currentIterationCounter.ValueParameter.ActualName = "CurrentIteration";
235      currentIterationCounter.Successor = omegaUpdaterPlaceholder;
236
237      omegaUpdaterPlaceholder.Name = "(Omega Updater)";
238      omegaUpdaterPlaceholder.OperatorParameter.ActualName = "OmegaUpdater";
239      omegaUpdaterPlaceholder.Successor = velocityBoundsUpdaterPlaceholder;
240
241      velocityBoundsUpdaterPlaceholder.Name = "(Velocity Bounds Updater)";
242      velocityBoundsUpdaterPlaceholder.OperatorParameter.ActualName = "VelocityBoundsUpdater";
243      velocityBoundsUpdaterPlaceholder.Successor = currentIterationComparator;
244
245      currentIterationComparator.LeftSideParameter.ActualName = "CurrentIteration";
246      currentIterationComparator.Comparison = new Comparison(ComparisonType.Less);
247      currentIterationComparator.RightSideParameter.ActualName = "MaxIterations";
248      currentIterationComparator.ResultParameter.ActualName = "ContinueIteration";
249      currentIterationComparator.Successor = conditionalBranch;
250
251      conditionalBranch.Name = "ContinueIteration?";
252      conditionalBranch.ConditionParameter.ActualName = "ContinueIteration";
253      conditionalBranch.TrueBranch = uniformSubScopeProcessor;
254
255      InitializeAnalyzers();
256      InitializeUpdaters();
257      UpdateAnalyzers();
258    }
259
260    private static void InitializeParticleCreator(CombinedOperator particleCreator) {
261      Placeholder positionCreator = new Placeholder();
262      Assigner personalBestPositionAssigner = new Assigner();
263      UniformRandomRealVectorCreator velocityCreator = new UniformRandomRealVectorCreator();
264
265      particleCreator.Name = "Particle Creator";
266      particleCreator.OperatorGraph.InitialOperator = positionCreator;
267
268      positionCreator.Name = "(SolutionCreator)";
269      positionCreator.OperatorParameter.ActualName = "SolutionCreator";
270      positionCreator.Successor = personalBestPositionAssigner;
271
272      personalBestPositionAssigner.LeftSideParameter.ActualName = "PersonalBestPoint";
273      personalBestPositionAssigner.RightSideParameter.ActualName = "Point";
274      personalBestPositionAssigner.Successor = velocityCreator;
275
276      velocityCreator.LengthParameter.ActualName = "ProblemSize";
277      velocityCreator.BoundsParameter.ActualName = "VelocityBounds";
278      velocityCreator.RealVectorParameter.ActualName = "Velocity";
279    }
280
281    public override IDeepCloneable Clone(Cloner cloner) {
282      return new ParticleSwarmOptimization(this, cloner);
283    }
284
285    public override void Prepare() {
286      if (Problem != null) base.Prepare();
287    }
288
289    #region Events
290    protected override void OnProblemChanged() {
291      UpdateAnalyzers();
292      ParameterizeAnalyzers();
293      Problem.Evaluator.QualityParameter.ActualNameChanged += new EventHandler(Evaluator_QualityParameter_ActualNameChanged);
294      base.OnProblemChanged();
295    }
296
297    #endregion
298
299    #region Helpers
300    private void InitializeParticleUpdaters() {
301    }
302
303    private void Evaluator_QualityParameter_ActualNameChanged(object sender, EventArgs e) {
304    }
305
306    private void InitializeAnalyzers() {
307      qualityAnalyzer = new BestAverageWorstQualityAnalyzer();
308      ParameterizeAnalyzers();
309    }
310
311    private void InitializeUpdaters() {
312      OmegaUpdater.ValueParameter.ActualName = OmegaParameter.Name;
313      foreach (IDiscreteDoubleValueModifier op in ApplicationManager.Manager.GetInstances<IDiscreteDoubleValueModifier>()) {
314        OmegaUpdater.ModifierParameter.ValidValues.Add(op);
315        op.EndIndexParameter.ActualName = MaxIterationsParameter.Name;
316        op.StartIndexParameter.Value = new IntValue(0);
317        op.IndexParameter.ActualName = "CurrentIteration";
318        op.ValueParameter.ActualName = OmegaUpdater.ValueParameter.ActualName;
319        op.StartValueParameter.Value = new DoubleValue(OmegaParameter.Value.Value);
320        op.EndValueParameter.Value = new DoubleValue(-2);
321      }
322      VelocityBoundsUpdater.ValueParameter.ActualName = VelocityBoundsParameter.Name;
323      foreach (IDiscreteDoubleValueModifier op in ApplicationManager.Manager.GetInstances<IDiscreteDoubleValueModifier>()) {
324        VelocityBoundsUpdater.ModifierParameter.ValidValues.Add(op);
325        op.EndIndexParameter.ActualName = MaxIterationsParameter.Name;
326        op.StartIndexParameter.Value = new IntValue(0);
327        op.IndexParameter.ActualName = "CurrentIteration";
328        op.ValueParameter.ActualName = VelocityBoundsUpdater.ScaleParameter.Name;
329        op.StartValueParameter.Value = new DoubleValue(VelocityBoundsUpdater.ScaleParameter.Value.Value);
330        op.EndValueParameter.Value = new DoubleValue(0);
331        }
332    }
333
334    private void ParameterizeAnalyzers() {
335      if (Problem != null) {
336        qualityAnalyzer.MaximizationParameter.ActualName = Problem.MaximizationParameter.Name;
337        qualityAnalyzer.QualityParameter.ActualName = Problem.Evaluator.QualityParameter.ActualName;
338        qualityAnalyzer.BestKnownQualityParameter.ActualName = Problem.BestKnownQualityParameter.Name;
339      }
340    }
341
342    private void UpdateAnalyzers() {
343      Analyzer.Operators.Clear();
344      if (Problem != null) {
345        foreach (IAnalyzer analyzer in Problem.Operators.OfType<IAnalyzer>())
346          Analyzer.Operators.Add(analyzer);
347      }
348      Analyzer.Operators.Add(qualityAnalyzer);
349    }
350
351    #endregion
352  }
353}
Note: See TracBrowser for help on using the repository browser.