- Timestamp:
- 08/29/17 11:28:16 (7 years ago)
- Location:
- branches/EfficientGlobalOptimization/HeuristicLab.Algorithms.EGO/DiscreteEGO
- Files:
-
- 1 added
- 7 copied
Legend:
- Unmodified
- Added
- Removed
-
branches/EfficientGlobalOptimization/HeuristicLab.Algorithms.EGO/DiscreteEGO/DiscreteAdaptiveSamplingAlgorithm.cs
r15340 r15343 8 8 using HeuristicLab.Core; 9 9 using HeuristicLab.Data; 10 using HeuristicLab.Encodings. RealVectorEncoding;10 using HeuristicLab.Encodings.IntegerVectorEncoding; 11 11 using HeuristicLab.Operators; 12 12 using HeuristicLab.Optimization; … … 18 18 19 19 namespace HeuristicLab.Algorithms.EGO { 20 [Item(" Adaptive Sampling Algorithm (EGO)", "Anadaptive sampling algorithm.")]20 [Item("Discrete Adaptive Sampling Algorithm (D-EGO)", "A discrete adaptive sampling algorithm.")] 21 21 [Creatable(CreatableAttribute.Categories.SingleSolutionAlgorithms, Priority = 150)] 22 22 [StorableClass] 23 public class AdaptiveSamplingAlgorithm : HeuristicOptimizationEngineAlgorithm, IStorableContent {23 public class DiscreteAdaptiveSamplingAlgorithm : HeuristicOptimizationEngineAlgorithm, IStorableContent { 24 24 public string Filename { get; set; } 25 25 … … 80 80 private BestAverageWorstQualityAnalyzer singleObjectiveQualityAnalyzer; 81 81 [Storable] 82 private CorrelationAnalyzer correlationAnalyzer;83 [Storable] 84 private EvaluatedSolutionsAnalyzer sampleAnalyzer;82 private DiscreteCorrelationAnalyzer correlationAnalyzer; 83 [Storable] 84 private DiscreteEvaluatedSolutionsAnalyzer sampleAnalyzer; 85 85 [Storable] 86 86 private ModelQualityAnalyzer modelAnalyzer; … … 102 102 #region Problem-dependent Operators 103 103 [Storable] 104 private SampleCollector sampleCollector;105 [Storable] 106 private InfillSolver infillSolver;104 private DiscreteSampleCollector sampleCollector; 105 [Storable] 106 private DiscreteInfillSolver infillSolver; 107 107 [Storable] 108 108 private SolutionsCreator infillSolutionsCreator; … … 112 112 #region Constructors 113 113 [StorableConstructor] 114 protected AdaptiveSamplingAlgorithm(bool deserializing) : base(deserializing) { }114 protected DiscreteAdaptiveSamplingAlgorithm(bool deserializing) : base(deserializing) { } 115 115 [StorableHook(HookType.AfterDeserialization)] 116 116 private void AfterDeserialization() { 117 117 Initialize(); 118 118 } 119 protected AdaptiveSamplingAlgorithm(AdaptiveSamplingAlgorithm original, Cloner cloner) : base(original, cloner) {119 protected DiscreteAdaptiveSamplingAlgorithm(DiscreteAdaptiveSamplingAlgorithm original, Cloner cloner) : base(original, cloner) { 120 120 singleObjectiveQualityAnalyzer = cloner.Clone(original.singleObjectiveQualityAnalyzer); 121 121 evaluationsTerminator = cloner.Clone(original.evaluationsTerminator); … … 134 134 } 135 135 public override IDeepCloneable Clone(Cloner cloner) { 136 return new AdaptiveSamplingAlgorithm(this, cloner);137 } 138 public AdaptiveSamplingAlgorithm() {136 return new DiscreteAdaptiveSamplingAlgorithm(this, cloner); 137 } 138 public DiscreteAdaptiveSamplingAlgorithm() { 139 139 140 140 #region Add parameters … … 148 148 new PluginExpectedImprovement() 149 149 }; 150 var cmaes = new CMAEvolutionStrategy.CMAEvolutionStrategy{151 MaximumGenerations = 300,152 PopulationSize = 50,153 Problem = new InfillProblem()150 var cmaes = new OffspringSelectionGeneticAlgorithm.OffspringSelectionGeneticAlgorithm { 151 MaximumGenerations = new IntValue(300), 152 PopulationSize = new IntValue(50), 153 Problem = new DiscreteInfillProblem() 154 154 }; 155 155 var model = new GaussianProcessRegression { … … 194 194 Operators.Add(modelbuilder); 195 195 196 sampleCollector = new SampleCollector { Name = "Collect Sample" };196 sampleCollector = new DiscreteSampleCollector { Name = "Collect Sample" }; 197 197 Operators.Add(sampleCollector); 198 198 infillSolutionsCreator = new SolutionsCreator { Name = "Create Adaptive Solutions" }; 199 199 Operators.Add(infillSolutionsCreator); 200 infillSolver = new InfillSolver();200 infillSolver = new DiscreteInfillSolver(); 201 201 Operators.Add(infillSolver); 202 202 … … 230 230 variableCreator.CollectedValues.Add(new ValueParameter<IRegressionSolution>(modelVariableName, "The regression solution representing the model for EGO", null)); 231 231 variableCreator.CollectedValues.Add(new FixedValueParameter<BoolValue>(initialPhaseVariableName, new BoolValue(false))); 232 variableCreator.CollectedValues.Add(new ValueParameter< DoubleMatrix>(infillBoundsVariableName));232 variableCreator.CollectedValues.Add(new ValueParameter<IntMatrix>(infillBoundsVariableName)); 233 233 variableCreator.Successor = resultsCollector; 234 234 … … 301 301 Operators.Add(singleObjectiveQualityAnalyzer); 302 302 303 correlationAnalyzer = new CorrelationAnalyzer();303 correlationAnalyzer = new DiscreteCorrelationAnalyzer(); 304 304 correlationAnalyzer.ModelParameter.ActualName = modelVariableName; 305 305 Operators.Add(correlationAnalyzer); 306 306 307 sampleAnalyzer = new EvaluatedSolutionsAnalyzer();307 sampleAnalyzer = new DiscreteEvaluatedSolutionsAnalyzer(); 308 308 sampleAnalyzer.PhaseParameter.ActualName = initialPhaseVariableName; 309 309 Operators.Add(sampleAnalyzer); … … 354 354 public override void Start(CancellationToken cancellationToken) { 355 355 ParameterizeProblemSpecificOperators(); 356 (( InfillProblem)InfillOptimizationAlgorithm.Problem).InfillCriterion = InfillCriterion;356 ((DiscreteInfillProblem)InfillOptimizationAlgorithm.Problem).InfillCriterion = InfillCriterion; 357 357 ParameterizeCancellableOperators(cancellationToken); 358 358 base.Start(cancellationToken); … … 387 387 singleObjectiveQualityAnalyzer.QualityParameter.Depth = 1; 388 388 correlationAnalyzer.QualityParameter.Depth = 1; 389 correlationAnalyzer. RealVectorParameter.Depth = 1;389 correlationAnalyzer.IntegerVectorParameter.Depth = 1; 390 390 sampleAnalyzer.QualityParameter.Depth = 1; 391 sampleAnalyzer. RealVectorParameter.Depth = 1;391 sampleAnalyzer.IntegerVectorParameter.Depth = 1; 392 392 393 393 if (SingleObjectiveProblem == null) return; … … 418 418 if (SingleObjectiveProblem == null) throw new ArgumentException("Adaptive sampling requires a single objective problem"); 419 419 infillSolver.MaximizationParameter.ActualName = SingleObjectiveProblem.MaximizationParameter.Name; 420 var rcreator = Problem.SolutionCreator as I RealVectorCreator;421 if (rcreator == null) throw new ArgumentException(" Adaptive sampling requires realvectors as solution candidates");420 var rcreator = Problem.SolutionCreator as IIntegerVectorCreator; 421 if (rcreator == null) throw new ArgumentException("Discrete Adaptive sampling requires integer vectors as solution candidates"); 422 422 423 423 infillSolver.LengthParameter.ActualName = rcreator.LengthParameter.ActualName; … … 425 425 infillSolver.LengthParameter.Value = rcreator.LengthParameter.Value; 426 426 infillSolver.BoundsParameter.Value = rcreator.BoundsParameter.Value; 427 infillSolver. RealVectorParameter.ActualName = rcreator.RealVectorParameter.ActualName;428 429 sampleCollector. RealVectorParameter.ActualName = rcreator.RealVectorParameter.ActualName;427 infillSolver.IntegerVectorParameter.ActualName = rcreator.IntegerVectorParameter.ActualName; 428 429 sampleCollector.IntegerVectorParameter.ActualName = rcreator.IntegerVectorParameter.ActualName; 430 430 sampleCollector.QualityParameter.ActualName = SingleObjectiveProblem.Evaluator.QualityParameter.ActualName; 431 431 432 correlationAnalyzer. RealVectorParameter.ActualName = rcreator.RealVectorParameter.ActualName;433 sampleAnalyzer. RealVectorParameter.ActualName = rcreator.RealVectorParameter.ActualName;432 correlationAnalyzer.IntegerVectorParameter.ActualName = rcreator.IntegerVectorParameter.ActualName; 433 sampleAnalyzer.IntegerVectorParameter.ActualName = rcreator.IntegerVectorParameter.ActualName; 434 434 } 435 435 private void ParameterizeCancellableOperators(CancellationToken cancellation) { … … 451 451 } 452 452 private void OnInfillCriterionChanged(object sender, EventArgs e) { 453 (( InfillProblem)InfillOptimizationAlgorithm.Problem).InfillCriterion = InfillCriterion;453 ((DiscreteInfillProblem)InfillOptimizationAlgorithm.Problem).InfillCriterion = InfillCriterion; 454 454 } 455 455 private void OnInfillAlgorithmChanged(object sender, EventArgs e) { 456 InfillOptimizationAlgorithm.Problem = new InfillProblem { InfillCriterion = InfillCriterion };456 InfillOptimizationAlgorithm.Problem = new DiscreteInfillProblem { InfillCriterion = InfillCriterion }; 457 457 InfillOptimizationAlgorithm.ProblemChanged -= OnInfillProblemChanged; //avoid double attaching 458 458 InfillOptimizationAlgorithm.ProblemChanged += OnInfillProblemChanged; … … 461 461 //enforce an infill problem for the infill optimization algorithm 462 462 InfillOptimizationAlgorithm.ProblemChanged -= OnInfillProblemChanged; 463 InfillOptimizationAlgorithm.Problem = new InfillProblem { InfillCriterion = InfillCriterion };463 InfillOptimizationAlgorithm.Problem = new DiscreteInfillProblem { InfillCriterion = InfillCriterion }; 464 464 InfillOptimizationAlgorithm.ProblemChanged += OnInfillProblemChanged; 465 465 } -
branches/EfficientGlobalOptimization/HeuristicLab.Algorithms.EGO/DiscreteEGO/DiscreteCorrelationAnalyzer.cs
r15340 r15343 26 26 using HeuristicLab.Core; 27 27 using HeuristicLab.Data; 28 using HeuristicLab.Encodings. RealVectorEncoding;28 using HeuristicLab.Encodings.IntegerVectorEncoding; 29 29 using HeuristicLab.Operators; 30 30 using HeuristicLab.Optimization; … … 34 34 35 35 namespace HeuristicLab.Algorithms.EGO { 36 [Item(" CorrelationAnalyzer", "Analyzes the correlation between perdictions and actual fitness values")]36 [Item("DiscreteCorrelationAnalyzer", "Analyzes the correlation between perdictions and actual fitness values")] 37 37 [StorableClass] 38 public class CorrelationAnalyzer : SingleSuccessorOperator, IAnalyzer, IResultsOperator {38 public class DiscreteCorrelationAnalyzer : SingleSuccessorOperator, IAnalyzer, IResultsOperator { 39 39 public override bool CanChangeName => true; 40 40 public bool EnabledByDefault => false; 41 41 42 public IScopeTreeLookupParameter< RealVector> RealVectorParameter => (IScopeTreeLookupParameter<RealVector>)Parameters["RealVector"];42 public IScopeTreeLookupParameter<IntegerVector> IntegerVectorParameter => (IScopeTreeLookupParameter<IntegerVector>)Parameters["IntegerVector"]; 43 43 public IScopeTreeLookupParameter<DoubleValue> QualityParameter => (IScopeTreeLookupParameter<DoubleValue>)Parameters["Quality"]; 44 44 public ILookupParameter<IRegressionSolution> ModelParameter => (ILookupParameter<IRegressionSolution>)Parameters["Model"]; … … 49 49 50 50 [StorableConstructor] 51 protected CorrelationAnalyzer(bool deserializing) : base(deserializing) { }52 protected CorrelationAnalyzer(CorrelationAnalyzer original, Cloner cloner) : base(original, cloner) { }53 public CorrelationAnalyzer() {54 Parameters.Add(new ScopeTreeLookupParameter< RealVector>("RealVector", "The vector which should be collected."));51 protected DiscreteCorrelationAnalyzer(bool deserializing) : base(deserializing) { } 52 protected DiscreteCorrelationAnalyzer(DiscreteCorrelationAnalyzer original, Cloner cloner) : base(original, cloner) { } 53 public DiscreteCorrelationAnalyzer() { 54 Parameters.Add(new ScopeTreeLookupParameter<IntegerVector>("IntegerVector", "The vector which should be collected.")); 55 55 Parameters.Add(new ScopeTreeLookupParameter<DoubleValue>("Quality", "The quality associated which this vector")); 56 56 Parameters.Add(new LookupParameter<IRegressionSolution>("Model", "The model of this iteration")); … … 59 59 60 60 public override IDeepCloneable Clone(Cloner cloner) { 61 return new CorrelationAnalyzer(this, cloner);61 return new DiscreteCorrelationAnalyzer(this, cloner); 62 62 } 63 63 … … 66 66 var results = ResultsParameter.ActualValue; 67 67 var q = QualityParameter.ActualValue.Select(x => x.Value).ToArray(); 68 var p = RealVectorParameter.ActualValue.ToArray();68 var p = IntegerVectorParameter.ActualValue.ToArray(); 69 69 if (model == null) return base.Apply(); 70 70 var plot = CreateScatterPlotResult(results); -
branches/EfficientGlobalOptimization/HeuristicLab.Algorithms.EGO/DiscreteEGO/DiscreteEfficientGlobalOptimizationAlgorithm.cs
r15340 r15343 25 25 using System.Threading; 26 26 using HeuristicLab.Algorithms.DataAnalysis; 27 using HeuristicLab.Algorithms.OffspringSelectionGeneticAlgorithm; 27 28 using HeuristicLab.Analysis; 28 29 using HeuristicLab.Common; 29 30 using HeuristicLab.Core; 30 31 using HeuristicLab.Data; 31 using HeuristicLab.Encodings. RealVectorEncoding;32 using HeuristicLab.Encodings.IntegerVectorEncoding; 32 33 using HeuristicLab.Optimization; 33 34 using HeuristicLab.Parameters; … … 40 41 [StorableClass] 41 42 [Creatable(CreatableAttribute.Categories.Algorithms, Priority = 95)] 42 [Item(" EfficientGlobalOptimizationAlgorithm", "Solves a problem by sequentially learning a model, solving a subproblem on the model and evaluating the best found solution for this subproblem.")]43 public class EfficientGlobalOptimizationAlgorithm : BasicAlgorithm, ISurrogateAlgorithm<RealVector> {43 [Item("DiscreteEfficientGlobalOptimizationAlgorithm", "Solves a problem by sequentially learning a model, solving a subproblem on the model and evaluating the best found solution for this subproblem.")] 44 public class DiscreteEfficientGlobalOptimizationAlgorithm : BasicAlgorithm, ISurrogateAlgorithm<IntegerVector> { 44 45 #region Basic-Alg-Essentials 45 46 public override bool SupportsPause => true; … … 95 96 public IFixedValueParameter<BoolValue> RemoveDuplicatesParameter => Parameters[RemoveDuplicatesParamterName] as IFixedValueParameter<BoolValue>; 96 97 public IFixedValueParameter<FileValue> InitialSamplesParameter => Parameters[InitialSamplesParameterName] as IFixedValueParameter<FileValue>; 97 public IValueParameter< RealVector> BaselineVectorParameter => Parameters[BaselineVectorParameterName] as IValueParameter<RealVector>;98 public IConstrainedValueParameter<IInitialSampling > InitialSamplingPlanParameter => Parameters[InitialSamplingPlanParamterName] as IConstrainedValueParameter<IInitialSampling>;98 public IValueParameter<IntegerVector> BaselineVectorParameter => Parameters[BaselineVectorParameterName] as IValueParameter<IntegerVector>; 99 public IConstrainedValueParameter<IInitialSampling<IntegerVector>> InitialSamplingPlanParameter => Parameters[InitialSamplingPlanParamterName] as IConstrainedValueParameter<IInitialSampling<IntegerVector>>; 99 100 #endregion 100 101 … … 111 112 public bool SetSeedRandomly => SetSeedRandomlyParameter.Value.Value; 112 113 public int MaximalDatasetSize => MaximalDataSetSizeParameter.Value.Value; 113 private IEnumerable<Tuple< RealVector, double>> DataSamples => Samples.Count > MaximalDatasetSize && MaximalDatasetSize > 0114 private IEnumerable<Tuple<IntegerVector, double>> DataSamples => Samples.Count > MaximalDatasetSize && MaximalDatasetSize > 0 114 115 ? Samples.Skip(Samples.Count - MaximalDatasetSize) 115 116 : Samples; 116 117 private bool RemoveDuplicates => RemoveDuplicatesParameter.Value.Value; 117 private RealVector BaselineVector => BaselineVectorParameter.Value;118 private IInitialSampling InitialSamplingPlan => InitialSamplingPlanParameter.Value;118 private IntegerVector BaselineVector => BaselineVectorParameter.Value; 119 private IInitialSampling<IntegerVector> InitialSamplingPlan => InitialSamplingPlanParameter.Value; 119 120 #endregion 120 121 … … 123 124 private IRandom Random = new MersenneTwister(); 124 125 [Storable] 125 private List<Tuple< RealVector, double>> Samples;126 private List<Tuple<IntegerVector, double>> Samples; 126 127 [Storable] 127 private List<Tuple< RealVector, double>> InitialSamples;128 private List<Tuple<IntegerVector, double>> InitialSamples; 128 129 #endregion 129 130 … … 133 134 set { ((DoubleValue)Results[BestQualityResultName].Value).Value = value; } 134 135 } 135 private RealVector ResultsBestSolution {136 get { return ( RealVector)Results[BestSolutionResultName].Value; }136 private IntegerVector ResultsBestSolution { 137 get { return (IntegerVector)Results[BestSolutionResultName].Value; } 137 138 set { Results[BestSolutionResultName].Value = value; } 138 139 } … … 157 158 #region HLConstructors 158 159 [StorableConstructor] 159 protected EfficientGlobalOptimizationAlgorithm(bool deserializing) : base(deserializing) { }160 protected DiscreteEfficientGlobalOptimizationAlgorithm(bool deserializing) : base(deserializing) { } 160 161 [StorableHook(HookType.AfterDeserialization)] 161 162 protected void AfterDeseialization() { 162 163 RegisterEventhandlers(); 163 164 } 164 protected EfficientGlobalOptimizationAlgorithm(EfficientGlobalOptimizationAlgorithm original, Cloner cloner) : base(original, cloner) {165 protected DiscreteEfficientGlobalOptimizationAlgorithm(DiscreteEfficientGlobalOptimizationAlgorithm original, Cloner cloner) : base(original, cloner) { 165 166 Random = cloner.Clone(Random); 166 if (original.Samples != null) Samples = original.Samples.Select(x => new Tuple< RealVector, double>(cloner.Clone(x.Item1), x.Item2)).ToList();167 if (original.InitialSamples != null) InitialSamples = original.InitialSamples.Select(x => new Tuple< RealVector, double>(cloner.Clone(x.Item1), x.Item2)).ToList();167 if (original.Samples != null) Samples = original.Samples.Select(x => new Tuple<IntegerVector, double>(cloner.Clone(x.Item1), x.Item2)).ToList(); 168 if (original.InitialSamples != null) InitialSamples = original.InitialSamples.Select(x => new Tuple<IntegerVector, double>(cloner.Clone(x.Item1), x.Item2)).ToList(); 168 169 RegisterEventhandlers(); 169 170 } 170 public override IDeepCloneable Clone(Cloner cloner) { return new EfficientGlobalOptimizationAlgorithm(this, cloner); }171 public EfficientGlobalOptimizationAlgorithm() {171 public override IDeepCloneable Clone(Cloner cloner) { return new DiscreteEfficientGlobalOptimizationAlgorithm(this, cloner); } 172 public DiscreteEfficientGlobalOptimizationAlgorithm() { 172 173 IProblemInstanceExporter dummy = new RegressionProblem(); //this variable is irrelevant 173 174 //the dummy variable enforces a using-Statement for HeuristicLab.Problems.Instances 174 //"new ValueParameter<IDataAnalysisAlgorithm<IRegressionProblem>>" requires no using using-Statement, but nontheless it requires HeuristicLab.Problems.Instances to be referenced175 //"new ValueParameter<IDataAnalysisAlgorithm<IRegressionProblem>>" requires no using-Statement, but nontheless it requires HeuristicLab.Problems.Instances to be referenced 175 176 //Having HeuristicLab.Problems.Instances referenced but not used, causes the Essential-Unit-tests to fail. 176 177 177 var cmaes = new CMAEvolutionStrategy.CMAEvolutionStrategy{178 MaximumGenerations = 300,179 PopulationSize = 50178 var cmaes = new OffspringSelectionGeneticAlgorithm.OffspringSelectionGeneticAlgorithm() { 179 MaximumGenerations = new IntValue(300), 180 PopulationSize = new IntValue(50) 180 181 }; 181 182 var model = new GaussianProcessRegression { … … 195 196 Parameters.Add(new FixedValueParameter<BoolValue>(RemoveDuplicatesParamterName, "Wether duplicate samples should be replaced by a single sample with an averaged quality. This GREATLY decreases the chance of ill conditioned models (unbuildable models) but is not theoretically sound as the model ignores the increasing certainty in this region")); 196 197 Parameters.Add(new FixedValueParameter<FileValue>(InitialSamplesParameterName, "The file specifying some initial samples used to jump start the algorithm. These samples are not counted as evaluations. If InitialEvaluations is more than the samples specified in the file, the rest is uniformly random generated and evaluated.", new FileValue())); 197 Parameters.Add(new ValueParameter< RealVector>(BaselineVectorParameterName, "A vector used to create a baseline, this vector is evaluated once and is not part of the modeling process (has no influence on algorithm performance)"));198 Parameters.Add(new ValueParameter<IntegerVector>(BaselineVectorParameterName, "A vector used to create a baseline, this vector is evaluated once and is not part of the modeling process (has no influence on algorithm performance)")); 198 199 var eqi = new ExpectedQuantileImprovement(); 199 200 eqi.MaxEvaluationsParameter.Value = MaximumEvaluationsParameter.Value; 200 201 var criteria = new ItemSet<IInfillCriterion> { new ExpectedImprovement(), new AugmentedExpectedImprovement(), new ExpectedQuality(), eqi, new MinimalQuantileCriterium(), new PluginExpectedImprovement() }; 201 202 Parameters.Add(new ConstrainedValueParameter<IInfillCriterion>(InfillCriterionParameterName, "Decision what value should decide the next sample", criteria, criteria.First())); 202 var intialSamplingPlans = new ItemSet<IInitialSampling > { new UniformRandomSampling(), new LatinHyperCubeDesignCreator() };203 Parameters.Add(new ConstrainedValueParameter<IInitialSampling >(InitialSamplingPlanParamterName, "Determies the initial samples from which the first model can be built.", intialSamplingPlans, intialSamplingPlans.First()));203 var intialSamplingPlans = new ItemSet<IInitialSampling<IntegerVector>> { new UniformRandomDiscreteSampling() }; 204 Parameters.Add(new ConstrainedValueParameter<IInitialSampling<IntegerVector>>(InitialSamplingPlanParamterName, "Determies the initial samples from which the first model can be built.", intialSamplingPlans, intialSamplingPlans.First())); 204 205 SetInfillProblem(); 205 206 RegisterEventhandlers(); 206 207 } 207 208 #endregion 208 public void SetInitialSamples( RealVector[] individuals, double[] qualities) {209 InitialSamples = individuals.Zip(qualities, (individual, d) => new Tuple< RealVector, double>(individual, d)).ToList();209 public void SetInitialSamples(IntegerVector[] individuals, double[] qualities) { 210 InitialSamples = individuals.Zip(qualities, (individual, d) => new Tuple<IntegerVector, double>(individual, d)).ToList(); 210 211 } 211 212 protected override void Initialize(CancellationToken cancellationToken) { 212 213 base.Initialize(cancellationToken); 213 214 //encoding 214 var enc = Problem.Encoding as RealVectorEncoding;215 if (enc == null) throw new ArgumentException("The EGO algorithm can only be applied to RealVectorEncodings");216 var infillProblem = InfillOptimizationAlgorithm.Problem as InfillProblem;217 if (infillProblem == null) throw new ArgumentException("InfillOptimizationAlgorithm has no InfillProblem. Troubles with Eventhandling?");215 var enc = Problem.Encoding as IntegerVectorEncoding; 216 if (enc == null) throw new ArgumentException("The EGO algorithm can only be applied to IntegerVectorEncodings"); 217 var infillProblem = InfillOptimizationAlgorithm.Problem as DiscreteInfillProblem; 218 if (infillProblem == null) throw new ArgumentException("InfillOptimizationAlgorithm has no DiscreteInfillProblem. Troubles with Eventhandling?"); 218 219 219 220 //random 220 221 if (SetSeedRandomly) SeedParameter.Value.Value = new System.Random().Next(); 221 222 Random.Reset(Seed); 222 Samples = InitialSamples?.ToList() ?? new List<Tuple< RealVector, double>>();223 Samples = InitialSamples?.ToList() ?? new List<Tuple<IntegerVector, double>>(); 223 224 224 225 //results 225 226 Results.Add(new Result(IterationsResultName, new IntValue(0))); 226 227 Results.Add(new Result(EvaluatedSoultionsResultName, new IntValue(Samples.Count))); 227 Results.Add(new Result(BestSolutionResultName, new RealVector(1)));228 Results.Add(new Result(BestSolutionResultName, new IntegerVector(1))); 228 229 Results.Add(new Result(BestQualityResultName, new DoubleValue(Problem.Maximization ? double.MinValue : double.MaxValue))); 229 230 Results.Add(new Result(RegressionSolutionResultName, typeof(IRegressionSolution))); … … 241 242 //initial samples 242 243 if (Samples.Count < InitialEvaluations) { 243 var points = InitialSamplingPlan.GetSamples(InitialEvaluations - Samples.Count, Samples.Select(x => x.Item1).ToArray(), ( RealVectorEncoding)Problem.Encoding, Random);244 var points = InitialSamplingPlan.GetSamples(InitialEvaluations - Samples.Count, Samples.Select(x => x.Item1).ToArray(), (IntegerVectorEncoding)Problem.Encoding, Random); 244 245 foreach (var t in points) { 245 246 try { 246 247 Samples.Add(Evaluate(t)); 247 248 cancellationToken.ThrowIfCancellationRequested(); 248 } finally { 249 } 250 finally { 249 251 Analyze(); 250 252 } … … 259 261 for (var i = 0; i < GenerationSize; i++) { 260 262 var samplepoint = OptimizeInfillProblem(cancellationToken); 263 if (RemoveDuplicates) { 264 265 } 261 266 var sample = Evaluate(samplepoint); 262 267 Samples.Add(sample); … … 264 269 } 265 270 266 } finally { 271 } 272 finally { 267 273 Analyze(); 268 274 } … … 298 304 } 299 305 private void InfillCriterionChanged(object sender, EventArgs e) { 300 var infillProblem = InfillOptimizationAlgorithm.Problem as InfillProblem;301 if (infillProblem == null) throw new ArgumentException("InfillOptimizationAlgorithm has no InfillProblem. Troubles with Eventhandling?");306 var infillProblem = InfillOptimizationAlgorithm.Problem as DiscreteInfillProblem; 307 if (infillProblem == null) throw new ArgumentException("InfillOptimizationAlgorithm has no DiscreteInfillProblem. Troubles with Eventhandling?"); 302 308 infillProblem.InfillCriterion = InfillCriterion; 303 309 } … … 326 332 #region helpers 327 333 private IRegressionSolution BuildModel(CancellationToken cancellationToken) { 328 var dataset = EgoUtilities.GetDataSet(DataSamples.ToList() , RemoveDuplicates);334 var dataset = EgoUtilities.GetDataSet(DataSamples.ToList()); 329 335 var problemdata = new RegressionProblemData(dataset, dataset.VariableNames.Where(x => !x.Equals("output")), "output"); 330 336 problemdata.TrainingPartition.Start = 0; … … 363 369 solution = sol; 364 370 } 365 } catch (ArgumentException) { } 371 } 372 catch (ArgumentException) { } 366 373 } 367 374 … … 380 387 return solution; 381 388 } 382 private RealVector OptimizeInfillProblem(CancellationToken cancellationToken) {389 private IntegerVector OptimizeInfillProblem(CancellationToken cancellationToken) { 383 390 //parameterize and check InfillProblem 384 var infillProblem = InfillOptimizationAlgorithm.Problem as InfillProblem;391 var infillProblem = InfillOptimizationAlgorithm.Problem as DiscreteInfillProblem; 385 392 if (infillProblem == null) throw new ArgumentException("InfillOptimizationAlgorithm does not have an InfillProblem."); 386 393 if (infillProblem.InfillCriterion != InfillCriterion) throw new ArgumentException("InfillCiriterion for Problem is not correctly set."); 387 var enc = Problem.Encoding as RealVectorEncoding;394 var enc = Problem.Encoding as IntegerVectorEncoding; 388 395 infillProblem.Encoding.Bounds = enc.Bounds; 389 396 infillProblem.Encoding.Length = enc.Length; … … 392 399 393 400 394 RealVector bestVector = null;401 IntegerVector bestVector = null; 395 402 var bestValue = infillProblem.Maximization ? double.NegativeInfinity : double.PositiveInfinity; 396 403 for (var i = 0; i < InfillOptimizationRestarts; i++) { … … 399 406 cancellationToken.ThrowIfCancellationRequested(); 400 407 //extract results 401 if (!res.ContainsKey( InfillProblem.BestInfillSolutionResultName)) throw new ArgumentException("The InfillOptimizationAlgorithm did not return a best solution");402 var v = res[ InfillProblem.BestInfillSolutionResultName].Value as RealVector;403 if (!res.ContainsKey( InfillProblem.BestInfillQualityResultName)) throw new ArgumentException("The InfillOptimizationAlgorithm did not return a best quality");404 var d = res[ InfillProblem.BestInfillQualityResultName].Value as DoubleValue;408 if (!res.ContainsKey(DiscreteInfillProblem.BestInfillSolutionResultName)) throw new ArgumentException("The InfillOptimizationAlgorithm did not return a best solution"); 409 var v = res[DiscreteInfillProblem.BestInfillSolutionResultName].Value as IntegerVector; 410 if (!res.ContainsKey(DiscreteInfillProblem.BestInfillQualityResultName)) throw new ArgumentException("The InfillOptimizationAlgorithm did not return a best quality"); 411 var d = res[DiscreteInfillProblem.BestInfillQualityResultName].Value as DoubleValue; 405 412 if (d == null || v == null) throw new ArgumentException("The InfillOptimizationAlgorithm did not return the expected result types"); 406 413 //check for improvement … … 456 463 } 457 464 458 private Individual GetIndividual(RealVector r) { 465 466 467 private Individual GetIndividual(IntegerVector r) { 459 468 var scope = new Scope(); 460 469 scope.Variables.Add(new Variable(Problem.Encoding.Name, r)); 461 470 return new SingleEncodingIndividual(Problem.Encoding, scope); 462 471 } 463 private Tuple< RealVector, double> Evaluate(RealVector point) {464 return new Tuple< RealVector, double>(point, Problem.Evaluate(GetIndividual(point), Random));472 private Tuple<IntegerVector, double> Evaluate(IntegerVector point) { 473 return new Tuple<IntegerVector, double>(point, Problem.Evaluate(GetIndividual(point), Random)); 465 474 } 466 475 467 476 private void SetInfillProblem() { 468 InfillOptimizationAlgorithm.Problem = new InfillProblem { InfillCriterion = InfillCriterion };477 InfillOptimizationAlgorithm.Problem = new DiscreteInfillProblem { InfillCriterion = InfillCriterion }; 469 478 } 470 479 #endregion -
branches/EfficientGlobalOptimization/HeuristicLab.Algorithms.EGO/DiscreteEGO/DiscreteEvaluatedSolutionsAnalyzer.cs
r15340 r15343 26 26 using HeuristicLab.Core; 27 27 using HeuristicLab.Data; 28 using HeuristicLab.Encodings. RealVectorEncoding;28 using HeuristicLab.Encodings.IntegerVectorEncoding; 29 29 using HeuristicLab.Operators; 30 30 using HeuristicLab.Optimization; … … 33 33 34 34 namespace HeuristicLab.Algorithms.EGO { 35 /// <summary> 36 /// A base class for operators that manipulate real-valued vectors. 37 /// </summary> 38 [Item("EvaluatedSolutionsAnalyzer", "Displays the evaluated Solutions for one or two dimensional problems")] 35 [Item("DiscreteEvaluatedSolutionsAnalyzer", "Displays the evaluated Solutions for one or two dimensional problems")] 39 36 [StorableClass] 40 public class EvaluatedSolutionsAnalyzer : SingleSuccessorOperator, IAnalyzer, IResultsOperator {37 public class DiscreteEvaluatedSolutionsAnalyzer : SingleSuccessorOperator, IAnalyzer, IResultsOperator { 41 38 public override bool CanChangeName => true; 42 39 public bool EnabledByDefault => false; 43 40 44 public IScopeTreeLookupParameter< RealVector> RealVectorParameter => (IScopeTreeLookupParameter<RealVector>)Parameters["RealVector"];41 public IScopeTreeLookupParameter<IntegerVector> IntegerVectorParameter => (IScopeTreeLookupParameter<IntegerVector>)Parameters["IntegerVector"]; 45 42 public IScopeTreeLookupParameter<DoubleValue> QualityParameter => (IScopeTreeLookupParameter<DoubleValue>)Parameters["Quality"]; 46 43 public ILookupParameter<ResultCollection> ResultsParameter => (ILookupParameter<ResultCollection>)Parameters["Results"]; … … 53 50 54 51 [StorableConstructor] 55 protected EvaluatedSolutionsAnalyzer(bool deserializing) : base(deserializing) { }56 protected EvaluatedSolutionsAnalyzer(EvaluatedSolutionsAnalyzer original, Cloner cloner) : base(original, cloner) { }57 public EvaluatedSolutionsAnalyzer() {58 Parameters.Add(new ScopeTreeLookupParameter< RealVector>("RealVector", "The vector which should be collected."));52 protected DiscreteEvaluatedSolutionsAnalyzer(bool deserializing) : base(deserializing) { } 53 protected DiscreteEvaluatedSolutionsAnalyzer(DiscreteEvaluatedSolutionsAnalyzer original, Cloner cloner) : base(original, cloner) { } 54 public DiscreteEvaluatedSolutionsAnalyzer() { 55 Parameters.Add(new ScopeTreeLookupParameter<IntegerVector>("IntegerVector", "The vector which should be collected.")); 59 56 Parameters.Add(new ScopeTreeLookupParameter<DoubleValue>("Quality", "The quality associated which this vector")); 60 57 Parameters.Add(new LookupParameter<BoolValue>("InitialPhase", "Whether the initial phase has finished")); … … 63 60 64 61 public override IDeepCloneable Clone(Cloner cloner) { 65 return new EvaluatedSolutionsAnalyzer(this, cloner);62 return new DiscreteEvaluatedSolutionsAnalyzer(this, cloner); 66 63 } 67 64 68 65 public sealed override IOperation Apply() { 69 var p = RealVectorParameter.ActualValue.ToArray();66 var p = IntegerVectorParameter.ActualValue.ToArray(); 70 67 if (p.Length == 0 || p[0].Length > 2 || p[0].Length == 0) return base.Apply(); 71 68 var results = ResultsParameter.ActualValue; -
branches/EfficientGlobalOptimization/HeuristicLab.Algorithms.EGO/DiscreteEGO/DiscreteInfillProblem.cs
r15340 r15343 26 26 using HeuristicLab.Core; 27 27 using HeuristicLab.Data; 28 using HeuristicLab.Encodings.IntegerVectorEncoding; 28 29 using HeuristicLab.Encodings.RealVectorEncoding; 29 30 using HeuristicLab.Optimization; … … 33 34 namespace HeuristicLab.Algorithms.EGO { 34 35 [StorableClass] 35 [Item(" InfillProblem", "A problem for finding the most interesing potential new sampling Points by optimizing some InfillCriterion")]36 public sealed class InfillProblem : SingleObjectiveBasicProblem<RealVectorEncoding> {36 [Item("DiscreteInfillProblem", "A problem for finding the most interesing potential new sampling Points by optimizing some InfillCriterion")] 37 public sealed class DiscreteInfillProblem : SingleObjectiveBasicProblem<IntegerVectorEncoding> { 37 38 38 39 public override bool Maximization => true; … … 47 48 private IInfillCriterion infillCriterion; 48 49 49 public IInfillCriterion InfillCriterion 50 { 50 public IInfillCriterion InfillCriterion { 51 51 get { return infillCriterion; } 52 set 53 { 52 set { 54 53 infillCriterion = value; 55 infillCriterion.Encoding = Encoding;54 infillCriterion.Encoding = GetRealVectorEncoding(Encoding); 56 55 } 57 56 } … … 60 59 #region Constructors 61 60 [StorableConstructor] 62 private InfillProblem(bool deserializing) : base(deserializing) { }63 private InfillProblem(InfillProblem original, Cloner cloner) : base(original, cloner) {61 private DiscreteInfillProblem(bool deserializing) : base(deserializing) { } 62 private DiscreteInfillProblem(DiscreteInfillProblem original, Cloner cloner) : base(original, cloner) { 64 63 infillCriterion = cloner.Clone(original.infillCriterion); 65 64 } 66 public InfillProblem() { }67 public override IDeepCloneable Clone(Cloner cloner) { return new InfillProblem(this, cloner); }65 public DiscreteInfillProblem() { } 66 public override IDeepCloneable Clone(Cloner cloner) { return new DiscreteInfillProblem(this, cloner); } 68 67 #endregion 69 68 70 69 public override double Evaluate(Individual individual, IRandom r) { 71 return !InBounds(individual. RealVector(), Encoding.Bounds) ? double.MinValue : InfillCriterion.Evaluate(individual.RealVector());70 return !InBounds(individual.IntegerVector(), Encoding.Bounds) ? double.MinValue : InfillCriterion.Evaluate(individual.IntegerVector().ToRealVector()); 72 71 } 73 72 public override void Analyze(Individual[] individuals, double[] qualities, ResultCollection results, IRandom random) { … … 76 75 var newQuality = qualities[best]; 77 76 if (!results.ContainsKey(BestInfillQualityResultName)) { 78 results.Add(new Result(BestInfillSolutionResultName, ( RealVector)individuals[best].RealVector().Clone()));77 results.Add(new Result(BestInfillSolutionResultName, (IntegerVector)individuals[best].IntegerVector().Clone())); 79 78 results.Add(new Result(BestInfillQualityResultName, new DoubleValue(newQuality))); 80 79 return; … … 83 82 if (qold == null) throw new ArgumentException("Old best quality is not a double value. Conflicting Analyzers?"); 84 83 if (qold.Value >= newQuality) return; 85 results[BestInfillSolutionResultName].Value = ( RealVector)individuals[best].RealVector().Clone();84 results[BestInfillSolutionResultName].Value = (IntegerVector)individuals[best].IntegerVector().Clone(); 86 85 qold.Value = newQuality; 87 86 } … … 89 88 var bounds = Encoding.Bounds; 90 89 var michalewiczIteration = 0; 90 var sigma = new DoubleArray(new double[] { 1.0 }); 91 91 92 while (true) { 92 93 var neighbour = individual.Copy(); 93 var r = neighbour.RealVector(); 94 switch (random.Next(5)) { 95 case 0: UniformOnePositionManipulator.Apply(random, r, bounds); break; 96 case 1: UniformOnePositionManipulator.Apply(random, r, bounds); break;//FixedNormalAllPositionsManipulator.Apply(random, r, new RealVector(new[] { 0.1 })); break; 97 case 2: MichalewiczNonUniformAllPositionsManipulator.Apply(random, r, bounds, new IntValue(michalewiczIteration++), new IntValue(10000), new DoubleValue(5.0)); break; 98 case 3: MichalewiczNonUniformOnePositionManipulator.Apply(random, r, bounds, new IntValue(michalewiczIteration++), new IntValue(10000), new DoubleValue(5.0)); break; 99 case 4: BreederGeneticAlgorithmManipulator.Apply(random, r, bounds, new DoubleValue(0.1)); break; 94 var r = neighbour.IntegerVector(); 95 switch (random.Next(3) % 3) { 96 case 0: HeuristicLab.Encodings.IntegerVectorEncoding.UniformOnePositionManipulator.Apply(random, r, bounds); break; 97 case 1: HeuristicLab.Encodings.IntegerVectorEncoding.RoundedNormalAllPositionsManipulator.Apply(random, r, bounds, sigma); break;//FixedNormalAllPositionsManipulator.Apply(random, r, new RealVector(new[] { 0.1 })); break; 98 case 2: HeuristicLab.Encodings.IntegerVectorEncoding.UniformSomePositionsManipulator.Apply(random, r, bounds, 0.1); break; 100 99 default: throw new NotImplementedException(); 101 100 } … … 108 107 infillCriterion.RegressionSolution = model; 109 108 infillCriterion.ExpensiveMaximization = expensiveMaximization; 110 infillCriterion.Encoding = Encoding;109 infillCriterion.Encoding = GetRealVectorEncoding(Encoding); 111 110 infillCriterion.Initialize(); 112 111 } 113 112 114 113 #region helpers 115 private static bool InBounds( RealVector r, DoubleMatrix bounds) {114 private static bool InBounds(IntegerVector r, IntMatrix bounds) { 116 115 return !r.Where((t, i) => t < bounds[i % bounds.Rows, 0] || t > bounds[i % bounds.Rows, 1]).Any(); 116 } 117 118 private static RealVectorEncoding GetRealVectorEncoding(IntegerVectorEncoding enc) { 119 var res = new RealVectorEncoding(enc.Length); 120 res.Bounds = new DoubleMatrix(enc.Bounds.Rows, enc.Bounds.Columns); 121 for (int r = 0; r < res.Bounds.Rows; r++) 122 for (int c = 0; c < res.Bounds.Columns; c++) 123 res.Bounds[r, c] = enc.Bounds[r, c]; 124 return res; 125 126 117 127 } 118 128 #endregion -
branches/EfficientGlobalOptimization/HeuristicLab.Algorithms.EGO/DiscreteEGO/DiscreteInfillSolver.cs
r15340 r15343 22 22 using System; 23 23 using System.Threading; 24 using System.Linq; 25 using System.Collections.Generic; 24 26 using HeuristicLab.Common; 25 27 using HeuristicLab.Core; 26 28 using HeuristicLab.Data; 27 using HeuristicLab.Encodings. RealVectorEncoding;29 using HeuristicLab.Encodings.IntegerVectorEncoding; 28 30 using HeuristicLab.Optimization; 29 31 using HeuristicLab.Parameters; … … 32 34 33 35 namespace HeuristicLab.Algorithms.EGO { 34 /// <summary> 35 /// A base class for operators that manipulate real-valued vectors. 36 /// </summary> 37 [Item("InfillSolver", "A RealVectorCreator that creates candidates by optimizing an infill-subproblem")] 36 [Item("DiscreteInfillSolver", "An IntegerVectorCreator that creates candidates by optimizing an infill-subproblem")] 38 37 [StorableClass] 39 public class InfillSolver : RealVectorCreator, ICancellableOperator {38 public class DiscreteInfillSolver : IntegerVectorCreator, ICancellableOperator { 40 39 41 40 public ILookupParameter<IAlgorithm> InfillOptimizationAlgorithmParamter => (ILookupParameter<IAlgorithm>)Parameters["InfillAlgorithm"]; … … 44 43 public ILookupParameter<BoolValue> RemoveDuplicatesParameter => (ILookupParameter<BoolValue>)Parameters["RemoveDuplicates"]; 45 44 public IFixedValueParameter<DoubleValue> DuplicateCutoffParameter => (IFixedValueParameter<DoubleValue>)Parameters["Duplicates Cutoff"]; 46 public ILookupParameter< DoubleMatrix> InfillBoundsParameter => (ILookupParameter<DoubleMatrix>)Parameters["InfillBounds"];45 public ILookupParameter<IntMatrix> InfillBoundsParameter => (ILookupParameter<IntMatrix>)Parameters["InfillBounds"]; 47 46 48 47 public CancellationToken Cancellation { get; set; } 49 48 50 49 [StorableConstructor] 51 protected InfillSolver(bool deserializing) : base(deserializing) { }52 protected InfillSolver(InfillSolver original, Cloner cloner) : base(original, cloner) { }53 public InfillSolver() {50 protected DiscreteInfillSolver(bool deserializing) : base(deserializing) { } 51 protected DiscreteInfillSolver(DiscreteInfillSolver original, Cloner cloner) : base(original, cloner) { } 52 public DiscreteInfillSolver() { 54 53 Parameters.Add(new LookupParameter<IAlgorithm>("InfillAlgorithm", "The algorithm used to optimize the infill problem") { Hidden = true }); 55 54 Parameters.Add(new LookupParameter<IRegressionSolution>("Model", "The RegressionSolution upon which the InfillProblem operates") { Hidden = true }); … … 57 56 Parameters.Add(new LookupParameter<BoolValue>("RemoveDuplicates", "Whether duplicates shall be removed") { Hidden = true }); 58 57 Parameters.Add(new FixedValueParameter<DoubleValue>("Duplicates Cutoff", "The cut off radius for", new DoubleValue(0.01)) { Hidden = false }); 59 Parameters.Add(new LookupParameter< DoubleMatrix>("InfillBounds", "The bounds applied for infill solving") { Hidden = true });58 Parameters.Add(new LookupParameter<IntMatrix>("InfillBounds", "The bounds applied for infill solving") { Hidden = true }); 60 59 } 61 60 62 61 public override IDeepCloneable Clone(Cloner cloner) { 63 return new InfillSolver(this, cloner);62 return new DiscreteInfillSolver(this, cloner); 64 63 } 65 64 66 protected override RealVector Create(IRandom random, IntValue length, DoubleMatrix bounds) {65 protected override IntegerVector Create(IRandom random, IntValue length, IntMatrix bounds) { 67 66 var infillBounds = InfillBoundsParameter.ActualValue; 68 67 if (infillBounds != null && infillBounds.Rows > 0) { … … 75 74 var res = OptimizeInfillProblem(alg, model, max, bounds, length.Value, random); 76 75 var rad = DuplicateCutoffParameter.Value.Value; 77 if (!RemoveDuplicatesParameter.ActualValue.Value || !(GetMinDifference(model.ProblemData.Dataset, res) < rad * rad)) return res; 78 for (var i = 0; i < res.Length; i++) res[i] += random.NextDouble() * rad * 2; 76 if (!RemoveDuplicatesParameter.ActualValue.Value || GetMinDifference(model.ProblemData.Dataset, res) >= rad * rad) return res; 77 78 bool changed = false; 79 var steps = 0; 80 var dims = new List<int>(); 81 82 //TODO this may take a long time to compute if many samples have already been evaluated in the surrounding area 83 //as the preferred region can not be sampled denser and denser due to the disceretization, the variance between two sampled points may be impossible to decease 84 85 //TODO speed up GetMinDifferecnce via tree-structure 86 while (!changed || GetMinDifference(model.ProblemData.Dataset, res) < rad * rad) { 87 if (dims.Count == 0) { 88 if (!changed && steps > 0) throw new ArgumentException("Can not avoid duplicate"); 89 dims = Enumerable.Range(0, res.Length).ToList(); 90 steps++; 91 changed = false; 92 } 93 var i = random.Next(dims.Count); 94 var dim = dims[i]; 95 dims.RemoveAt(i); 96 var step = bounds[dim % bounds.Rows, 2] * steps; 97 var low = checkIntBounds(bounds, dim, res[dim] - step); 98 var high = checkIntBounds(bounds, dim, res[dim] + step); 99 if (!low && !high) continue; 100 else if (low && high) res[dim] += (random.NextDouble() < 0.5 ? -step : step); 101 else if (low) res[dim] -= step; 102 else res[dim] += step; 103 changed = true; 104 } 79 105 return res; 80 106 } 81 107 82 private RealVector OptimizeInfillProblem(IAlgorithm algorithm, IRegressionSolution model, bool maximization, DoubleMatrix bounds, int length, IRandom random) { 83 var infillProblem = algorithm.Problem as InfillProblem; 108 109 private bool checkIntBounds(IntMatrix b, int row, int value) { 110 var bi = row % b.Rows; 111 var l = b[bi, 0]; 112 var h = b[bi, 1]; 113 var s = b[bi, 2]; 114 return l <= value && h >= value && (value - l) % s == 0; 115 } 116 117 private IntegerVector OptimizeInfillProblem(IAlgorithm algorithm, IRegressionSolution model, bool maximization, IntMatrix bounds, int length, IRandom random) { 118 var infillProblem = algorithm.Problem as DiscreteInfillProblem; 84 119 if (infillProblem == null) throw new ArgumentException("The algortihm has no InfillProblem to solve"); 85 120 infillProblem.Encoding.Length = length; … … 87 122 infillProblem.Initialize(model, maximization); 88 123 var res = EgoUtilities.SyncRunSubAlgorithm(algorithm, random.Next(int.MaxValue), Cancellation); 89 var v = res[ InfillProblem.BestInfillSolutionResultName].Value as RealVector;124 var v = res[DiscreteInfillProblem.BestInfillSolutionResultName].Value as IntegerVector; 90 125 algorithm.Runs.Clear(); 91 126 return v; 92 127 } 93 128 94 private static double GetMinDifference(IDataset data, RealVector r) {129 private static double GetMinDifference(IDataset data, IntegerVector r) { 95 130 var mind = double.MaxValue; 96 131 for (var i = 0; i < data.Rows; i++) { -
branches/EfficientGlobalOptimization/HeuristicLab.Algorithms.EGO/DiscreteEGO/DiscreteSampleCollector.cs
r15340 r15343 23 23 using HeuristicLab.Core; 24 24 using HeuristicLab.Data; 25 using HeuristicLab.Encodings. RealVectorEncoding;25 using HeuristicLab.Encodings.IntegerVectorEncoding; 26 26 using HeuristicLab.Operators; 27 27 using HeuristicLab.Parameters; … … 30 30 31 31 namespace HeuristicLab.Algorithms.EGO { 32 /// <summary> 33 /// A base class for operators that manipulate real-valued vectors. 34 /// </summary> 35 [Item("SampleCollector", "Collects RealVectors into a modifiablbe dataset")] 32 [Item("DiscreteSampleCollector", "Collects IntegerVectors into a modifiablbe dataset")] 36 33 [StorableClass] 37 public class SampleCollector : InstrumentedOperator {34 public class DiscreteSampleCollector : InstrumentedOperator { 38 35 public override bool CanChangeName => true; 39 36 40 public ILookupParameter< RealVector> RealVectorParameter => (ILookupParameter<RealVector>)Parameters["RealVector"];37 public ILookupParameter<IntegerVector> IntegerVectorParameter => (ILookupParameter<IntegerVector>)Parameters["IntegerVector"]; 41 38 public ILookupParameter<DoubleValue> QualityParameter => (ILookupParameter<DoubleValue>)Parameters["Quality"]; 42 39 public ILookupParameter<ModifiableDataset> DatasetParameter => (ILookupParameter<ModifiableDataset>)Parameters["Dataset"]; 43 40 44 41 [StorableConstructor] 45 protected SampleCollector(bool deserializing) : base(deserializing) { }46 protected SampleCollector(SampleCollector original, Cloner cloner) : base(original, cloner) { }47 public SampleCollector() {48 Parameters.Add(new LookupParameter< RealVector>("RealVector", "The vector which should be collected."));42 protected DiscreteSampleCollector(bool deserializing) : base(deserializing) { } 43 protected DiscreteSampleCollector(DiscreteSampleCollector original, Cloner cloner) : base(original, cloner) { } 44 public DiscreteSampleCollector() { 45 Parameters.Add(new LookupParameter<IntegerVector>("IntegerVector", "The vector which should be collected.")); 49 46 Parameters.Add(new LookupParameter<DoubleValue>("Quality", "The quality associated which this vector")); 50 47 Parameters.Add(new LookupParameter<ModifiableDataset>("Dataset", "The Dataset in wich new samples are stored.")); … … 52 49 53 50 public override IDeepCloneable Clone(Cloner cloner) { 54 return new SampleCollector(this, cloner);51 return new DiscreteSampleCollector(this, cloner); 55 52 } 56 53 57 54 public sealed override IOperation InstrumentedApply() { 58 var vector = RealVectorParameter.ActualValue;55 var vector = IntegerVectorParameter.ActualValue; 59 56 var quality = QualityParameter.ActualValue.Value; 60 57 var data = DatasetParameter.ActualValue; … … 71 68 72 69 73 private static void AddRow(ModifiableDataset data, RealVector vector, double quality) {70 private static void AddRow(ModifiableDataset data, IntegerVector vector, double quality) { 74 71 var row = new object[vector.Length + 1]; 75 72 for (var i = 0; i < vector.Length; i++) 76 row[i] = vector[i];73 row[i] = (double)vector[i]; 77 74 row[vector.Length] = quality; 78 75 data.AddRow(row);
Note: See TracChangeset
for help on using the changeset viewer.