Free cookie consent management tool by TermsFeed Policy Generator

source: branches/EfficientGlobalOptimization/HeuristicLab.Algorithms.EGO/DiscreteEGO/DiscreteAdaptiveSamplingAlgorithm.cs @ 15870

Last change on this file since 15870 was 15343, checked in by bwerth, 7 years ago

#2745 added discretized EGO-version for use with IntegerVectors

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