Free cookie consent management tool by TermsFeed Policy Generator

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

Last change on this file since 4839 was 4068, checked in by swagner, 14 years ago

Sorted usings and removed unused usings in entire solution (#1094)

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