Free cookie consent management tool by TermsFeed Policy Generator

source: branches/2745_EfficientGlobalOptimization/HeuristicLab.Algorithms.EGO/AdaptiveSamplingAlgorithm.cs @ 18174

Last change on this file since 18174 was 17332, checked in by bwerth, 5 years ago

#2745 updated persistence to HEAL.Attic

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