Free cookie consent management tool by TermsFeed Policy Generator

source: branches/EfficientGlobalOptimization/HeuristicLab.Algorithms.EGO/AdaptiveSamplingAlgorithm.cs @ 15258

Last change on this file since 15258 was 15064, checked in by bwerth, 7 years ago

#2745 implemented EGO as EngineAlgorithm + some simplifications in the IInfillCriterion interface

File size: 28.8 KB
Line 
1using System;
2using System.Collections.Generic;
3using System.Linq;
4using HeuristicLab.Algorithms.DataAnalysis;
5using HeuristicLab.Analysis;
6using HeuristicLab.Common;
7using HeuristicLab.Core;
8using HeuristicLab.Data;
9using HeuristicLab.Encodings.RealVectorEncoding;
10using HeuristicLab.Operators;
11using HeuristicLab.Optimization;
12using HeuristicLab.Optimization.Operators;
13using HeuristicLab.Parameters;
14using HeuristicLab.Persistence.Default.CompositeSerializers.Storable;
15using HeuristicLab.Problems.DataAnalysis;
16using HeuristicLab.Random;
17
18namespace HeuristicLab.Algorithms.EGO {
19  [Item("Adaptive Sampling Algorithm (EGO)", "An adaptive sampling algorithm.")]
20  [Creatable(CreatableAttribute.Categories.SingleSolutionAlgorithms, Priority = 150)]
21  [StorableClass]
22  public class AdaptiveSamplingAlgorithm : HeuristicOptimizationEngineAlgorithm, IStorableContent {
23    public string Filename { get; set; }
24
25    #region Problem Properties
26    public override Type ProblemType => typeof(IHeuristicOptimizationProblem);
27    private ISingleObjectiveHeuristicOptimizationProblem SingleObjectiveProblem => Problem as ISingleObjectiveHeuristicOptimizationProblem;
28    #endregion
29
30    #region Parameter Names
31    private const string InfillCriterionParameterName = "InfillCriterion";
32    private const string InitialEvaluationsParameterName = "Initial Evaluations";
33    private const string TerminatorParameterName = "Terminator";
34    private const string SeedParameterName = "Seed";
35    private const string SetSeedRandomlyParameterName = "SetSeedRandomly";
36    private const string RegressionAlgorithmParameterName = "RegressionAlgorithm";
37    private const string InfillOptimizationAlgorithmParameterName = "InfillOptimizationAlgorithm";
38    private const string AnalyzerParameterName = "Analyzers";
39    private const string RemoveDuplicatesParamterName = "PerturbDuplicates";
40    private const string MaxModelSizeParameterName = "Maximal Model Size";
41    #endregion
42
43    #region Parameter Properties
44    public IFixedValueParameter<IntValue> SeedParameter => (IFixedValueParameter<IntValue>)Parameters[SeedParameterName];
45    public IFixedValueParameter<BoolValue> SetSeedRandomlyParameter => (IFixedValueParameter<BoolValue>)Parameters[SetSeedRandomlyParameterName];
46    public IFixedValueParameter<MultiTerminator> TerminatorParameter => (IFixedValueParameter<MultiTerminator>)Parameters[TerminatorParameterName];
47    public IFixedValueParameter<IntValue> InitialEvaluationsParameter => (IFixedValueParameter<IntValue>)Parameters[InitialEvaluationsParameterName];
48    public IConstrainedValueParameter<IInfillCriterion> InfillCriterionParameter => Parameters[InfillCriterionParameterName] as IConstrainedValueParameter<IInfillCriterion>;
49    public IValueParameter<Algorithm> InfillOptimizationAlgorithmParameter => Parameters[InfillOptimizationAlgorithmParameterName] as IValueParameter<Algorithm>;
50    public IValueParameter<IDataAnalysisAlgorithm<IRegressionProblem>> RegressionAlgorithmParameter => Parameters[RegressionAlgorithmParameterName] as IValueParameter<IDataAnalysisAlgorithm<IRegressionProblem>>;
51    private IFixedValueParameter<MultiAnalyzer> AnalyzerParameter => (IFixedValueParameter<MultiAnalyzer>)Parameters[AnalyzerParameterName];
52    public IFixedValueParameter<BoolValue> RemoveDuplicatesParameter => (IFixedValueParameter<BoolValue>)Parameters[RemoveDuplicatesParamterName];
53    public IFixedValueParameter<IntValue> MaxModelSizeParameter => (IFixedValueParameter<IntValue>)Parameters[MaxModelSizeParameterName];
54    #endregion
55
56    #region Properties
57    public int Seed => SeedParameter.Value.Value;
58    public bool SetSeedRandomly => SetSeedRandomlyParameter.Value.Value;
59    public MultiTerminator Terminator => TerminatorParameter.Value;
60    public MultiAnalyzer Analyzer => AnalyzerParameter.Value;
61    public int InitialEvaluations => InitialEvaluationsParameter.Value.Value;
62    public IInfillCriterion InfillCriterion => InfillCriterionParameter.Value;
63    public Algorithm InfillOptimizationAlgorithm => InfillOptimizationAlgorithmParameter.Value;
64    public IDataAnalysisAlgorithm<IRegressionProblem> RegressionAlgorithm => RegressionAlgorithmParameter.Value;
65    public bool RemoveDuplicates => RemoveDuplicatesParameter.Value.Value;
66    public int MaxModelSize => MaxModelSizeParameter.Value.Value;
67    #endregion
68
69    #region Helper Properties
70    private SolutionsCreator SolutionsCreator => OperatorGraph.Iterate().OfType<SolutionsCreator>().First();
71    #endregion
72
73    #region Preconfigured Analyzers
74    [Storable]
75    private BestAverageWorstQualityAnalyzer singleObjectiveQualityAnalyzer;
76    [Storable]
77    private CorrelationAnalyzer correlationAnalyzer;
78    [Storable]
79    private EvaluatedSolutionsAnalyzer sampleAnalyzer;
80    [Storable]
81    private ModelQualityAnalyzer modelAnalyzer;
82    [Storable]
83    private VariableVariabilityAnalyzer variabilityAnalyzer;
84    [Storable]
85    private FitnessClusteringAnalyzer fitnessClusterAnalyzer;
86    #endregion
87
88    #region Preconfigured Terminators
89    [Storable]
90    private ComparisonTerminator<IntValue> evaluationsTerminator;
91    [Storable]
92    private ExecutionTimeTerminator executionTimeTerminator;
93    [Storable]
94    private SingleObjectiveQualityTerminator qualityTerminator;
95    #endregion
96
97    #region Problem-dependent Operators
98    [Storable]
99    private SampleCollector sampleCollector;
100    [Storable]
101    private InfillSolver infillSolver;
102    [Storable]
103    private SolutionsCreator infillSolutionsCreator;
104    #endregion
105
106    #region Constructors
107    [StorableConstructor]
108    protected AdaptiveSamplingAlgorithm(bool deserializing) : base(deserializing) { }
109    [StorableHook(HookType.AfterDeserialization)]
110    private void AfterDeserialization() {
111      Initialize();
112    }
113    protected AdaptiveSamplingAlgorithm(AdaptiveSamplingAlgorithm original, Cloner cloner) : base(original, cloner) {
114      singleObjectiveQualityAnalyzer = cloner.Clone(original.singleObjectiveQualityAnalyzer);
115      evaluationsTerminator = cloner.Clone(original.evaluationsTerminator);
116      qualityTerminator = cloner.Clone(original.qualityTerminator);
117      executionTimeTerminator = cloner.Clone(original.executionTimeTerminator);
118      sampleCollector = cloner.Clone(original.sampleCollector);
119      infillSolver = cloner.Clone(original.infillSolver);
120      infillSolutionsCreator = cloner.Clone(original.infillSolutionsCreator);
121      correlationAnalyzer = cloner.Clone(original.correlationAnalyzer);
122      sampleAnalyzer = cloner.Clone(original.sampleAnalyzer);
123      modelAnalyzer = cloner.Clone(original.modelAnalyzer);
124      fitnessClusterAnalyzer = cloner.Clone(original.fitnessClusterAnalyzer);
125      Initialize();
126    }
127    public override IDeepCloneable Clone(Cloner cloner) {
128      return new AdaptiveSamplingAlgorithm(this, cloner);
129    }
130    public AdaptiveSamplingAlgorithm() {
131
132      #region Add parameters
133      var criteria = new ItemSet<IInfillCriterion> {
134        new AugmentedExpectedImprovement(),
135        new ExpectedImprovement(),
136        new ExpectedQuality(),
137        new ExpectedQuantileImprovement(),
138        new MinimalQuantileCriterium(),
139        new NeighbourDistance(),
140        new PluginExpectedImprovement()
141      };
142      var cmaes = new CMAEvolutionStrategy.CMAEvolutionStrategy {
143        MaximumGenerations = 300,
144        PopulationSize = 50,
145        Problem = new InfillProblem()
146      };
147      var model = new GaussianProcessRegression {
148        Problem = new RegressionProblem()
149      };
150      model.CovarianceFunctionParameter.Value = new CovarianceRationalQuadraticIso();
151
152      Parameters.Add(new FixedValueParameter<IntValue>(SeedParameterName, "The random seed used to initialize the new pseudo random number generator.", new IntValue(0)));
153      Parameters.Add(new FixedValueParameter<BoolValue>(SetSeedRandomlyParameterName, "True if the random seed should be set to a random value, otherwise false.", new BoolValue(true)));
154      Parameters.Add(new FixedValueParameter<MultiTerminator>("Terminator", "The termination criteria that defines if the algorithm should continue or stop.", new MultiTerminator()));
155      Parameters.Add(new FixedValueParameter<MultiAnalyzer>(AnalyzerParameterName, "The operator used to analyze the solutions each iteration.", new MultiAnalyzer()));
156      Parameters.Add(new FixedValueParameter<IntValue>(InitialEvaluationsParameterName, "The number of random solutions that are evaluated (in parallel) per iteration.", new IntValue(100)));
157      Parameters.Add(new ConstrainedValueParameter<IInfillCriterion>(InfillCriterionParameterName, "Decision what value should decide the next sample", criteria, criteria.OfType<ExpectedImprovement>().Single()));
158      Parameters.Add(new ValueParameter<IDataAnalysisAlgorithm<IRegressionProblem>>(RegressionAlgorithmParameterName, "The model used to approximate the problem", model));
159      Parameters.Add(new ValueParameter<Algorithm>(InfillOptimizationAlgorithmParameterName, "The algorithm used to solve the expected improvement subproblem", cmaes));
160      Parameters.Add(new FixedValueParameter<BoolValue>(RemoveDuplicatesParamterName, "Whether (almost) duplicate points in the dataset should be perturbed before evaluation (this greatly increases numerical stability for some model types)", new BoolValue(true)));
161      Parameters.Add(new FixedValueParameter<IntValue>("Maximal Model Size", "The maximum number of sample points used to build the model", new IntValue(-1)));
162      #endregion
163
164      #region Create operators
165      var randomCreator = new RandomCreator();
166      var variableCreator = new VariableCreator { Name = "Initialize Variables" };
167      var resultsCollector = new ResultsCollector();
168      var solutionCreator = new SolutionsCreator { Name = "Create Initial Solutions" };
169      var analyzerPlaceholder = new Placeholder { Name = "Analyzer (Placeholder)" };
170      var evaluationsCounter = new IntCounter { Name = "Increment EvaluatedSolutions" };
171      var solutionsCollectorProcessor = new UniformSubScopesProcessor { Name = "Collect Samples to Dataset" };
172      var phaseChecker = new ConditionalBranch { Name = "Inital Samples evaluated?" };
173      var initialPhaseChecker = new Comparator { Name = "Compare Initial Samples to evaluated Solutions" };
174      var modelbuilder = new ModelBuilder { Name = "Build Model" };
175      sampleCollector = new SampleCollector { Name = "Collect Sample" };
176      infillSolutionsCreator = new SolutionsCreator { Name = "Create Adaptive Solutions" };
177      infillSolver = new InfillSolver();
178      var subScopesRemover = new SubScopesRemover();
179      var iterationsCounter = new IntCounter { Name = "Increment Iterations" };
180      var terminationOperator = new TerminationOperator();
181      #endregion
182
183      #region Wire operators
184      const string iterationsVariableName = "Iterations";
185      const string evaluatedSolutionsVariableName = "EvaluatedSolutions";
186      const string datasetVariableName = "SampleSet";
187      const string modelVariableName = "Model";
188      const string initialPhaseVariableName = "InitialPhase";
189      const string infillBoundsVariableName = "InfillBounds";
190
191      OperatorGraph.InitialOperator = randomCreator;
192
193      randomCreator.SeedParameter.Value = null;
194      randomCreator.SeedParameter.ActualName = SeedParameter.Name;
195      randomCreator.SetSeedRandomlyParameter.Value = null;
196      randomCreator.SetSeedRandomlyParameter.ActualName = SetSeedRandomlyParameter.Name;
197      randomCreator.Successor = variableCreator;
198
199      variableCreator.CollectedValues.Add(new ValueParameter<IntValue>(iterationsVariableName, new IntValue(0)));
200      variableCreator.CollectedValues.Add(new ValueParameter<IntValue>(evaluatedSolutionsVariableName, new IntValue(0)));
201      variableCreator.CollectedValues.Add(new ValueParameter<ModifiableDataset>(datasetVariableName, new ModifiableDataset()));
202      variableCreator.CollectedValues.Add(new ValueParameter<IRegressionSolution>(modelVariableName, "The regression solution representing the model for EGO", null));
203      variableCreator.CollectedValues.Add(new FixedValueParameter<BoolValue>(initialPhaseVariableName, new BoolValue(false)));
204      variableCreator.CollectedValues.Add(new ValueParameter<DoubleMatrix>(infillBoundsVariableName));
205      variableCreator.Successor = resultsCollector;
206
207      resultsCollector.CollectedValues.Add(new LookupParameter<IntValue>(iterationsVariableName, "The current iteration number."));
208      resultsCollector.CollectedValues.Add(new LookupParameter<IntValue>(evaluatedSolutionsVariableName, "The current number of evaluated solutions."));
209      resultsCollector.CollectedValues.Add(new LookupParameter<ModifiableDataset>(datasetVariableName, "A dataset containing all evaluated solutions"));
210      resultsCollector.Successor = phaseChecker;
211
212      phaseChecker.ConditionParameter.ActualName = initialPhaseVariableName;
213      phaseChecker.FalseBranch = solutionCreator;
214      phaseChecker.TrueBranch = modelbuilder;
215
216      #region Adaptive Phase
217      modelbuilder.DatasetParameter.ActualName = datasetVariableName;
218      modelbuilder.ModelParameter.ActualName = modelVariableName;
219      modelbuilder.RegressionAlgorithmParameter.ActualName = RegressionAlgorithmParameter.Name;
220      ParameterizeStochasticOperator(modelbuilder);
221      modelbuilder.Successor = infillSolutionsCreator;
222      modelbuilder.MaxModelSizeParameter.ActualName = MaxModelSizeParameter.Name;
223
224      infillSolutionsCreator.SolutionCreatorParameter.Value = infillSolver;
225      infillSolutionsCreator.Successor = evaluationsCounter;
226      infillSolutionsCreator.NumberOfSolutionsParameter.Value = new IntValue(1);
227
228      infillSolver.InfillOptimizationAlgorithmParamter.ActualName = InfillOptimizationAlgorithmParameterName;
229      infillSolver.ModelParameter.ActualName = modelVariableName;
230      infillSolver.RemoveDuplicatesParameter.ActualName = RemoveDuplicatesParameter.Name;
231      infillSolver.InfillBoundsParameter.ActualName = infillBoundsVariableName;
232      #endregion
233
234      #region Initial Phase
235      solutionCreator.NumberOfSolutionsParameter.Value = new IntValue(1);
236      solutionCreator.ParallelParameter.Value.Value = true;
237      solutionCreator.Successor = evaluationsCounter;
238      #endregion
239
240      evaluationsCounter.ValueParameter.ActualName = evaluatedSolutionsVariableName;
241      evaluationsCounter.Increment = null;
242      evaluationsCounter.IncrementParameter.Value = new IntValue(1);
243      evaluationsCounter.Successor = initialPhaseChecker;
244
245      initialPhaseChecker.Comparison = new Comparison(ComparisonType.GreaterOrEqual);
246      initialPhaseChecker.LeftSideParameter.ActualName = evaluatedSolutionsVariableName;
247      initialPhaseChecker.RightSideParameter.ActualName = InitialEvaluationsParameterName;
248      initialPhaseChecker.ResultParameter.ActualName = initialPhaseVariableName;
249      initialPhaseChecker.Successor = analyzerPlaceholder;
250
251      analyzerPlaceholder.OperatorParameter.ActualName = AnalyzerParameter.Name;
252      analyzerPlaceholder.Successor = solutionsCollectorProcessor;
253
254      solutionsCollectorProcessor.Operator = sampleCollector;
255      solutionsCollectorProcessor.Depth.Value = 1;
256      solutionsCollectorProcessor.Successor = subScopesRemover;
257
258      sampleCollector.DatasetParameter.ActualName = datasetVariableName;
259
260      subScopesRemover.RemoveAllSubScopes = true;
261      subScopesRemover.Successor = iterationsCounter;
262
263      iterationsCounter.ValueParameter.ActualName = "Iterations";
264      iterationsCounter.Increment = new IntValue(1);
265      iterationsCounter.Successor = terminationOperator;
266
267
268
269      terminationOperator.TerminatorParameter.ActualName = TerminatorParameter.Name;
270      terminationOperator.ContinueBranch = phaseChecker;
271
272      #endregion
273
274      #region Create analyzers
275      singleObjectiveQualityAnalyzer = new BestAverageWorstQualityAnalyzer();
276      correlationAnalyzer = new CorrelationAnalyzer();
277      correlationAnalyzer.ModelParameter.ActualName = modelVariableName;
278
279      sampleAnalyzer = new EvaluatedSolutionsAnalyzer();
280      sampleAnalyzer.PhaseParameter.ActualName = initialPhaseVariableName;
281
282      modelAnalyzer = new ModelQualityAnalyzer();
283      modelAnalyzer.ModelParameter.ActualName = modelVariableName;
284
285      variabilityAnalyzer = new VariableVariabilityAnalyzer();
286      variabilityAnalyzer.DatasetParameter.ActualName = datasetVariableName;
287      variabilityAnalyzer.InitialEvaluationsParameter.ActualName = InitialEvaluationsParameter.Name;
288
289      fitnessClusterAnalyzer = new FitnessClusteringAnalyzer();
290      fitnessClusterAnalyzer.DatasetParameter.ActualName = datasetVariableName;
291      #endregion
292
293      #region Create terminators
294
295      evaluationsTerminator = new ComparisonTerminator<IntValue>("EvaluatedSolutions", ComparisonType.Less,
296        new IntValue(1000)) { Name = "Evaluated solutions." };
297      qualityTerminator = new SingleObjectiveQualityTerminator { Name = "Quality" };
298      executionTimeTerminator = new ExecutionTimeTerminator(this, new TimeSpanValue(TimeSpan.FromMinutes(5)));
299
300      #endregion
301
302      #region Parameterize
303      UpdateAnalyzers();
304      ParameterizeAnalyzers();
305      UpdateTerminators();
306      #endregion
307
308      Initialize();
309    }
310    #endregion
311
312    private void Initialize() {
313      if (SingleObjectiveProblem != null) {
314        SingleObjectiveProblem.Evaluator.QualityParameter.ActualNameChanged +=
315         Evaluator_QualityParameter_ActualNameChanged;
316      }
317
318      singleObjectiveQualityAnalyzer.CurrentBestQualityParameter.NameChanged +=
319        QualityAnalyzer_CurrentBestQualityParameter_NameChanged;
320      RegisterParameterEvents();
321    }
322
323    #region Parameterization
324    private void ParameterizeTerminators() {
325      if (SingleObjectiveProblem != null)
326        qualityTerminator.Parameterize(singleObjectiveQualityAnalyzer.CurrentBestQualityParameter,
327          SingleObjectiveProblem);
328    }
329    private void ParameterizeAnalyzers() {
330      //TODO how to guarantee ResultsParameters and QualityParameters are really there? This seems hardcoded
331      singleObjectiveQualityAnalyzer.ResultsParameter.ActualName = "Results";
332      singleObjectiveQualityAnalyzer.ResultsParameter.Hidden = true;
333      singleObjectiveQualityAnalyzer.QualityParameter.Depth = 1;
334      correlationAnalyzer.ResultsParameter.ActualName = "Results";
335      correlationAnalyzer.ResultsParameter.Hidden = true;
336      correlationAnalyzer.QualityParameter.Depth = 1;
337      correlationAnalyzer.RealVectorParameter.Depth = 1;
338      sampleAnalyzer.ResultsParameter.ActualName = "Results";
339      sampleAnalyzer.ResultsParameter.Hidden = true;
340      sampleAnalyzer.QualityParameter.Depth = 1;
341      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
348      if (SingleObjectiveProblem == null) return;
349      singleObjectiveQualityAnalyzer.MaximizationParameter.ActualName = SingleObjectiveProblem.MaximizationParameter.Name;
350      singleObjectiveQualityAnalyzer.MaximizationParameter.Hidden = true;
351      singleObjectiveQualityAnalyzer.QualityParameter.ActualName = SingleObjectiveProblem.Evaluator.QualityParameter.ActualName;
352      singleObjectiveQualityAnalyzer.QualityParameter.Hidden = true;
353      singleObjectiveQualityAnalyzer.BestKnownQualityParameter.ActualName = SingleObjectiveProblem.BestKnownQualityParameter.Name;
354      singleObjectiveQualityAnalyzer.BestKnownQualityParameter.Hidden = true;
355      correlationAnalyzer.QualityParameter.ActualName = SingleObjectiveProblem.Evaluator.QualityParameter.ActualName;
356      correlationAnalyzer.QualityParameter.Hidden = true;
357      sampleAnalyzer.QualityParameter.ActualName = SingleObjectiveProblem.Evaluator.QualityParameter.ActualName;
358      sampleAnalyzer.QualityParameter.Hidden = true;
359    }
360    private void ParameterizeSolutionsCreators() {
361      SolutionsCreator.EvaluatorParameter.ActualName = Problem.EvaluatorParameter.Name;
362      SolutionsCreator.SolutionCreatorParameter.ActualName = Problem.SolutionCreatorParameter.Name;
363      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;
370    }
371    private void ParameterizeProblemSpecificOperators() {
372      if (SingleObjectiveProblem == null) throw new ArgumentException("Adaptive sampling requires a single objective problem");
373      infillSolver.MaximizationParameter.ActualName = SingleObjectiveProblem.MaximizationParameter.Name;
374      var rcreator = Problem.SolutionCreator as IRealVectorCreator;
375      if (rcreator == null) throw new ArgumentException("Adaptive sampling requires real vectors as solution candidates");
376      infillSolver.LengthParameter.ActualName = rcreator.LengthParameter.ActualName;
377      infillSolver.BoundsParameter.ActualName = rcreator.BoundsParameter.ActualName;
378      // if (rcreator.LengthParameter.Value != null)
379      infillSolver.LengthParameter.Value = rcreator.LengthParameter.Value;
380      // if (rcreator.BoundsParameter.Value != null)
381      infillSolver.BoundsParameter.Value = rcreator.BoundsParameter.Value;
382      infillSolver.RealVectorParameter.ActualName = rcreator.RealVectorParameter.ActualName;
383
384      sampleCollector.RealVectorParameter.ActualName = rcreator.RealVectorParameter.ActualName;
385      sampleCollector.QualityParameter.ActualName = SingleObjectiveProblem.Evaluator.QualityParameter.ActualName;
386
387      correlationAnalyzer.RealVectorParameter.ActualName = rcreator.RealVectorParameter.ActualName;
388      sampleAnalyzer.RealVectorParameter.ActualName = rcreator.RealVectorParameter.ActualName;
389    }
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
411    private void RegisterParameterEvents() {
412      InfillOptimizationAlgorithmParameter.ValueChanged += OnInfillAlgorithmChanged;
413      InfillOptimizationAlgorithm.ProblemChanged += OnInfillProblemChanged;
414      InfillCriterionParameter.ValueChanged += OnInfillCriterionChanged;
415    }
416    private void OnInfillCriterionChanged(object sender, EventArgs e) {
417      ((InfillProblem)InfillOptimizationAlgorithm.Problem).InfillCriterion = InfillCriterion;
418    }
419    private void OnInfillAlgorithmChanged(object sender, EventArgs e) {
420      InfillOptimizationAlgorithm.Problem = new InfillProblem { InfillCriterion = InfillCriterion };
421      InfillOptimizationAlgorithm.ProblemChanged -= OnInfillProblemChanged; //avoid double attaching
422      InfillOptimizationAlgorithm.ProblemChanged += OnInfillProblemChanged;
423    }
424    private void OnInfillProblemChanged(object sender, EventArgs e) {
425      //enforce an infill problem for the infill optimization algorithm
426      InfillOptimizationAlgorithm.ProblemChanged -= OnInfillProblemChanged;
427      InfillOptimizationAlgorithm.Problem = new InfillProblem { InfillCriterion = InfillCriterion };
428      InfillOptimizationAlgorithm.ProblemChanged += OnInfillProblemChanged;
429    }
430    protected override void OnProblemChanged() {
431      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
446      UpdateAnalyzers();
447      UpdateTerminators();
448    }
449    protected override void RegisterProblemEvents() {
450      base.RegisterProblemEvents();
451      var maximizationParameter = (IValueParameter<BoolValue>)SingleObjectiveProblem?.MaximizationParameter;
452      if (maximizationParameter != null) maximizationParameter.ValueChanged += MaximizationParameter_ValueChanged;
453
454    }
455    protected override void DeregisterProblemEvents() {
456      var maximizationParameter = (IValueParameter<BoolValue>)SingleObjectiveProblem?.MaximizationParameter;
457      if (maximizationParameter != null) maximizationParameter.ValueChanged -= MaximizationParameter_ValueChanged;
458      base.DeregisterProblemEvents();
459    }
460    protected override void Problem_SolutionCreatorChanged(object sender, EventArgs e) {
461      base.Problem_SolutionCreatorChanged(sender, e);
462      ParameterizeStochasticOperator(Problem.SolutionCreator);
463
464      if (SingleObjectiveProblem != null) SingleObjectiveProblem.Evaluator.QualityParameter.ActualNameChanged += Evaluator_QualityParameter_ActualNameChanged;
465
466      ParameterizeSolutionsCreators();
467      ParameterizeAnalyzers();
468    }
469    protected override void Problem_EvaluatorChanged(object sender, EventArgs e) {
470      base.Problem_EvaluatorChanged(sender, e);
471      foreach (var @operator in Problem.Operators.OfType<IOperator>())
472        ParameterizeStochasticOperator(@operator);
473
474      UpdateAnalyzers();
475
476      ParameterizeSolutionsCreators();
477    }
478    protected override void Problem_OperatorsChanged(object sender, EventArgs e) {
479      base.Problem_OperatorsChanged(sender, e);
480      //TODO ParameterizeIterationBasedOperators();
481      UpdateTerminators();
482    }
483    private void MaximizationParameter_ValueChanged(object sender, EventArgs e) {
484      ParameterizeTerminators();
485    }
486    private void Evaluator_QualityParameter_ActualNameChanged(object sender, EventArgs e) {
487      ParameterizeAnalyzers();
488    }
489    private void QualityAnalyzer_CurrentBestQualityParameter_NameChanged(object sender, EventArgs e) {
490      ParameterizeTerminators();
491    }
492    #endregion
493
494    #region Updates
495    private void UpdateAnalyzers() {
496      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>())
507        Analyzer.Operators.Add(analyzer, analyzer.EnabledByDefault);
508    }
509    private void UpdateTerminators() {
510      var newTerminators = new Dictionary<ITerminator, bool> {
511        {
512          evaluationsTerminator,
513          !Terminator.Operators.Contains(evaluationsTerminator) ||
514          Terminator.Operators.ItemChecked(evaluationsTerminator)
515        }, {
516          executionTimeTerminator,
517          Terminator.Operators.Contains(executionTimeTerminator) &&
518          Terminator.Operators.ItemChecked(executionTimeTerminator)
519        }
520      };
521      if (Problem != null) {
522        if (SingleObjectiveProblem != null)
523          newTerminators.Add(qualityTerminator,
524            Terminator.Operators.Contains(qualityTerminator) && Terminator.Operators.ItemChecked(qualityTerminator));
525        foreach (var terminator in Problem.Operators.OfType<ITerminator>())
526          newTerminators.Add(terminator,
527            !Terminator.Operators.Contains(terminator) || Terminator.Operators.ItemChecked(terminator));
528      }
529
530      Terminator.Operators.Clear();
531      foreach (var newTerminator in newTerminators)
532        Terminator.Operators.Add(newTerminator.Key, newTerminator.Value);
533    }
534    #endregion
535
536  }
537
538}
Note: See TracBrowser for help on using the repository browser.