Free cookie consent management tool by TermsFeed Policy Generator

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

Last change on this file since 6212 was 5941, checked in by mkofler, 14 years ago

#852: Set the default inertia value to 1 for consistency reasons.

File size: 18.3 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]
[5809]40  public sealed class ParticleSwarmOptimization : HeuristicOptimizationEngineAlgorithm, IStorableContent {
[5033]41
[3348]42    #region Problem Properties
43    public override Type ProblemType {
[5809]44      get { return typeof(ISingleObjectiveHeuristicOptimizationProblem); }
[3348]45    }
[5809]46    public new ISingleObjectiveHeuristicOptimizationProblem Problem {
47      get { return (ISingleObjectiveHeuristicOptimizationProblem)base.Problem; }
[3348]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()));
[5941]156      Parameters.Add(new ValueParameter<DoubleValue>("Inertia", "Inertia weight on a particle's movement (omega).", new DoubleValue(1)));
[5560]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)));
[5844]159      Parameters.Add(new ConstrainedValueParameter<IParticleCreator>("ParticleCreator", "Operator that creates a new particle."));
[5560]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"));
[5866]165      ParticleUpdaterParameter.Hidden = true;
[5033]166
[3348]167      RandomCreator randomCreator = new RandomCreator();
[5033]168      VariableCreator variableCreator = new VariableCreator();
[5866]169      Assigner currentInertiaAssigner = new Assigner();
[5560]170      solutionsCreator = new SolutionsCreator();
[5643]171      SubScopesCounter subScopesCounter = new SubScopesCounter();
[5209]172      Placeholder topologyInitializerPlaceholder = new Placeholder();
[5560]173      mainLoop = new ParticleSwarmOptimizationMainLoop();
[3348]174
[5033]175      OperatorGraph.InitialOperator = randomCreator;
[3682]176
[5033]177      randomCreator.SetSeedRandomlyParameter.Value = null;
[3348]178      randomCreator.SeedParameter.Value = null;
[5033]179      randomCreator.Successor = variableCreator;
[4068]180
[5935]181      variableCreator.CollectedValues.Add(new ValueParameter<IntValue>("Iterations", new IntValue(0)));
[5866]182      variableCreator.Successor = currentInertiaAssigner;
[4068]183
[5866]184      currentInertiaAssigner.Name = "CurrentInertia := Inertia";
185      currentInertiaAssigner.LeftSideParameter.ActualName = "CurrentInertia";
186      currentInertiaAssigner.RightSideParameter.ActualName = "Inertia";
187      currentInertiaAssigner.Successor = solutionsCreator;
[5645]188
[5033]189      solutionsCreator.NumberOfSolutionsParameter.ActualName = "SwarmSize";
[5568]190      ParameterizeSolutionsCreator();
[5643]191      solutionsCreator.Successor = subScopesCounter;
[4068]192
[5643]193      subScopesCounter.Name = "Initialize EvaluatedSolutions";
194      subScopesCounter.ValueParameter.ActualName = "EvaluatedSolutions";
195      subScopesCounter.Successor = topologyInitializerPlaceholder;
196
[5209]197      topologyInitializerPlaceholder.Name = "(TopologyInitializer)";
198      topologyInitializerPlaceholder.OperatorParameter.ActualName = "TopologyInitializer";
[5568]199      topologyInitializerPlaceholder.Successor = mainLoop;
[5209]200
[5560]201      mainLoop.AnalyzerParameter.ActualName = AnalyzerParameter.Name;
[5645]202      mainLoop.InertiaParameter.ActualName = "CurrentInertia";
[5560]203      mainLoop.MaxIterationsParameter.ActualName = MaxIterationsParameter.Name;
[5568]204      mainLoop.NeighborBestAttractionParameter.ActualName = NeighborBestAttractionParameter.Name;
[5560]205      mainLoop.InertiaUpdaterParameter.ActualName = InertiaUpdaterParameter.Name;
206      mainLoop.ParticleUpdaterParameter.ActualName = ParticleUpdaterParameter.Name;
207      mainLoop.PersonalBestAttractionParameter.ActualName = PersonalBestAttractionParameter.Name;
208      mainLoop.RandomParameter.ActualName = randomCreator.RandomParameter.ActualName;
[5568]209      mainLoop.SwarmSizeParameter.ActualName = SwarmSizeParameter.Name;
210      mainLoop.TopologyUpdaterParameter.ActualName = TopologyUpdaterParameter.Name;
[5560]211      mainLoop.RandomParameter.ActualName = randomCreator.RandomParameter.ActualName;
212      mainLoop.ResultsParameter.ActualName = "Results";
[3682]213
[3719]214      InitializeAnalyzers();
[5560]215      InitializeParticleCreator();
[5561]216      InitializeSwarmUpdater();
[5568]217      ParameterizeSolutionsCreator();
[3719]218      UpdateAnalyzers();
[5560]219      UpdateInertiaUpdater();
220      InitInertiaUpdater();
[5410]221      UpdateTopologyInitializer();
[5342]222      Initialize();
[5568]223      ParameterizeMainLoop();
[3348]224    }
225
[5410]226    public override IDeepCloneable Clone(Cloner cloner) {
227      return new ParticleSwarmOptimization(this, cloner);
[5342]228    }
229
[5435]230    [StorableHook(HookType.AfterDeserialization)]
231    private void AfterDeserialization() {
232      Initialize();
233    }
234
[5410]235    public override void Prepare() {
[5560]236      if (Problem != null && ParticleCreator != null && ParticleUpdater != null) {
[5410]237        base.Prepare();
[5342]238      }
239    }
240
[5410]241    #region Events
242    protected override void OnProblemChanged() {
243      UpdateAnalyzers();
244      ParameterizeAnalyzers();
[5560]245      UpdateTopologyParameters();
246      InitializeParticleCreator();
[5561]247      InitializeSwarmUpdater();
[5568]248      ParameterizeSolutionsCreator();
[5410]249      base.OnProblemChanged();
[5342]250    }
251
252    void TopologyInitializerParameter_ValueChanged(object sender, EventArgs e) {
[5410]253      this.UpdateTopologyParameters();
254    }
255    #endregion
[5342]256
[5410]257    #region Helpers
258    private void Initialize() {
259      TopologyInitializerParameter.ValueChanged += new EventHandler(TopologyInitializerParameter_ValueChanged);
260    }
261
[5560]262    private void InitializeParticleCreator() {
263      if (Problem != null) {
264        IParticleCreator oldParticleCreator = ParticleCreator;
265        ParticleCreatorParameter.ValidValues.Clear();
266        foreach (IParticleCreator Creator in Problem.Operators.OfType<IParticleCreator>().OrderBy(x => x.Name)) {
267          ParticleCreatorParameter.ValidValues.Add(Creator);
268        }
269        if (oldParticleCreator != null) {
270          IParticleCreator creator = ParticleCreatorParameter.ValidValues.FirstOrDefault(x => x.GetType() == oldParticleCreator.GetType());
271          if (creator != null) ParticleCreator = creator;
[5568]272        }
[5560]273      }
[3348]274    }
275
[5410]276    private void InitializeAnalyzers() {
277      qualityAnalyzer = new BestAverageWorstQualityAnalyzer();
[5581]278      qualityAnalyzer.ResultsParameter.ActualName = "Results";
[5410]279      ParameterizeAnalyzers();
[3348]280    }
281
[5410]282    private void ParameterizeAnalyzers() {
[5312]283      if (Problem != null) {
[5410]284        qualityAnalyzer.MaximizationParameter.ActualName = Problem.MaximizationParameter.Name;
285        qualityAnalyzer.QualityParameter.ActualName = Problem.Evaluator.QualityParameter.ActualName;
286        qualityAnalyzer.BestKnownQualityParameter.ActualName = Problem.BestKnownQualityParameter.Name;
[5312]287      }
[3348]288    }
289
[5410]290    private void UpdateAnalyzers() {
291      Analyzer.Operators.Clear();
292      if (Problem != null) {
293        foreach (IAnalyzer analyzer in Problem.Operators.OfType<IAnalyzer>())
294          Analyzer.Operators.Add(analyzer);
295      }
296      Analyzer.Operators.Add(qualityAnalyzer);
[3348]297    }
[3415]298
[5560]299    private void InitInertiaUpdater() {
300      foreach (IDiscreteDoubleValueModifier updater in InertiaUpdaterParameter.ValidValues) {
[5311]301        updater.EndIndexParameter.ActualName = MaxIterationsParameter.Name;
[5935]302        updater.EndIndexParameter.Hidden = true;
[5311]303        updater.StartIndexParameter.Value = new IntValue(0);
[5893]304        updater.StartIndexParameter.Hidden = true;
[5935]305        updater.IndexParameter.ActualName = "Iterations";
[5645]306        updater.ValueParameter.ActualName = "CurrentInertia";
[5311]307        updater.StartValueParameter.Value = new DoubleValue(1);
[5941]308        updater.EndValueParameter.Value = new DoubleValue(1E-10);
[5311]309      }
310    }
311
[5560]312    private void UpdateInertiaUpdater() {
313      IDiscreteDoubleValueModifier oldInertiaUpdater = InertiaUpdater;
314      InertiaUpdaterParameter.ValidValues.Clear();
[5311]315      foreach (IDiscreteDoubleValueModifier updater in ApplicationManager.Manager.GetInstances<IDiscreteDoubleValueModifier>().OrderBy(x => x.Name)) {
[5560]316        InertiaUpdaterParameter.ValidValues.Add(updater);
[5311]317      }
[5560]318      if (oldInertiaUpdater != null) {
319        IDiscreteDoubleValueModifier updater = InertiaUpdaterParameter.ValidValues.FirstOrDefault(x => x.GetType() == oldInertiaUpdater.GetType());
320        if (updater != null) InertiaUpdaterParameter.Value = updater;
[5311]321      }
322    }
323
[5410]324    private void UpdateTopologyInitializer() {
325      ITopologyInitializer oldTopologyInitializer = TopologyInitializer;
326      TopologyInitializerParameter.ValidValues.Clear();
327      foreach (ITopologyInitializer topologyInitializer in ApplicationManager.Manager.GetInstances<ITopologyInitializer>().OrderBy(x => x.Name)) {
328        TopologyInitializerParameter.ValidValues.Add(topologyInitializer);
[3348]329      }
[5410]330      if (oldTopologyInitializer != null && TopologyInitializerParameter.ValidValues.Any(x => x.GetType() == oldTopologyInitializer.GetType()))
331        TopologyInitializer = TopologyInitializerParameter.ValidValues.FirstOrDefault(x => x.GetType() == oldTopologyInitializer.GetType());
332      UpdateTopologyParameters();
[3348]333    }
[3415]334
[5410]335    private void UpdateTopologyParameters() {
336      ITopologyUpdater oldTopologyUpdater = TopologyUpdater;
337      IParticleUpdater oldParticleUpdater = ParticleUpdater;
338      ClearTopologyParameters();
[5560]339      if (Problem != null) {
340        if (TopologyInitializer != null) {
341          foreach (ITopologyUpdater topologyUpdater in ApplicationManager.Manager.GetInstances<ITopologyUpdater>())
342            TopologyUpdaterParameter.ValidValues.Add(topologyUpdater);
343          foreach (IParticleUpdater particleUpdater in Problem.Operators.OfType<ILocalParticleUpdater>().OrderBy(x => x.Name))
344            ParticleUpdaterParameter.ValidValues.Add(particleUpdater);
345        } else {
346          foreach (IParticleUpdater particleUpdater in Problem.Operators.OfType<IGlobalParticleUpdater>().OrderBy(x => x.Name))
347            ParticleUpdaterParameter.ValidValues.Add(particleUpdater);
348        }
349        if (oldTopologyUpdater != null) {
350          ITopologyUpdater newTopologyUpdater = TopologyUpdaterParameter.ValidValues.FirstOrDefault(x => x.GetType() == oldParticleUpdater.GetType());
351          if (newTopologyUpdater != null) TopologyUpdater = newTopologyUpdater;
352        }
353        if (oldParticleUpdater != null) {
354          IParticleUpdater newParticleUpdater = ParticleUpdaterParameter.ValidValues.FirstOrDefault(x => x.GetType() == oldParticleUpdater.GetType());
355          if (newParticleUpdater != null) ParticleUpdater = newParticleUpdater;
356        }
[3682]357      }
358    }
359
[5410]360    private void ClearTopologyParameters() {
361      TopologyUpdaterParameter.ValidValues.Clear();
362      ParticleUpdaterParameter.ValidValues.Clear();
363    }
[5560]364
365    private void ParameterizeSolutionsCreator() {
366      if (Problem != null) {
367        solutionsCreator.EvaluatorParameter.ActualName = Problem.EvaluatorParameter.Name;
368        solutionsCreator.SolutionCreatorParameter.ActualName = ParticleCreatorParameter.Name;
369      }
370    }
371
372    private void ParameterizeMainLoop() {
[5568]373      if (Problem != null) {
[5561]374        mainLoop.EvaluatorParameter.ActualName = Problem.EvaluatorParameter.Name;
375      }
[5560]376    }
[5561]377
378    private void InitializeSwarmUpdater() {
379      if (Problem != null) {
380        ISwarmUpdater updater = Problem.Operators.OfType<ISwarmUpdater>().FirstOrDefault();
[5568]381        SwarmUpdaterParameter.ValidValues.Clear();
[5868]382        if (updater != null) {
383          SwarmUpdaterParameter.ValidValues.Add(updater);
384          SwarmUpdaterParameter.Value = updater;
385        }
[5561]386      }
387    }
[3348]388    #endregion
[5410]389
[3348]390  }
391}
Note: See TracBrowser for help on using the repository browser.