Changeset 13909 for branches/HeuristicLab.Algorithms.CMAEvolutionStrategy
- Timestamp:
- 06/17/16 14:13:55 (8 years ago)
- Location:
- branches/HeuristicLab.Algorithms.CMAEvolutionStrategy/sources
- Files:
-
- 7 edited
Legend:
- Unmodified
- Added
- Removed
-
branches/HeuristicLab.Algorithms.CMAEvolutionStrategy/sources/3.3/CMAEvolutionStrategy.cs
r13793 r13909 35 35 using HeuristicLab.Random; 36 36 37 namespace HeuristicLab.Algorithms.CMAEvolutionStrategy { 38 [Item("CMA Evolution Strategy", "An evolution strategy based on covariance matrix adaptation.")] 39 [StorableClass] 40 public sealed class CMAEvolutionStrategy : HeuristicOptimizationEngineAlgorithm, IStorableContent { 41 public string Filename { get; set; } 42 #region Strings 43 private const string SeedName = "Seed"; 44 private const string SetSeedRandomlyName = "SetSeedRandomly"; 45 private const string PopulationSizeName = "PopulationSize"; 46 private const string InitialIterationsName = "InitialIterations"; 47 private const string InitialSigmaName = "InitialSigma"; 48 private const string MuName = "Mu"; 49 private const string CMAInitializerName = "CMAInitializer"; 50 private const string CMAMutatorName = "CMAMutator"; 51 private const string CMARecombinatorName = "CMARecombinator"; 52 private const string CMAUpdaterName = "CMAUpdater"; 53 private const string AnalyzerName = "Analyzer"; 54 private const string MaximumGenerationsName = "MaximumGenerations"; 55 private const string MaximumEvaluatedSolutionsName = "MaximumEvaluatedSolutions"; 56 private const string TargetQualityName = "TargetQuality"; 57 private const string MinimumQualityChangeName = "MinimumQualityChange"; 58 private const string MinimumQualityHistoryChangeName = "MinimumQualityHistoryChange"; 59 private const string MinimumStandardDeviationName = "MinimumStandardDeviation"; 60 private const string MaximumStandardDeviationChangeName = "MaximumStandardDeviationChange"; 61 #endregion 62 63 #region Problem Properties 64 public override Type ProblemType { 65 get { return typeof(ISingleObjectiveHeuristicOptimizationProblem); } 37 namespace HeuristicLab.Algorithms.CMAEvolutionStrategy 38 { 39 [Item("CMA Evolution Strateg_y", "An evolution strategy based on covariance matrix adaptation.")] 40 [StorableClass] 41 public sealed class CMAEvolutionStrategy : HeuristicOptimizationEngineAlgorithm, IStorableContent 42 { 43 public string Filename { get; set; } 44 #region Strings 45 private const string SeedName = "Seed"; 46 private const string SetSeedRandomlyName = "SetSeedRandomly"; 47 private const string PopulationSizeName = "PopulationSize"; 48 private const string InitialIterationsName = "InitialIterations"; 49 private const string InitialSigmaName = "InitialSigma"; 50 private const string MuName = "Mu"; 51 private const string CMAInitializerName = "CMAInitializer"; 52 private const string CMAMutatorName = "CMAMutator"; 53 private const string CMARecombinatorName = "CMARecombinator"; 54 private const string CMAUpdaterName = "CMAUpdater"; 55 private const string AnalyzerName = "Analyzer"; 56 private const string MaximumGenerationsName = "MaximumGenerations"; 57 private const string MaximumEvaluatedSolutionsName = "MaximumEvaluatedSolutions"; 58 private const string TargetQualityName = "TargetQuality"; 59 private const string MinimumQualityChangeName = "MinimumQualityChange"; 60 private const string MinimumQualityHistoryChangeName = "MinimumQualityHistoryChange"; 61 private const string MinimumStandardDeviationName = "MinimumStandardDeviation"; 62 private const string MaximumStandardDeviationChangeName = "MaximumStandardDeviationChange"; 63 #endregion 64 65 #region Problem Properties 66 public override Type ProblemType 67 { 68 get { return typeof(ISingleObjectiveHeuristicOptimizationProblem); } 69 } 70 public new ISingleObjectiveHeuristicOptimizationProblem Problem 71 { 72 get { return (ISingleObjectiveHeuristicOptimizationProblem)base.Problem; } 73 set { base.Problem = value; } 74 } 75 #endregion 76 77 #region Parameter Properties 78 public IValueParameter<MultiAnalyzer> AnalyzerParameter 79 { 80 get { return (IValueParameter<MultiAnalyzer>)Parameters[AnalyzerName]; } 81 } 82 private IFixedValueParameter<IntValue> SeedParameter 83 { 84 get { return (IFixedValueParameter<IntValue>)Parameters[SeedName]; } 85 } 86 private IFixedValueParameter<BoolValue> SetSeedRandomlyParameter 87 { 88 get { return (IFixedValueParameter<BoolValue>)Parameters[SetSeedRandomlyName]; } 89 } 90 private IFixedValueParameter<IntValue> PopulationSizeParameter 91 { 92 get { return (IFixedValueParameter<IntValue>)Parameters[PopulationSizeName]; } 93 } 94 private IFixedValueParameter<IntValue> InitialIterationsParameter 95 { 96 get { return (IFixedValueParameter<IntValue>)Parameters[InitialIterationsName]; } 97 } 98 public IValueParameter<DoubleArray> InitialSigmaParameter 99 { 100 get { return (IValueParameter<DoubleArray>)Parameters[InitialSigmaName]; } 101 } 102 private OptionalValueParameter<IntValue> MuParameter 103 { 104 get { return (OptionalValueParameter<IntValue>)Parameters[MuName]; } 105 } 106 public IConstrainedValueParameter<ICMAInitializer> CMAInitializerParameter 107 { 108 get { return (IConstrainedValueParameter<ICMAInitializer>)Parameters[CMAInitializerName]; } 109 } 110 public IConstrainedValueParameter<ICMAManipulator> CMAMutatorParameter 111 { 112 get { return (IConstrainedValueParameter<ICMAManipulator>)Parameters[CMAMutatorName]; } 113 } 114 public IConstrainedValueParameter<ICMARecombinator> CMARecombinatorParameter 115 { 116 get { return (IConstrainedValueParameter<ICMARecombinator>)Parameters[CMARecombinatorName]; } 117 } 118 public IConstrainedValueParameter<ICMAUpdater> CMAUpdaterParameter 119 { 120 get { return (IConstrainedValueParameter<ICMAUpdater>)Parameters[CMAUpdaterName]; } 121 } 122 private IFixedValueParameter<IntValue> MaximumGenerationsParameter 123 { 124 get { return (IFixedValueParameter<IntValue>)Parameters[MaximumGenerationsName]; } 125 } 126 private IFixedValueParameter<IntValue> MaximumEvaluatedSolutionsParameter 127 { 128 get { return (IFixedValueParameter<IntValue>)Parameters[MaximumEvaluatedSolutionsName]; } 129 } 130 private IFixedValueParameter<DoubleValue> TargetQualityParameter 131 { 132 get { return (IFixedValueParameter<DoubleValue>)Parameters[TargetQualityName]; } 133 } 134 private IFixedValueParameter<DoubleValue> MinimumQualityChangeParameter 135 { 136 get { return (IFixedValueParameter<DoubleValue>)Parameters[MinimumQualityChangeName]; } 137 } 138 private IFixedValueParameter<DoubleValue> MinimumQualityHistoryChangeParameter 139 { 140 get { return (IFixedValueParameter<DoubleValue>)Parameters[MinimumQualityHistoryChangeName]; } 141 } 142 private IFixedValueParameter<DoubleValue> MinimumStandardDeviationParameter 143 { 144 get { return (IFixedValueParameter<DoubleValue>)Parameters[MinimumStandardDeviationName]; } 145 } 146 private IFixedValueParameter<DoubleValue> MaximumStandardDeviationChangeParameter 147 { 148 get { return (IFixedValueParameter<DoubleValue>)Parameters[MaximumStandardDeviationChangeName]; } 149 } 150 #endregion 151 152 #region Properties 153 public int Seed 154 { 155 get { return SeedParameter.Value.Value; } 156 set { SeedParameter.Value.Value = value; } 157 } 158 public bool SetSeedRandomly 159 { 160 get { return SetSeedRandomlyParameter.Value.Value; } 161 set { SetSeedRandomlyParameter.Value.Value = value; } 162 } 163 public int PopulationSize 164 { 165 get { return PopulationSizeParameter.Value.Value; } 166 set { PopulationSizeParameter.Value.Value = value; } 167 } 168 public int InitialIterations 169 { 170 get { return InitialIterationsParameter.Value.Value; } 171 set { InitialIterationsParameter.Value.Value = value; } 172 } 173 public int MaximumGenerations 174 { 175 get { return MaximumGenerationsParameter.Value.Value; } 176 set { MaximumGenerationsParameter.Value.Value = value; } 177 } 178 public int MaximumEvaluatedSolutions 179 { 180 get { return MaximumEvaluatedSolutionsParameter.Value.Value; } 181 set { MaximumEvaluatedSolutionsParameter.Value.Value = value; } 182 } 183 public double TargetQuality 184 { 185 get { return TargetQualityParameter.Value.Value; } 186 set { TargetQualityParameter.Value.Value = value; } 187 } 188 public double MinimumQualityChange 189 { 190 get { return MinimumQualityChangeParameter.Value.Value; } 191 set { MinimumQualityChangeParameter.Value.Value = value; } 192 } 193 public double MinimumQualityHistoryChange 194 { 195 get { return MinimumQualityHistoryChangeParameter.Value.Value; } 196 set { MinimumQualityHistoryChangeParameter.Value.Value = value; } 197 } 198 public double MinimumStandardDeviation 199 { 200 get { return MinimumStandardDeviationParameter.Value.Value; } 201 set { MinimumStandardDeviationParameter.Value.Value = value; } 202 } 203 public double MaximumStandardDeviationChange 204 { 205 get { return MaximumStandardDeviationChangeParameter.Value.Value; } 206 set { MaximumStandardDeviationChangeParameter.Value.Value = value; } 207 } 208 public DoubleArray InitialSigma 209 { 210 get { return InitialSigmaParameter.Value; } 211 set { InitialSigmaParameter.Value = value; } 212 } 213 public IntValue Mu 214 { 215 get { return MuParameter.Value; } 216 set { MuParameter.Value = value; } 217 } 218 public ICMAInitializer CMAInitializer 219 { 220 get { return CMAInitializerParameter.Value; } 221 set { CMAInitializerParameter.Value = value; } 222 } 223 public ICMAManipulator CMAMutator 224 { 225 get { return CMAMutatorParameter.Value; } 226 set { CMAMutatorParameter.Value = value; } 227 } 228 public ICMARecombinator CMARecombinator 229 { 230 get { return CMARecombinatorParameter.Value; } 231 set { CMARecombinatorParameter.Value = value; } 232 } 233 public MultiAnalyzer Analyzer 234 { 235 get { return AnalyzerParameter.Value; } 236 set { AnalyzerParameter.Value = value; } 237 } 238 public ICMAUpdater CMAUpdater 239 { 240 get { return CMAUpdaterParameter.Value; } 241 set { CMAUpdaterParameter.Value = value; } 242 } 243 244 private RandomCreator RandomCreator 245 { 246 get { return (RandomCreator)OperatorGraph.InitialOperator; } 247 } 248 249 [Storable] 250 private BestAverageWorstQualityAnalyzer qualityAnalyzer; 251 [Storable] 252 private CMAAnalyzer cmaAnalyzer; 253 [Storable] 254 private Placeholder solutionCreator; 255 [Storable] 256 private Placeholder populationSolutionCreator; 257 [Storable] 258 private Placeholder evaluator; 259 [Storable] 260 private SubScopesSorter sorter; 261 [Storable] 262 private Terminator terminator; 263 #endregion 264 265 [StorableConstructor] 266 private CMAEvolutionStrategy(bool deserializing) : base(deserializing) { } 267 private CMAEvolutionStrategy(CMAEvolutionStrategy original, Cloner cloner) 268 : base(original, cloner) 269 { 270 qualityAnalyzer = cloner.Clone(original.qualityAnalyzer); 271 cmaAnalyzer = cloner.Clone(original.cmaAnalyzer); 272 solutionCreator = cloner.Clone(original.solutionCreator); 273 populationSolutionCreator = cloner.Clone(original.populationSolutionCreator); 274 evaluator = cloner.Clone(original.evaluator); 275 sorter = cloner.Clone(original.sorter); 276 terminator = cloner.Clone(original.terminator); 277 RegisterEventHandlers(); 278 } 279 public CMAEvolutionStrategy() 280 : base() 281 { 282 Parameters.Add(new FixedValueParameter<IntValue>(SeedName, "The random seed used to initialize the new pseudo random number generator.", new IntValue(0))); 283 Parameters.Add(new FixedValueParameter<BoolValue>(SetSeedRandomlyName, "True if the random seed should be set to a random value, otherwise false.", new BoolValue(true))); 284 Parameters.Add(new FixedValueParameter<IntValue>(PopulationSizeName, "λ (lambda) - the size of the offspring population.", new IntValue(20))); 285 Parameters.Add(new FixedValueParameter<IntValue>(InitialIterationsName, "The number of iterations that should be performed with only axis parallel mutation.", new IntValue(0))); 286 Parameters.Add(new FixedValueParameter<DoubleArray>(InitialSigmaName, "The initial sigma can be a single value or a value for each dimension. All values need to be > 0.", new DoubleArray(new[] { 0.5 }))); 287 Parameters.Add(new OptionalValueParameter<IntValue>(MuName, "Optional, the mu best offspring that should be considered for update of the new mean and strategy parameters. If not given it will be automatically calculated.")); 288 Parameters.Add(new ConstrainedValueParameter<ICMARecombinator>(CMARecombinatorName, "The operator used to calculate the new mean.")); 289 Parameters.Add(new ConstrainedValueParameter<ICMAManipulator>(CMAMutatorName, "The operator used to manipulate a point.")); 290 Parameters.Add(new ConstrainedValueParameter<ICMAInitializer>(CMAInitializerName, "The operator that initializes the covariance matrix and strategy parameters.")); 291 Parameters.Add(new ConstrainedValueParameter<ICMAUpdater>(CMAUpdaterName, "The operator that updates the covariance matrix and strategy parameters.")); 292 Parameters.Add(new ValueParameter<MultiAnalyzer>(AnalyzerName, "The operator used to analyze each generation.", new MultiAnalyzer())); 293 Parameters.Add(new FixedValueParameter<IntValue>(MaximumGenerationsName, "The maximum number of generations which should be processed.", new IntValue(1000))); 294 Parameters.Add(new FixedValueParameter<IntValue>(MaximumEvaluatedSolutionsName, "The maximum number of evaluated solutions that should be computed.", new IntValue(int.MaxValue))); 295 Parameters.Add(new FixedValueParameter<DoubleValue>(TargetQualityName, "(stopFitness) Surpassing this quality value terminates the algorithm.", new DoubleValue(double.NaN))); 296 Parameters.Add(new FixedValueParameter<DoubleValue>(MinimumQualityChangeName, "(stopTolFun) If the range of fitness values is less than a certain value the algorithm terminates (set to 0 or positive value to enable).", new DoubleValue(double.NaN))); 297 Parameters.Add(new FixedValueParameter<DoubleValue>(MinimumQualityHistoryChangeName, "(stopTolFunHist) If the range of fitness values is less than a certain value for a certain time the algorithm terminates (set to 0 or positive to enable).", new DoubleValue(double.NaN))); 298 Parameters.Add(new FixedValueParameter<DoubleValue>(MinimumStandardDeviationName, "(stopTolXFactor) If the standard deviation falls below a certain value the algorithm terminates (set to 0 or positive to enable).", new DoubleValue(double.NaN))); 299 Parameters.Add(new FixedValueParameter<DoubleValue>(MaximumStandardDeviationChangeName, "(stopTolUpXFactor) If the standard deviation changes by a value larger than this parameter the algorithm stops (set to a value > 0 to enable).", new DoubleValue(double.NaN))); 300 301 var randomCreator = new RandomCreator(); 302 var variableCreator = new VariableCreator(); 303 var resultsCollector = new ResultsCollector(); 304 var cmaInitializer = new Placeholder(); 305 solutionCreator = new Placeholder(); 306 var subScopesCreator = new SubScopesCreator(); 307 var ussp1 = new UniformSubScopesProcessor(); 308 populationSolutionCreator = new Placeholder(); 309 var cmaMutator = new Placeholder(); 310 var ussp2 = new UniformSubScopesProcessor(); 311 evaluator = new Placeholder(); 312 var subScopesCounter = new SubScopesCounter(); 313 sorter = new SubScopesSorter(); 314 var analyzer = new Placeholder(); 315 var cmaRecombinator = new Placeholder(); 316 var generationsCounter = new IntCounter(); 317 var cmaUpdater = new Placeholder(); 318 terminator = new Terminator(); 319 320 OperatorGraph.InitialOperator = randomCreator; 321 322 randomCreator.RandomParameter.ActualName = "Random"; 323 randomCreator.SeedParameter.ActualName = SeedParameter.Name; 324 randomCreator.SeedParameter.Value = null; 325 randomCreator.SetSeedRandomlyParameter.ActualName = SetSeedRandomlyParameter.Name; 326 randomCreator.SetSeedRandomlyParameter.Value = null; 327 randomCreator.Successor = variableCreator; 328 329 variableCreator.Name = "Initialize Variables"; 330 variableCreator.CollectedValues.Add(new ValueParameter<IntValue>("EvaluatedSolutions", new IntValue(0))); 331 variableCreator.CollectedValues.Add(new ValueParameter<IntValue>("Generations", new IntValue(0))); 332 variableCreator.Successor = resultsCollector; 333 334 resultsCollector.CollectedValues.Add(new LookupParameter<IntValue>("EvaluatedSolutions")); 335 resultsCollector.CollectedValues.Add(new LookupParameter<IntValue>("Generations")); 336 resultsCollector.ResultsParameter.ActualName = "Results"; 337 resultsCollector.Successor = cmaInitializer; 338 339 cmaInitializer.Name = "Initialize Strategy Parameters"; 340 cmaInitializer.OperatorParameter.ActualName = CMAInitializerParameter.Name; 341 cmaInitializer.Successor = subScopesCreator; 342 343 subScopesCreator.NumberOfSubScopesParameter.ActualName = PopulationSizeParameter.Name; 344 subScopesCreator.Successor = ussp1; 345 346 ussp1.Name = "Create population"; 347 ussp1.Parallel = new BoolValue(false); 348 ussp1.Operator = populationSolutionCreator; 349 ussp1.Successor = solutionCreator; 350 351 populationSolutionCreator.Name = "Initialize arx"; 352 // populationSolutionCreator.OperatorParameter will be wired 353 populationSolutionCreator.Successor = null; 354 355 solutionCreator.Name = "Initialize xmean"; 356 // solutionCreator.OperatorParameter will be wired 357 solutionCreator.Successor = cmaMutator; 358 359 cmaMutator.Name = "Sample population"; 360 cmaMutator.OperatorParameter.ActualName = CMAMutatorParameter.Name; 361 cmaMutator.Successor = ussp2; 362 363 ussp2.Name = "Evaluate offspring"; 364 ussp2.Parallel = new BoolValue(true); 365 ussp2.Operator = evaluator; 366 ussp2.Successor = subScopesCounter; 367 368 evaluator.Name = "Evaluator"; 369 // evaluator.OperatorParameter will be wired 370 evaluator.Successor = null; 371 372 subScopesCounter.Name = "Count EvaluatedSolutions"; 373 subScopesCounter.AccumulateParameter.Value = new BoolValue(true); 374 subScopesCounter.ValueParameter.ActualName = "EvaluatedSolutions"; 375 subScopesCounter.Successor = sorter; 376 377 // sorter.ValueParameter will be wired 378 // sorter.DescendingParameter will be wired 379 sorter.Successor = analyzer; 380 381 analyzer.Name = "Analyzer"; 382 analyzer.OperatorParameter.ActualName = AnalyzerParameter.Name; 383 analyzer.Successor = cmaRecombinator; 384 385 cmaRecombinator.Name = "Create new xmean"; 386 cmaRecombinator.OperatorParameter.ActualName = CMARecombinatorParameter.Name; 387 cmaRecombinator.Successor = generationsCounter; 388 389 generationsCounter.Name = "Generations++"; 390 generationsCounter.IncrementParameter.Value = new IntValue(1); 391 generationsCounter.ValueParameter.ActualName = "Generations"; 392 generationsCounter.Successor = cmaUpdater; 393 394 cmaUpdater.Name = "Update distributions"; 395 cmaUpdater.OperatorParameter.ActualName = CMAUpdaterParameter.Name; 396 cmaUpdater.Successor = terminator; 397 398 terminator.Continue = cmaMutator; 399 terminator.Terminate = null; 400 401 qualityAnalyzer = new BestAverageWorstQualityAnalyzer(); 402 cmaAnalyzer = new CMAAnalyzer(); 403 404 InitializeOperators(); 405 RegisterEventHandlers(); 406 Parameterize(); 407 } 408 409 public override IDeepCloneable Clone(Cloner cloner) 410 { 411 return new CMAEvolutionStrategy(this, cloner); 412 } 413 414 [StorableHook(HookType.AfterDeserialization)] 415 private void AfterDeserialization() 416 { 417 RegisterEventHandlers(); 418 } 419 420 public override void Prepare() 421 { 422 if (Problem != null) base.Prepare(); 423 } 424 425 protected override void OnStarted() 426 { 427 if (!(Problem.SolutionCreator is IRealVectorCreator)) 428 throw new InvalidOperationException("Problems that do not use RealVectorEncoding cannot be solved by CMA-ES."); 429 base.OnStarted(); 430 } 431 432 #region Events 433 protected override void OnProblemChanged() 434 { 435 Problem.Evaluator.QualityParameter.ActualNameChanged += Evaluator_QualityParameter_ActualNameChanged; 436 var creator = Problem.SolutionCreator as IRealVectorCreator; 437 if (creator != null) 438 { 439 creator.RealVectorParameter.ActualNameChanged += RealVectorCreator_Changed; 440 creator.LengthParameter.ActualNameChanged += RealVectorCreator_Changed; 441 creator.LengthParameter.ValueChanged += RealVectorCreator_Changed; 442 creator.BoundsParameter.ActualNameChanged += RealVectorCreator_Changed; 443 creator.BoundsParameter.ValueChanged += RealVectorCreator_Changed; 444 } 445 UpdateOperators(); 446 UpdateAnalyzers(); 447 Parameterize(); 448 base.OnProblemChanged(); 449 } 450 protected override void Problem_SolutionCreatorChanged(object sender, EventArgs e) 451 { 452 var creator = Problem.SolutionCreator as IRealVectorCreator; 453 if (creator != null) 454 { 455 creator.RealVectorParameter.ActualNameChanged += RealVectorCreator_Changed; 456 creator.LengthParameter.ActualNameChanged += RealVectorCreator_Changed; 457 creator.LengthParameter.ValueChanged += RealVectorCreator_Changed; 458 creator.BoundsParameter.ActualNameChanged += RealVectorCreator_Changed; 459 creator.BoundsParameter.ValueChanged += RealVectorCreator_Changed; 460 } 461 Parameterize(); 462 base.Problem_SolutionCreatorChanged(sender, e); 463 } 464 protected override void Problem_EvaluatorChanged(object sender, EventArgs e) 465 { 466 Problem.Evaluator.QualityParameter.ActualNameChanged += Evaluator_QualityParameter_ActualNameChanged; 467 Parameterize(); 468 base.Problem_EvaluatorChanged(sender, e); 469 } 470 protected override void Problem_OperatorsChanged(object sender, EventArgs e) 471 { 472 UpdateOperators(); 473 UpdateAnalyzers(); 474 Parameterize(); 475 base.Problem_OperatorsChanged(sender, e); 476 } 477 private void Evaluator_QualityParameter_ActualNameChanged(object sender, EventArgs e) 478 { 479 Parameterize(); 480 } 481 private bool cmaesInitializerSync; 482 private void CMAESInitializerParameter_ValueChanged(object sender, EventArgs e) 483 { 484 if (cmaesInitializerSync) return; 485 UpdateOperators(); 486 Parameterize(); 487 } 488 private void RealVectorCreator_Changed(object sender, EventArgs e) 489 { 490 Parameterize(); 491 } 492 #endregion 493 494 #region Helpers 495 private void RegisterEventHandlers() 496 { 497 CMAInitializerParameter.ValueChanged += CMAESInitializerParameter_ValueChanged; 498 if (Problem != null) 499 { 500 Problem.Evaluator.QualityParameter.ActualNameChanged += Evaluator_QualityParameter_ActualNameChanged; 501 var creator = Problem.SolutionCreator as IRealVectorCreator; 502 if (creator != null) 503 { 504 creator.RealVectorParameter.ActualNameChanged += RealVectorCreator_Changed; 505 creator.LengthParameter.ActualNameChanged += RealVectorCreator_Changed; 506 creator.LengthParameter.ValueChanged += RealVectorCreator_Changed; 507 creator.BoundsParameter.ActualNameChanged += RealVectorCreator_Changed; 508 creator.BoundsParameter.ValueChanged += RealVectorCreator_Changed; 509 } 510 } 511 } 512 private void InitializeOperators() 513 { 514 foreach (var op in ApplicationManager.Manager.GetInstances<ICMAInitializer>()) 515 CMAInitializerParameter.ValidValues.Add(op); 516 foreach (var op in ApplicationManager.Manager.GetInstances<ICMAManipulator>().Where(x => x.CMAType == CMAInitializer.CMAType)) 517 CMAMutatorParameter.ValidValues.Add(op); 518 foreach (var op in ApplicationManager.Manager.GetInstances<ICMARecombinator>().Where(x => x.CMAType == CMAInitializer.CMAType)) 519 CMARecombinatorParameter.ValidValues.Add(op); 520 foreach (var op in ApplicationManager.Manager.GetInstances<ICMAUpdater>().Where(x => x.CMAType == CMAInitializer.CMAType)) 521 CMAUpdaterParameter.ValidValues.Add(op); 522 } 523 private void UpdateOperators() 524 { 525 cmaesInitializerSync = true; 526 try 527 { 528 var oldMutator = CMAMutator; 529 var oldRecombinator = CMARecombinator; 530 var oldUpdater = CMAUpdater; 531 532 if (CMAInitializer != null && (oldMutator == null || oldMutator.CMAType != CMAInitializer.CMAType)) 533 { 534 CMAMutatorParameter.ValidValues.Clear(); 535 foreach (var op in ApplicationManager.Manager.GetInstances<ICMAManipulator>().Where(x => x.CMAType == CMAInitializer.CMAType)) 536 CMAMutatorParameter.ValidValues.Add(op); 537 CMAMutator = CMAMutatorParameter.ValidValues.First(); 538 } 539 540 if (CMAInitializer != null && (oldRecombinator == null || oldRecombinator.CMAType != CMAInitializer.CMAType)) 541 { 542 CMARecombinatorParameter.ValidValues.Clear(); 543 foreach (var op in ApplicationManager.Manager.GetInstances<ICMARecombinator>().Where(x => x.CMAType == CMAInitializer.CMAType)) 544 CMARecombinatorParameter.ValidValues.Add(op); 545 CMARecombinator = CMARecombinatorParameter.ValidValues.First(); 546 } 547 548 if (CMAInitializer != null && (oldUpdater == null || oldUpdater.CMAType != CMAInitializer.CMAType)) 549 { 550 CMAUpdaterParameter.ValidValues.Clear(); 551 foreach (var op in ApplicationManager.Manager.GetInstances<ICMAUpdater>().Where(x => x.CMAType == CMAInitializer.CMAType)) 552 CMAUpdaterParameter.ValidValues.Add(op); 553 CMAUpdater = CMAUpdaterParameter.ValidValues.First(); 554 } 555 } 556 finally { cmaesInitializerSync = false; } 557 } 558 private void UpdateAnalyzers() 559 { 560 Analyzer.Operators.Clear(); 561 if (Problem != null) 562 { 563 foreach (var analyzer in Problem.Operators.OfType<IAnalyzer>()) 564 { 565 foreach (var param in analyzer.Parameters.OfType<IScopeTreeLookupParameter>()) 566 param.Depth = 1; 567 Analyzer.Operators.Add(analyzer, analyzer.EnabledByDefault); 568 } 569 } 570 Analyzer.Operators.Add(qualityAnalyzer, qualityAnalyzer.EnabledByDefault); 571 Analyzer.Operators.Add(cmaAnalyzer, cmaAnalyzer.EnabledByDefault); 572 } 573 private void Parameterize() 574 { 575 576 foreach (var op in CMAInitializerParameter.ValidValues) 577 { 578 op.PopulationSizeParameter.ActualName = PopulationSizeParameter.Name; 579 op.PopulationSizeParameter.Hidden = true; 580 op.MuParameter.ActualName = MuParameter.Name; 581 op.MuParameter.Hidden = true; 582 op.InitialIterationsParameter.Value = null; 583 op.InitialIterationsParameter.ActualName = InitialIterationsParameter.Name; 584 op.InitialIterationsParameter.Hidden = true; 585 op.InitialSigmaParameter.Value = null; 586 op.InitialSigmaParameter.ActualName = InitialSigmaParameter.Name; 587 op.InitialSigmaParameter.Hidden = true; 588 589 op.DimensionParameter.Hidden = false; 590 591 ParameterizeStochasticOperator(op); 592 ParameterizeIterationBasedOperator(op); 593 } 594 595 foreach (var op in CMAMutatorParameter.ValidValues) 596 { 597 op.PopulationSizeParameter.ActualName = PopulationSizeParameter.Name; 598 op.PopulationSizeParameter.Hidden = true; 599 600 op.MeanParameter.Hidden = false; 601 op.BoundsParameter.Hidden = false; 602 op.RealVectorParameter.Hidden = false; 603 604 ParameterizeStochasticOperator(op); 605 ParameterizeIterationBasedOperator(op); 606 } 607 608 foreach (var op in CMARecombinatorParameter.ValidValues) 609 { 610 op.OldMeanParameter.ActualName = "XOld"; 611 op.OldMeanParameter.Hidden = true; 612 613 op.OffspringParameter.Hidden = false; 614 op.MeanParameter.Hidden = false; 615 616 ParameterizeStochasticOperator(op); 617 ParameterizeIterationBasedOperator(op); 618 } 619 620 foreach (var op in CMAUpdaterParameter.ValidValues) 621 { 622 op.MaximumEvaluatedSolutionsParameter.ActualName = MaximumEvaluatedSolutionsParameter.Name; 623 op.MaximumEvaluatedSolutionsParameter.Hidden = true; 624 op.OldMeanParameter.ActualName = "XOld"; 625 op.OldMeanParameter.Hidden = true; 626 627 op.MeanParameter.Hidden = false; 628 op.OffspringParameter.Hidden = false; 629 op.QualityParameter.Hidden = false; 630 631 ParameterizeStochasticOperator(op); 632 ParameterizeIterationBasedOperator(op); 633 } 634 635 terminator.IterationsParameter.ActualName = "Generations"; 636 terminator.MaximumIterationsParameter.ActualName = MaximumGenerationsParameter.Name; 637 terminator.EvaluatedSolutionsParameter.ActualName = "EvaluatedSolutions"; 638 terminator.InitialSigmaParameter.ActualName = InitialSigmaParameter.Name; 639 terminator.MaximumEvaluatedSolutionsParameter.ActualName = MaximumEvaluatedSolutionsParameter.Name; 640 terminator.MaximumStandardDeviationChangeParameter.ActualName = MaximumStandardDeviationChangeParameter.Name; 641 terminator.MinimumQualityChangeParameter.ActualName = MinimumQualityChangeParameter.Name; 642 terminator.MinimumQualityHistoryChangeParameter.ActualName = MinimumQualityHistoryChangeParameter.Name; 643 terminator.MinimumStandardDeviationParameter.ActualName = MinimumStandardDeviationParameter.Name; 644 terminator.TargetQualityParameter.ActualName = TargetQualityParameter.Name; 645 if (CMAUpdater != null) 646 terminator.DegenerateStateParameter.ActualName = CMAUpdater.DegenerateStateParameter.ActualName; 647 648 var creator = Problem != null ? (Problem.SolutionCreator as IRealVectorCreator) : null; 649 if (Problem != null && creator != null) 650 { 651 652 solutionCreator.OperatorParameter.ActualName = Problem.SolutionCreatorParameter.Name; 653 #region Backwards compatible code, remove with 3.4 654 if (populationSolutionCreator != null) // BackwardsCompatibility3.3 655 // ONLY REMOVE THE CONDITION 656 populationSolutionCreator.OperatorParameter.ActualName = Problem.SolutionCreatorParameter.Name; 657 #endregion 658 evaluator.OperatorParameter.ActualName = Problem.EvaluatorParameter.Name; 659 sorter.DescendingParameter.ActualName = Problem.MaximizationParameter.Name; 660 sorter.ValueParameter.ActualName = Problem.Evaluator.QualityParameter.ActualName; 661 terminator.MaximizationParameter.ActualName = Problem.MaximizationParameter.Name; 662 terminator.QualityParameter.ActualName = Problem.Evaluator.QualityParameter.Name; 663 664 foreach (var op in CMAInitializerParameter.ValidValues) 665 { 666 if (creator.LengthParameter.Value == null) 667 { 668 op.DimensionParameter.ActualName = creator.LengthParameter.ActualName; 669 op.DimensionParameter.Value = null; 670 } 671 else op.DimensionParameter.Value = creator.LengthParameter.Value; 672 op.DimensionParameter.Hidden = true; 673 } 674 675 foreach (var op in CMAMutatorParameter.ValidValues) 676 { 677 op.MeanParameter.ActualName = creator.RealVectorParameter.ActualName; 678 op.MeanParameter.Hidden = true; 679 if (creator.BoundsParameter.Value == null) 680 { 681 op.BoundsParameter.ActualName = creator.BoundsParameter.ActualName; 682 op.BoundsParameter.Value = null; 683 } 684 else op.BoundsParameter.Value = creator.BoundsParameter.Value; 685 op.BoundsParameter.Hidden = true; 686 op.RealVectorParameter.ActualName = creator.RealVectorParameter.ActualName; 687 op.RealVectorParameter.Depth = 1; 688 op.RealVectorParameter.Hidden = true; 689 } 690 691 foreach (var op in CMARecombinatorParameter.ValidValues) 692 { 693 op.MeanParameter.ActualName = creator.RealVectorParameter.ActualName; 694 op.MeanParameter.Hidden = true; 695 op.OffspringParameter.ActualName = creator.RealVectorParameter.ActualName; 696 op.OffspringParameter.Depth = 1; 697 op.OffspringParameter.Hidden = true; 698 } 699 700 foreach (var op in CMAUpdaterParameter.ValidValues) 701 { 702 op.MeanParameter.ActualName = creator.RealVectorParameter.ActualName; 703 op.MeanParameter.Hidden = true; 704 op.OffspringParameter.ActualName = creator.RealVectorParameter.ActualName; 705 op.OffspringParameter.Depth = 1; 706 op.OffspringParameter.Hidden = true; 707 op.QualityParameter.ActualName = Problem.Evaluator.QualityParameter.ActualName; 708 op.QualityParameter.Hidden = true; 709 } 710 711 foreach (var op in Problem.Operators.OfType<IStochasticOperator>()) 712 { 713 op.RandomParameter.ActualName = RandomCreator.RandomParameter.ActualName; 714 op.RandomParameter.Hidden = true; 715 } 716 717 qualityAnalyzer.MaximizationParameter.ActualName = Problem.MaximizationParameter.Name; 718 qualityAnalyzer.MaximizationParameter.Hidden = true; 719 qualityAnalyzer.QualityParameter.ActualName = Problem.Evaluator.QualityParameter.ActualName; 720 qualityAnalyzer.QualityParameter.Depth = 1; 721 qualityAnalyzer.QualityParameter.Hidden = true; 722 qualityAnalyzer.BestKnownQualityParameter.ActualName = Problem.BestKnownQualityParameter.Name; 723 qualityAnalyzer.BestKnownQualityParameter.Hidden = true; 724 725 cmaAnalyzer.QualityParameter.ActualName = Problem.Evaluator.QualityParameter.ActualName; 726 cmaAnalyzer.QualityParameter.Depth = 1; 727 cmaAnalyzer.QualityParameter.Hidden = true; 728 cmaAnalyzer.MeanParameter.ActualName = creator.RealVectorParameter.ActualName; 729 cmaAnalyzer.MeanParameter.Hidden = true; 730 731 foreach (var op in Problem.Operators.OfType<IIterationBasedOperator>()) 732 { 733 op.IterationsParameter.ActualName = "Generations"; 734 op.IterationsParameter.Hidden = true; 735 op.MaximumIterationsParameter.ActualName = MaximumGenerationsParameter.Name; 736 op.MaximumIterationsParameter.Hidden = true; 737 } 738 } 739 else 740 { 741 qualityAnalyzer.MaximizationParameter.Hidden = false; 742 qualityAnalyzer.QualityParameter.Hidden = false; 743 qualityAnalyzer.BestKnownQualityParameter.Hidden = false; 744 745 cmaAnalyzer.MeanParameter.Hidden = false; 746 } 747 748 qualityAnalyzer.ResultsParameter.ActualName = "Results"; 749 qualityAnalyzer.ResultsParameter.Hidden = true; 750 cmaAnalyzer.ResultsParameter.ActualName = "Results"; 751 cmaAnalyzer.ResultsParameter.Hidden = true; 752 } 753 754 private void ParameterizeStochasticOperator(IOperator op) 755 { 756 var sOp = op as IStochasticOperator; 757 if (sOp != null) sOp.RandomParameter.ActualName = RandomCreator.RandomParameter.ActualName; 758 } 759 760 private void ParameterizeIterationBasedOperator(IOperator op) 761 { 762 var iOp = op as IIterationBasedOperator; 763 if (iOp != null) 764 { 765 iOp.IterationsParameter.ActualName = "Generations"; 766 iOp.MaximumIterationsParameter.ActualName = MaximumGenerationsParameter.Name; 767 } 768 } 769 #endregion 66 770 } 67 public new ISingleObjectiveHeuristicOptimizationProblem Problem {68 get { return (ISingleObjectiveHeuristicOptimizationProblem)base.Problem; }69 set { base.Problem = value; }70 }71 #endregion72 73 #region Parameter Properties74 public IValueParameter<MultiAnalyzer> AnalyzerParameter {75 get { return (IValueParameter<MultiAnalyzer>)Parameters[AnalyzerName]; }76 }77 private IFixedValueParameter<IntValue> SeedParameter {78 get { return (IFixedValueParameter<IntValue>)Parameters[SeedName]; }79 }80 private IFixedValueParameter<BoolValue> SetSeedRandomlyParameter {81 get { return (IFixedValueParameter<BoolValue>)Parameters[SetSeedRandomlyName]; }82 }83 private IFixedValueParameter<IntValue> PopulationSizeParameter {84 get { return (IFixedValueParameter<IntValue>)Parameters[PopulationSizeName]; }85 }86 private IFixedValueParameter<IntValue> InitialIterationsParameter {87 get { return (IFixedValueParameter<IntValue>)Parameters[InitialIterationsName]; }88 }89 public IValueParameter<DoubleArray> InitialSigmaParameter {90 get { return (IValueParameter<DoubleArray>)Parameters[InitialSigmaName]; }91 }92 private OptionalValueParameter<IntValue> MuParameter {93 get { return (OptionalValueParameter<IntValue>)Parameters[MuName]; }94 }95 public IConstrainedValueParameter<ICMAInitializer> CMAInitializerParameter {96 get { return (IConstrainedValueParameter<ICMAInitializer>)Parameters[CMAInitializerName]; }97 }98 public IConstrainedValueParameter<ICMAManipulator> CMAMutatorParameter {99 get { return (IConstrainedValueParameter<ICMAManipulator>)Parameters[CMAMutatorName]; }100 }101 public IConstrainedValueParameter<ICMARecombinator> CMARecombinatorParameter {102 get { return (IConstrainedValueParameter<ICMARecombinator>)Parameters[CMARecombinatorName]; }103 }104 public IConstrainedValueParameter<ICMAUpdater> CMAUpdaterParameter {105 get { return (IConstrainedValueParameter<ICMAUpdater>)Parameters[CMAUpdaterName]; }106 }107 private IFixedValueParameter<IntValue> MaximumGenerationsParameter {108 get { return (IFixedValueParameter<IntValue>)Parameters[MaximumGenerationsName]; }109 }110 private IFixedValueParameter<IntValue> MaximumEvaluatedSolutionsParameter {111 get { return (IFixedValueParameter<IntValue>)Parameters[MaximumEvaluatedSolutionsName]; }112 }113 private IFixedValueParameter<DoubleValue> TargetQualityParameter {114 get { return (IFixedValueParameter<DoubleValue>)Parameters[TargetQualityName]; }115 }116 private IFixedValueParameter<DoubleValue> MinimumQualityChangeParameter {117 get { return (IFixedValueParameter<DoubleValue>)Parameters[MinimumQualityChangeName]; }118 }119 private IFixedValueParameter<DoubleValue> MinimumQualityHistoryChangeParameter {120 get { return (IFixedValueParameter<DoubleValue>)Parameters[MinimumQualityHistoryChangeName]; }121 }122 private IFixedValueParameter<DoubleValue> MinimumStandardDeviationParameter {123 get { return (IFixedValueParameter<DoubleValue>)Parameters[MinimumStandardDeviationName]; }124 }125 private IFixedValueParameter<DoubleValue> MaximumStandardDeviationChangeParameter {126 get { return (IFixedValueParameter<DoubleValue>)Parameters[MaximumStandardDeviationChangeName]; }127 }128 #endregion129 130 #region Properties131 public int Seed {132 get { return SeedParameter.Value.Value; }133 set { SeedParameter.Value.Value = value; }134 }135 public bool SetSeedRandomly {136 get { return SetSeedRandomlyParameter.Value.Value; }137 set { SetSeedRandomlyParameter.Value.Value = value; }138 }139 public int PopulationSize {140 get { return PopulationSizeParameter.Value.Value; }141 set { PopulationSizeParameter.Value.Value = value; }142 }143 public int InitialIterations {144 get { return InitialIterationsParameter.Value.Value; }145 set { InitialIterationsParameter.Value.Value = value; }146 }147 public int MaximumGenerations {148 get { return MaximumGenerationsParameter.Value.Value; }149 set { MaximumGenerationsParameter.Value.Value = value; }150 }151 public int MaximumEvaluatedSolutions {152 get { return MaximumEvaluatedSolutionsParameter.Value.Value; }153 set { MaximumEvaluatedSolutionsParameter.Value.Value = value; }154 }155 public double TargetQuality {156 get { return TargetQualityParameter.Value.Value; }157 set { TargetQualityParameter.Value.Value = value; }158 }159 public double MinimumQualityChange {160 get { return MinimumQualityChangeParameter.Value.Value; }161 set { MinimumQualityChangeParameter.Value.Value = value; }162 }163 public double MinimumQualityHistoryChange {164 get { return MinimumQualityHistoryChangeParameter.Value.Value; }165 set { MinimumQualityHistoryChangeParameter.Value.Value = value; }166 }167 public double MinimumStandardDeviation {168 get { return MinimumStandardDeviationParameter.Value.Value; }169 set { MinimumStandardDeviationParameter.Value.Value = value; }170 }171 public double MaximumStandardDeviationChange {172 get { return MaximumStandardDeviationChangeParameter.Value.Value; }173 set { MaximumStandardDeviationChangeParameter.Value.Value = value; }174 }175 public DoubleArray InitialSigma {176 get { return InitialSigmaParameter.Value; }177 set { InitialSigmaParameter.Value = value; }178 }179 public IntValue Mu {180 get { return MuParameter.Value; }181 set { MuParameter.Value = value; }182 }183 public ICMAInitializer CMAInitializer {184 get { return CMAInitializerParameter.Value; }185 set { CMAInitializerParameter.Value = value; }186 }187 public ICMAManipulator CMAMutator {188 get { return CMAMutatorParameter.Value; }189 set { CMAMutatorParameter.Value = value; }190 }191 public ICMARecombinator CMARecombinator {192 get { return CMARecombinatorParameter.Value; }193 set { CMARecombinatorParameter.Value = value; }194 }195 public MultiAnalyzer Analyzer {196 get { return AnalyzerParameter.Value; }197 set { AnalyzerParameter.Value = value; }198 }199 public ICMAUpdater CMAUpdater {200 get { return CMAUpdaterParameter.Value; }201 set { CMAUpdaterParameter.Value = value; }202 }203 204 private RandomCreator RandomCreator {205 get { return (RandomCreator)OperatorGraph.InitialOperator; }206 }207 208 [Storable]209 private BestAverageWorstQualityAnalyzer qualityAnalyzer;210 [Storable]211 private CMAAnalyzer cmaAnalyzer;212 [Storable]213 private Placeholder solutionCreator;214 [Storable]215 private Placeholder populationSolutionCreator;216 [Storable]217 private Placeholder evaluator;218 [Storable]219 private SubScopesSorter sorter;220 [Storable]221 private Terminator terminator;222 #endregion223 224 [StorableConstructor]225 private CMAEvolutionStrategy(bool deserializing) : base(deserializing) { }226 private CMAEvolutionStrategy(CMAEvolutionStrategy original, Cloner cloner)227 : base(original, cloner) {228 qualityAnalyzer = cloner.Clone(original.qualityAnalyzer);229 cmaAnalyzer = cloner.Clone(original.cmaAnalyzer);230 solutionCreator = cloner.Clone(original.solutionCreator);231 populationSolutionCreator = cloner.Clone(original.populationSolutionCreator);232 evaluator = cloner.Clone(original.evaluator);233 sorter = cloner.Clone(original.sorter);234 terminator = cloner.Clone(original.terminator);235 RegisterEventHandlers();236 }237 public CMAEvolutionStrategy()238 : base() {239 Parameters.Add(new FixedValueParameter<IntValue>(SeedName, "The random seed used to initialize the new pseudo random number generator.", new IntValue(0)));240 Parameters.Add(new FixedValueParameter<BoolValue>(SetSeedRandomlyName, "True if the random seed should be set to a random value, otherwise false.", new BoolValue(true)));241 Parameters.Add(new FixedValueParameter<IntValue>(PopulationSizeName, "λ (lambda) - the size of the offspring population.", new IntValue(20)));242 Parameters.Add(new FixedValueParameter<IntValue>(InitialIterationsName, "The number of iterations that should be performed with only axis parallel mutation.", new IntValue(0)));243 Parameters.Add(new FixedValueParameter<DoubleArray>(InitialSigmaName, "The initial sigma can be a single value or a value for each dimension. All values need to be > 0.", new DoubleArray(new[] { 0.5 })));244 Parameters.Add(new OptionalValueParameter<IntValue>(MuName, "Optional, the mu best offspring that should be considered for update of the new mean and strategy parameters. If not given it will be automatically calculated."));245 Parameters.Add(new ConstrainedValueParameter<ICMARecombinator>(CMARecombinatorName, "The operator used to calculate the new mean."));246 Parameters.Add(new ConstrainedValueParameter<ICMAManipulator>(CMAMutatorName, "The operator used to manipulate a point."));247 Parameters.Add(new ConstrainedValueParameter<ICMAInitializer>(CMAInitializerName, "The operator that initializes the covariance matrix and strategy parameters."));248 Parameters.Add(new ConstrainedValueParameter<ICMAUpdater>(CMAUpdaterName, "The operator that updates the covariance matrix and strategy parameters."));249 Parameters.Add(new ValueParameter<MultiAnalyzer>(AnalyzerName, "The operator used to analyze each generation.", new MultiAnalyzer()));250 Parameters.Add(new FixedValueParameter<IntValue>(MaximumGenerationsName, "The maximum number of generations which should be processed.", new IntValue(1000)));251 Parameters.Add(new FixedValueParameter<IntValue>(MaximumEvaluatedSolutionsName, "The maximum number of evaluated solutions that should be computed.", new IntValue(int.MaxValue)));252 Parameters.Add(new FixedValueParameter<DoubleValue>(TargetQualityName, "(stopFitness) Surpassing this quality value terminates the algorithm.", new DoubleValue(double.NaN)));253 Parameters.Add(new FixedValueParameter<DoubleValue>(MinimumQualityChangeName, "(stopTolFun) If the range of fitness values is less than a certain value the algorithm terminates (set to 0 or positive value to enable).", new DoubleValue(double.NaN)));254 Parameters.Add(new FixedValueParameter<DoubleValue>(MinimumQualityHistoryChangeName, "(stopTolFunHist) If the range of fitness values is less than a certain value for a certain time the algorithm terminates (set to 0 or positive to enable).", new DoubleValue(double.NaN)));255 Parameters.Add(new FixedValueParameter<DoubleValue>(MinimumStandardDeviationName, "(stopTolXFactor) If the standard deviation falls below a certain value the algorithm terminates (set to 0 or positive to enable).", new DoubleValue(double.NaN)));256 Parameters.Add(new FixedValueParameter<DoubleValue>(MaximumStandardDeviationChangeName, "(stopTolUpXFactor) If the standard deviation changes by a value larger than this parameter the algorithm stops (set to a value > 0 to enable).", new DoubleValue(double.NaN)));257 258 var randomCreator = new RandomCreator();259 var variableCreator = new VariableCreator();260 var resultsCollector = new ResultsCollector();261 var cmaInitializer = new Placeholder();262 solutionCreator = new Placeholder();263 var subScopesCreator = new SubScopesCreator();264 var ussp1 = new UniformSubScopesProcessor();265 populationSolutionCreator = new Placeholder();266 var cmaMutator = new Placeholder();267 var ussp2 = new UniformSubScopesProcessor();268 evaluator = new Placeholder();269 var subScopesCounter = new SubScopesCounter();270 sorter = new SubScopesSorter();271 var analyzer = new Placeholder();272 var cmaRecombinator = new Placeholder();273 var generationsCounter = new IntCounter();274 var cmaUpdater = new Placeholder();275 terminator = new Terminator();276 277 OperatorGraph.InitialOperator = randomCreator;278 279 randomCreator.RandomParameter.ActualName = "Random";280 randomCreator.SeedParameter.ActualName = SeedParameter.Name;281 randomCreator.SeedParameter.Value = null;282 randomCreator.SetSeedRandomlyParameter.ActualName = SetSeedRandomlyParameter.Name;283 randomCreator.SetSeedRandomlyParameter.Value = null;284 randomCreator.Successor = variableCreator;285 286 variableCreator.Name = "Initialize Variables";287 variableCreator.CollectedValues.Add(new ValueParameter<IntValue>("EvaluatedSolutions", new IntValue(0)));288 variableCreator.CollectedValues.Add(new ValueParameter<IntValue>("Generations", new IntValue(0)));289 variableCreator.Successor = resultsCollector;290 291 resultsCollector.CollectedValues.Add(new LookupParameter<IntValue>("EvaluatedSolutions"));292 resultsCollector.CollectedValues.Add(new LookupParameter<IntValue>("Generations"));293 resultsCollector.ResultsParameter.ActualName = "Results";294 resultsCollector.Successor = cmaInitializer;295 296 cmaInitializer.Name = "Initialize Strategy Parameters";297 cmaInitializer.OperatorParameter.ActualName = CMAInitializerParameter.Name;298 cmaInitializer.Successor = subScopesCreator;299 300 subScopesCreator.NumberOfSubScopesParameter.ActualName = PopulationSizeParameter.Name;301 subScopesCreator.Successor = ussp1;302 303 ussp1.Name = "Create population";304 ussp1.Parallel = new BoolValue(false);305 ussp1.Operator = populationSolutionCreator;306 ussp1.Successor = solutionCreator;307 308 populationSolutionCreator.Name = "Initialize arx";309 // populationSolutionCreator.OperatorParameter will be wired310 populationSolutionCreator.Successor = null;311 312 solutionCreator.Name = "Initialize xmean";313 // solutionCreator.OperatorParameter will be wired314 solutionCreator.Successor = cmaMutator;315 316 cmaMutator.Name = "Sample population";317 cmaMutator.OperatorParameter.ActualName = CMAMutatorParameter.Name;318 cmaMutator.Successor = ussp2;319 320 ussp2.Name = "Evaluate offspring";321 ussp2.Parallel = new BoolValue(true);322 ussp2.Operator = evaluator;323 ussp2.Successor = subScopesCounter;324 325 evaluator.Name = "Evaluator";326 // evaluator.OperatorParameter will be wired327 evaluator.Successor = null;328 329 subScopesCounter.Name = "Count EvaluatedSolutions";330 subScopesCounter.AccumulateParameter.Value = new BoolValue(true);331 subScopesCounter.ValueParameter.ActualName = "EvaluatedSolutions";332 subScopesCounter.Successor = sorter;333 334 // sorter.ValueParameter will be wired335 // sorter.DescendingParameter will be wired336 sorter.Successor = analyzer;337 338 analyzer.Name = "Analyzer";339 analyzer.OperatorParameter.ActualName = AnalyzerParameter.Name;340 analyzer.Successor = cmaRecombinator;341 342 cmaRecombinator.Name = "Create new xmean";343 cmaRecombinator.OperatorParameter.ActualName = CMARecombinatorParameter.Name;344 cmaRecombinator.Successor = generationsCounter;345 346 generationsCounter.Name = "Generations++";347 generationsCounter.IncrementParameter.Value = new IntValue(1);348 generationsCounter.ValueParameter.ActualName = "Generations";349 generationsCounter.Successor = cmaUpdater;350 351 cmaUpdater.Name = "Update distributions";352 cmaUpdater.OperatorParameter.ActualName = CMAUpdaterParameter.Name;353 cmaUpdater.Successor = terminator;354 355 terminator.Continue = cmaMutator;356 terminator.Terminate = null;357 358 qualityAnalyzer = new BestAverageWorstQualityAnalyzer();359 cmaAnalyzer = new CMAAnalyzer();360 361 InitializeOperators();362 RegisterEventHandlers();363 Parameterize();364 }365 366 public override IDeepCloneable Clone(Cloner cloner) {367 return new CMAEvolutionStrategy(this, cloner);368 }369 370 [StorableHook(HookType.AfterDeserialization)]371 private void AfterDeserialization() {372 RegisterEventHandlers();373 }374 375 public override void Prepare() {376 if (Problem != null) base.Prepare();377 }378 379 protected override void OnStarted() {380 if (!(Problem.SolutionCreator is IRealVectorCreator))381 throw new InvalidOperationException("Problems that do not use RealVectorEncoding cannot be solved by CMA-ES.");382 base.OnStarted();383 }384 385 #region Events386 protected override void OnProblemChanged() {387 Problem.Evaluator.QualityParameter.ActualNameChanged += Evaluator_QualityParameter_ActualNameChanged;388 var creator = Problem.SolutionCreator as IRealVectorCreator;389 if (creator != null) {390 creator.RealVectorParameter.ActualNameChanged += RealVectorCreator_Changed;391 creator.LengthParameter.ActualNameChanged += RealVectorCreator_Changed;392 creator.LengthParameter.ValueChanged += RealVectorCreator_Changed;393 creator.BoundsParameter.ActualNameChanged += RealVectorCreator_Changed;394 creator.BoundsParameter.ValueChanged += RealVectorCreator_Changed;395 }396 UpdateOperators();397 UpdateAnalyzers();398 Parameterize();399 base.OnProblemChanged();400 }401 protected override void Problem_SolutionCreatorChanged(object sender, EventArgs e) {402 var creator = Problem.SolutionCreator as IRealVectorCreator;403 if (creator != null) {404 creator.RealVectorParameter.ActualNameChanged += RealVectorCreator_Changed;405 creator.LengthParameter.ActualNameChanged += RealVectorCreator_Changed;406 creator.LengthParameter.ValueChanged += RealVectorCreator_Changed;407 creator.BoundsParameter.ActualNameChanged += RealVectorCreator_Changed;408 creator.BoundsParameter.ValueChanged += RealVectorCreator_Changed;409 }410 Parameterize();411 base.Problem_SolutionCreatorChanged(sender, e);412 }413 protected override void Problem_EvaluatorChanged(object sender, EventArgs e) {414 Problem.Evaluator.QualityParameter.ActualNameChanged += Evaluator_QualityParameter_ActualNameChanged;415 Parameterize();416 base.Problem_EvaluatorChanged(sender, e);417 }418 protected override void Problem_OperatorsChanged(object sender, EventArgs e) {419 UpdateOperators();420 UpdateAnalyzers();421 Parameterize();422 base.Problem_OperatorsChanged(sender, e);423 }424 private void Evaluator_QualityParameter_ActualNameChanged(object sender, EventArgs e) {425 Parameterize();426 }427 private bool cmaesInitializerSync;428 private void CMAESInitializerParameter_ValueChanged(object sender, EventArgs e) {429 if (cmaesInitializerSync) return;430 UpdateOperators();431 Parameterize();432 }433 private void RealVectorCreator_Changed(object sender, EventArgs e) {434 Parameterize();435 }436 #endregion437 438 #region Helpers439 private void RegisterEventHandlers() {440 CMAInitializerParameter.ValueChanged += CMAESInitializerParameter_ValueChanged;441 if (Problem != null) {442 Problem.Evaluator.QualityParameter.ActualNameChanged += Evaluator_QualityParameter_ActualNameChanged;443 var creator = Problem.SolutionCreator as IRealVectorCreator;444 if (creator != null) {445 creator.RealVectorParameter.ActualNameChanged += RealVectorCreator_Changed;446 creator.LengthParameter.ActualNameChanged += RealVectorCreator_Changed;447 creator.LengthParameter.ValueChanged += RealVectorCreator_Changed;448 creator.BoundsParameter.ActualNameChanged += RealVectorCreator_Changed;449 creator.BoundsParameter.ValueChanged += RealVectorCreator_Changed;450 }451 }452 }453 private void InitializeOperators() {454 foreach (var op in ApplicationManager.Manager.GetInstances<ICMAInitializer>())455 CMAInitializerParameter.ValidValues.Add(op);456 foreach (var op in ApplicationManager.Manager.GetInstances<ICMAManipulator>().Where(x => x.CMAType == CMAInitializer.CMAType))457 CMAMutatorParameter.ValidValues.Add(op);458 foreach (var op in ApplicationManager.Manager.GetInstances<ICMARecombinator>().Where(x => x.CMAType == CMAInitializer.CMAType))459 CMARecombinatorParameter.ValidValues.Add(op);460 foreach (var op in ApplicationManager.Manager.GetInstances<ICMAUpdater>().Where(x => x.CMAType == CMAInitializer.CMAType))461 CMAUpdaterParameter.ValidValues.Add(op);462 }463 private void UpdateOperators() {464 cmaesInitializerSync = true;465 try {466 var oldMutator = CMAMutator;467 var oldRecombinator = CMARecombinator;468 var oldUpdater = CMAUpdater;469 470 if (CMAInitializer != null && (oldMutator == null || oldMutator.CMAType != CMAInitializer.CMAType)) {471 CMAMutatorParameter.ValidValues.Clear();472 foreach (var op in ApplicationManager.Manager.GetInstances<ICMAManipulator>().Where(x => x.CMAType == CMAInitializer.CMAType))473 CMAMutatorParameter.ValidValues.Add(op);474 CMAMutator = CMAMutatorParameter.ValidValues.First();475 }476 477 if (CMAInitializer != null && (oldRecombinator == null || oldRecombinator.CMAType != CMAInitializer.CMAType)) {478 CMARecombinatorParameter.ValidValues.Clear();479 foreach (var op in ApplicationManager.Manager.GetInstances<ICMARecombinator>().Where(x => x.CMAType == CMAInitializer.CMAType))480 CMARecombinatorParameter.ValidValues.Add(op);481 CMARecombinator = CMARecombinatorParameter.ValidValues.First();482 }483 484 if (CMAInitializer != null && (oldUpdater == null || oldUpdater.CMAType != CMAInitializer.CMAType)) {485 CMAUpdaterParameter.ValidValues.Clear();486 foreach (var op in ApplicationManager.Manager.GetInstances<ICMAUpdater>().Where(x => x.CMAType == CMAInitializer.CMAType))487 CMAUpdaterParameter.ValidValues.Add(op);488 CMAUpdater = CMAUpdaterParameter.ValidValues.First();489 }490 }491 finally { cmaesInitializerSync = false; }492 }493 private void UpdateAnalyzers() {494 Analyzer.Operators.Clear();495 if (Problem != null) {496 foreach (var analyzer in Problem.Operators.OfType<IAnalyzer>()) {497 foreach (var param in analyzer.Parameters.OfType<IScopeTreeLookupParameter>())498 param.Depth = 1;499 Analyzer.Operators.Add(analyzer, analyzer.EnabledByDefault);500 }501 }502 Analyzer.Operators.Add(qualityAnalyzer, qualityAnalyzer.EnabledByDefault);503 Analyzer.Operators.Add(cmaAnalyzer, cmaAnalyzer.EnabledByDefault);504 }505 private void Parameterize() {506 507 foreach (var op in CMAInitializerParameter.ValidValues) {508 op.PopulationSizeParameter.ActualName = PopulationSizeParameter.Name;509 op.PopulationSizeParameter.Hidden = true;510 op.MuParameter.ActualName = MuParameter.Name;511 op.MuParameter.Hidden = true;512 op.InitialIterationsParameter.Value = null;513 op.InitialIterationsParameter.ActualName = InitialIterationsParameter.Name;514 op.InitialIterationsParameter.Hidden = true;515 op.InitialSigmaParameter.Value = null;516 op.InitialSigmaParameter.ActualName = InitialSigmaParameter.Name;517 op.InitialSigmaParameter.Hidden = true;518 519 op.DimensionParameter.Hidden = false;520 521 ParameterizeStochasticOperator(op);522 ParameterizeIterationBasedOperator(op);523 }524 525 foreach (var op in CMAMutatorParameter.ValidValues) {526 op.PopulationSizeParameter.ActualName = PopulationSizeParameter.Name;527 op.PopulationSizeParameter.Hidden = true;528 529 op.MeanParameter.Hidden = false;530 op.BoundsParameter.Hidden = false;531 op.RealVectorParameter.Hidden = false;532 533 ParameterizeStochasticOperator(op);534 ParameterizeIterationBasedOperator(op);535 }536 537 foreach (var op in CMARecombinatorParameter.ValidValues) {538 op.OldMeanParameter.ActualName = "XOld";539 op.OldMeanParameter.Hidden = true;540 541 op.OffspringParameter.Hidden = false;542 op.MeanParameter.Hidden = false;543 544 ParameterizeStochasticOperator(op);545 ParameterizeIterationBasedOperator(op);546 }547 548 foreach (var op in CMAUpdaterParameter.ValidValues) {549 op.MaximumEvaluatedSolutionsParameter.ActualName = MaximumEvaluatedSolutionsParameter.Name;550 op.MaximumEvaluatedSolutionsParameter.Hidden = true;551 op.OldMeanParameter.ActualName = "XOld";552 op.OldMeanParameter.Hidden = true;553 554 op.MeanParameter.Hidden = false;555 op.OffspringParameter.Hidden = false;556 op.QualityParameter.Hidden = false;557 558 ParameterizeStochasticOperator(op);559 ParameterizeIterationBasedOperator(op);560 }561 562 terminator.IterationsParameter.ActualName = "Generations";563 terminator.MaximumIterationsParameter.ActualName = MaximumGenerationsParameter.Name;564 terminator.EvaluatedSolutionsParameter.ActualName = "EvaluatedSolutions";565 terminator.InitialSigmaParameter.ActualName = InitialSigmaParameter.Name;566 terminator.MaximumEvaluatedSolutionsParameter.ActualName = MaximumEvaluatedSolutionsParameter.Name;567 terminator.MaximumStandardDeviationChangeParameter.ActualName = MaximumStandardDeviationChangeParameter.Name;568 terminator.MinimumQualityChangeParameter.ActualName = MinimumQualityChangeParameter.Name;569 terminator.MinimumQualityHistoryChangeParameter.ActualName = MinimumQualityHistoryChangeParameter.Name;570 terminator.MinimumStandardDeviationParameter.ActualName = MinimumStandardDeviationParameter.Name;571 terminator.TargetQualityParameter.ActualName = TargetQualityParameter.Name;572 if (CMAUpdater != null)573 terminator.DegenerateStateParameter.ActualName = CMAUpdater.DegenerateStateParameter.ActualName;574 575 var creator = Problem != null ? (Problem.SolutionCreator as IRealVectorCreator) : null;576 if (Problem != null && creator != null) {577 578 solutionCreator.OperatorParameter.ActualName = Problem.SolutionCreatorParameter.Name;579 #region Backwards compatible code, remove with 3.4580 if (populationSolutionCreator != null) // BackwardsCompatibility3.3581 // ONLY REMOVE THE CONDITION582 populationSolutionCreator.OperatorParameter.ActualName = Problem.SolutionCreatorParameter.Name;583 #endregion584 evaluator.OperatorParameter.ActualName = Problem.EvaluatorParameter.Name;585 sorter.DescendingParameter.ActualName = Problem.MaximizationParameter.Name;586 sorter.ValueParameter.ActualName = Problem.Evaluator.QualityParameter.ActualName;587 terminator.MaximizationParameter.ActualName = Problem.MaximizationParameter.Name;588 terminator.QualityParameter.ActualName = Problem.Evaluator.QualityParameter.Name;589 590 foreach (var op in CMAInitializerParameter.ValidValues) {591 if (creator.LengthParameter.Value == null) {592 op.DimensionParameter.ActualName = creator.LengthParameter.ActualName;593 op.DimensionParameter.Value = null;594 } else op.DimensionParameter.Value = creator.LengthParameter.Value;595 op.DimensionParameter.Hidden = true;596 }597 598 foreach (var op in CMAMutatorParameter.ValidValues) {599 op.MeanParameter.ActualName = creator.RealVectorParameter.ActualName;600 op.MeanParameter.Hidden = true;601 if (creator.BoundsParameter.Value == null) {602 op.BoundsParameter.ActualName = creator.BoundsParameter.ActualName;603 op.BoundsParameter.Value = null;604 } else op.BoundsParameter.Value = creator.BoundsParameter.Value;605 op.BoundsParameter.Hidden = true;606 op.RealVectorParameter.ActualName = creator.RealVectorParameter.ActualName;607 op.RealVectorParameter.Depth = 1;608 op.RealVectorParameter.Hidden = true;609 }610 611 foreach (var op in CMARecombinatorParameter.ValidValues) {612 op.MeanParameter.ActualName = creator.RealVectorParameter.ActualName;613 op.MeanParameter.Hidden = true;614 op.OffspringParameter.ActualName = creator.RealVectorParameter.ActualName;615 op.OffspringParameter.Depth = 1;616 op.OffspringParameter.Hidden = true;617 }618 619 foreach (var op in CMAUpdaterParameter.ValidValues) {620 op.MeanParameter.ActualName = creator.RealVectorParameter.ActualName;621 op.MeanParameter.Hidden = true;622 op.OffspringParameter.ActualName = creator.RealVectorParameter.ActualName;623 op.OffspringParameter.Depth = 1;624 op.OffspringParameter.Hidden = true;625 op.QualityParameter.ActualName = Problem.Evaluator.QualityParameter.ActualName;626 op.QualityParameter.Hidden = true;627 }628 629 foreach (var op in Problem.Operators.OfType<IStochasticOperator>()) {630 op.RandomParameter.ActualName = RandomCreator.RandomParameter.ActualName;631 op.RandomParameter.Hidden = true;632 }633 634 qualityAnalyzer.MaximizationParameter.ActualName = Problem.MaximizationParameter.Name;635 qualityAnalyzer.MaximizationParameter.Hidden = true;636 qualityAnalyzer.QualityParameter.ActualName = Problem.Evaluator.QualityParameter.ActualName;637 qualityAnalyzer.QualityParameter.Depth = 1;638 qualityAnalyzer.QualityParameter.Hidden = true;639 qualityAnalyzer.BestKnownQualityParameter.ActualName = Problem.BestKnownQualityParameter.Name;640 qualityAnalyzer.BestKnownQualityParameter.Hidden = true;641 642 cmaAnalyzer.QualityParameter.ActualName = Problem.Evaluator.QualityParameter.ActualName;643 cmaAnalyzer.QualityParameter.Depth = 1;644 cmaAnalyzer.QualityParameter.Hidden = true;645 cmaAnalyzer.MeanParameter.ActualName = creator.RealVectorParameter.ActualName;646 cmaAnalyzer.MeanParameter.Hidden = true;647 648 foreach (var op in Problem.Operators.OfType<IIterationBasedOperator>()) {649 op.IterationsParameter.ActualName = "Generations";650 op.IterationsParameter.Hidden = true;651 op.MaximumIterationsParameter.ActualName = MaximumGenerationsParameter.Name;652 op.MaximumIterationsParameter.Hidden = true;653 }654 } else {655 qualityAnalyzer.MaximizationParameter.Hidden = false;656 qualityAnalyzer.QualityParameter.Hidden = false;657 qualityAnalyzer.BestKnownQualityParameter.Hidden = false;658 659 cmaAnalyzer.MeanParameter.Hidden = false;660 }661 662 qualityAnalyzer.ResultsParameter.ActualName = "Results";663 qualityAnalyzer.ResultsParameter.Hidden = true;664 cmaAnalyzer.ResultsParameter.ActualName = "Results";665 cmaAnalyzer.ResultsParameter.Hidden = true;666 }667 668 private void ParameterizeStochasticOperator(IOperator op) {669 var sOp = op as IStochasticOperator;670 if (sOp != null) sOp.RandomParameter.ActualName = RandomCreator.RandomParameter.ActualName;671 }672 673 private void ParameterizeIterationBasedOperator(IOperator op) {674 var iOp = op as IIterationBasedOperator;675 if (iOp != null) {676 iOp.IterationsParameter.ActualName = "Generations";677 iOp.MaximumIterationsParameter.ActualName = MaximumGenerationsParameter.Name;678 }679 }680 #endregion681 }682 771 } -
branches/HeuristicLab.Algorithms.CMAEvolutionStrategy/sources/3.3/HeuristicLab.Algorithms.CMAEvolutionStrategy-3.3.csproj
r13793 r13909 102 102 <ItemGroup> 103 103 <Reference Include="HeuristicLab.Analysis-3.3"> 104 <HintPath>..\..\..\ trunk\sources\bin\HeuristicLab.Analysis-3.3.dll</HintPath>104 <HintPath>..\..\..\..\trunk\sources\bin\HeuristicLab.Analysis-3.3.dll</HintPath> 105 105 </Reference> 106 106 <Reference Include="HeuristicLab.Collections-3.3"> 107 <HintPath>..\..\..\ trunk\sources\bin\HeuristicLab.Collections-3.3.dll</HintPath>107 <HintPath>..\..\..\..\trunk\sources\bin\HeuristicLab.Collections-3.3.dll</HintPath> 108 108 </Reference> 109 109 <Reference Include="HeuristicLab.Common-3.3"> 110 <HintPath>..\..\..\ trunk\sources\bin\HeuristicLab.Common-3.3.dll</HintPath>110 <HintPath>..\..\..\..\trunk\sources\bin\HeuristicLab.Common-3.3.dll</HintPath> 111 111 </Reference> 112 112 <Reference Include="HeuristicLab.Core-3.3"> 113 <HintPath>..\..\..\ trunk\sources\bin\HeuristicLab.Core-3.3.dll</HintPath>113 <HintPath>..\..\..\..\trunk\sources\bin\HeuristicLab.Core-3.3.dll</HintPath> 114 114 </Reference> 115 115 <Reference Include="HeuristicLab.Data-3.3"> 116 <HintPath>..\..\..\ trunk\sources\bin\HeuristicLab.Data-3.3.dll</HintPath>116 <HintPath>..\..\..\..\trunk\sources\bin\HeuristicLab.Data-3.3.dll</HintPath> 117 117 </Reference> 118 118 <Reference Include="HeuristicLab.Encodings.RealVectorEncoding-3.3"> 119 <HintPath>..\..\..\ trunk\sources\bin\HeuristicLab.Encodings.RealVectorEncoding-3.3.dll</HintPath>119 <HintPath>..\..\..\..\trunk\sources\bin\HeuristicLab.Encodings.RealVectorEncoding-3.3.dll</HintPath> 120 120 </Reference> 121 121 <Reference Include="HeuristicLab.Operators-3.3"> 122 <HintPath>..\..\..\ trunk\sources\bin\HeuristicLab.Operators-3.3.dll</HintPath>122 <HintPath>..\..\..\..\trunk\sources\bin\HeuristicLab.Operators-3.3.dll</HintPath> 123 123 </Reference> 124 124 <Reference Include="HeuristicLab.Optimization-3.3"> 125 <HintPath>..\..\..\ trunk\sources\bin\HeuristicLab.Optimization-3.3.dll</HintPath>125 <HintPath>..\..\..\..\trunk\sources\bin\HeuristicLab.Optimization-3.3.dll</HintPath> 126 126 </Reference> 127 127 <Reference Include="HeuristicLab.Optimization.Operators-3.3"> 128 <HintPath>..\..\..\ trunk\sources\bin\HeuristicLab.Optimization.Operators-3.3.dll</HintPath>128 <HintPath>..\..\..\..\trunk\sources\bin\HeuristicLab.Optimization.Operators-3.3.dll</HintPath> 129 129 </Reference> 130 130 <Reference Include="HeuristicLab.Parameters-3.3"> 131 <HintPath>..\..\..\ trunk\sources\bin\HeuristicLab.Parameters-3.3.dll</HintPath>131 <HintPath>..\..\..\..\trunk\sources\bin\HeuristicLab.Parameters-3.3.dll</HintPath> 132 132 </Reference> 133 133 <Reference Include="HeuristicLab.Persistence-3.3"> 134 <HintPath>..\..\..\ trunk\sources\bin\HeuristicLab.Persistence-3.3.dll</HintPath>134 <HintPath>..\..\..\..\trunk\sources\bin\HeuristicLab.Persistence-3.3.dll</HintPath> 135 135 </Reference> 136 136 <Reference Include="HeuristicLab.PluginInfrastructure-3.3"> 137 <HintPath>..\..\..\ trunk\sources\bin\HeuristicLab.PluginInfrastructure-3.3.dll</HintPath>137 <HintPath>..\..\..\..\trunk\sources\bin\HeuristicLab.PluginInfrastructure-3.3.dll</HintPath> 138 138 </Reference> 139 139 <Reference Include="HeuristicLab.Problems.Instances-3.3"> 140 <HintPath>..\..\..\ trunk\sources\bin\HeuristicLab.Problems.Instances-3.3.dll</HintPath>140 <HintPath>..\..\..\..\trunk\sources\bin\HeuristicLab.Problems.Instances-3.3.dll</HintPath> 141 141 </Reference> 142 142 <Reference Include="HeuristicLab.Problems.MultiObjectiveTestFunctions-3.3"> 143 <HintPath>..\..\..\ trunk\sources\bin\HeuristicLab.Problems.MultiObjectiveTestFunctions-3.3.dll</HintPath>143 <HintPath>..\..\..\..\trunk\sources\bin\HeuristicLab.Problems.MultiObjectiveTestFunctions-3.3.dll</HintPath> 144 144 </Reference> 145 145 <Reference Include="HeuristicLab.Random-3.3"> 146 <HintPath>..\..\..\ trunk\sources\bin\HeuristicLab.Random-3.3.dll</HintPath>146 <HintPath>..\..\..\..\trunk\sources\bin\HeuristicLab.Random-3.3.dll</HintPath> 147 147 </Reference> 148 148 <Reference Include="System" /> -
branches/HeuristicLab.Algorithms.CMAEvolutionStrategy/sources/3.3/MOCMAES/CrowdingIndicator.cs
r13793 r13909 1 using System; 1 using HeuristicLab.Data; 2 using HeuristicLab.Encodings.RealVectorEncoding; 3 using HeuristicLab.Optimization; 4 using HeuristicLab.Problems.MultiObjectiveTestFunctions; 5 using System; 6 using System.Linq; 2 7 3 namespace HeuristicLab.Algorithms.CMAEvolutionStrategy { 4 class CrowdingIndicator : IIndicator { 5 int IIndicator.leastContributer<R>(R[] front, Func<R, double[]> extractor) { 8 namespace HeuristicLab.Algorithms.CMAEvolutionStrategy 9 { 10 class CrowdingIndicator : IIndicator 11 { 6 12 7 throw new NotImplementedException(); 13 14 int IIndicator.leastContributer<R>(R[] front, Func<R, double[]> extractor, MultiObjectiveTestFunctionProblem problem) 15 { 16 DoubleMatrix bounds = problem.Bounds; 17 int mindex = 1; 18 double min = Double.MaxValue; 19 double[] pointsums = new double[front.Count()]; 20 21 for (int dim = 0; dim < problem.Objectives; dim++) 22 { 23 double[] arr = front.Select(x => extractor.Invoke(x)[dim]).ToArray(); 24 Array.Sort(arr); 25 double fmax = problem.Bounds[dim % bounds.Rows, 1]; 26 double fmin = bounds[dim % bounds.Rows, 0]; 27 int pointIdx = 0; 28 foreach (R point in front) 29 { 30 double d = 0; 31 int pos = Array.BinarySearch(arr, extractor.Invoke(point)[dim]); 32 33 d = pos != 0 && pos != arr.Count() - 1 ? (arr[pos + 1] - arr[pos - 1]) / (fmax - fmin) : Double.PositiveInfinity; 34 pointsums[pointIdx] += d; 35 36 37 pointIdx++; 38 } 39 } 40 //find min 41 for (int pointIdx = 0; pointIdx < pointsums.Length; pointIdx++) 42 { 43 double d = pointsums[pointIdx]; 44 if (!Double.IsInfinity(d) && min > d) 45 { 46 mindex = pointIdx; 47 min = d; 48 } 49 } 50 51 return mindex; 52 } 8 53 } 9 }10 54 } -
branches/HeuristicLab.Algorithms.CMAEvolutionStrategy/sources/3.3/MOCMAES/IIndicator.cs
r13793 r13909 1 using System; 1 using HeuristicLab.Problems.MultiObjectiveTestFunctions; 2 using System; 2 3 3 namespace HeuristicLab.Algorithms.CMAEvolutionStrategy { 4 public interface IIndicator { 5 int leastContributer<R>(R[] front_, Func<R, double[]> extractor); 6 } 4 namespace HeuristicLab.Algorithms.CMAEvolutionStrategy 5 { 6 public interface IIndicator 7 { 8 int leastContributer<R>(R[] front_, Func<R, double[]> extractor, MultiObjectiveTestFunctionProblem problem); 9 } 7 10 } -
branches/HeuristicLab.Algorithms.CMAEvolutionStrategy/sources/3.3/MOCMAES/MOCMASEvolutionStrategy.cs
r13793 r13909 32 32 using HeuristicLab.Parameters; 33 33 using HeuristicLab.Persistence.Default.CompositeSerializers.Storable; 34 using HeuristicLab.Random; 34 35 using HeuristicLab.Problems.MultiObjectiveTestFunctions; 35 using HeuristicLab.Random; 36 37 namespace HeuristicLab.Algorithms.CMAEvolutionStrategy { 38 [Item("MOCMAS Evolution Strategy (MOCMASES)", "A multi objective evolution strategy based on covariance matrix adaptation. Code is based on 'Covariance Matrix Adaptation for Multi - objective Optimization' by Igel, Hansen and Roth")] 39 [Creatable(CreatableAttribute.Categories.PopulationBasedAlgorithms, Priority = 210)] 40 [StorableClass] 41 public class MOCMASEvolutionStrategy : BasicAlgorithm { 42 public override Type ProblemType { 43 get { return typeof(MultiObjectiveTestFunctionProblem); } 36 using System.Linq; 37 38 namespace HeuristicLab.Algorithms.CMAEvolutionStrategy 39 { 40 [Item("MOCMAS Evolution Strategy (MOCMASES)", "A multi objective evolution strategy based on covariance matrix adaptation. Code is based on 'Covariance Matrix Adaptation for Multi - objective Optimization' by Igel, Hansen and Roth")] 41 [Creatable(CreatableAttribute.Categories.PopulationBasedAlgorithms, Priority = 210)] 42 [StorableClass] 43 public class MOCMASEvolutionStrategy : BasicAlgorithm 44 { 45 public override Type ProblemType 46 { 47 get { return typeof(MultiObjectiveTestFunctionProblem); } 48 } 49 public new MultiObjectiveTestFunctionProblem Problem 50 { 51 get { return (MultiObjectiveTestFunctionProblem)base.Problem; } 52 set { base.Problem = value; } 53 } 54 55 private readonly IRandom random = new MersenneTwister(); 56 57 58 #region ParameterNames 59 private const string MaximumRuntimeName = "Maximum Runtime"; 60 private const string SeedName = "Seed"; 61 private const string SetSeedRandomlyName = "SetSeedRandomly"; 62 private const string PopulationSizeName = "PopulationSize"; 63 private const string InitialIterationsName = "InitialIterations"; 64 private const string InitialSigmaName = "InitialSigma"; 65 private const string MuName = "Mu"; 66 private const string CMAInitializerName = "CMAInitializer"; 67 private const string CMAMutatorName = "CMAMutator"; 68 private const string CMARecombinatorName = "CMARecombinator"; 69 private const string CMAUpdaterName = "CMAUpdater"; 70 private const string AnalyzerName = "Analyzer"; 71 private const string MaximumGenerationsName = "MaximumGenerations"; 72 private const string MaximumEvaluatedSolutionsName = "MaximumEvaluatedSolutions"; 73 private const string TargetQualityName = "TargetQuality"; 74 private const string MinimumQualityChangeName = "MinimumQualityChange"; 75 private const string MinimumQualityHistoryChangeName = "MinimumQualityHistoryChange"; 76 private const string MinimumStandardDeviationName = "MinimumStandardDeviation"; 77 private const string MaximumStandardDeviationChangeName = "MaximumStandardDeviationChange"; 78 #endregion 79 80 #region ParameterProperties 81 public IFixedValueParameter<IntValue> MaximumRuntimeParameter 82 { 83 get { return (IFixedValueParameter<IntValue>)Parameters[MaximumRuntimeName]; } 84 } 85 public IFixedValueParameter<IntValue> SeedParameter 86 { 87 get { return (IFixedValueParameter<IntValue>)Parameters[SeedName]; } 88 } 89 public FixedValueParameter<BoolValue> SetSeedRandomlyParameter 90 { 91 get { return (FixedValueParameter<BoolValue>)Parameters[SetSeedRandomlyName]; } 92 } 93 private IFixedValueParameter<IntValue> PopulationSizeParameter 94 { 95 get { return (IFixedValueParameter<IntValue>)Parameters[PopulationSizeName]; } 96 } 97 public IValueParameter<MultiAnalyzer> AnalyzerParameter 98 { 99 get { return (IValueParameter<MultiAnalyzer>)Parameters[AnalyzerName]; } 100 } 101 private IFixedValueParameter<IntValue> InitialIterationsParameter 102 { 103 get { return (IFixedValueParameter<IntValue>)Parameters[InitialIterationsName]; } 104 } 105 public IValueParameter<DoubleValue> InitialSigmaParameter 106 { 107 get { return (IValueParameter<DoubleValue>)Parameters[InitialSigmaName]; } 108 } 109 private OptionalValueParameter<IntValue> MuParameter 110 { 111 get { return (OptionalValueParameter<IntValue>)Parameters[MuName]; } 112 } 113 private IFixedValueParameter<IntValue> MaximumGenerationsParameter 114 { 115 get { return (IFixedValueParameter<IntValue>)Parameters[MaximumGenerationsName]; } 116 } 117 private IFixedValueParameter<IntValue> MaximumEvaluatedSolutionsParameter 118 { 119 get { return (IFixedValueParameter<IntValue>)Parameters[MaximumEvaluatedSolutionsName]; } 120 } 121 private IFixedValueParameter<DoubleValue> TargetQualityParameter 122 { 123 get { return (IFixedValueParameter<DoubleValue>)Parameters[TargetQualityName]; } 124 } 125 private IFixedValueParameter<DoubleValue> MinimumQualityChangeParameter 126 { 127 get { return (IFixedValueParameter<DoubleValue>)Parameters[MinimumQualityChangeName]; } 128 } 129 private IFixedValueParameter<DoubleValue> MinimumQualityHistoryChangeParameter 130 { 131 get { return (IFixedValueParameter<DoubleValue>)Parameters[MinimumQualityHistoryChangeName]; } 132 } 133 private IFixedValueParameter<DoubleValue> MinimumStandardDeviationParameter 134 { 135 get { return (IFixedValueParameter<DoubleValue>)Parameters[MinimumStandardDeviationName]; } 136 } 137 private IFixedValueParameter<DoubleValue> MaximumStandardDeviationChangeParameter 138 { 139 get { return (IFixedValueParameter<DoubleValue>)Parameters[MaximumStandardDeviationChangeName]; } 140 } 141 #endregion 142 143 #region Properties 144 public int MaximumRuntime 145 { 146 get { return MaximumRuntimeParameter.Value.Value; } 147 set { MaximumRuntimeParameter.Value.Value = value; } 148 } 149 public int Seed 150 { 151 get { return SeedParameter.Value.Value; } 152 set { SeedParameter.Value.Value = value; } 153 } 154 public bool SetSeedRandomly 155 { 156 get { return SetSeedRandomlyParameter.Value.Value; } 157 set { SetSeedRandomlyParameter.Value.Value = value; } 158 } 159 public int PopulationSize 160 { 161 get { return PopulationSizeParameter.Value.Value; } 162 set { PopulationSizeParameter.Value.Value = value; } 163 } 164 public int InitialIterations 165 { 166 get { return InitialIterationsParameter.Value.Value; } 167 set { InitialIterationsParameter.Value.Value = value; } 168 } 169 public int MaximumGenerations 170 { 171 get { return MaximumGenerationsParameter.Value.Value; } 172 set { MaximumGenerationsParameter.Value.Value = value; } 173 } 174 public int MaximumEvaluatedSolutions 175 { 176 get { return MaximumEvaluatedSolutionsParameter.Value.Value; } 177 set { MaximumEvaluatedSolutionsParameter.Value.Value = value; } 178 } 179 public double TargetQuality 180 { 181 get { return TargetQualityParameter.Value.Value; } 182 set { TargetQualityParameter.Value.Value = value; } 183 } 184 public double MinimumQualityChange 185 { 186 get { return MinimumQualityChangeParameter.Value.Value; } 187 set { MinimumQualityChangeParameter.Value.Value = value; } 188 } 189 public double MinimumQualityHistoryChange 190 { 191 get { return MinimumQualityHistoryChangeParameter.Value.Value; } 192 set { MinimumQualityHistoryChangeParameter.Value.Value = value; } 193 } 194 public double MinimumStandardDeviation 195 { 196 get { return MinimumStandardDeviationParameter.Value.Value; } 197 set { MinimumStandardDeviationParameter.Value.Value = value; } 198 } 199 public double MaximumStandardDeviationChange 200 { 201 get { return MaximumStandardDeviationChangeParameter.Value.Value; } 202 set { MaximumStandardDeviationChangeParameter.Value.Value = value; } 203 } 204 public DoubleValue InitialSigma 205 { 206 get { return InitialSigmaParameter.Value; } 207 set { InitialSigmaParameter.Value = value; } 208 } 209 public IntValue Mu 210 { 211 get { return MuParameter.Value; } 212 set { MuParameter.Value = value; } 213 } 214 215 #endregion 216 217 #region ResultsProperties 218 private int ResultsEvaluations 219 { 220 get { return ((IntValue)Results["Evaluations"].Value).Value; } 221 set { ((IntValue)Results["Evaluations"].Value).Value = value; } 222 } 223 private int ResultsIterations 224 { 225 get { return ((IntValue)Results["Iterations"].Value).Value; } 226 set { ((IntValue)Results["Iterations"].Value).Value = value; } 227 } 228 229 //Datatable 230 private DataTable ResultsQualities 231 { 232 get { return ((DataTable)Results["Timetable"].Value); } 233 } 234 private DataRow ResultsHypervolumeBest 235 { 236 get { return ResultsQualities.Rows["Best Hypervolume"]; } 237 } 238 private DataRow ResultsHypervolumeIteration 239 { 240 get { return ResultsQualities.Rows["Iteration Hypervolume"]; } 241 } 242 private DataRow ResultsGenerationalDistanceIteration 243 { 244 get { return ResultsQualities.Rows["Iteration Generational Distance"]; } 245 } 246 private DataRow ResultsInvertedGenerationalDistanceIteration 247 { 248 get { return ResultsQualities.Rows["Iteration Inverted Generational Distance"]; } 249 } 250 private DataRow ResultsCrowdingIteration 251 { 252 get { return ResultsQualities.Rows["Iteration Crowding"]; } 253 } 254 255 256 //QualityIndicators 257 private double ResultsHypervolume 258 { 259 get { return ((DoubleValue)Results["Hypervolume"].Value).Value; } 260 set { ((DoubleValue)Results["Hypervolume"].Value).Value = value; } 261 } 262 private double ResultsGenerationalDistance 263 { 264 get { return ((DoubleValue)Results["Generational Distance"].Value).Value; } 265 set { ((DoubleValue)Results["Generational Distance"].Value).Value = value; } 266 } 267 private double ResultsInvertedGenerationalDistance 268 { 269 get { return ((DoubleValue)Results["Inverted Generational Distance"].Value).Value; } 270 set { ((DoubleValue)Results["Inverted Generational Distance"].Value).Value = value; } 271 } 272 private double ResultsCrowding 273 { 274 get { return ((DoubleValue)Results["Crowding"].Value).Value; } 275 set { ((DoubleValue)Results["Crowding"].Value).Value = value; } 276 } 277 private double ResultsBestHypervolume 278 { 279 get { return ((DoubleValue)Results["Best Hypervolume"].Value).Value; } 280 set { ((DoubleValue)Results["Best Hypervolume"].Value).Value = value; } 281 } 282 private double ResultsBestKnownHypervolume 283 { 284 get { return ((DoubleValue)Results["Best Known Hypervolume"].Value).Value; } 285 set { ((DoubleValue)Results["Best Known Hypervolume"].Value).Value = value; } 286 } 287 288 //Solutions 289 private DoubleMatrix ResultsSolutions 290 { 291 get { return ((DoubleMatrix)Results["Solutions"].Value); } 292 set { Results["Solutions"].Value = value; } 293 } 294 private MOSolution ResultsSolutionsPlot 295 { 296 get { return ((MOSolution)Results["Solutions Scatterplot"].Value); } 297 set { Results["Solutions Scatterplot"].Value = value; } 298 } 299 #endregion 300 301 #region constructors and hlBoilerPlate-code 302 [StorableConstructor] 303 protected MOCMASEvolutionStrategy(bool deserializing) : base(deserializing) { } 304 305 protected MOCMASEvolutionStrategy(MOCMASEvolutionStrategy original, Cloner cloner) 306 : base(original, cloner) 307 { 308 } 309 310 public override IDeepCloneable Clone(Cloner cloner) 311 { 312 return new MOCMASEvolutionStrategy(this, cloner); 313 } 314 315 public MOCMASEvolutionStrategy() 316 { 317 Parameters.Add(new FixedValueParameter<IntValue>(MaximumRuntimeName, "The maximum runtime in seconds after which the algorithm stops. Use -1 to specify no limit for the runtime", new IntValue(3600))); 318 Parameters.Add(new FixedValueParameter<IntValue>(SeedName, "The random seed used to initialize the new pseudo random number generator.", new IntValue(0))); 319 Parameters.Add(new FixedValueParameter<BoolValue>(SetSeedRandomlyName, "True if the random seed should be set to a random value, otherwise false.", new BoolValue(true))); 320 Parameters.Add(new FixedValueParameter<IntValue>(PopulationSizeName, "λ (lambda) - the size of the offspring population.", new IntValue(20))); 321 Parameters.Add(new FixedValueParameter<IntValue>(InitialIterationsName, "The number of iterations that should be performed with only axis parallel mutation.", new IntValue(0))); 322 Parameters.Add(new FixedValueParameter<DoubleValue>(InitialSigmaName, "The initial sigma can be a single value or a value for each dimension. All values need to be > 0.", new DoubleValue(0.5))); 323 Parameters.Add(new OptionalValueParameter<IntValue>(MuName, "Optional, the mu best offspring that should be considered for update of the new mean and strategy parameters. If not given it will be automatically calculated.")); 324 Parameters.Add(new ValueParameter<MultiAnalyzer>(AnalyzerName, "The operator used to analyze each generation.", new MultiAnalyzer())); 325 Parameters.Add(new FixedValueParameter<IntValue>(MaximumGenerationsName, "The maximum number of generations which should be processed.", new IntValue(1000))); 326 Parameters.Add(new FixedValueParameter<IntValue>(MaximumEvaluatedSolutionsName, "The maximum number of evaluated solutions that should be computed.", new IntValue(int.MaxValue))); 327 Parameters.Add(new FixedValueParameter<DoubleValue>(TargetQualityName, "(stopFitness) Surpassing this quality value terminates the algorithm.", new DoubleValue(double.NaN))); 328 Parameters.Add(new FixedValueParameter<DoubleValue>(MinimumQualityChangeName, "(stopTolFun) If the range of fitness values is less than a certain value the algorithm terminates (set to 0 or positive value to enable).", new DoubleValue(double.NaN))); 329 Parameters.Add(new FixedValueParameter<DoubleValue>(MinimumQualityHistoryChangeName, "(stopTolFunHist) If the range of fitness values is less than a certain value for a certain time the algorithm terminates (set to 0 or positive to enable).", new DoubleValue(double.NaN))); 330 Parameters.Add(new FixedValueParameter<DoubleValue>(MinimumStandardDeviationName, "(stopTolXFactor) If the standard deviation falls below a certain value the algorithm terminates (set to 0 or positive to enable).", new DoubleValue(double.NaN))); 331 Parameters.Add(new FixedValueParameter<DoubleValue>(MaximumStandardDeviationChangeName, "(stopTolUpXFactor) If the standard deviation changes by a value larger than this parameter the algorithm stops (set to a value > 0 to enable).", new DoubleValue(double.NaN))); 332 333 } 334 #endregion 335 #region updates 336 private void updatePopulation(CMAHansenIndividual[] parents) 337 { 338 int[] offspringSucess = new int[solutions.Length]; 339 int offspringLength = parents.Length - solutions.Length; 340 341 for (int i = 0; i < offspringLength; i++) 342 { 343 if (parents[i + solutions.Length].selected) 344 { 345 updateAsOffspring(parents[i + solutions.Length]); 346 347 //TODO this may change if more offspring per parent is allowed 348 offspringSucess[i] += CMAHansenIndividual.success; 349 } 350 } 351 for (int i = 0; i < solutions.Length; i++) 352 { 353 if (parents[i].selected) 354 { 355 updateAsParent(parents[i], offspringSucess[i]); 356 } 357 } 358 359 solutions = new CMAHansenIndividual[solutions.Length]; 360 int j = 0; 361 foreach (CMAHansenIndividual ind in parents) 362 { 363 if (ind.selected) 364 { 365 solutions[j++] = ind; 366 } 367 } 368 369 } 370 371 private void updateAsParent(CMAHansenIndividual c, int v) 372 { 373 c.successProbability = (1 - stepSizeLearningRate) * c.successProbability + stepSizeLearningRate * (v == CMAHansenIndividual.success ? 1 : 0); 374 c.sigma *= Math.Exp(1 / stepSizeDampeningFactor * (c.successProbability - targetSuccessProbability) / (1 - targetSuccessProbability)); 375 if (v != CMAHansenIndividual.failure) return; 376 if (c.successProbability < successThreshold) 377 { 378 double stepNormSqr = c.getSetpNormSqr(); 379 double rate = covarianceMatrixUnlearningRate; 380 if (stepNormSqr > 1 && 1 < covarianceMatrixUnlearningRate * (2 * stepNormSqr - 1)) 381 { 382 rate = 1 / (2 * stepNormSqr - 1); 383 } 384 rankOneUpdate(c, 1 + rate, -rate, c.lastStep); 385 386 } 387 else 388 { 389 roundUpdate(c); 390 } 391 392 } 393 394 private void updateAsOffspring(CMAHansenIndividual c) 395 { 396 c.successProbability = (1 - stepSizeLearningRate) * c.successProbability + stepSizeLearningRate; 397 c.sigma *= Math.Exp(1 / stepSizeDampeningFactor * (c.successProbability - targetSuccessProbability) / (1 - targetSuccessProbability)); 398 double evolutionpathUpdateWeight = evolutionPathLearningRate * (2.0 - evolutionPathLearningRate); 399 if (c.successProbability < successThreshold) 400 { 401 c.updateEvolutionPath(1 - evolutionPathLearningRate, evolutionpathUpdateWeight); 402 rankOneUpdate(c, 1 - covarianceMatrixLearningRate, covarianceMatrixLearningRate, c.evolutionPath); 403 } 404 else 405 { 406 roundUpdate(c); 407 } 408 } 409 410 private void rankOneUpdate(CMAHansenIndividual c, double v1, double v2, RealVector lastStep) 411 { 412 c.choleskyUpdate(lastStep, v1, v2); 413 } 414 415 private void roundUpdate(CMAHansenIndividual c) 416 { 417 double evolutionPathUpdateWeight = evolutionPathLearningRate * (2.0 - evolutionPathLearningRate); 418 c.updateEvolutionPath(1 - evolutionPathLearningRate, 0); 419 rankOneUpdate(c, 1 - covarianceMatrixLearningRate + evolutionPathUpdateWeight, 420 covarianceMatrixLearningRate, c.evolutionPath); 421 } 422 #endregion 423 #region selection 424 425 private T[] merge<T>(T[] parents, T[] offspring) 426 { 427 T[] merged = new T[parents.Length + offspring.Length]; 428 for (int i = 0; i < parents.Length; i++) 429 { 430 merged[i] = parents[i]; 431 } 432 for (int i = 0; i < offspring.Length; i++) 433 { 434 merged[i + parents.Length] = offspring[i]; 435 } 436 return merged; 437 } 438 439 private void selection(CMAHansenIndividual[] parents, int length) 440 { 441 //perform a nondominated sort to assign the rank to every element 442 var fronts = NonDominatedSort(parents); 443 444 //deselect the highest rank fronts until we would end up with less or equal mu elements 445 int rank = fronts.Count - 1; 446 int popSize = parents.Length; 447 while (popSize - fronts[rank].Count >= length) 448 { 449 var front = fronts[rank]; 450 foreach (var i in front) i.selected = false; 451 popSize -= front.Count; 452 rank--; 453 } 454 455 //now use the indicator to deselect the worst approximating elements of the last selected front 456 var front_ = fronts[rank]; 457 for (; popSize > length; popSize--) 458 { 459 int lc = indicator.leastContributer<CMAHansenIndividual>(front_.ToArray(), x => x.penalizedFitness, Problem); //TODO: This is a battel in its own right to be fought another day 460 front_[lc].selected = false; 461 front_.Swap(lc, front_.Count - 1); 462 front_.RemoveAt(front_.Count - 1); 463 } 464 } 465 #endregion 466 #region penalize Box-Constraints 467 private void penalizeEvaluate(IEnumerable<CMAHansenIndividual> offspring) 468 { 469 foreach (CMAHansenIndividual child in offspring) 470 { 471 penalizeEvaluate(child); 472 } 473 } 474 475 private void penalizeEvaluate(CMAHansenIndividual offspring) 476 { 477 if (isFeasable(offspring.x)) 478 { 479 offspring.fitness = Problem.Evaluate(offspring.x, random); 480 ResultsEvaluations++; 481 offspring.penalizedFitness = offspring.fitness; 482 } 483 else 484 { 485 RealVector t = closestFeasible(offspring.x); 486 offspring.fitness = Problem.Evaluate(t, random); 487 ResultsEvaluations++; 488 offspring.penalizedFitness = penalize(offspring.x, t, offspring.fitness); 489 } 490 } 491 492 private double[] penalize(RealVector x, RealVector t, double[] fitness) 493 { 494 double[] d = new double[fitness.Length]; 495 double penality = penalize(x, t); 496 for (int i = 0; i < fitness.Length; i++) 497 { 498 d[i] = fitness[i] + penality; 499 } 500 return d; 501 } 502 503 private double penalize(RealVector x, RealVector t) 504 { 505 double sum = 0; 506 for (int i = 0; i < x.Length; i++) 507 { 508 double d = x[i] - t[i]; 509 sum += d * d; 510 } 511 return sum; 512 } 513 514 private RealVector closestFeasible(RealVector x) 515 { 516 DoubleMatrix bounds = Problem.Bounds; 517 RealVector r = new RealVector(x.Length); 518 for (int i = 0; i < x.Length; i++) 519 { 520 int dim = i % bounds.Rows; 521 r[i] = Math.Min(Math.Max(bounds[dim, 0], x[i]), bounds[dim, 1]); 522 } 523 return r; 524 } 525 526 private bool isFeasable(RealVector offspring) 527 { 528 DoubleMatrix bounds = Problem.Bounds; 529 for (int i = 0; i < offspring.Length; i++) 530 { 531 int dim = i % bounds.Rows; 532 if (bounds[dim, 0] > offspring[i] || offspring[i] > bounds[dim, 1]) return false; 533 } 534 return true; 535 } 536 537 #endregion 538 #region mutation 539 private CMAHansenIndividual[] generateOffspring() 540 { 541 CMAHansenIndividual[] offspring = new CMAHansenIndividual[PopulationSize]; //TODO this changes if 1,1-ES is replaced with 1,n-ES 542 for (int i = 0; i < PopulationSize; i++) 543 { 544 offspring[i] = new CMAHansenIndividual(solutions[i]); 545 offspring[i].mutate(gauss); 546 } 547 return offspring; 548 } 549 #endregion 550 551 #region initialization 552 private CMAHansenIndividual initializeIndividual(RealVector x) 553 { 554 var zeros = new RealVector(x.Length); 555 var identity = new double[x.Length, x.Length]; 556 for (int i = 0; i < x.Length; i++) 557 { 558 identity[i, i] = 1; 559 } 560 return new CMAHansenIndividual(x, targetSuccessProbability, InitialSigma.Value, zeros, identity); 561 } 562 563 private void initSolutions() 564 { 565 solutions = new CMAHansenIndividual[PopulationSize]; 566 for (int i = 0; i < PopulationSize; i++) 567 { 568 RealVector x = new RealVector(Problem.ProblemSize); // uniform distibution in all dimesions assumed TODO is there a better way to initialize RandomVectors 569 var bounds = Problem.Bounds; 570 for (int j = 0; j < Problem.Objectives; j++) 571 { 572 int dim = j % bounds.Rows; 573 x[j] = random.NextDouble() * (bounds[dim, 1] - bounds[dim, 0]) + bounds[dim, 0]; 574 } 575 solutions[i] = initializeIndividual(x); 576 } 577 penalizeEvaluate(solutions); 578 } 579 580 private void initStrategy() 581 { 582 int lambda = 1; 583 double n = Problem.ProblemSize; 584 indicator = new CrowdingIndicator(); 585 gauss = new NormalDistributedRandom(random, 0, 1); 586 targetSuccessProbability = 1.0 / (5.0 + Math.Sqrt(lambda) / 2.0); 587 stepSizeDampeningFactor = 1.0 + n / (2.0 * lambda); 588 stepSizeLearningRate = targetSuccessProbability * lambda / (2.0 + targetSuccessProbability * lambda); 589 evolutionPathLearningRate = 2.0 / (n + 2.0); 590 covarianceMatrixLearningRate = 2.0 / (n * n + 6.0); 591 covarianceMatrixUnlearningRate = 0.4 / (Math.Pow(n, 1.6) + 1); 592 successThreshold = 0.44; 593 594 } 595 596 597 private void initResults() 598 { 599 Results.Add(new Result("Iterations", new IntValue(0))); 600 Results.Add(new Result("Evaluations", new IntValue(0))); 601 602 Results.Add(new Result("Hypervolume", new DoubleValue(0))); 603 Results.Add(new Result("Best Hypervolume", new DoubleValue(0))); 604 Results.Add(new Result("Generational Distance", new DoubleValue(0))); 605 Results.Add(new Result("Inverted Generational Distance", new DoubleValue(0))); 606 Results.Add(new Result("Crowding", new DoubleValue(0))); 607 608 var table = new DataTable("QualityIndicators"); 609 Results.Add(new Result("Timetable", table)); 610 table.Rows.Add(new DataRow("Best Hypervolume")); 611 table.Rows.Add(new DataRow("Iteration Hypervolume")); 612 table.Rows.Add(new DataRow("Iteration Crowding")); 613 table.Rows.Add(new DataRow("Iteration Generational Distance")); 614 table.Rows.Add(new DataRow("Iteration Inverted Generational Distance")); 615 616 617 618 Results.Add(new Result("Solutions", new DoubleMatrix())); 619 Results.Add(new Result("Solutions Scatterplot", new MOSolution(null, null, Problem.BestKnownFront.ToArray<double[]>(), Problem.Objectives))); 620 621 622 if (Problem.BestKnownFront != null) 623 { 624 Results.Add(new Result("Best Known Hypervolume", new DoubleValue(Hypervolume.Calculate(Problem.BestKnownFront, Problem.TestFunction.ReferencePoint(Problem.Objectives), Problem.Maximization)))); 625 } 626 } 627 #endregion 628 629 #region analyze 630 private void analyzeSolutions() 631 { 632 //solutions 633 ResultsSolutionsPlot = new MOSolution(solutions.Select(x => x.fitness).ToArray<double[]>(), 634 solutions.Select(x => ToArray(x.x)).ToArray<double[]>(), 635 ResultsSolutionsPlot.ParetoFront, 636 ResultsSolutionsPlot.Objectives); 637 ResultsSolutions = ToMatrix(solutions.Select(x => ToArray(x.x))); 638 analyzeQualityIndicators(); 639 640 } 641 642 private void analyzeQualityIndicators() 643 { 644 645 var front = NonDominatedSelect.selectNonDominatedVectors(solutions.Select(x => x.fitness), Problem.Maximization, true); 646 front = NonDominatedSelect.removeNonReferenceDominatingVectors(front, Problem.TestFunction.ReferencePoint(Problem.Objectives), Problem.Maximization, false); 647 var bounds = ToArray(Problem.Bounds); 648 ResultsCrowding = Crowding.Calculate(front, bounds); 649 ResultsGenerationalDistance = Problem.BestKnownFront != null ? GenerationalDistance.Calculate(front, Problem.BestKnownFront, 1) : Double.NaN; 650 651 ResultsInvertedGenerationalDistance = Problem.BestKnownFront != null ? InvertedGenerationalDistance.Calculate(front, Problem.BestKnownFront, 1) : Double.NaN; 652 653 ResultsHypervolume = Hypervolume.Calculate(front, Problem.TestFunction.ReferencePoint(Problem.Objectives), Problem.Maximization); 654 ResultsBestHypervolume = Math.Max(ResultsHypervolume, ResultsBestHypervolume); 655 656 //Datalines 657 ResultsHypervolumeBest.Values.Add(ResultsBestHypervolume); 658 ResultsHypervolumeIteration.Values.Add(ResultsHypervolume); 659 ResultsCrowdingIteration.Values.Add(ResultsCrowding); 660 ResultsGenerationalDistanceIteration.Values.Add(ResultsGenerationalDistance); 661 ResultsInvertedGenerationalDistanceIteration.Values.Add(ResultsInvertedGenerationalDistance); 662 663 664 } 665 #endregion 666 667 668 //MU = populationSize 669 #region mainloop 670 protected override void Run(CancellationToken cancellationToken) 671 { 672 // Set up the algorithm 673 if (SetSeedRandomly) Seed = new System.Random().Next(); 674 random.Reset(Seed); 675 676 initResults(); 677 initStrategy(); 678 initSolutions(); 679 680 // Loop until iteration limit reached or canceled. 681 for (ResultsIterations = 1; ResultsIterations < MaximumGenerations; ResultsIterations++) 682 { 683 try 684 { 685 iterate(); 686 cancellationToken.ThrowIfCancellationRequested(); 687 } 688 finally 689 { 690 analyzeSolutions(); 691 } 692 } 693 } 694 695 protected override void OnExecutionTimeChanged() 696 { 697 base.OnExecutionTimeChanged(); 698 if (CancellationTokenSource == null) return; 699 if (MaximumRuntime == -1) return; 700 if (ExecutionTime.TotalSeconds > MaximumRuntime) CancellationTokenSource.Cancel(); 701 } 702 703 private void iterate() 704 { 705 CMAHansenIndividual[] offspring = generateOffspring(); 706 penalizeEvaluate(offspring); 707 var parents = merge(solutions, offspring); 708 selection(parents, solutions.Length); 709 updatePopulation(parents); 710 711 } 712 #endregion 713 714 #region bernhard properties 715 private NormalDistributedRandom gauss; 716 private CMAHansenIndividual[] solutions; 717 private const double penalizeFactor = 1e-6; 718 private IIndicator indicator; 719 720 private double stepSizeLearningRate; //=cp learning rate in [0,1] 721 private double stepSizeDampeningFactor; //d 722 private double targetSuccessProbability;// p^target_succ 723 private double evolutionPathLearningRate;//cc 724 private double covarianceMatrixLearningRate;//ccov 725 private double covarianceMatrixUnlearningRate; //from shark 726 private double successThreshold; //ptresh 727 #endregion 728 729 private class CMAHansenIndividual 730 { 731 public static readonly int success = 1; 732 public static readonly int noSuccess = 2; 733 public static readonly int failure = 3; 734 735 736 //Chromosome 737 public RealVector x; 738 public double successProbability; 739 public double sigma;//stepsize 740 public RealVector evolutionPath; // pc 741 public RealVector lastStep; 742 public RealVector lastZ; 743 private double[,] lowerCholesky; 744 745 746 //Phenotype 747 public double[] fitness; 748 public double[] penalizedFitness; 749 public bool selected = true; 750 751 internal double rank; 752 753 754 755 /// <summary> 756 /// 757 /// </summary> 758 /// <param name="x">has to be 0-vector with correct lenght</param> 759 /// <param name="p_succ">has to be ptargetsucc</param> 760 /// <param name="sigma">initialSigma</param> 761 /// <param name="pc">has to be 0-vector with correct lenght</param> 762 /// <param name="C">has to be a symmetric positive definit Covariance matrix</param> 763 public CMAHansenIndividual(RealVector x, double p_succ, double sigma, RealVector pc, double[,] C) 764 { 765 this.x = x; 766 this.successProbability = p_succ; 767 this.sigma = sigma; 768 this.evolutionPath = pc; 769 choleskyDecomposition(C); 770 } 771 772 private void choleskyDecomposition(double[,] C) 773 { 774 if (C.GetLength(0) != C.GetLength(1)) throw new ArgumentException("Covariancematrix is not quadratic"); 775 int n = C.GetLength(0); 776 lowerCholesky = new double[n, n]; 777 double[,] A = lowerCholesky; 778 for (int i = 0; i < n; i++) 779 { 780 for (int j = 0; j <= i; j++) 781 { 782 A[i, j] = C[i, j]; //simulate inplace transform 783 double sum = A[i, j]; 784 for (int k = 0; k < j; k++) 785 { 786 sum = sum - A[i, k] * A[j, k]; 787 if (i > j) { A[i, j] = sum / A[j, j]; } 788 else if (sum > 0) 789 { 790 A[i, i] = Math.Sqrt(sum); 791 } 792 else 793 { 794 throw new ArgumentException("Covariancematrix is not symetric positiv definit"); 795 } 796 } 797 } 798 799 } 800 } 801 802 public CMAHansenIndividual(CMAHansenIndividual other) 803 { 804 805 806 this.successProbability = other.successProbability; 807 this.sigma = other.sigma; 808 809 // no no no make DEEP copies 810 this.evolutionPath = (RealVector)other.evolutionPath.Clone(); 811 this.x = (RealVector)other.x.Clone(); 812 813 814 this.lowerCholesky = (double[,])other.lowerCholesky.Clone(); 815 } 816 817 public void updateEvolutionPath(double learningRate, double updateWeight) 818 { 819 updateWeight = Math.Sqrt(updateWeight); 820 for (int i = 0; i < evolutionPath.Length; i++) 821 { 822 evolutionPath[i] *= learningRate; 823 evolutionPath[i] += updateWeight * lastStep[i]; 824 } 825 } 826 827 public double getSetpNormSqr() 828 { 829 double sum = 0; 830 foreach (double d in lastZ) 831 { 832 sum += d * d; 833 } 834 return sum; 835 } 836 837 public void choleskyUpdate(RealVector v, double alpha, double beta) 838 { 839 int n = v.Length; 840 double[] temp = new double[n]; 841 for (int i = 0; i < n; i++) temp[i] = v[i]; 842 double betaPrime = 1; 843 double a = Math.Sqrt(alpha); 844 for (int j = 0; j < n; j++) 845 { 846 double Ljj = a * lowerCholesky[j, j]; 847 double dj = Ljj * Ljj; 848 double wj = temp[j]; 849 double swj2 = beta * wj * wj; 850 double gamma = dj * betaPrime + swj2; 851 double x = dj + swj2 / betaPrime; 852 if (x < 0.0) throw new ArgumentException("Update makes Covariancematrix indefinite"); 853 double nLjj = Math.Sqrt(x); 854 lowerCholesky[j, j] = nLjj; 855 betaPrime += swj2 / dj; 856 if (j + 1 < n) 857 { 858 for (int i = j + 1; i < n; i++) 859 { 860 lowerCholesky[i, j] *= a; 861 } 862 for (int i = j + 1; i < n; i++) 863 { 864 temp[i] = wj / Ljj * lowerCholesky[i, j]; 865 } 866 if (gamma == 0) continue; 867 for (int i = j + 1; i < n; i++) 868 { 869 lowerCholesky[i, j] *= nLjj / Ljj; 870 } 871 for (int i = j + 1; i < n; i++) 872 { 873 lowerCholesky[i, j] += (nLjj * beta * wj / gamma) * temp[i]; 874 } 875 } 876 877 } 878 879 } 880 881 public void mutate(NormalDistributedRandom gauss) 882 { 883 884 //sampling a random z from N(0,I) where I is the Identity matrix; 885 lastZ = new RealVector(x.Length); 886 int n = lastZ.Length; 887 for (int i = 0; i < n; i++) 888 { 889 lastZ[i] = gauss.NextDouble(); 890 } 891 //Matrixmultiplication: lastStep = lowerCholesky * lastZ; 892 lastStep = new RealVector(x.Length); 893 for (int i = 0; i < n; i++) 894 { 895 double sum = 0; 896 for (int j = 0; j <= i; j++) 897 { 898 sum += lowerCholesky[i, j] * lastZ[j]; 899 } 900 lastStep[i] = sum; 901 } 902 903 //add the step to x weighted by stepsize; 904 for (int i = 0; i < x.Length; i++) 905 { 906 x[i] += sigma * lastStep[i]; 907 } 908 909 } 910 911 } 912 913 //blatantly stolen form HeuristicLab.Optimization.Operators.FastNonDominatedSort 914 #region FastNonDominatedSort 915 private enum DominationResult { Dominates, IsDominated, IsNonDominated }; 916 917 private List<List<CMAHansenIndividual>> NonDominatedSort(CMAHansenIndividual[] individuals) 918 { 919 bool dominateOnEqualQualities = false; 920 bool[] maximization = Problem.Maximization; 921 if (individuals == null) throw new InvalidOperationException(Name + ": No qualities found."); 922 int populationSize = individuals.Length; 923 924 List<List<CMAHansenIndividual>> fronts = new List<List<CMAHansenIndividual>>(); 925 Dictionary<CMAHansenIndividual, List<int>> dominatedScopes = new Dictionary<CMAHansenIndividual, List<int>>(); 926 int[] dominationCounter = new int[populationSize]; 927 //ItemArray<IntValue> rank = new ItemArray<IntValue>(populationSize); 928 929 for (int pI = 0; pI < populationSize - 1; pI++) 930 { 931 CMAHansenIndividual p = individuals[pI]; 932 List<int> dominatedScopesByp; 933 if (!dominatedScopes.TryGetValue(p, out dominatedScopesByp)) 934 dominatedScopes[p] = dominatedScopesByp = new List<int>(); 935 for (int qI = pI + 1; qI < populationSize; qI++) 936 { 937 DominationResult test = Dominates(individuals[pI], individuals[qI], maximization, dominateOnEqualQualities); 938 if (test == DominationResult.Dominates) 939 { 940 dominatedScopesByp.Add(qI); 941 dominationCounter[qI] += 1; 942 } 943 else if (test == DominationResult.IsDominated) 944 { 945 dominationCounter[pI] += 1; 946 if (!dominatedScopes.ContainsKey(individuals[qI])) 947 dominatedScopes.Add(individuals[qI], new List<int>()); 948 dominatedScopes[individuals[qI]].Add(pI); 949 } 950 if (pI == populationSize - 2 951 && qI == populationSize - 1 952 && dominationCounter[qI] == 0) 953 { 954 //rank[qI] = new IntValue(0); 955 AddToFront(individuals[qI], fronts, 0); 956 } 957 } 958 if (dominationCounter[pI] == 0) 959 { 960 //rank[pI] = new IntValue(0); 961 AddToFront(p, fronts, 0); 962 } 963 } 964 int i = 0; 965 while (i < fronts.Count && fronts[i].Count > 0) 966 { 967 List<CMAHansenIndividual> nextFront = new List<CMAHansenIndividual>(); 968 foreach (CMAHansenIndividual p in fronts[i]) 969 { 970 List<int> dominatedScopesByp; 971 if (dominatedScopes.TryGetValue(p, out dominatedScopesByp)) 972 { 973 for (int k = 0; k < dominatedScopesByp.Count; k++) 974 { 975 int dominatedScope = dominatedScopesByp[k]; 976 dominationCounter[dominatedScope] -= 1; 977 if (dominationCounter[dominatedScope] == 0) 978 { 979 //rank[dominatedScope] = new IntValue(i + 1); 980 nextFront.Add(individuals[dominatedScope]); 981 } 982 } 983 } 984 } 985 i += 1; 986 fronts.Add(nextFront); 987 } 988 989 //RankParameter.ActualValue = rank; 990 991 //scope.SubScopes.Clear(); 992 993 CMAHansenIndividual[] result = new CMAHansenIndividual[individuals.Length]; 994 995 for (i = 0; i < fronts.Count; i++) 996 { 997 foreach (var p in fronts[i]) 998 { 999 p.rank = i; 1000 } 1001 } 1002 return fronts; 1003 } 1004 1005 private static void AddToFront(CMAHansenIndividual p, List<List<CMAHansenIndividual>> fronts, int i) 1006 { 1007 if (i == fronts.Count) fronts.Add(new List<CMAHansenIndividual>()); 1008 fronts[i].Add(p); 1009 } 1010 1011 private static DominationResult Dominates(CMAHansenIndividual left, CMAHansenIndividual right, bool[] maximizations, bool dominateOnEqualQualities) 1012 { 1013 return Dominates(left.penalizedFitness, right.penalizedFitness, maximizations, dominateOnEqualQualities); 1014 } 1015 1016 private static DominationResult Dominates(double[] left, double[] right, bool[] maximizations, bool dominateOnEqualQualities) 1017 { 1018 //mkommend Caution: do not use LINQ.SequenceEqual for comparing the two quality arrays (left and right) due to performance reasons 1019 if (dominateOnEqualQualities) 1020 { 1021 var equal = true; 1022 for (int i = 0; i < left.Length; i++) 1023 { 1024 if (left[i] != right[i]) 1025 { 1026 equal = false; 1027 break; 1028 } 1029 } 1030 if (equal) return DominationResult.Dominates; 1031 } 1032 1033 bool leftIsBetter = false, rightIsBetter = false; 1034 for (int i = 0; i < left.Length; i++) 1035 { 1036 if (IsDominated(left[i], right[i], maximizations[i])) rightIsBetter = true; 1037 else if (IsDominated(right[i], left[i], maximizations[i])) leftIsBetter = true; 1038 if (leftIsBetter && rightIsBetter) break; 1039 } 1040 1041 if (leftIsBetter && !rightIsBetter) return DominationResult.Dominates; 1042 if (!leftIsBetter && rightIsBetter) return DominationResult.IsDominated; 1043 return DominationResult.IsNonDominated; 1044 } 1045 1046 private static bool IsDominated(double left, double right, bool maximization) 1047 { 1048 return maximization && left < right 1049 || !maximization && left > right; 1050 } 1051 1052 #endregion 1053 1054 1055 1056 #region conversions 1057 1058 public double[] ToArray(RealVector r) 1059 { 1060 double[] d = new double[r.Length]; 1061 for (int i = 0; i < r.Length; i++) 1062 { 1063 d[i] = r[i]; 1064 } 1065 return d; 1066 } 1067 1068 public DoubleMatrix ToMatrix(IEnumerable<double[]> data) 1069 { 1070 var d2 = data.ToArray<double[]>(); 1071 DoubleMatrix mat = new DoubleMatrix(d2.Length, d2[0].Length); 1072 for (int i = 0; i < mat.Rows; i++) 1073 { 1074 for (int j = 0; j < mat.Columns; j++) 1075 { 1076 mat[i, j] = d2[i][j]; 1077 } 1078 } 1079 return mat; 1080 } 1081 public double[,] ToArray(DoubleMatrix data) 1082 { 1083 1084 double[,] mat = new double[data.Rows, data.Columns]; 1085 for (int i = 0; i < data.Rows; i++) 1086 { 1087 for (int j = 0; j < data.Columns; j++) 1088 { 1089 mat[i, j] = data[i, j]; 1090 } 1091 } 1092 return mat; 1093 } 1094 1095 #endregion 44 1096 } 45 public new MultiObjectiveTestFunctionProblem Problem {46 get { return (MultiObjectiveTestFunctionProblem)base.Problem; }47 set { base.Problem = value; }48 }49 50 private readonly IRandom random = new MersenneTwister();51 52 53 #region ParameterNames54 private const string MaximumRuntimeName = "Maximum Runtime";55 private const string SeedName = "Seed";56 private const string SetSeedRandomlyName = "SetSeedRandomly";57 private const string PopulationSizeName = "PopulationSize";58 private const string InitialIterationsName = "InitialIterations";59 private const string InitialSigmaName = "InitialSigma";60 private const string MuName = "Mu";61 private const string CMAInitializerName = "CMAInitializer";62 private const string CMAMutatorName = "CMAMutator";63 private const string CMARecombinatorName = "CMARecombinator";64 private const string CMAUpdaterName = "CMAUpdater";65 private const string AnalyzerName = "Analyzer";66 private const string MaximumGenerationsName = "MaximumGenerations";67 private const string MaximumEvaluatedSolutionsName = "MaximumEvaluatedSolutions";68 private const string TargetQualityName = "TargetQuality";69 private const string MinimumQualityChangeName = "MinimumQualityChange";70 private const string MinimumQualityHistoryChangeName = "MinimumQualityHistoryChange";71 private const string MinimumStandardDeviationName = "MinimumStandardDeviation";72 private const string MaximumStandardDeviationChangeName = "MaximumStandardDeviationChange";73 #endregion74 75 #region ParameterProperties76 public IFixedValueParameter<IntValue> MaximumRuntimeParameter {77 get { return (IFixedValueParameter<IntValue>)Parameters[MaximumRuntimeName]; }78 }79 public IFixedValueParameter<IntValue> SeedParameter {80 get { return (IFixedValueParameter<IntValue>)Parameters[SeedName]; }81 }82 public FixedValueParameter<BoolValue> SetSeedRandomlyParameter {83 get { return (FixedValueParameter<BoolValue>)Parameters[SetSeedRandomlyName]; }84 }85 private IFixedValueParameter<IntValue> PopulationSizeParameter {86 get { return (IFixedValueParameter<IntValue>)Parameters[PopulationSizeName]; }87 }88 public IValueParameter<MultiAnalyzer> AnalyzerParameter {89 get { return (IValueParameter<MultiAnalyzer>)Parameters[AnalyzerName]; }90 }91 private IFixedValueParameter<IntValue> InitialIterationsParameter {92 get { return (IFixedValueParameter<IntValue>)Parameters[InitialIterationsName]; }93 }94 public IValueParameter<DoubleValue> InitialSigmaParameter {95 get { return (IValueParameter<DoubleValue>)Parameters[InitialSigmaName]; }96 }97 private OptionalValueParameter<IntValue> MuParameter {98 get { return (OptionalValueParameter<IntValue>)Parameters[MuName]; }99 }100 public IConstrainedValueParameter<ICMAInitializer> CMAInitializerParameter {101 get { return (IConstrainedValueParameter<ICMAInitializer>)Parameters[CMAInitializerName]; }102 }103 public IConstrainedValueParameter<ICMAManipulator> CMAMutatorParameter {104 get { return (IConstrainedValueParameter<ICMAManipulator>)Parameters[CMAMutatorName]; }105 }106 public IConstrainedValueParameter<ICMARecombinator> CMARecombinatorParameter {107 get { return (IConstrainedValueParameter<ICMARecombinator>)Parameters[CMARecombinatorName]; }108 }109 public IConstrainedValueParameter<ICMAUpdater> CMAUpdaterParameter {110 get { return (IConstrainedValueParameter<ICMAUpdater>)Parameters[CMAUpdaterName]; }111 }112 private IFixedValueParameter<IntValue> MaximumGenerationsParameter {113 get { return (IFixedValueParameter<IntValue>)Parameters[MaximumGenerationsName]; }114 }115 private IFixedValueParameter<IntValue> MaximumEvaluatedSolutionsParameter {116 get { return (IFixedValueParameter<IntValue>)Parameters[MaximumEvaluatedSolutionsName]; }117 }118 private IFixedValueParameter<DoubleValue> TargetQualityParameter {119 get { return (IFixedValueParameter<DoubleValue>)Parameters[TargetQualityName]; }120 }121 private IFixedValueParameter<DoubleValue> MinimumQualityChangeParameter {122 get { return (IFixedValueParameter<DoubleValue>)Parameters[MinimumQualityChangeName]; }123 }124 private IFixedValueParameter<DoubleValue> MinimumQualityHistoryChangeParameter {125 get { return (IFixedValueParameter<DoubleValue>)Parameters[MinimumQualityHistoryChangeName]; }126 }127 private IFixedValueParameter<DoubleValue> MinimumStandardDeviationParameter {128 get { return (IFixedValueParameter<DoubleValue>)Parameters[MinimumStandardDeviationName]; }129 }130 private IFixedValueParameter<DoubleValue> MaximumStandardDeviationChangeParameter {131 get { return (IFixedValueParameter<DoubleValue>)Parameters[MaximumStandardDeviationChangeName]; }132 }133 #endregion134 135 #region Properties136 public int MaximumRuntime {137 get { return MaximumRuntimeParameter.Value.Value; }138 set { MaximumRuntimeParameter.Value.Value = value; }139 }140 public int Seed {141 get { return SeedParameter.Value.Value; }142 set { SeedParameter.Value.Value = value; }143 }144 public bool SetSeedRandomly {145 get { return SetSeedRandomlyParameter.Value.Value; }146 set { SetSeedRandomlyParameter.Value.Value = value; }147 }148 public int PopulationSize {149 get { return PopulationSizeParameter.Value.Value; }150 set { PopulationSizeParameter.Value.Value = value; }151 }152 public int InitialIterations {153 get { return InitialIterationsParameter.Value.Value; }154 set { InitialIterationsParameter.Value.Value = value; }155 }156 public int MaximumGenerations {157 get { return MaximumGenerationsParameter.Value.Value; }158 set { MaximumGenerationsParameter.Value.Value = value; }159 }160 public int MaximumEvaluatedSolutions {161 get { return MaximumEvaluatedSolutionsParameter.Value.Value; }162 set { MaximumEvaluatedSolutionsParameter.Value.Value = value; }163 }164 public double TargetQuality {165 get { return TargetQualityParameter.Value.Value; }166 set { TargetQualityParameter.Value.Value = value; }167 }168 public double MinimumQualityChange {169 get { return MinimumQualityChangeParameter.Value.Value; }170 set { MinimumQualityChangeParameter.Value.Value = value; }171 }172 public double MinimumQualityHistoryChange {173 get { return MinimumQualityHistoryChangeParameter.Value.Value; }174 set { MinimumQualityHistoryChangeParameter.Value.Value = value; }175 }176 public double MinimumStandardDeviation {177 get { return MinimumStandardDeviationParameter.Value.Value; }178 set { MinimumStandardDeviationParameter.Value.Value = value; }179 }180 public double MaximumStandardDeviationChange {181 get { return MaximumStandardDeviationChangeParameter.Value.Value; }182 set { MaximumStandardDeviationChangeParameter.Value.Value = value; }183 }184 public DoubleValue InitialSigma {185 get { return InitialSigmaParameter.Value; }186 set { InitialSigmaParameter.Value = value; }187 }188 public IntValue Mu {189 get { return MuParameter.Value; }190 set { MuParameter.Value = value; }191 }192 public ICMAInitializer CMAInitializer {193 get { return CMAInitializerParameter.Value; }194 set { CMAInitializerParameter.Value = value; }195 }196 public ICMAManipulator CMAMutator {197 get { return CMAMutatorParameter.Value; }198 set { CMAMutatorParameter.Value = value; }199 }200 public ICMARecombinator CMARecombinator {201 get { return CMARecombinatorParameter.Value; }202 set { CMARecombinatorParameter.Value = value; }203 }204 public MultiAnalyzer Analyzer {205 get { return AnalyzerParameter.Value; }206 set { AnalyzerParameter.Value = value; }207 }208 public ICMAUpdater CMAUpdater {209 get { return CMAUpdaterParameter.Value; }210 set { CMAUpdaterParameter.Value = value; }211 }212 213 #endregion214 215 #region ResultsProperties216 private double ResultsBestQuality {217 get { return ((DoubleValue)Results["Best Quality"].Value).Value; }218 set { ((DoubleValue)Results["Best Quality"].Value).Value = value; }219 }220 221 private RealVector ResultsBestSolution {222 get { return (RealVector)Results["Best Solution"].Value; }223 set { Results["Best Solution"].Value = value; }224 }225 226 private int ResultsBestFoundOnEvaluation {227 get { return ((IntValue)Results["Evaluation Best Solution Was Found"].Value).Value; }228 set { ((IntValue)Results["Evaluation Best Solution Was Found"].Value).Value = value; }229 }230 231 private int ResultsEvaluations {232 get { return ((IntValue)Results["Evaluations"].Value).Value; }233 set { ((IntValue)Results["Evaluations"].Value).Value = value; }234 }235 private int ResultsIterations {236 get { return ((IntValue)Results["Iterations"].Value).Value; }237 set { ((IntValue)Results["Iterations"].Value).Value = value; }238 }239 240 private DataTable ResultsQualities {241 get { return ((DataTable)Results["Qualities"].Value); }242 }243 private DataRow ResultsQualitiesBest {244 get { return ResultsQualities.Rows["Best Quality"]; }245 }246 247 private DataRow ResultsQualitiesIteration {248 get { return ResultsQualities.Rows["Iteration Quality"]; }249 }250 251 #endregion252 253 #region constructors and hlBoilerPlate-code254 [StorableConstructor]255 protected MOCMASEvolutionStrategy(bool deserializing) : base(deserializing) { }256 257 protected MOCMASEvolutionStrategy(MOCMASEvolutionStrategy original, Cloner cloner)258 : base(original, cloner) {259 }260 261 public override IDeepCloneable Clone(Cloner cloner) {262 return new MOCMASEvolutionStrategy(this, cloner);263 }264 265 public MOCMASEvolutionStrategy() {266 Parameters.Add(new FixedValueParameter<IntValue>(MaximumRuntimeName, "The maximum runtime in seconds after which the algorithm stops. Use -1 to specify no limit for the runtime", new IntValue(3600)));267 Parameters.Add(new FixedValueParameter<IntValue>(SeedName, "The random seed used to initialize the new pseudo random number generator.", new IntValue(0)));268 Parameters.Add(new FixedValueParameter<BoolValue>(SetSeedRandomlyName, "True if the random seed should be set to a random value, otherwise false.", new BoolValue(true)));269 Parameters.Add(new FixedValueParameter<IntValue>(PopulationSizeName, "λ (lambda) - the size of the offspring population.", new IntValue(20)));270 Parameters.Add(new FixedValueParameter<IntValue>(InitialIterationsName, "The number of iterations that should be performed with only axis parallel mutation.", new IntValue(0)));271 Parameters.Add(new FixedValueParameter<DoubleValue>(InitialSigmaName, "The initial sigma can be a single value or a value for each dimension. All values need to be > 0.", new DoubleValue(0.5)));272 Parameters.Add(new OptionalValueParameter<IntValue>(MuName, "Optional, the mu best offspring that should be considered for update of the new mean and strategy parameters. If not given it will be automatically calculated."));273 Parameters.Add(new ConstrainedValueParameter<ICMARecombinator>(CMARecombinatorName, "The operator used to calculate the new mean."));274 Parameters.Add(new ConstrainedValueParameter<ICMAManipulator>(CMAMutatorName, "The operator used to manipulate a point."));275 Parameters.Add(new ConstrainedValueParameter<ICMAInitializer>(CMAInitializerName, "The operator that initializes the covariance matrix and strategy parameters."));276 Parameters.Add(new ConstrainedValueParameter<ICMAUpdater>(CMAUpdaterName, "The operator that updates the covariance matrix and strategy parameters."));277 Parameters.Add(new ValueParameter<MultiAnalyzer>(AnalyzerName, "The operator used to analyze each generation.", new MultiAnalyzer()));278 Parameters.Add(new FixedValueParameter<IntValue>(MaximumGenerationsName, "The maximum number of generations which should be processed.", new IntValue(1000)));279 Parameters.Add(new FixedValueParameter<IntValue>(MaximumEvaluatedSolutionsName, "The maximum number of evaluated solutions that should be computed.", new IntValue(int.MaxValue)));280 Parameters.Add(new FixedValueParameter<DoubleValue>(TargetQualityName, "(stopFitness) Surpassing this quality value terminates the algorithm.", new DoubleValue(double.NaN)));281 Parameters.Add(new FixedValueParameter<DoubleValue>(MinimumQualityChangeName, "(stopTolFun) If the range of fitness values is less than a certain value the algorithm terminates (set to 0 or positive value to enable).", new DoubleValue(double.NaN)));282 Parameters.Add(new FixedValueParameter<DoubleValue>(MinimumQualityHistoryChangeName, "(stopTolFunHist) If the range of fitness values is less than a certain value for a certain time the algorithm terminates (set to 0 or positive to enable).", new DoubleValue(double.NaN)));283 Parameters.Add(new FixedValueParameter<DoubleValue>(MinimumStandardDeviationName, "(stopTolXFactor) If the standard deviation falls below a certain value the algorithm terminates (set to 0 or positive to enable).", new DoubleValue(double.NaN)));284 Parameters.Add(new FixedValueParameter<DoubleValue>(MaximumStandardDeviationChangeName, "(stopTolUpXFactor) If the standard deviation changes by a value larger than this parameter the algorithm stops (set to a value > 0 to enable).", new DoubleValue(double.NaN)));285 286 }287 #endregion288 289 #region updates290 private void updatePopulation(CMAHansenIndividual[] parents) {291 int[] offspringSucess = new int[solutions.Length];292 int offspringLength = parents.Length - solutions.Length;293 294 for (int i = 0; i < offspringLength; i++) {295 if (parents[i + solutions.Length].selected) {296 updateAsOffspring(parents[i + solutions.Length]);297 298 //TODO this may change if more offspring per parent is allowed299 offspringSucess[i] += CMAHansenIndividual.success;300 }301 }302 for (int i = 0; i < solutions.Length; i++) {303 if (parents[i].selected) {304 updateAsParent(parents[i], offspringSucess[i]);305 }306 }307 308 solutions = new CMAHansenIndividual[solutions.Length];309 int j = 0;310 foreach (CMAHansenIndividual ind in parents) {311 if (ind.selected) {312 solutions[j++] = ind;313 }314 }315 316 }317 318 private void updateAsParent(CMAHansenIndividual c, int v) {319 c.successProbability = (1 - stepSizeLearningRate) * c.successProbability + stepSizeLearningRate * (v == CMAHansenIndividual.success ? 1 : 0);320 c.sigma *= Math.Exp(1 / stepSizeDampeningFactor * (c.successProbability - targetSuccessProbability) / (1 - targetSuccessProbability));321 if (v != CMAHansenIndividual.failure) return;322 if (c.successProbability < successThreshold) {323 double stepNormSqr = c.getSetpNormSqr();324 double rate = covarianceMatrixUnlearningRate;325 if (stepNormSqr > 1 && 1 < covarianceMatrixUnlearningRate * (2 * stepNormSqr - 1)) {326 rate = 1 / (2 * stepNormSqr - 1);327 }328 rankOneUpdate(c, 1 + rate, -rate, c.lastStep);329 330 } else {331 roundUpdate(c);332 }333 334 }335 336 private void updateAsOffspring(CMAHansenIndividual c) {337 c.successProbability = (1 - stepSizeLearningRate) * c.successProbability + stepSizeLearningRate;338 c.sigma *= Math.Exp(1 / stepSizeDampeningFactor * (c.successProbability - targetSuccessProbability) / (1 - targetSuccessProbability));339 double evolutionpathUpdateWeight = evolutionPathLearningRate * (2.0 - evolutionPathLearningRate);340 if (c.successProbability < successThreshold) {341 c.updateEvolutionPath(1 - evolutionPathLearningRate, evolutionpathUpdateWeight);342 rankOneUpdate(c, 1 - covarianceMatrixLearningRate, covarianceMatrixLearningRate, c.evolutionPath);343 } else {344 roundUpdate(c);345 }346 }347 348 private void rankOneUpdate(CMAHansenIndividual c, double v1, double v2, RealVector lastStep) {349 c.choleskyUpdate(lastStep, v1, v2);350 }351 352 private void roundUpdate(CMAHansenIndividual c) {353 double evolutionPathUpdateWeight = evolutionPathLearningRate * (2.0 - evolutionPathLearningRate);354 c.updateEvolutionPath(1 - evolutionPathLearningRate, 0);355 rankOneUpdate(c, 1 - covarianceMatrixLearningRate + evolutionPathUpdateWeight,356 covarianceMatrixLearningRate, c.evolutionPath);357 }358 #endregion359 360 #region selection361 362 private T[] merge<T>(T[] parents, T[] offspring) {363 T[] merged = new T[parents.Length + offspring.Length];364 for (int i = 0; i < parents.Length; i++) {365 merged[i] = parents[i];366 }367 for (int i = 0; i < offspring.Length; i++) {368 merged[i + parents.Length] = offspring[i];369 }370 return merged;371 }372 373 private void selection(CMAHansenIndividual[] parents, int length) {374 //perform a nondominated sort to assign the rank to every element375 var fronts = NonDominatedSort(parents);376 377 //deselect the highest rank fronts until we would end up with less or equal mu elements378 int rank = fronts.Count - 1;379 int popSize = parents.Length;380 while (popSize - fronts[rank].Count >= length) {381 var front = fronts[rank];382 foreach (var i in front) i.selected = false;383 popSize -= front.Count;384 rank--;385 }386 387 //now use the indicator to deselect the worst approximating elements of the last selected front388 var front_ = fronts[rank];389 for (; popSize > length; popSize--) {390 int lc = indicator.leastContributer<CMAHansenIndividual>(front_.ToArray(), x => x.penalizedFitness); //TODO: This is a battel in its own right to be fought another day391 front_[lc].selected = false;392 front_.Swap(lc, front_.Count - 1);393 fronts.RemoveAt(front_.Count - 1);394 }395 }396 #endregion397 398 #region penalize Box-Constraints399 private void penalizeEvaluate(IEnumerable<CMAHansenIndividual> offspring) {400 foreach (CMAHansenIndividual child in offspring) {401 penalizeEvaluate(child);402 }403 }404 405 private void penalizeEvaluate(CMAHansenIndividual offspring) {406 if (isFeasable(offspring.x)) {407 offspring.fitness = Problem.Evaluate(offspring.x, random);408 offspring.penalizedFitness = offspring.fitness;409 } else {410 RealVector t = closestFeasible(offspring.x);411 offspring.fitness = Problem.Evaluate(t, random);412 offspring.penalizedFitness = penalize(offspring.x, t, offspring.fitness);413 }414 }415 416 private double[] penalize(RealVector x, RealVector t, double[] fitness) {417 double[] d = new double[fitness.Length];418 double penality = penalize(x, t);419 for (int i = 0; i < fitness.Length; i++) {420 d[i] = fitness[i] + penality;421 }422 return d;423 }424 425 private double penalize(RealVector x, RealVector t) {426 double sum = 0;427 for (int i = 0; i < x.Length; i++) {428 double d = x[i] - t[i];429 sum += d * d;430 }431 return sum;432 }433 434 private RealVector closestFeasible(RealVector x) {435 DoubleMatrix bounds = Problem.Bounds;436 RealVector r = new RealVector(x.Length);437 for (int i = 0; i < x.Length; i++) {438 r[i] = Math.Min(Math.Max(bounds[i, 0], x[i]), bounds[i, 1]);439 }440 return r;441 }442 443 private bool isFeasable(RealVector offspring) {444 DoubleMatrix bounds = Problem.Bounds;445 for (int i = 0; i < offspring.Length; i++) {446 if (bounds[i, 0] > offspring[i] || offspring[i] > bounds[i, 1]) return false;447 }448 return true;449 }450 451 #endregion452 453 #region mutation454 private CMAHansenIndividual[] generateOffspring() {455 CMAHansenIndividual[] offspring = new CMAHansenIndividual[PopulationSize]; //TODO this changes if 1,1-ES is replaced with 1,n-ES456 for (int i = 0; i < offspring.Length; i++) {457 offspring[i] = new CMAHansenIndividual(solutions[i]);458 offspring[i].mutate(gauss);459 }460 return offspring;461 }462 #endregion463 464 #region initialization465 private CMAHansenIndividual initializeIndividual(RealVector x) {466 var zeros = new RealVector(x.Length);467 var identity = new double[x.Length, x.Length];468 for (int i = 0; i < x.Length; i++) {469 identity[i, i] = 1;470 }471 return new CMAHansenIndividual(x, targetSuccessProbability, InitialSigma.Value, zeros, identity);472 }473 474 private void initSolutions() {475 for (int i = 0; i < PopulationSize; i++) {476 RealVector x = null; //TODO get those with magic477 solutions[i] = initializeIndividual(x);478 }479 penalizeEvaluate(solutions);480 }481 482 private void initStrategy() {483 int lambda = 1;484 double n = Problem.ProblemSize;485 indicator = new CrowdingIndicator();486 gauss = new NormalDistributedRandom(random, 0, 1);487 targetSuccessProbability = 1.0 / (5.0 + Math.Sqrt(lambda) / 2.0);488 stepSizeDampeningFactor = 1.0 + n / (2.0 * lambda);489 stepSizeLearningRate = targetSuccessProbability * lambda / (2.0 + targetSuccessProbability * lambda);490 evolutionPathLearningRate = 2.0 / (n + 2.0);491 covarianceMatrixLearningRate = 2.0 / (n * n + 6.0);492 covarianceMatrixUnlearningRate = 0.4 / (Math.Pow(n, 1.6) + 1);493 successThreshold = 0.44;494 495 }496 497 #endregion498 499 #region analyze500 private void analyzeSolutions() {501 //TODO give HyperVolume stuff502 //Problem.Analyze();503 504 }505 506 #endregion507 508 509 //MU = populationSize510 #region mainloop511 protected override void Run(CancellationToken cancellationToken) {512 // Set up the algorithm513 if (SetSeedRandomly) Seed = new System.Random().Next();514 random.Reset(Seed);515 516 517 // Set up the results display518 Results.Add(new Result("Iterations", new IntValue(0)));519 Results.Add(new Result("Evaluations", new IntValue(0)));520 var table = new DataTable("Hypervolumes");521 table.Rows.Add(new DataRow("Best Hypervolumes"));522 var iterationRows = new DataRow("Iteration Hypervolumes");523 iterationRows.VisualProperties.LineStyle = DataRowVisualProperties.DataRowLineStyle.Dot;524 table.Rows.Add(iterationRows);525 Results.Add(new Result("Hypervolumes", table));526 527 528 initStrategy();529 initSolutions();530 531 532 533 // Loop until iteration limit reached or canceled.534 for (ResultsIterations = 0; ResultsIterations < MaximumGenerations; ResultsIterations++) {535 536 try {537 iterate();538 cancellationToken.ThrowIfCancellationRequested();539 }540 finally {541 }542 }543 }544 545 protected override void OnExecutionTimeChanged() {546 base.OnExecutionTimeChanged();547 if (CancellationTokenSource == null) return;548 if (MaximumRuntime == -1) return;549 if (ExecutionTime.TotalSeconds > MaximumRuntime) CancellationTokenSource.Cancel();550 }551 552 private void iterate() {553 CMAHansenIndividual[] offspring = generateOffspring();554 penalizeEvaluate(offspring);555 selection(merge(solutions, offspring), solutions.Length);556 updatePopulation(offspring);557 558 }559 #endregion560 561 #region bernhard properties562 private NormalDistributedRandom gauss;563 private CMAHansenIndividual[] solutions;564 private const double penalizeFactor = 1e-6;565 private IIndicator indicator;566 567 private double stepSizeLearningRate; //=cp learning rate in [0,1]568 private double stepSizeDampeningFactor; //d569 private double targetSuccessProbability;// p^target_succ570 private double evolutionPathLearningRate;//cc571 private double covarianceMatrixLearningRate;//ccov572 private double covarianceMatrixUnlearningRate; //from shark573 private double successThreshold; //ptresh574 #endregion575 576 private class CMAHansenIndividual {577 public static readonly int success = 1;578 public static readonly int noSuccess = 2;579 public static readonly int failure = 3;580 581 582 //Chromosome583 public RealVector x;584 public double successProbability;585 public double sigma;//stepsize586 public RealVector evolutionPath; // pc587 public RealVector lastStep;588 public RealVector lastZ;589 private double[,] lowerCholesky;590 591 592 //Phenotype593 public double[] fitness;594 public double[] penalizedFitness;595 public bool selected = true;596 597 internal double rank;598 599 600 601 /// <summary>602 ///603 /// </summary>604 /// <param name="x">has to be 0-vector with correct lenght</param>605 /// <param name="p_succ">has to be ptargetsucc</param>606 /// <param name="sigma">initialSigma</param>607 /// <param name="pc">has to be 0-vector with correct lenght</param>608 /// <param name="C">has to be a symmetric positive definit Covariance matrix</param>609 public CMAHansenIndividual(RealVector x, double p_succ, double sigma, RealVector pc, double[,] C) {610 this.x = x;611 this.successProbability = p_succ;612 this.sigma = sigma;613 this.evolutionPath = pc;614 choleskyDecomposition(C);615 }616 617 private void choleskyDecomposition(double[,] C) {618 if (C.GetLength(0) != C.GetLength(1)) throw new ArgumentException("Covariancematrix is not quadratic");619 int n = C.GetLength(0);620 lowerCholesky = new double[n, n];621 double[,] A = lowerCholesky;622 for (int i = 0; i < n; i++) {623 for (int j = 0; j <= i; j++) {624 A[i, j] = C[i, j]; //simulate inplace transform625 double sum = A[i, j];626 for (int k = 0; k < j; k++) {627 sum = sum - A[i, k] * A[j, k];628 if (i > j) { A[i, j] = sum / A[j, j]; } else if (sum > 0) {629 A[i, i] = Math.Sqrt(sum);630 } else {631 throw new ArgumentException("Covariancematrix is not symetric positiv definit");632 }633 }634 }635 636 }637 }638 639 public CMAHansenIndividual(CMAHansenIndividual other) {640 641 642 this.successProbability = other.successProbability;643 this.sigma = other.sigma;644 645 // no no no make DEEP copies646 this.x = (RealVector)other.x.Clone(); //This may be ommited647 this.evolutionPath = (RealVector)other.evolutionPath.Clone();648 this.lastStep = (RealVector)lastStep.Clone(); //This may be ommited649 this.lastZ = (RealVector)lastZ.Clone(); //This may be ommited650 651 652 this.lowerCholesky = (double[,])other.lowerCholesky.Clone();653 }654 655 public void updateEvolutionPath(double learningRate, double updateWeight) {656 updateWeight = Math.Sqrt(updateWeight);657 for (int i = 0; i < evolutionPath.Length; i++) {658 evolutionPath[i] *= learningRate;659 evolutionPath[i] += updateWeight * lastStep[i];660 }661 }662 663 public double getSetpNormSqr() {664 double sum = 0;665 foreach (double d in lastZ) {666 sum += d * d;667 }668 return sum;669 }670 671 public void choleskyUpdate(RealVector v, double alpha, double beta) {672 int n = v.Length;673 double[] temp = new double[n];674 for (int i = 0; i < n; i++) temp[i] = v[i];675 double betaPrime = 1;676 double a = Math.Sqrt(alpha);677 for (int j = 0; j < n; j++) {678 double Ljj = a * lowerCholesky[j, j];679 double dj = Ljj * Ljj;680 double wj = temp[j];681 double swj2 = beta * wj * wj;682 double gamma = dj * betaPrime + swj2;683 double x = dj + swj2 / betaPrime;684 if (x < 0.0) throw new ArgumentException("Update makes Covariancematrix indefinite");685 double nLjj = Math.Sqrt(x);686 lowerCholesky[j, j] = nLjj;687 betaPrime += swj2 / dj;688 if (j + 1 < n) {689 for (int i = j + 1; i < n; i++) {690 lowerCholesky[i, j] *= a;691 }692 for (int i = j + 1; i < n; i++) {693 temp[i] = wj / Ljj * lowerCholesky[i, j];694 }695 if (gamma == 0) continue;696 for (int i = j + 1; i < n; i++) {697 lowerCholesky[i, j] *= nLjj / Ljj;698 }699 for (int i = j + 1; i < n; i++) {700 lowerCholesky[i, j] += (nLjj * beta * wj / gamma) * temp[i];701 }702 }703 704 }705 706 }707 708 public void mutate(NormalDistributedRandom gauss) {709 710 //sampling a random z from N(0,I) where I is the Identity matrix;711 int n = lastZ.Length;712 for (int i = 0; i < n; i++) {713 lastZ[i] = gauss.NextDouble();714 }715 //Matrixmultiplication: lastStep = lowerCholesky * lastZ;716 for (int i = 0; i < n; i++) {717 double sum = 0;718 for (int j = 0; j <= i; j++) {719 sum += lowerCholesky[i, j] * lastZ[j];720 }721 lastStep[i] = sum;722 }723 724 //add the step to x weighted by stepsize;725 for (int i = 0; i < x.Length; i++) {726 x[i] += sigma * lastStep[i];727 }728 729 }730 731 }732 733 //blatantly stolen form HeuristicLab.Optimization.Operators.FastNonDominatedSort734 #region FastNonDominatedSort735 private enum DominationResult { Dominates, IsDominated, IsNonDominated };736 737 private List<List<CMAHansenIndividual>> NonDominatedSort(CMAHansenIndividual[] individuals) {738 bool dominateOnEqualQualities = false;739 bool[] maximization = Problem.Maximization;740 if (individuals == null) throw new InvalidOperationException(Name + ": No qualities found.");741 int populationSize = individuals.Length;742 743 List<List<CMAHansenIndividual>> fronts = new List<List<CMAHansenIndividual>>();744 Dictionary<CMAHansenIndividual, List<int>> dominatedScopes = new Dictionary<CMAHansenIndividual, List<int>>();745 int[] dominationCounter = new int[populationSize];746 //ItemArray<IntValue> rank = new ItemArray<IntValue>(populationSize);747 748 for (int pI = 0; pI < populationSize - 1; pI++) {749 CMAHansenIndividual p = individuals[pI];750 List<int> dominatedScopesByp;751 if (!dominatedScopes.TryGetValue(p, out dominatedScopesByp))752 dominatedScopes[p] = dominatedScopesByp = new List<int>();753 for (int qI = pI + 1; qI < populationSize; qI++) {754 DominationResult test = Dominates(individuals[pI], individuals[qI], maximization, dominateOnEqualQualities);755 if (test == DominationResult.Dominates) {756 dominatedScopesByp.Add(qI);757 dominationCounter[qI] += 1;758 } else if (test == DominationResult.IsDominated) {759 dominationCounter[pI] += 1;760 if (!dominatedScopes.ContainsKey(individuals[qI]))761 dominatedScopes.Add(individuals[qI], new List<int>());762 dominatedScopes[individuals[qI]].Add(pI);763 }764 if (pI == populationSize - 2765 && qI == populationSize - 1766 && dominationCounter[qI] == 0) {767 //rank[qI] = new IntValue(0);768 AddToFront(individuals[qI], fronts, 0);769 }770 }771 if (dominationCounter[pI] == 0) {772 //rank[pI] = new IntValue(0);773 AddToFront(p, fronts, 0);774 }775 }776 int i = 0;777 while (i < fronts.Count && fronts[i].Count > 0) {778 List<CMAHansenIndividual> nextFront = new List<CMAHansenIndividual>();779 foreach (CMAHansenIndividual p in fronts[i]) {780 List<int> dominatedScopesByp;781 if (dominatedScopes.TryGetValue(p, out dominatedScopesByp)) {782 for (int k = 0; k < dominatedScopesByp.Count; k++) {783 int dominatedScope = dominatedScopesByp[k];784 dominationCounter[dominatedScope] -= 1;785 if (dominationCounter[dominatedScope] == 0) {786 //rank[dominatedScope] = new IntValue(i + 1);787 nextFront.Add(individuals[dominatedScope]);788 }789 }790 }791 }792 i += 1;793 fronts.Add(nextFront);794 }795 796 //RankParameter.ActualValue = rank;797 798 //scope.SubScopes.Clear();799 800 CMAHansenIndividual[] result = new CMAHansenIndividual[individuals.Length];801 int j = 0;802 803 for (i = 0; i < fronts.Count; i++) {804 foreach (var p in fronts[i]) {805 p.rank = i;806 }807 }808 return fronts;809 }810 811 812 private static void AddToFront(CMAHansenIndividual p, List<List<CMAHansenIndividual>> fronts, int i) {813 if (i == fronts.Count) fronts.Add(new List<CMAHansenIndividual>());814 fronts[i].Add(p);815 }816 817 private static DominationResult Dominates(CMAHansenIndividual left, CMAHansenIndividual right, bool[] maximizations, bool dominateOnEqualQualities) {818 return Dominates(left.penalizedFitness, right.penalizedFitness, maximizations, dominateOnEqualQualities);819 }820 821 private static DominationResult Dominates(double[] left, double[] right, bool[] maximizations, bool dominateOnEqualQualities) {822 //mkommend Caution: do not use LINQ.SequenceEqual for comparing the two quality arrays (left and right) due to performance reasons823 if (dominateOnEqualQualities) {824 var equal = true;825 for (int i = 0; i < left.Length; i++) {826 if (left[i] != right[i]) {827 equal = false;828 break;829 }830 }831 if (equal) return DominationResult.Dominates;832 }833 834 bool leftIsBetter = false, rightIsBetter = false;835 for (int i = 0; i < left.Length; i++) {836 if (IsDominated(left[i], right[i], maximizations[i])) rightIsBetter = true;837 else if (IsDominated(right[i], left[i], maximizations[i])) leftIsBetter = true;838 if (leftIsBetter && rightIsBetter) break;839 }840 841 if (leftIsBetter && !rightIsBetter) return DominationResult.Dominates;842 if (!leftIsBetter && rightIsBetter) return DominationResult.IsDominated;843 return DominationResult.IsNonDominated;844 }845 846 private static bool IsDominated(double left, double right, bool maximization) {847 return maximization && left < right848 || !maximization && left > right;849 }850 851 #endregion852 }853 1097 } -
branches/HeuristicLab.Algorithms.CMAEvolutionStrategy/sources/3.4/HeuristicLab.Algorithms.CMAEvolutionStrategy-3.4.csproj
r13793 r13909 100 100 <ItemGroup> 101 101 <Reference Include="ALGLIB-3.7.0"> 102 <HintPath>..\..\..\ trunk\sources\bin\ALGLIB-3.7.0.dll</HintPath>102 <HintPath>..\..\..\..\trunk\sources\bin\ALGLIB-3.7.0.dll</HintPath> 103 103 </Reference> 104 104 <Reference Include="HeuristicLab.Analysis-3.3"> 105 <HintPath>..\..\..\ trunk\sources\bin\HeuristicLab.Analysis-3.3.dll</HintPath>105 <HintPath>..\..\..\..\trunk\sources\bin\HeuristicLab.Analysis-3.3.dll</HintPath> 106 106 </Reference> 107 107 <Reference Include="HeuristicLab.Collections-3.3"> 108 <HintPath>..\..\..\ trunk\sources\bin\HeuristicLab.Collections-3.3.dll</HintPath>108 <HintPath>..\..\..\..\trunk\sources\bin\HeuristicLab.Collections-3.3.dll</HintPath> 109 109 </Reference> 110 110 <Reference Include="HeuristicLab.Common-3.3"> 111 <HintPath>..\..\..\ trunk\sources\bin\HeuristicLab.Common-3.3.dll</HintPath>111 <HintPath>..\..\..\..\trunk\sources\bin\HeuristicLab.Common-3.3.dll</HintPath> 112 112 </Reference> 113 113 <Reference Include="HeuristicLab.Core-3.3"> 114 <HintPath>..\..\..\ trunk\sources\bin\HeuristicLab.Core-3.3.dll</HintPath>114 <HintPath>..\..\..\..\trunk\sources\bin\HeuristicLab.Core-3.3.dll</HintPath> 115 115 </Reference> 116 116 <Reference Include="HeuristicLab.Data-3.3"> 117 <HintPath>..\..\..\ trunk\sources\bin\HeuristicLab.Data-3.3.dll</HintPath>117 <HintPath>..\..\..\..\trunk\sources\bin\HeuristicLab.Data-3.3.dll</HintPath> 118 118 </Reference> 119 119 <Reference Include="HeuristicLab.Encodings.RealVectorEncoding-3.3"> 120 <HintPath>..\..\..\ trunk\sources\bin\HeuristicLab.Encodings.RealVectorEncoding-3.3.dll</HintPath>120 <HintPath>..\..\..\..\trunk\sources\bin\HeuristicLab.Encodings.RealVectorEncoding-3.3.dll</HintPath> 121 121 </Reference> 122 122 <Reference Include="HeuristicLab.Operators-3.3"> 123 <HintPath>..\..\..\ trunk\sources\bin\HeuristicLab.Operators-3.3.dll</HintPath>123 <HintPath>..\..\..\..\trunk\sources\bin\HeuristicLab.Operators-3.3.dll</HintPath> 124 124 </Reference> 125 125 <Reference Include="HeuristicLab.Optimization-3.3"> 126 <HintPath>..\..\..\ trunk\sources\bin\HeuristicLab.Optimization-3.3.dll</HintPath>126 <HintPath>..\..\..\..\trunk\sources\bin\HeuristicLab.Optimization-3.3.dll</HintPath> 127 127 </Reference> 128 128 <Reference Include="HeuristicLab.Optimization.Operators-3.3"> 129 <HintPath>..\..\..\ trunk\sources\bin\HeuristicLab.Optimization.Operators-3.3.dll</HintPath>129 <HintPath>..\..\..\..\trunk\sources\bin\HeuristicLab.Optimization.Operators-3.3.dll</HintPath> 130 130 </Reference> 131 131 <Reference Include="HeuristicLab.Parameters-3.3"> 132 <HintPath>..\..\..\ trunk\sources\bin\HeuristicLab.Parameters-3.3.dll</HintPath>132 <HintPath>..\..\..\..\trunk\sources\bin\HeuristicLab.Parameters-3.3.dll</HintPath> 133 133 </Reference> 134 134 <Reference Include="HeuristicLab.Persistence-3.3"> 135 <HintPath>..\..\..\ trunk\sources\bin\HeuristicLab.Persistence-3.3.dll</HintPath>135 <HintPath>..\..\..\..\trunk\sources\bin\HeuristicLab.Persistence-3.3.dll</HintPath> 136 136 </Reference> 137 137 <Reference Include="HeuristicLab.PluginInfrastructure-3.3"> 138 <HintPath>..\..\..\trunk\sources\bin\HeuristicLab.PluginInfrastructure-3.3.dll</HintPath> 138 <HintPath>..\..\..\..\trunk\sources\bin\HeuristicLab.PluginInfrastructure-3.3.dll</HintPath> 139 </Reference> 140 <Reference Include="HeuristicLab.Problems.Instances-3.3"> 141 <HintPath>..\..\..\..\trunk\sources\bin\HeuristicLab.Problems.Instances-3.3.dll</HintPath> 139 142 </Reference> 140 143 <Reference Include="HeuristicLab.Random-3.3"> 141 <HintPath>..\..\..\ trunk\sources\bin\HeuristicLab.Random-3.3.dll</HintPath>144 <HintPath>..\..\..\..\trunk\sources\bin\HeuristicLab.Random-3.3.dll</HintPath> 142 145 </Reference> 143 146 <Reference Include="System" /> -
branches/HeuristicLab.Algorithms.CMAEvolutionStrategy/sources/BernhardCMAES_Soultion/HeuristicLab.Algorithms.MOCMAEvolutionStrategy.csproj
r13793 r13909 89 89 </ItemGroup> 90 90 <ItemGroup> 91 < Compile Include="Properties\AssemblyInfo.cs" />91 <None Include="Properties\AssemblyInfo.cs.frame" /> 92 92 </ItemGroup> 93 93 <Import Project="$(MSBuildToolsPath)\Microsoft.CSharp.targets" />
Note: See TracChangeset
for help on using the changeset viewer.