Free cookie consent management tool by TermsFeed Policy Generator

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

Last change on this file since 3832 was 3816, checked in by swagner, 14 years ago

Removed sorting of analyzer provided by problems (#893)

File size: 12.8 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.Collections.Generic;
24using System.Linq;
25using HeuristicLab.Common;
26using HeuristicLab.Core;
27using HeuristicLab.Data;
28using HeuristicLab.Encodings.RealVectorEncoding;
29using HeuristicLab.Optimization;
30using HeuristicLab.Operators;
31using HeuristicLab.Optimization.Operators;
32using HeuristicLab.Parameters;
33using HeuristicLab.Persistence.Default.CompositeSerializers.Storable;
34using HeuristicLab.PluginInfrastructure;
35using HeuristicLab.Random;
36using HeuristicLab.Analysis;
37
38namespace HeuristicLab.Algorithms.ParticleSwarmOptimization {
39  [Item("Particle Swarm Optimization", "A particle swarm optimization algorithm.")]
40  [Creatable("Algorithms")]
41  [StorableClass]
42  public sealed class ParticleSwarmOptimization : EngineAlgorithm {
43    #region Problem Properties
44    public override Type ProblemType {
45      get { return typeof(ISingleObjectiveProblem); }
46    }
47    public new ISingleObjectiveProblem Problem {
48      get { return (ISingleObjectiveProblem)base.Problem; }
49      set { base.Problem = value; }
50    }
51    public IRealVectorEncoder Encoder {
52      get { return EncoderParameter.Value; }
53      set { EncoderParameter.Value = value; }
54    }
55    public MultiAnalyzer Analyzer {
56      get { return AnalyzerParameter.Value; }
57      set { AnalyzerParameter.Value = value; }
58    }
59    #endregion
60
61    #region Parameter Properties
62    private ValueParameter<IntValue> SeedParameter {
63      get { return (ValueParameter<IntValue>)Parameters["Seed"]; }
64    }
65    private ValueParameter<BoolValue> SetSeedRandomlyParameter {
66      get { return (ValueParameter<BoolValue>)Parameters["SetSeedRandomly"]; }
67    }
68    private ValueParameter<IntValue> SwarmSizeParameter {
69      get { return (ValueParameter<IntValue>)Parameters["SwarmSize"]; }
70    }
71    private ValueParameter<IntValue> MaxIterationsParameter {
72      get { return (ValueParameter<IntValue>)Parameters["MaxIterations"]; }
73    }
74    private OptionalConstrainedValueParameter<IRealVectorEncoder> EncoderParameter {
75      get { return (OptionalConstrainedValueParameter<IRealVectorEncoder>)Parameters["Encoder"]; }
76    }
77    private ValueParameter<MultiAnalyzer> AnalyzerParameter {
78      get { return (ValueParameter<MultiAnalyzer>)Parameters["Analyzer"]; }
79    }
80    #endregion
81
82    #region Properties
83    [Storable]
84    private ParticleSwarmOptimizationMainLoop mainLoop; // Check this !
85    private ParticleSwarmOptimizationMainLoop MainLoop {
86      get { return mainLoop; }
87    }
88    [Storable]
89    private Assigner bestLocalQualityInitalizer; // Check this !
90    private Assigner BestLocalQualityInitalizer {
91      get { return bestLocalQualityInitalizer; }
92    }
93    [Storable]
94    private BestAverageWorstQualityAnalyzer qualityAnalyzer;
95    #endregion
96
97    public ParticleSwarmOptimization()
98      : base() {
99      Parameters.Add(new ValueParameter<IntValue>("Seed", "The random seed used to initialize the new pseudo random number generator.", new IntValue(0)));
100      Parameters.Add(new ValueParameter<BoolValue>("SetSeedRandomly", "True if the random seed should be set to a random value, otherwise false.", new BoolValue(true)));
101      Parameters.Add(new ValueParameter<IntValue>("SwarmSize", "Size of the particle swarm.", new IntValue(10)));
102      Parameters.Add(new ValueParameter<IntValue>("MaxIterations", "Maximal number of iterations.", new IntValue(1000)));
103      Parameters.Add(new ConstrainedValueParameter<IRealVectorEncoder>("Encoder", "The operator used to encode solutions as position vector."));
104      Parameters.Add(new ValueParameter<MultiAnalyzer>("Analyzer", "The operator used to analyze each generation.", new MultiAnalyzer()));
105      RandomCreator randomCreator = new RandomCreator();
106      SolutionsCreator solutionsCreator = new SolutionsCreator();
107      UniformSubScopesProcessor uniformSubScopesProcessor = new UniformSubScopesProcessor();
108      UniformSubScopesProcessor uniformSubScopesProcessor2 = new UniformSubScopesProcessor();
109      VariableCreator variableCreator = new VariableCreator();
110      VariableCreator localVariableCreator = new VariableCreator();
111      Placeholder encoder = new Placeholder();
112      UniformRandomRealVectorCreator velocityVectorCreator = new UniformRandomRealVectorCreator();
113      bestLocalQualityInitalizer = new Assigner();
114      Assigner bestLocalPositionInitalizer = new Assigner();
115      Assigner bestGlobalPositionInitalizer = new Assigner();
116      mainLoop = new ParticleSwarmOptimizationMainLoop();
117      BestAverageWorstQualityCalculator bawCalculator = new BestAverageWorstQualityCalculator();
118      Comparator comparator = new Comparator();
119      ConditionalBranch branch = new ConditionalBranch();
120
121      variableCreator.CollectedValues.Add(new ValueParameter<RealVector>("CurrentBestPosition", new RealVector()));
122      variableCreator.CollectedValues.Add(new ValueParameter<DoubleMatrix>("ZeroBounds", new DoubleMatrix(new double[,] { { 0, 0 } })));
123      variableCreator.CollectedValues.Add(new ValueParameter<IntValue>("Length", new IntValue(2)));
124
125      localVariableCreator.CollectedValues.Add(new ValueParameter<DoubleValue>("BestQuality", new DoubleValue(0)));
126      localVariableCreator.CollectedValues.Add(new ValueParameter<RealVector>("BestPosition", new RealVector()));
127
128      randomCreator.RandomParameter.ActualName = "Random";
129      randomCreator.SeedParameter.ActualName = SeedParameter.Name;
130      randomCreator.SeedParameter.Value = null;
131      randomCreator.SetSeedRandomlyParameter.ActualName = SetSeedRandomlyParameter.Name;
132      randomCreator.SetSeedRandomlyParameter.Value = null;
133     
134      solutionsCreator.NumberOfSolutionsParameter.ActualName = SwarmSizeParameter.Name;
135     
136      encoder.OperatorParameter.ActualName = "Encoder";
137     
138      velocityVectorCreator.BoundsParameter.ActualName = "ZeroBounds";
139      velocityVectorCreator.RealVectorParameter.ActualName = "Velocity";
140
141      bestLocalQualityInitalizer.LeftSideParameter.ActualName = "BestQuality"; // cloned value
142      bestLocalQualityInitalizer.RightSideParameter.ActualName = "Quality"; // FIXME!!! Should be mapped
143
144      bestLocalPositionInitalizer.LeftSideParameter.ActualName = "BestPosition";
145      bestLocalPositionInitalizer.RightSideParameter.ActualName = "Position"; // FixMe
146
147      bestGlobalPositionInitalizer.LeftSideParameter.ActualName = "CurrentBestPosition";
148      bestGlobalPositionInitalizer.RightSideParameter.ActualName = "BestPosition";
149
150      bawCalculator.AverageQualityParameter.ActualName = "CurrentAverageBestQuality";
151      bawCalculator.BestQualityParameter.ActualName = "CurrentBestBestQuality";
152      bawCalculator.MaximizationParameter.ActualName = "Maximization"; // FIXME
153      bawCalculator.QualityParameter.ActualName = "Quality";
154      bawCalculator.WorstQualityParameter.ActualName = "CurrentWorstBestQuality";
155
156      comparator.Comparison = new Comparison(ComparisonType.Equal);
157      comparator.LeftSideParameter.ActualName = "Quality";
158      comparator.ResultParameter.ActualName = "NewGlobalBest";
159      comparator.RightSideParameter.ActualName = "CurrentBestBestQuality";
160
161      branch.ConditionParameter.ActualName = "NewGlobalBest";
162      branch.TrueBranch = bestGlobalPositionInitalizer; // copy position vector
163
164      mainLoop.MaximumGenerationsParameter.ActualName = MaxIterationsParameter.Name;
165      mainLoop.ResultsParameter.ActualName = "Results";
166      mainLoop.AnalyzerParameter.ActualName = AnalyzerParameter.Name;
167
168      OperatorGraph.InitialOperator = randomCreator;
169      randomCreator.Successor = solutionsCreator;
170      solutionsCreator.Successor = variableCreator;
171      variableCreator.Successor = uniformSubScopesProcessor;
172      uniformSubScopesProcessor.Operator = encoder;
173      encoder.Successor = velocityVectorCreator;
174      velocityVectorCreator.Successor = localVariableCreator;
175      localVariableCreator.Successor = bestLocalQualityInitalizer;
176      bestLocalQualityInitalizer.Successor = bestLocalPositionInitalizer;
177      uniformSubScopesProcessor.Successor = bawCalculator; // mainLoop;
178      bawCalculator.Successor = uniformSubScopesProcessor2;
179      uniformSubScopesProcessor2.Operator = comparator;
180      comparator.Successor = branch;
181      uniformSubScopesProcessor2.Successor = mainLoop;
182      InitializeAnalyzers();
183      UpdateAnalyzers();
184      Initialize();
185    }
186
187    [StorableHook(HookType.AfterDeserialization)]
188    private void Initialize() {
189      EncoderParameter.ValueChanged += new EventHandler(EncoderParameter_ValueChanged);
190      if (Problem != null) {
191        bestLocalQualityInitalizer.RightSideParameter.ActualName = Problem.Evaluator.QualityParameter.ActualName;
192      }
193    }
194
195    [StorableConstructor]
196    private ParticleSwarmOptimization(bool deserializing) : base(deserializing) { }
197
198    public override IDeepCloneable Clone(Cloner cloner) {
199      ParticleSwarmOptimization clone = (ParticleSwarmOptimization)base.Clone(cloner);
200      clone.Initialize();
201      return clone;
202    }
203
204    public override void Prepare() {
205      if (Problem != null) base.Prepare();
206    }
207
208    #region Events
209    protected override void OnProblemChanged() {
210      UpdateEncoders();
211      UpdateAnalyzers();
212      ParameterizeAnalyzers();
213      bestLocalQualityInitalizer.RightSideParameter.ActualName = Problem.Evaluator.QualityParameter.ActualName;
214      Problem.Evaluator.QualityParameter.ActualNameChanged += new EventHandler(Evaluator_QualityParameter_ActualNameChanged);
215      MainLoop.EvaluatorParameter.ActualName = Problem.EvaluatorParameter.Name;
216      base.OnProblemChanged();
217    }
218
219    private void EncoderParameter_ValueChanged(object sender, EventArgs e) {
220      //MainLoop.EncoderParameter.ActualValue = (IRealVectorEncoder) EncoderParameter.ActualValue;
221      //((UniformSubScopesProcessor)((VariableCreator)((SolutionsCreator)((RandomCreator)OperatorGraph.InitialOperator).Successor).Successor).Successor).Operator = EncoderParameter.Value;
222      //((SingleSuccessorOperator)EncoderParameter.Value).Successor = ((SingleSuccessorOperator)old).Successor;
223    }
224    #endregion
225
226    #region Helpers
227    private void Evaluator_QualityParameter_ActualNameChanged(object sender, EventArgs e) {
228      //
229      //
230    }
231
232    private void UpdateEncoders() {
233      IRealVectorEncoder oldEncoder = EncoderParameter.Value;
234      EncoderParameter.ValidValues.Clear();
235      List<IRealVectorEncoder> encoders = Problem.Operators.OfType<IRealVectorEncoder>().OrderBy(x => x.Name).ToList<IRealVectorEncoder>();
236      if (encoders.Count > 0) {  // ToDo: Add wiring; else: use Position Vector directly --> name matching
237        foreach (IRealVectorEncoder encoder in Problem.Operators.OfType<IRealVectorEncoder>().OrderBy(x => x.Name)) {
238          EncoderParameter.ValidValues.Add(encoder);
239          ((ILookupParameter)encoder.RealVectorParameter).ActualName = "Position";
240        }
241        if (oldEncoder != null) {
242          IRealVectorEncoder encoder = EncoderParameter.ValidValues.FirstOrDefault(x => x.GetType() == oldEncoder.GetType());
243          if (encoder != null) EncoderParameter.Value = encoder;
244        }
245      }
246    }
247
248    private void InitializeAnalyzers() {
249      qualityAnalyzer = new BestAverageWorstQualityAnalyzer();
250      ParameterizeAnalyzers();
251    }
252
253    private void ParameterizeAnalyzers() {
254      qualityAnalyzer.ResultsParameter.ActualName = "Results";
255      if (Problem != null) {
256        qualityAnalyzer.MaximizationParameter.ActualName = Problem.MaximizationParameter.Name;
257        qualityAnalyzer.QualityParameter.ActualName = Problem.Evaluator.QualityParameter.ActualName;
258        qualityAnalyzer.BestKnownQualityParameter.ActualName = Problem.BestKnownQualityParameter.Name;
259      }
260    }
261
262    private void UpdateAnalyzers() {
263      Analyzer.Operators.Clear();
264      if (Problem != null) {
265        foreach (IAnalyzer analyzer in Problem.Operators.OfType<IAnalyzer>())
266          Analyzer.Operators.Add(analyzer);
267      }
268      Analyzer.Operators.Add(qualityAnalyzer);
269    }
270
271    #endregion
272  }
273}
Note: See TracBrowser for help on using the repository browser.