Free cookie consent management tool by TermsFeed Policy Generator

source: trunk/sources/HeuristicLab.Algorithms.ParticleSwarmOptimization/3.3/ParticleSwarmOptimization.cs @ 5643

Last change on this file since 5643 was 5643, checked in by mkofler, 13 years ago

#852: PSO code refactoring. Cleanup and minor improvements.

File size: 19.0 KB
RevLine 
[3348]1#region License Information
2/* HeuristicLab
[5445]3 * Copyright (C) 2002-2011 Heuristic and Evolutionary Algorithms Laboratory (HEAL)
[3348]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;
[4068]24using HeuristicLab.Analysis;
[3376]25using HeuristicLab.Common;
[3348]26using HeuristicLab.Core;
27using HeuristicLab.Data;
[4068]28using HeuristicLab.Operators;
[3348]29using HeuristicLab.Optimization;
30using HeuristicLab.Optimization.Operators;
31using HeuristicLab.Parameters;
32using HeuristicLab.Persistence.Default.CompositeSerializers.Storable;
[5209]33using HeuristicLab.PluginInfrastructure;
[3368]34using HeuristicLab.Random;
[3348]35
36namespace HeuristicLab.Algorithms.ParticleSwarmOptimization {
[5209]37  [Item("Particle Swarm Optimization", "A particle swarm optimization algorithm based on the description in Pedersen, M.E.H. (2010). PhD thesis. University of Southampton.")]
[3348]38  [Creatable("Algorithms")]
39  [StorableClass]
[5435]40  public sealed class ParticleSwarmOptimization : EngineAlgorithm, IStorableContent {
[5033]41
[3348]42    #region Problem Properties
43    public override Type ProblemType {
44      get { return typeof(ISingleObjectiveProblem); }
45    }
46    public new ISingleObjectiveProblem Problem {
47      get { return (ISingleObjectiveProblem)base.Problem; }
48      set { base.Problem = value; }
49    }
[3682]50    public MultiAnalyzer Analyzer {
51      get { return AnalyzerParameter.Value; }
52      set { AnalyzerParameter.Value = value; }
53    }
[5560]54    public IDiscreteDoubleValueModifier InertiaUpdater {
55      get { return InertiaUpdaterParameter.Value; }
56      set { InertiaUpdaterParameter.Value = value; }
[5225]57    }
[4068]58    #endregion
[3348]59
60    #region Parameter Properties
[5410]61    public IValueParameter<IntValue> SeedParameter {
62      get { return (IValueParameter<IntValue>)Parameters["Seed"]; }
[3348]63    }
[5410]64    public IValueParameter<BoolValue> SetSeedRandomlyParameter {
65      get { return (IValueParameter<BoolValue>)Parameters["SetSeedRandomly"]; }
[3348]66    }
[5410]67    public IValueParameter<IntValue> SwarmSizeParameter {
68      get { return (IValueParameter<IntValue>)Parameters["SwarmSize"]; }
[3348]69    }
[5410]70    public IValueParameter<IntValue> MaxIterationsParameter {
71      get { return (IValueParameter<IntValue>)Parameters["MaxIterations"]; }
[3348]72    }
[5560]73    public IValueParameter<DoubleValue> InertiaParameter {
74      get { return (IValueParameter<DoubleValue>)Parameters["Inertia"]; }
[3348]75    }
[5560]76    public IValueParameter<DoubleValue> PersonalBestAttractionParameter {
77      get { return (IValueParameter<DoubleValue>)Parameters["PersonalBestAttraction"]; }
[5033]78    }
[5568]79    public IValueParameter<DoubleValue> NeighborBestAttractionParameter {
80      get { return (IValueParameter<DoubleValue>)Parameters["NeighborBestAttraction"]; }
[5033]81    }
[5410]82    public IValueParameter<MultiAnalyzer> AnalyzerParameter {
83      get { return (IValueParameter<MultiAnalyzer>)Parameters["Analyzer"]; }
[3682]84    }
[5560]85    public ConstrainedValueParameter<IParticleCreator> ParticleCreatorParameter {
86      get { return (ConstrainedValueParameter<IParticleCreator>)Parameters["ParticleCreator"]; }
[5033]87    }
[5209]88    public ConstrainedValueParameter<IParticleUpdater> ParticleUpdaterParameter {
89      get { return (ConstrainedValueParameter<IParticleUpdater>)Parameters["ParticleUpdater"]; }
90    }
[5410]91    public OptionalConstrainedValueParameter<ITopologyInitializer> TopologyInitializerParameter {
92      get { return (OptionalConstrainedValueParameter<ITopologyInitializer>)Parameters["TopologyInitializer"]; }
[5209]93    }
[5410]94    public OptionalConstrainedValueParameter<ITopologyUpdater> TopologyUpdaterParameter {
95      get { return (OptionalConstrainedValueParameter<ITopologyUpdater>)Parameters["TopologyUpdater"]; }
[5209]96    }
[5560]97    public OptionalConstrainedValueParameter<IDiscreteDoubleValueModifier> InertiaUpdaterParameter {
98      get { return (OptionalConstrainedValueParameter<IDiscreteDoubleValueModifier>)Parameters["InertiaUpdater"]; }
[5225]99    }
[5568]100    public ConstrainedValueParameter<ISwarmUpdater> SwarmUpdaterParameter {
101      get { return (ConstrainedValueParameter<ISwarmUpdater>)Parameters["SwarmUpdater"]; }
102
103    }
[3348]104    #endregion
105
106    #region Properties
[5316]107
108    public string Filename { get; set; }
109
[3719]110    [Storable]
[3682]111    private BestAverageWorstQualityAnalyzer qualityAnalyzer;
[5342]112
[5560]113    [Storable]
114    private SolutionsCreator solutionsCreator;
115
116    [Storable]
117    private ParticleSwarmOptimizationMainLoop mainLoop;
118
[5342]119    public ITopologyInitializer TopologyInitializer {
120      get { return TopologyInitializerParameter.Value; }
121      set { TopologyInitializerParameter.Value = value; }
122    }
123
124    public ITopologyUpdater TopologyUpdater {
125      get { return TopologyUpdaterParameter.Value; }
126      set { TopologyUpdaterParameter.Value = value; }
127    }
128
[5560]129    public IParticleCreator ParticleCreator {
130      get { return ParticleCreatorParameter.Value; }
131      set { ParticleCreatorParameter.Value = value; }
132    }
133
[5342]134    public IParticleUpdater ParticleUpdater {
135      get { return ParticleUpdaterParameter.Value; }
136      set { ParticleUpdaterParameter.Value = value; }
137    }
[3348]138    #endregion
139
[5033]140    [StorableConstructor]
[5435]141    private ParticleSwarmOptimization(bool deserializing) : base(deserializing) { }
142    private ParticleSwarmOptimization(ParticleSwarmOptimization original, Cloner cloner)
[5033]143      : base(original, cloner) {
144      qualityAnalyzer = cloner.Clone(original.qualityAnalyzer);
[5560]145      solutionsCreator = cloner.Clone(original.solutionsCreator);
[5561]146      mainLoop = cloner.Clone(original.mainLoop);
[5342]147      Initialize();
[5033]148    }
[3348]149    public ParticleSwarmOptimization()
150      : base() {
151      Parameters.Add(new ValueParameter<IntValue>("Seed", "The random seed used to initialize the new pseudo random number generator.", new IntValue(0)));
152      Parameters.Add(new ValueParameter<BoolValue>("SetSeedRandomly", "True if the random seed should be set to a random value, otherwise false.", new BoolValue(true)));
[3724]153      Parameters.Add(new ValueParameter<IntValue>("SwarmSize", "Size of the particle swarm.", new IntValue(10)));
[3348]154      Parameters.Add(new ValueParameter<IntValue>("MaxIterations", "Maximal number of iterations.", new IntValue(1000)));
[3682]155      Parameters.Add(new ValueParameter<MultiAnalyzer>("Analyzer", "The operator used to analyze each generation.", new MultiAnalyzer()));
[5560]156      Parameters.Add(new ValueParameter<DoubleValue>("Inertia", "Inertia weight on a particle's movement (omega).", new DoubleValue(-0.2)));
157      Parameters.Add(new ValueParameter<DoubleValue>("PersonalBestAttraction", "Weight for particle's pull towards its personal best soution (phi_p).", new DoubleValue(-0.01)));
[5568]158      Parameters.Add(new ValueParameter<DoubleValue>("NeighborBestAttraction", "Weight for pull towards the neighborhood best solution or global best solution in case of a totally connected topology (phi_g).", new DoubleValue(3.7)));
[5560]159      Parameters.Add(new ConstrainedValueParameter<IParticleCreator>("ParticleCreator", "Operator creates a new particle."));
160      Parameters.Add(new ConstrainedValueParameter<IParticleUpdater>("ParticleUpdater", "Operator that updates a particle."));
161      Parameters.Add(new OptionalConstrainedValueParameter<ITopologyInitializer>("TopologyInitializer", "Creates neighborhood description vectors."));
162      Parameters.Add(new OptionalConstrainedValueParameter<ITopologyUpdater>("TopologyUpdater", "Updates the neighborhood description vectors."));
163      Parameters.Add(new OptionalConstrainedValueParameter<IDiscreteDoubleValueModifier>("InertiaUpdater", "Updates the omega parameter."));
[5568]164      Parameters.Add(new ConstrainedValueParameter<ISwarmUpdater>("SwarmUpdater", "Encoding-specific parameter which is provided by the problem. May provide additional encoding-specific parameters, such as velocity bounds for real valued problems"));
[5033]165
[3348]166      RandomCreator randomCreator = new RandomCreator();
[5033]167      VariableCreator variableCreator = new VariableCreator();
[5560]168      solutionsCreator = new SolutionsCreator();
[5643]169      SubScopesCounter subScopesCounter = new SubScopesCounter();
[5209]170      Placeholder topologyInitializerPlaceholder = new Placeholder();
[5033]171      Placeholder analyzerPlaceholder = new Placeholder();
[5560]172      mainLoop = new ParticleSwarmOptimizationMainLoop();
[3348]173
[5033]174      OperatorGraph.InitialOperator = randomCreator;
[3682]175
[5033]176      randomCreator.SetSeedRandomlyParameter.Value = null;
[3348]177      randomCreator.SeedParameter.Value = null;
[5033]178      randomCreator.Successor = variableCreator;
[4068]179
[5033]180      variableCreator.CollectedValues.Add(new ValueParameter<IntValue>("CurrentIteration", new IntValue(0)));
[5643]181      variableCreator.CollectedValues.Add(new ValueParameter<DoubleValue>("CurrentVelocityBounds", new DoubleValue(0)));
[5033]182      variableCreator.Successor = solutionsCreator;
[4068]183
[5033]184      solutionsCreator.NumberOfSolutionsParameter.ActualName = "SwarmSize";
[5568]185      ParameterizeSolutionsCreator();
[5643]186      solutionsCreator.Successor = subScopesCounter;
[4068]187
[5643]188      subScopesCounter.Name = "Initialize EvaluatedSolutions";
189      subScopesCounter.ValueParameter.ActualName = "EvaluatedSolutions";
190      subScopesCounter.Successor = topologyInitializerPlaceholder;
191
[5209]192      topologyInitializerPlaceholder.Name = "(TopologyInitializer)";
193      topologyInitializerPlaceholder.OperatorParameter.ActualName = "TopologyInitializer";
[5568]194      topologyInitializerPlaceholder.Successor = mainLoop;
[5209]195
[5560]196      mainLoop.AnalyzerParameter.ActualName = AnalyzerParameter.Name;
197      mainLoop.InertiaParameter.ActualName = InertiaParameter.Name;
198      mainLoop.MaxIterationsParameter.ActualName = MaxIterationsParameter.Name;
[5568]199      mainLoop.NeighborBestAttractionParameter.ActualName = NeighborBestAttractionParameter.Name;
[5560]200      mainLoop.InertiaUpdaterParameter.ActualName = InertiaUpdaterParameter.Name;
201      mainLoop.ParticleUpdaterParameter.ActualName = ParticleUpdaterParameter.Name;
202      mainLoop.PersonalBestAttractionParameter.ActualName = PersonalBestAttractionParameter.Name;
203      mainLoop.RandomParameter.ActualName = randomCreator.RandomParameter.ActualName;
[5568]204      mainLoop.SwarmSizeParameter.ActualName = SwarmSizeParameter.Name;
205      mainLoop.TopologyUpdaterParameter.ActualName = TopologyUpdaterParameter.Name;
[5560]206      mainLoop.RandomParameter.ActualName = randomCreator.RandomParameter.ActualName;
207      mainLoop.ResultsParameter.ActualName = "Results";
[3682]208
[3719]209      InitializeAnalyzers();
[5560]210      InitializeParticleCreator();
[5561]211      InitializeSwarmUpdater();
[5568]212      ParameterizeSolutionsCreator();
[3719]213      UpdateAnalyzers();
[5560]214      UpdateInertiaUpdater();
215      InitInertiaUpdater();
[5410]216      UpdateTopologyInitializer();
[5342]217      Initialize();
[5568]218      ParameterizeMainLoop();
[3348]219    }
220
[5410]221    public override IDeepCloneable Clone(Cloner cloner) {
222      return new ParticleSwarmOptimization(this, cloner);
[5342]223    }
224
[5435]225    [StorableHook(HookType.AfterDeserialization)]
226    private void AfterDeserialization() {
227      Initialize();
228    }
229
[5410]230    public override void Prepare() {
[5560]231      if (Problem != null && ParticleCreator != null && ParticleUpdater != null) {
[5410]232        base.Prepare();
[5643]233        VariableCreator creator = (VariableCreator)((RandomCreator)OperatorGraph.InitialOperator).Successor;
234        ValueParameter<DoubleValue> currentInertia = null;
235        if (creator.CollectedValues.ContainsKey("CurrentInertia")) {
236          currentInertia = (ValueParameter<DoubleValue>) creator.CollectedValues["CurrentInertia"];
237        } else {
238          currentInertia = new ValueParameter<DoubleValue>("CurrentInertia");
239          creator.CollectedValues.Add(currentInertia);
[5342]240        }
[5643]241        currentInertia.ActualValue = InertiaParameter.ActualValue;
[5342]242      }
243    }
244
[5410]245    #region Events
246    protected override void OnProblemChanged() {
247      UpdateAnalyzers();
248      ParameterizeAnalyzers();
[5560]249      UpdateTopologyParameters();
250      InitializeParticleCreator();
[5561]251      InitializeSwarmUpdater();
[5568]252      ParameterizeSolutionsCreator();
[5410]253      base.OnProblemChanged();
[5342]254    }
255
256    void TopologyInitializerParameter_ValueChanged(object sender, EventArgs e) {
[5410]257      this.UpdateTopologyParameters();
258    }
259
[5560]260    //void VelocityBoundsUpdaterParameter_ValueChanged(object sender, EventArgs e) {
261    //  if (VelocityBoundsParameter.Value != null) {
262    //    foreach (IDiscreteDoubleMatrixModifier matrixOp in VelocityBoundsUpdaterParameter.Value.ScalingOperatorParameter.ValidValues) {
263    //      matrixOp.ValueParameter.ActualName = VelocityBoundsUpdater.ScaleParameter.Name;
264    //      matrixOp.StartValueParameter.Value = new DoubleValue(VelocityBoundsUpdater.ScaleParameter.ActualValue.Value);
265    //    }
266    //  }
267    //}
[5410]268    #endregion
[5342]269
[5410]270    #region Helpers
271    private void Initialize() {
272      TopologyInitializerParameter.ValueChanged += new EventHandler(TopologyInitializerParameter_ValueChanged);
273    }
274
[5560]275    private void InitializeParticleCreator() {
276      if (Problem != null) {
277        IParticleCreator oldParticleCreator = ParticleCreator;
278        ParticleCreatorParameter.ValidValues.Clear();
279        foreach (IParticleCreator Creator in Problem.Operators.OfType<IParticleCreator>().OrderBy(x => x.Name)) {
280          ParticleCreatorParameter.ValidValues.Add(Creator);
281        }
282        if (oldParticleCreator != null) {
283          IParticleCreator creator = ParticleCreatorParameter.ValidValues.FirstOrDefault(x => x.GetType() == oldParticleCreator.GetType());
284          if (creator != null) ParticleCreator = creator;
[5568]285        }
[5560]286      }
[3348]287    }
288
[5410]289    private void InitializeAnalyzers() {
290      qualityAnalyzer = new BestAverageWorstQualityAnalyzer();
[5581]291      qualityAnalyzer.ResultsParameter.ActualName = "Results";
[5410]292      ParameterizeAnalyzers();
[3348]293    }
294
[5410]295    private void ParameterizeAnalyzers() {
[5312]296      if (Problem != null) {
[5410]297        qualityAnalyzer.MaximizationParameter.ActualName = Problem.MaximizationParameter.Name;
298        qualityAnalyzer.QualityParameter.ActualName = Problem.Evaluator.QualityParameter.ActualName;
299        qualityAnalyzer.BestKnownQualityParameter.ActualName = Problem.BestKnownQualityParameter.Name;
[5312]300      }
[3348]301    }
302
[5410]303    private void UpdateAnalyzers() {
304      Analyzer.Operators.Clear();
305      if (Problem != null) {
306        foreach (IAnalyzer analyzer in Problem.Operators.OfType<IAnalyzer>())
307          Analyzer.Operators.Add(analyzer);
308      }
309      Analyzer.Operators.Add(qualityAnalyzer);
[3348]310    }
[3415]311
[5560]312    private void InitInertiaUpdater() {
313      foreach (IDiscreteDoubleValueModifier updater in InertiaUpdaterParameter.ValidValues) {
[5311]314        updater.EndIndexParameter.ActualName = MaxIterationsParameter.Name;
315        updater.StartIndexParameter.Value = new IntValue(0);
316        updater.IndexParameter.ActualName = "CurrentIteration";
[5643]317        updater.ValueParameter.ActualName = "CurrentInertia";
[5311]318        updater.StartValueParameter.Value = new DoubleValue(1);
319        updater.EndValueParameter.Value = new DoubleValue(0);
320      }
321    }
322
[5560]323    private void UpdateInertiaUpdater() {
324      IDiscreteDoubleValueModifier oldInertiaUpdater = InertiaUpdater;
325      InertiaUpdaterParameter.ValidValues.Clear();
[5311]326      foreach (IDiscreteDoubleValueModifier updater in ApplicationManager.Manager.GetInstances<IDiscreteDoubleValueModifier>().OrderBy(x => x.Name)) {
[5560]327        InertiaUpdaterParameter.ValidValues.Add(updater);
[5311]328      }
[5560]329      if (oldInertiaUpdater != null) {
330        IDiscreteDoubleValueModifier updater = InertiaUpdaterParameter.ValidValues.FirstOrDefault(x => x.GetType() == oldInertiaUpdater.GetType());
331        if (updater != null) InertiaUpdaterParameter.Value = updater;
[5311]332      }
333    }
334
[5410]335    private void UpdateTopologyInitializer() {
336      ITopologyInitializer oldTopologyInitializer = TopologyInitializer;
337      TopologyInitializerParameter.ValidValues.Clear();
338      foreach (ITopologyInitializer topologyInitializer in ApplicationManager.Manager.GetInstances<ITopologyInitializer>().OrderBy(x => x.Name)) {
339        TopologyInitializerParameter.ValidValues.Add(topologyInitializer);
[3348]340      }
[5410]341      if (oldTopologyInitializer != null && TopologyInitializerParameter.ValidValues.Any(x => x.GetType() == oldTopologyInitializer.GetType()))
342        TopologyInitializer = TopologyInitializerParameter.ValidValues.FirstOrDefault(x => x.GetType() == oldTopologyInitializer.GetType());
343      UpdateTopologyParameters();
[3348]344    }
[3415]345
[5410]346    private void UpdateTopologyParameters() {
347      ITopologyUpdater oldTopologyUpdater = TopologyUpdater;
348      IParticleUpdater oldParticleUpdater = ParticleUpdater;
349      ClearTopologyParameters();
[5560]350      if (Problem != null) {
351        if (TopologyInitializer != null) {
352          foreach (ITopologyUpdater topologyUpdater in ApplicationManager.Manager.GetInstances<ITopologyUpdater>())
353            TopologyUpdaterParameter.ValidValues.Add(topologyUpdater);
354          foreach (IParticleUpdater particleUpdater in Problem.Operators.OfType<ILocalParticleUpdater>().OrderBy(x => x.Name))
355            ParticleUpdaterParameter.ValidValues.Add(particleUpdater);
356        } else {
357          foreach (IParticleUpdater particleUpdater in Problem.Operators.OfType<IGlobalParticleUpdater>().OrderBy(x => x.Name))
358            ParticleUpdaterParameter.ValidValues.Add(particleUpdater);
359        }
360        if (oldTopologyUpdater != null) {
361          ITopologyUpdater newTopologyUpdater = TopologyUpdaterParameter.ValidValues.FirstOrDefault(x => x.GetType() == oldParticleUpdater.GetType());
362          if (newTopologyUpdater != null) TopologyUpdater = newTopologyUpdater;
363        }
364        if (oldParticleUpdater != null) {
365          IParticleUpdater newParticleUpdater = ParticleUpdaterParameter.ValidValues.FirstOrDefault(x => x.GetType() == oldParticleUpdater.GetType());
366          if (newParticleUpdater != null) ParticleUpdater = newParticleUpdater;
367        }
[3682]368      }
369    }
370
[5410]371    private void ClearTopologyParameters() {
372      TopologyUpdaterParameter.ValidValues.Clear();
373      ParticleUpdaterParameter.ValidValues.Clear();
374    }
[5560]375
376    private void ParameterizeSolutionsCreator() {
377      if (Problem != null) {
378        solutionsCreator.EvaluatorParameter.ActualName = Problem.EvaluatorParameter.Name;
379        solutionsCreator.SolutionCreatorParameter.ActualName = ParticleCreatorParameter.Name;
380      }
381    }
382
383    private void ParameterizeMainLoop() {
[5568]384      if (Problem != null) {
[5561]385        mainLoop.EvaluatorParameter.ActualName = Problem.EvaluatorParameter.Name;
386      }
[5560]387    }
[5561]388
389    private void InitializeSwarmUpdater() {
390      if (Problem != null) {
391        ISwarmUpdater updater = Problem.Operators.OfType<ISwarmUpdater>().FirstOrDefault();
[5568]392        SwarmUpdaterParameter.ValidValues.Clear();
393        SwarmUpdaterParameter.ValidValues.Add(updater);
394        SwarmUpdaterParameter.Value = updater;
[5561]395      }
396    }
[3348]397    #endregion
[5410]398
[3348]399  }
400}
Note: See TracBrowser for help on using the repository browser.