Changeset 15338
- Timestamp:
- 08/22/17 15:01:46 (7 years ago)
- Location:
- branches/EfficientGlobalOptimization/HeuristicLab.Algorithms.EGO
- Files:
-
- 2 added
- 12 edited
Legend:
- Unmodified
- Added
- Removed
-
branches/EfficientGlobalOptimization/HeuristicLab.Algorithms.EGO/AdaptiveSamplingAlgorithm.cs
r15064 r15338 2 2 using System.Collections.Generic; 3 3 using System.Linq; 4 using System.Threading; 4 5 using HeuristicLab.Algorithms.DataAnalysis; 5 6 using HeuristicLab.Analysis; … … 49 50 public IValueParameter<Algorithm> InfillOptimizationAlgorithmParameter => Parameters[InfillOptimizationAlgorithmParameterName] as IValueParameter<Algorithm>; 50 51 public IValueParameter<IDataAnalysisAlgorithm<IRegressionProblem>> RegressionAlgorithmParameter => Parameters[RegressionAlgorithmParameterName] as IValueParameter<IDataAnalysisAlgorithm<IRegressionProblem>>; 51 p rivateIFixedValueParameter<MultiAnalyzer> AnalyzerParameter => (IFixedValueParameter<MultiAnalyzer>)Parameters[AnalyzerParameterName];52 public IFixedValueParameter<MultiAnalyzer> AnalyzerParameter => (IFixedValueParameter<MultiAnalyzer>)Parameters[AnalyzerParameterName]; 52 53 public IFixedValueParameter<BoolValue> RemoveDuplicatesParameter => (IFixedValueParameter<BoolValue>)Parameters[RemoveDuplicatesParamterName]; 53 54 public IFixedValueParameter<IntValue> MaxModelSizeParameter => (IFixedValueParameter<IntValue>)Parameters[MaxModelSizeParameterName]; … … 65 66 public bool RemoveDuplicates => RemoveDuplicatesParameter.Value.Value; 66 67 public int MaxModelSize => MaxModelSizeParameter.Value.Value; 67 #endregion68 69 #region Helper Properties70 68 private SolutionsCreator SolutionsCreator => OperatorGraph.Iterate().OfType<SolutionsCreator>().First(); 71 69 #endregion 72 70 71 72 73 #region Operators 74 75 [Storable] 76 private OperatorList Operators; 77 73 78 #region Preconfigured Analyzers 74 79 [Storable] … … 102 107 [Storable] 103 108 private SolutionsCreator infillSolutionsCreator; 109 #endregion 104 110 #endregion 105 111 … … 123 129 modelAnalyzer = cloner.Clone(original.modelAnalyzer); 124 130 fitnessClusterAnalyzer = cloner.Clone(original.fitnessClusterAnalyzer); 131 132 Operators = cloner.Clone(original.Operators); 125 133 Initialize(); 126 134 } … … 163 171 164 172 #region Create operators 173 Operators = new OperatorList(); 174 165 175 var randomCreator = new RandomCreator(); 176 Operators.Add(randomCreator); 166 177 var variableCreator = new VariableCreator { Name = "Initialize Variables" }; 178 Operators.Add(variableCreator); 167 179 var resultsCollector = new ResultsCollector(); 180 Operators.Add(resultsCollector); 168 181 var solutionCreator = new SolutionsCreator { Name = "Create Initial Solutions" }; 182 Operators.Add(solutionCreator); 169 183 var analyzerPlaceholder = new Placeholder { Name = "Analyzer (Placeholder)" }; 184 Operators.Add(analyzerPlaceholder); 170 185 var evaluationsCounter = new IntCounter { Name = "Increment EvaluatedSolutions" }; 186 Operators.Add(evaluationsCounter); 171 187 var solutionsCollectorProcessor = new UniformSubScopesProcessor { Name = "Collect Samples to Dataset" }; 188 Operators.Add(solutionsCollectorProcessor); 172 189 var phaseChecker = new ConditionalBranch { Name = "Inital Samples evaluated?" }; 190 Operators.Add(phaseChecker); 173 191 var initialPhaseChecker = new Comparator { Name = "Compare Initial Samples to evaluated Solutions" }; 192 Operators.Add(initialPhaseChecker); 174 193 var modelbuilder = new ModelBuilder { Name = "Build Model" }; 194 Operators.Add(modelbuilder); 195 175 196 sampleCollector = new SampleCollector { Name = "Collect Sample" }; 197 Operators.Add(sampleCollector); 176 198 infillSolutionsCreator = new SolutionsCreator { Name = "Create Adaptive Solutions" }; 199 Operators.Add(infillSolutionsCreator); 177 200 infillSolver = new InfillSolver(); 201 Operators.Add(infillSolver); 202 178 203 var subScopesRemover = new SubScopesRemover(); 204 Operators.Add(subScopesRemover); 179 205 var iterationsCounter = new IntCounter { Name = "Increment Iterations" }; 206 Operators.Add(iterationsCounter); 180 207 var terminationOperator = new TerminationOperator(); 208 Operators.Add(terminationOperator); 181 209 #endregion 182 210 … … 218 246 modelbuilder.ModelParameter.ActualName = modelVariableName; 219 247 modelbuilder.RegressionAlgorithmParameter.ActualName = RegressionAlgorithmParameter.Name; 220 ParameterizeStochasticOperator(modelbuilder); 248 221 249 modelbuilder.Successor = infillSolutionsCreator; 222 250 modelbuilder.MaxModelSizeParameter.ActualName = MaxModelSizeParameter.Name; … … 265 293 iterationsCounter.Successor = terminationOperator; 266 294 267 268 269 295 terminationOperator.TerminatorParameter.ActualName = TerminatorParameter.Name; 270 296 terminationOperator.ContinueBranch = phaseChecker; 271 272 297 #endregion 273 298 274 299 #region Create analyzers 275 300 singleObjectiveQualityAnalyzer = new BestAverageWorstQualityAnalyzer(); 301 Operators.Add(singleObjectiveQualityAnalyzer); 302 276 303 correlationAnalyzer = new CorrelationAnalyzer(); 277 304 correlationAnalyzer.ModelParameter.ActualName = modelVariableName; 305 Operators.Add(correlationAnalyzer); 278 306 279 307 sampleAnalyzer = new EvaluatedSolutionsAnalyzer(); 280 308 sampleAnalyzer.PhaseParameter.ActualName = initialPhaseVariableName; 309 Operators.Add(sampleAnalyzer); 281 310 282 311 modelAnalyzer = new ModelQualityAnalyzer(); 283 312 modelAnalyzer.ModelParameter.ActualName = modelVariableName; 313 Operators.Add(modelAnalyzer); 284 314 285 315 variabilityAnalyzer = new VariableVariabilityAnalyzer(); 286 316 variabilityAnalyzer.DatasetParameter.ActualName = datasetVariableName; 287 317 variabilityAnalyzer.InitialEvaluationsParameter.ActualName = InitialEvaluationsParameter.Name; 318 Operators.Add(variabilityAnalyzer); 288 319 289 320 fitnessClusterAnalyzer = new FitnessClusteringAnalyzer(); 290 321 fitnessClusterAnalyzer.DatasetParameter.ActualName = datasetVariableName; 322 Operators.Add(fitnessClusterAnalyzer); 291 323 #endregion 292 324 293 325 #region Create terminators 294 326 295 evaluationsTerminator = new ComparisonTerminator<IntValue>("EvaluatedSolutions", ComparisonType.Less, 296 new IntValue(1000)) { Name = "Evaluated solutions." };327 evaluationsTerminator = new ComparisonTerminator<IntValue>("EvaluatedSolutions", ComparisonType.Less, new IntValue(1000)) { Name = "Evaluated solutions." }; 328 Operators.Add(evaluationsTerminator); 297 329 qualityTerminator = new SingleObjectiveQualityTerminator { Name = "Quality" }; 330 Operators.Add(qualityTerminator); 298 331 executionTimeTerminator = new ExecutionTimeTerminator(this, new TimeSpanValue(TimeSpan.FromMinutes(5))); 299 332 Operators.Add(executionTimeTerminator); 300 333 #endregion 301 334 … … 303 336 UpdateAnalyzers(); 304 337 ParameterizeAnalyzers(); 338 ParameterizeStochasticOperators(Operators); 305 339 UpdateTerminators(); 306 340 #endregion … … 308 342 Initialize(); 309 343 } 310 #endregion311 344 312 345 private void Initialize() { 313 346 if (SingleObjectiveProblem != null) { 314 SingleObjectiveProblem.Evaluator.QualityParameter.ActualNameChanged += 315 Evaluator_QualityParameter_ActualNameChanged; 347 SingleObjectiveProblem.Evaluator.QualityParameter.ActualNameChanged += Evaluator_QualityParameter_ActualNameChanged; 316 348 } 317 318 singleObjectiveQualityAnalyzer.CurrentBestQualityParameter.NameChanged += 319 QualityAnalyzer_CurrentBestQualityParameter_NameChanged; 349 singleObjectiveQualityAnalyzer.CurrentBestQualityParameter.NameChanged += QualityAnalyzer_CurrentBestQualityParameter_NameChanged; 320 350 RegisterParameterEvents(); 351 } 352 #endregion 353 354 public override void Start(CancellationToken cancellationToken) { 355 ParameterizeProblemSpecificOperators(); 356 ((InfillProblem)InfillOptimizationAlgorithm.Problem).InfillCriterion = InfillCriterion; 357 ParameterizeCancellableOperators(cancellationToken); 358 base.Start(cancellationToken); 359 } 360 public override void Stop() { 361 if (InfillOptimizationAlgorithm.ExecutionState == ExecutionState.Started || InfillOptimizationAlgorithm.ExecutionState == ExecutionState.Paused) 362 InfillOptimizationAlgorithm.Stop(); 363 if (RegressionAlgorithm.ExecutionState == ExecutionState.Started || RegressionAlgorithm.ExecutionState == ExecutionState.Paused) 364 RegressionAlgorithm.Stop(); 365 base.Stop(); 366 } 367 public override void Pause() { 368 if (InfillOptimizationAlgorithm.ExecutionState == ExecutionState.Started) InfillOptimizationAlgorithm.Pause(); 369 if (RegressionAlgorithm.ExecutionState == ExecutionState.Started) RegressionAlgorithm.Pause(); 370 base.Pause(); 321 371 } 322 372 … … 328 378 } 329 379 private void ParameterizeAnalyzers() { 330 //TODO how to guarantee ResultsParameters and QualityParameters are really there? This seems hardcoded 380 foreach (var op in Operators.OfType<IResultsOperator>()) { 381 op.ResultsParameter.ActualName = "Results"; 382 op.ResultsParameter.Hidden = true; 383 } 384 331 385 singleObjectiveQualityAnalyzer.ResultsParameter.ActualName = "Results"; 332 386 singleObjectiveQualityAnalyzer.ResultsParameter.Hidden = true; 333 387 singleObjectiveQualityAnalyzer.QualityParameter.Depth = 1; 334 correlationAnalyzer.ResultsParameter.ActualName = "Results";335 correlationAnalyzer.ResultsParameter.Hidden = true;336 388 correlationAnalyzer.QualityParameter.Depth = 1; 337 389 correlationAnalyzer.RealVectorParameter.Depth = 1; 338 sampleAnalyzer.ResultsParameter.ActualName = "Results";339 sampleAnalyzer.ResultsParameter.Hidden = true;340 390 sampleAnalyzer.QualityParameter.Depth = 1; 341 391 sampleAnalyzer.RealVectorParameter.Depth = 1; 342 modelAnalyzer.ResultsParameter.ActualName = "Results";343 modelAnalyzer.ResultsParameter.Hidden = true;344 fitnessClusterAnalyzer.ResultsParameter.ActualName = "Results";345 fitnessClusterAnalyzer.ResultsParameter.Hidden = true;346 347 392 348 393 if (SingleObjectiveProblem == null) return; … … 362 407 SolutionsCreator.SolutionCreatorParameter.ActualName = Problem.SolutionCreatorParameter.Name; 363 408 infillSolutionsCreator.EvaluatorParameter.ActualName = Problem.EvaluatorParameter.Name; 364 } 365 private void ParameterizeStochasticOperator(IOperator @operator) { 366 var stochasticOperator = @operator as IStochasticOperator; 367 if (stochasticOperator == null) return; 368 stochasticOperator.RandomParameter.ActualName = "Random"; 369 stochasticOperator.RandomParameter.Hidden = true; 409 ParameterizeStochasticOperators(new[] { SolutionsCreator, infillSolutionsCreator }); 410 } 411 private static void ParameterizeStochasticOperators(IEnumerable<IItem> operators) { 412 foreach (var op in operators.OfType<IStochasticOperator>()) { 413 op.RandomParameter.ActualName = "Random"; 414 op.RandomParameter.Hidden = true; 415 } 370 416 } 371 417 private void ParameterizeProblemSpecificOperators() { … … 374 420 var rcreator = Problem.SolutionCreator as IRealVectorCreator; 375 421 if (rcreator == null) throw new ArgumentException("Adaptive sampling requires real vectors as solution candidates"); 422 376 423 infillSolver.LengthParameter.ActualName = rcreator.LengthParameter.ActualName; 377 424 infillSolver.BoundsParameter.ActualName = rcreator.BoundsParameter.ActualName; 378 // if (rcreator.LengthParameter.Value != null)379 425 infillSolver.LengthParameter.Value = rcreator.LengthParameter.Value; 380 // if (rcreator.BoundsParameter.Value != null)381 426 infillSolver.BoundsParameter.Value = rcreator.BoundsParameter.Value; 382 427 infillSolver.RealVectorParameter.ActualName = rcreator.RealVectorParameter.ActualName; … … 388 433 sampleAnalyzer.RealVectorParameter.ActualName = rcreator.RealVectorParameter.ActualName; 389 434 } 390 #endregion 391 392 public override void Start() { 393 ParameterizeProblemSpecificOperators(); 394 ((InfillProblem)InfillOptimizationAlgorithm.Problem).InfillCriterion = InfillCriterion; 395 base.Start(); 396 } 397 public override void Stop() { 398 if (InfillOptimizationAlgorithm.ExecutionState == ExecutionState.Started || InfillOptimizationAlgorithm.ExecutionState == ExecutionState.Paused) 399 InfillOptimizationAlgorithm.Stop(); 400 if (RegressionAlgorithm.ExecutionState == ExecutionState.Started || RegressionAlgorithm.ExecutionState == ExecutionState.Paused) 401 RegressionAlgorithm.Stop(); 402 base.Stop(); 403 } 404 public override void Pause() { 405 if (InfillOptimizationAlgorithm.ExecutionState == ExecutionState.Started) InfillOptimizationAlgorithm.Pause(); 406 if (RegressionAlgorithm.ExecutionState == ExecutionState.Started) RegressionAlgorithm.Pause(); 407 base.Pause(); 408 } 409 410 #region events 435 private void ParameterizeCancellableOperators(CancellationToken cancellation) { 436 foreach (var op in Operators.OfType<ICancellableOperator>()) 437 op.Cancellation = cancellation; 438 } 439 440 private void UnParameterizeCancellableOperators(CancellationToken cancellation) { 441 foreach (var op in Operators.OfType<ICancellableOperator>()) 442 op.Cancellation = CancellationToken.None; 443 } 444 #endregion 445 446 #region Events 411 447 private void RegisterParameterEvents() { 412 448 InfillOptimizationAlgorithmParameter.ValueChanged += OnInfillAlgorithmChanged; … … 428 464 InfillOptimizationAlgorithm.ProblemChanged += OnInfillProblemChanged; 429 465 } 466 430 467 protected override void OnProblemChanged() { 431 468 base.OnProblemChanged(); 432 ParameterizeStochasticOperator(Problem.SolutionCreator); 433 foreach (var @operator in Problem.Operators.OfType<IOperator>()) 434 ParameterizeStochasticOperator(@operator); 435 436 //TODO ParameterizeIterationBasedOperators(); 437 438 ParameterizeSolutionsCreators(); 439 ParameterizeAnalyzers(); 440 ParameterizeTerminators(); 441 442 if (SingleObjectiveProblem != null) 443 SingleObjectiveProblem.Evaluator.QualityParameter.ActualNameChanged += 444 Evaluator_QualityParameter_ActualNameChanged; 445 469 ParameterizeStochasticOperators(Problem.Operators); 446 470 UpdateAnalyzers(); 447 471 UpdateTerminators(); 472 ParameterizeSolutionsCreators(); 473 if (SingleObjectiveProblem != null) 474 SingleObjectiveProblem.Evaluator.QualityParameter.ActualNameChanged += Evaluator_QualityParameter_ActualNameChanged; 448 475 } 449 476 protected override void RegisterProblemEvents() { … … 460 487 protected override void Problem_SolutionCreatorChanged(object sender, EventArgs e) { 461 488 base.Problem_SolutionCreatorChanged(sender, e); 462 ParameterizeStochasticOperator(Problem.SolutionCreator); 463 464 if (SingleObjectiveProblem != null) SingleObjectiveProblem.Evaluator.QualityParameter.ActualNameChanged += Evaluator_QualityParameter_ActualNameChanged; 465 489 ParameterizeStochasticOperators(Problem.SolutionCreator.ToEnumerable()); 490 SingleObjectiveProblem.Evaluator.QualityParameter.ActualNameChanged += Evaluator_QualityParameter_ActualNameChanged; 466 491 ParameterizeSolutionsCreators(); 467 492 ParameterizeAnalyzers(); … … 469 494 protected override void Problem_EvaluatorChanged(object sender, EventArgs e) { 470 495 base.Problem_EvaluatorChanged(sender, e); 471 foreach (var @operator in Problem.Operators.OfType<IOperator>()) 472 ParameterizeStochasticOperator(@operator); 473 474 UpdateAnalyzers(); 475 496 ParameterizeStochasticOperators(Problem.Operators); 476 497 ParameterizeSolutionsCreators(); 477 498 } 478 499 protected override void Problem_OperatorsChanged(object sender, EventArgs e) { 479 500 base.Problem_OperatorsChanged(sender, e); 480 //TODO ParameterizeIterationBasedOperators();501 UpdateAnalyzers(); 481 502 UpdateTerminators(); 482 503 } 483 504 private void MaximizationParameter_ValueChanged(object sender, EventArgs e) { 505 ParameterizeAnalyzers(); 484 506 ParameterizeTerminators(); 485 507 } … … 490 512 ParameterizeTerminators(); 491 513 } 514 492 515 #endregion 493 516 … … 495 518 private void UpdateAnalyzers() { 496 519 Analyzer.Operators.Clear(); 497 if (Problem == null) return; 498 if (SingleObjectiveProblem != null) { 499 Analyzer.Operators.Add(singleObjectiveQualityAnalyzer, singleObjectiveQualityAnalyzer.EnabledByDefault); 500 Analyzer.Operators.Add(correlationAnalyzer, correlationAnalyzer.EnabledByDefault); 501 Analyzer.Operators.Add(sampleAnalyzer, sampleAnalyzer.EnabledByDefault); 502 Analyzer.Operators.Add(modelAnalyzer, modelAnalyzer.EnabledByDefault); 503 Analyzer.Operators.Add(variabilityAnalyzer, variabilityAnalyzer.EnabledByDefault); 504 Analyzer.Operators.Add(fitnessClusterAnalyzer, fitnessClusterAnalyzer.EnabledByDefault); 505 } 506 foreach (var analyzer in Problem.Operators.OfType<IAnalyzer>()) 520 if (SingleObjectiveProblem == null) return; 521 foreach (var analyzer in Operators.OfType<IAnalyzer>().Concat(SingleObjectiveProblem.Operators.OfType<IAnalyzer>())) 507 522 Analyzer.Operators.Add(analyzer, analyzer.EnabledByDefault); 523 ParameterizeAnalyzers(); 508 524 } 509 525 private void UpdateTerminators() { … … 519 535 } 520 536 }; 521 if (Problem != null) { 522 if (SingleObjectiveProblem != null) 523 newTerminators.Add(qualityTerminator, 524 Terminator.Operators.Contains(qualityTerminator) && Terminator.Operators.ItemChecked(qualityTerminator)); 537 if (SingleObjectiveProblem != null) { 538 newTerminators.Add(qualityTerminator, Terminator.Operators.Contains(qualityTerminator) && Terminator.Operators.ItemChecked(qualityTerminator)); 525 539 foreach (var terminator in Problem.Operators.OfType<ITerminator>()) 526 newTerminators.Add(terminator, 527 !Terminator.Operators.Contains(terminator) || Terminator.Operators.ItemChecked(terminator)); 540 newTerminators.Add(terminator, !Terminator.Operators.Contains(terminator) || Terminator.Operators.ItemChecked(terminator)); 528 541 } 529 530 542 Terminator.Operators.Clear(); 531 543 foreach (var newTerminator in newTerminators) 532 544 Terminator.Operators.Add(newTerminator.Key, newTerminator.Value); 533 }534 #endregion535 545 ParameterizeTerminators(); 546 } 547 #endregion 536 548 } 537 549 -
branches/EfficientGlobalOptimization/HeuristicLab.Algorithms.EGO/EfficientGlobalOptimizationAlgorithm.cs
r15064 r15338 45 45 public override bool SupportsPause => true; 46 46 public override Type ProblemType => typeof(SingleObjectiveBasicProblem<IEncoding>); 47 public new SingleObjectiveBasicProblem<IEncoding> Problem 48 { 47 public new SingleObjectiveBasicProblem<IEncoding> Problem { 49 48 get { return (SingleObjectiveBasicProblem<IEncoding>)base.Problem; } 50 49 set { base.Problem = value; } … … 130 129 131 130 #region ResultsProperties 132 private double ResultsBestQuality 133 { 131 private double ResultsBestQuality { 134 132 get { return ((DoubleValue)Results[BestQualityResultName].Value).Value; } 135 133 set { ((DoubleValue)Results[BestQualityResultName].Value).Value = value; } 136 134 } 137 private RealVector ResultsBestSolution 138 { 135 private RealVector ResultsBestSolution { 139 136 get { return (RealVector)Results[BestSolutionResultName].Value; } 140 137 set { Results[BestSolutionResultName].Value = value; } 141 138 } 142 private int ResultsEvaluations 143 { 139 private int ResultsEvaluations { 144 140 get { return ((IntValue)Results[EvaluatedSoultionsResultName].Value).Value; } 145 141 set { ((IntValue)Results[EvaluatedSoultionsResultName].Value).Value = value; } 146 142 } 147 private int ResultsIterations 148 { 143 private int ResultsIterations { 149 144 get { return ((IntValue)Results[IterationsResultName].Value).Value; } 150 145 set { ((IntValue)Results[IterationsResultName].Value).Value = value; } … … 154 149 private DataRow ResultsQualitiesWorst => ResultsQualities.Rows[WorstQualitiesRowResultName]; 155 150 private DataRow ResultsQualitiesIteration => ResultsQualities.Rows[CurrentQualitiesRowResultName]; 156 private IRegressionSolution ResultsModel 157 { 151 private IRegressionSolution ResultsModel { 158 152 get { return (IRegressionSolution)Results[RegressionSolutionResultName].Value; } 159 153 set { Results[RegressionSolutionResultName].Value = value; } … … 252 246 Samples.Add(Evaluate(t)); 253 247 cancellationToken.ThrowIfCancellationRequested(); 254 } 255 finally { 248 } finally { 256 249 Analyze(); 257 250 } … … 271 264 } 272 265 273 } 274 finally { 266 } finally { 275 267 Analyze(); 276 268 } … … 348 340 349 341 while (solution == null && i++ < 100) { 350 var results = EgoUtilities.SyncRunSubAlgorithm(RegressionAlgorithm, Random.Next(int.MaxValue) );342 var results = EgoUtilities.SyncRunSubAlgorithm(RegressionAlgorithm, Random.Next(int.MaxValue), cancellationToken); 351 343 solution = results.Select(x => x.Value).OfType<IRegressionSolution>().SingleOrDefault(); 352 344 cancellationToken.ThrowIfCancellationRequested(); … … 371 363 solution = sol; 372 364 } 373 } 374 catch (ArgumentException) { } 365 } catch (ArgumentException) { } 375 366 } 376 367 … … 405 396 for (var i = 0; i < InfillOptimizationRestarts; i++) { 406 397 //optimize 407 var res = EgoUtilities.SyncRunSubAlgorithm(InfillOptimizationAlgorithm, Random.Next(int.MaxValue) );398 var res = EgoUtilities.SyncRunSubAlgorithm(InfillOptimizationAlgorithm, Random.Next(int.MaxValue), cancellationToken); 408 399 cancellationToken.ThrowIfCancellationRequested(); 409 400 //extract results -
branches/EfficientGlobalOptimization/HeuristicLab.Algorithms.EGO/EgoUtilities.cs
r15064 r15338 24 24 using System.Linq; 25 25 using System.Threading; 26 using HeuristicLab.Common;27 26 using HeuristicLab.Core; 28 27 using HeuristicLab.Data; … … 64 63 65 64 //Sub-ALgorithms 66 public static ResultCollection SyncRunSubAlgorithm(IAlgorithm alg, int random) { 67 65 public static ResultCollection SyncRunSubAlgorithm(IAlgorithm alg, int random, CancellationToken cancellation) { 68 66 if (alg.Parameters.ContainsKey("SetSeedRandomly") && alg.Parameters.ContainsKey("Seed")) { 69 67 var setSeed = alg.Parameters["SetSeedRandomly"].ActualValue as BoolValue; … … 72 70 setSeed.Value = false; 73 71 seed.Value = random; 74 75 72 } 76 77 78 EventWaitHandle trigger = new AutoResetEvent(false);79 Exception ex = null;80 EventHandler<EventArgs<Exception>> exhandler = (sender, e) => { ex = e.Value; trigger.Set(); };81 EventHandler stoppedHandler = (sender, e) => trigger.Set();82 83 alg.ExceptionOccurred -= exhandler; //avoid double attaching in case of pause84 alg.ExceptionOccurred += exhandler;85 alg.Stopped -= stoppedHandler;86 alg.Stopped += stoppedHandler;87 alg.Paused -= stoppedHandler;88 alg.Paused += stoppedHandler;89 90 73 if (alg.ExecutionState != ExecutionState.Paused) alg.Prepare(); 91 alg.Start(); 92 trigger.WaitOne(); 93 alg.ExceptionOccurred -= exhandler; 94 alg.Stopped -= stoppedHandler; 95 if (ex != null) throw ex; 74 alg.Start(cancellation); 96 75 return alg.Results; 97 76 } 98 77 99 78 //RegressionModel extensions 100 p ublicconst double DuplicateResolution = 0.0001;79 private const double DuplicateResolution = 0.0001; 101 80 public static Dataset GetDataSet(IReadOnlyList<Tuple<RealVector, double>> samples, bool removeDuplicates) { 102 81 if (removeDuplicates) samples = RemoveDuplicates(samples); //TODO duplicate removal leads to incorrect uncertainty values in models -
branches/EfficientGlobalOptimization/HeuristicLab.Algorithms.EGO/HeuristicLab.Algorithms.EGO-3.4.csproj
r15064 r15338 118 118 <Compile Include="InfillCriteria\InfillCriterionBase.cs" /> 119 119 <Compile Include="InfillCriteria\ExpectedImprovement.cs" /> 120 <Compile Include="Interfaces\IResultsOperator.cs" /> 121 <Compile Include="Interfaces\ICancellableOperator.cs" /> 120 122 <Compile Include="Interfaces\IInitialSampling.cs" /> 121 123 <Compile Include="Interfaces\ISurrogateAlgorithm.cs" /> -
branches/EfficientGlobalOptimization/HeuristicLab.Algorithms.EGO/InfillCriteria/NeighbourDistance.cs
r15064 r15338 36 36 public class NeighbourDistance : InfillCriterionBase { 37 37 38 private IVantagePointTree<IEnumerable<double>> Points;38 private VantagePointTree<IEnumerable<double>> Points; 39 39 #region Constructors, Serialization and Cloning 40 40 [StorableConstructor] 41 41 protected NeighbourDistance(bool deserializing) : base(deserializing) { } 42 43 protected NeighbourDistance(NeighbourDistance original, Cloner cloner) : base(original, cloner) { 44 } 42 protected NeighbourDistance(NeighbourDistance original, Cloner cloner) : base(original, cloner) { } 45 43 public NeighbourDistance() { } 46 public override IDeepCloneable Clone(Cloner cloner) { 47 return new NeighbourDistance(this, cloner); 48 } 44 public override IDeepCloneable Clone(Cloner cloner) { return new NeighbourDistance(this, cloner); } 49 45 #endregion 50 46 … … 55 51 Points.Search(vector, 1, out neighbours, out distances); 56 52 return distances[0]; 57 //return RegressionSolution.ProblemData.AllIndices.Min(i => DistanceToSample(vector, i));58 53 } 59 54 60 55 public override void Initialize() { 61 56 Points = CreateTree(); 62 }63 64 private double DistanceToSample(RealVector vector, int i) {65 throw new NotImplementedException();66 57 } 67 58 -
branches/EfficientGlobalOptimization/HeuristicLab.Algorithms.EGO/Operators/CorrelationAnalyzer.cs
r15064 r15338 36 36 [Item("CorrelationAnalyzer", "Analyzes the correlation between perdictions and actual fitness values")] 37 37 [StorableClass] 38 public class CorrelationAnalyzer : SingleSuccessorOperator, IAnalyzer {38 public class CorrelationAnalyzer : SingleSuccessorOperator, IAnalyzer, IResultsOperator { 39 39 public override bool CanChangeName => true; 40 40 public bool EnabledByDefault => false; -
branches/EfficientGlobalOptimization/HeuristicLab.Algorithms.EGO/Operators/EvaluatedSolutionsAnalyzer.cs
r15064 r15338 38 38 [Item("EvaluatedSolutionsAnalyzer", "Displays the evaluated Solutions for one or two dimensional problems")] 39 39 [StorableClass] 40 public class EvaluatedSolutionsAnalyzer : SingleSuccessorOperator, IAnalyzer {40 public class EvaluatedSolutionsAnalyzer : SingleSuccessorOperator, IAnalyzer, IResultsOperator { 41 41 public override bool CanChangeName => true; 42 42 public bool EnabledByDefault => false; -
branches/EfficientGlobalOptimization/HeuristicLab.Algorithms.EGO/Operators/FitnessClusteringAnalyzer.cs
r15064 r15338 22 22 using System; 23 23 using System.Linq; 24 using System.Threading; 24 25 using HeuristicLab.Algorithms.DataAnalysis; 25 26 using HeuristicLab.Analysis; … … 32 33 using HeuristicLab.Persistence.Default.CompositeSerializers.Storable; 33 34 using HeuristicLab.Problems.DataAnalysis; 34 using HeuristicLab.Problems.SurrogateProblem;35 35 36 36 namespace HeuristicLab.Algorithms.EGO { 37 37 [Item("FitnessClusteringAnalyzer", "Analyzes the correlation between perdictions and actual fitness values")] 38 38 [StorableClass] 39 public class FitnessClusteringAnalyzer : SingleSuccessorOperator, IAnalyzer, IStochasticOperator {39 public class FitnessClusteringAnalyzer : SingleSuccessorOperator, IAnalyzer, IStochasticOperator, IResultsOperator { 40 40 public override bool CanChangeName => true; 41 41 public bool EnabledByDefault => false; … … 95 95 Problem = prob 96 96 }; 97 tsne.Classes Parameter.Value.Value = "cluster";98 var res = EgoUtilities.SyncRunSubAlgorithm(tsne, random.Next() );97 tsne.ClassesNameParameter.Value = tsne.ClassesNameParameter.ValidValues.FirstOrDefault(x => x.Value.Equals("cluster")); 98 var res = EgoUtilities.SyncRunSubAlgorithm(tsne, random.Next(), CancellationToken.None); 99 99 return res.Select(r => r.Value).OfType<ScatterPlot>().First(); 100 100 } … … 106 106 pd.TrainingPartition.Start = 0; 107 107 pd.TrainingPartition.End = dataset.Rows; 108 109 return ObservationWeightedKMeans.CreateKMeansSolution(pd, GetWeights(dataset), KParameter.Value.Value, 1000, random); 108 return KMeansClustering.CreateKMeansSolution(pd, KParameter.Value.Value, 1); 110 109 } 111 110 private double[] GetWeights(ModifiableDataset dataset) { -
branches/EfficientGlobalOptimization/HeuristicLab.Algorithms.EGO/Operators/InfillSolver.cs
r15064 r15338 21 21 22 22 using System; 23 using System.Threading; 23 24 using HeuristicLab.Common; 24 25 using HeuristicLab.Core; … … 36 37 [Item("InfillSolver", "A RealVectorCreator that creates candidates by optimizing an infill-subproblem")] 37 38 [StorableClass] 38 public class InfillSolver : RealVectorCreator {39 public class InfillSolver : RealVectorCreator, ICancellableOperator { 39 40 40 41 public ILookupParameter<IAlgorithm> InfillOptimizationAlgorithmParamter => (ILookupParameter<IAlgorithm>)Parameters["InfillAlgorithm"]; … … 44 45 public IFixedValueParameter<DoubleValue> DuplicateCutoffParameter => (IFixedValueParameter<DoubleValue>)Parameters["Duplicates Cutoff"]; 45 46 public ILookupParameter<DoubleMatrix> InfillBoundsParameter => (ILookupParameter<DoubleMatrix>)Parameters["InfillBounds"]; 47 48 public CancellationToken Cancellation { get; set; } 46 49 47 50 [StorableConstructor] … … 77 80 } 78 81 79 p ublic staticRealVector OptimizeInfillProblem(IAlgorithm algorithm, IRegressionSolution model, bool maximization, DoubleMatrix bounds, int length, IRandom random) {82 private RealVector OptimizeInfillProblem(IAlgorithm algorithm, IRegressionSolution model, bool maximization, DoubleMatrix bounds, int length, IRandom random) { 80 83 var infillProblem = algorithm.Problem as InfillProblem; 81 84 if (infillProblem == null) throw new ArgumentException("The algortihm has no InfillProblem to solve"); … … 83 86 infillProblem.Encoding.Bounds = bounds; 84 87 infillProblem.Initialize(model, maximization); 85 var res = EgoUtilities.SyncRunSubAlgorithm(algorithm, random.Next(int.MaxValue) );88 var res = EgoUtilities.SyncRunSubAlgorithm(algorithm, random.Next(int.MaxValue), Cancellation); 86 89 var v = res[InfillProblem.BestInfillSolutionResultName].Value as RealVector; 87 90 algorithm.Runs.Clear(); … … 104 107 105 108 109 106 110 } 107 111 } -
branches/EfficientGlobalOptimization/HeuristicLab.Algorithms.EGO/Operators/ModelBuilder.cs
r15064 r15338 22 22 using System; 23 23 using System.Linq; 24 using System.Threading; 24 25 using HeuristicLab.Algorithms.DataAnalysis; 25 26 using HeuristicLab.Common; … … 31 32 using HeuristicLab.Persistence.Default.CompositeSerializers.Storable; 32 33 using HeuristicLab.Problems.DataAnalysis; 34 using HeuristicLab.Problems.SurrogateProblem; 33 35 34 36 namespace HeuristicLab.Algorithms.EGO { … … 38 40 [Item("ModelBuilder", "Builds a model from a dataset and a given RegressionAlgorithm")] 39 41 [StorableClass] 40 public class ModelBuilder : InstrumentedOperator, IStochasticOperator {42 public class ModelBuilder : InstrumentedOperator, IStochasticOperator, ICancellableOperator { 41 43 public override bool CanChangeName => true; 44 public CancellationToken Cancellation { get; set; } 42 45 46 #region Parameter properties 43 47 public ILookupParameter<IDataAnalysisAlgorithm<IRegressionProblem>> RegressionAlgorithmParameter => (ILookupParameter<IDataAnalysisAlgorithm<IRegressionProblem>>)Parameters["RegressionAlgorithm"]; 44 48 public ILookupParameter<IRegressionSolution> ModelParameter => (ILookupParameter<IRegressionSolution>)Parameters["Model"]; … … 47 51 public ILookupParameter<IntValue> MaxModelSizeParameter => (ILookupParameter<IntValue>)Parameters["Maximal Model Size"]; 48 52 public ILookupParameter<DoubleMatrix> InfillBoundsParameter => (ILookupParameter<DoubleMatrix>)Parameters["InfillBounds"]; 53 #endregion 49 54 50 55 [StorableConstructor] … … 93 98 } 94 99 95 private staticIRegressionSolution BuildModel(IRandom random, IDataAnalysisAlgorithm<IRegressionProblem> regressionAlgorithm, IDataset dataset, IRegressionSolution oldSolution) {100 private IRegressionSolution BuildModel(IRandom random, IDataAnalysisAlgorithm<IRegressionProblem> regressionAlgorithm, IDataset dataset, IRegressionSolution oldSolution) { 96 101 //var dataset = EgoUtilities.GetDataSet(dataSamples, RemoveDuplicates); 97 102 var problemdata = new RegressionProblemData(dataset, dataset.VariableNames.Where(x => !x.Equals("output")), "output"); … … 108 113 109 114 while (solution == null && i++ < 100) { 110 var results = EgoUtilities.SyncRunSubAlgorithm(regressionAlgorithm, random.Next(int.MaxValue) );115 var results = EgoUtilities.SyncRunSubAlgorithm(regressionAlgorithm, random.Next(int.MaxValue), Cancellation); 111 116 solution = results.Select(x => x.Value).OfType<IRegressionSolution>().SingleOrDefault(); 112 117 } 113 118 114 //try creating a model with old hyperparameters and new dataset; 115 var gp = regressionAlgorithm as GaussianProcessRegression; 116 var oldmodel = oldSolution as GaussianProcessRegressionSolution; 117 if (gp != null && oldmodel != null) { 118 var mean = (IMeanFunction)oldmodel.Model.MeanFunction.Clone(); 119 var cov = (ICovarianceFunction)oldmodel.Model.CovarianceFunction.Clone(); 120 try { 121 var model = new GaussianProcessModel(problemdata.Dataset, problemdata.TargetVariable, 122 problemdata.AllowedInputVariables, problemdata.TrainingIndices, new[] { 0.0 }, mean, cov); 123 model.FixParameters(); 124 var sol = new GaussianProcessRegressionSolution(model, problemdata); 125 if (solution == null || solution.TrainingMeanSquaredError > sol.TrainingMeanSquaredError) { 126 solution = sol; 127 } 128 } 129 catch (ArgumentException) { } 130 } 119 if (regressionAlgorithm is GaussianProcessRegression && oldSolution != null) 120 solution = SanitizeGaussianProcess(oldSolution as GaussianProcessRegressionSolution, solution as GaussianProcessRegressionSolution, Cancellation); 121 122 if (regressionAlgorithm is M5RegressionTree && oldSolution != null) 123 solution = SanitizeM5Regression(oldSolution.Model as M5Model, solution, random, Cancellation); 124 131 125 132 126 regressionAlgorithm.Runs.Clear(); … … 134 128 135 129 } 130 131 private static IRegressionSolution SanitizeM5Regression(M5Model oldmodel, IRegressionSolution newSolution, IRandom random, CancellationToken cancellation) { 132 var problemdata = newSolution.ProblemData; 133 oldmodel.UpdateLeafModels(problemdata, problemdata.AllIndices, random, cancellation); 134 var oldSolution = oldmodel.CreateRegressionSolution(problemdata); 135 var magicDecision = newSolution.TrainingRSquared < oldSolution.TrainingRSquared - 0.05; 136 return magicDecision ? newSolution : oldmodel.CreateRegressionSolution(problemdata); 137 } 138 139 //try creating a model with old hyperparameters and new dataset; 140 private static IRegressionSolution SanitizeGaussianProcess(GaussianProcessRegressionSolution oldmodel, GaussianProcessRegressionSolution newSolution, CancellationToken cancellation) { 141 var problemdata = newSolution.ProblemData; 142 var mean = (IMeanFunction)oldmodel.Model.MeanFunction.Clone(); 143 var cov = (ICovarianceFunction)oldmodel.Model.CovarianceFunction.Clone(); 144 try { 145 var model = new GaussianProcessModel(problemdata.Dataset, problemdata.TargetVariable, problemdata.AllowedInputVariables, problemdata.TrainingIndices, new[] { 0.0 }, mean, cov); 146 cancellation.ThrowIfCancellationRequested(); 147 model.FixParameters(); 148 var sol = new GaussianProcessRegressionSolution(model, problemdata); 149 if (newSolution.TrainingMeanSquaredError > sol.TrainingMeanSquaredError) { 150 newSolution = sol; 151 } 152 } catch (ArgumentException) { } 153 return newSolution; 154 } 155 136 156 } 137 157 } -
branches/EfficientGlobalOptimization/HeuristicLab.Algorithms.EGO/Operators/ModelQualityAnalyzer.cs
r15064 r15338 35 35 [Item("ModelQualityAnalyzer", "Collects RealVectors into a modifiablbe dataset")] 36 36 [StorableClass] 37 public class ModelQualityAnalyzer : SingleSuccessorOperator, IAnalyzer {37 public class ModelQualityAnalyzer : SingleSuccessorOperator, IAnalyzer, IResultsOperator { 38 38 public override bool CanChangeName => true; 39 39 public bool EnabledByDefault => false; -
branches/EfficientGlobalOptimization/HeuristicLab.Algorithms.EGO/Operators/VariableVariabilityAnalyzer.cs
r15064 r15338 35 35 [Item("VariableVariabilityAnalyzer", "Analyzes the correlation between perdictions and actual fitness values")] 36 36 [StorableClass] 37 public class VariableVariabilityAnalyzer : SingleSuccessorOperator, IAnalyzer {37 public class VariableVariabilityAnalyzer : SingleSuccessorOperator, IAnalyzer, IResultsOperator { 38 38 public override bool CanChangeName => true; 39 39 public bool EnabledByDefault => false;
Note: See TracChangeset
for help on using the changeset viewer.