Changeset 15343


Ignore:
Timestamp:
08/29/17 11:28:16 (5 years ago)
Author:
bwerth
Message:

#2745 added discretized EGO-version for use with IntegerVectors

Location:
branches/EfficientGlobalOptimization/HeuristicLab.Algorithms.EGO
Files:
1 added
13 edited
8 copied

Legend:

Unmodified
Added
Removed
  • branches/EfficientGlobalOptimization/HeuristicLab.Algorithms.EGO/AdaptiveSamplingAlgorithm.cs

    r15338 r15343  
    6868    private SolutionsCreator SolutionsCreator => OperatorGraph.Iterate().OfType<SolutionsCreator>().First();
    6969    #endregion
    70 
    71 
    7270
    7371    #region Operators
  • branches/EfficientGlobalOptimization/HeuristicLab.Algorithms.EGO/DiscreteEGO/DiscreteAdaptiveSamplingAlgorithm.cs

    r15340 r15343  
    88using HeuristicLab.Core;
    99using HeuristicLab.Data;
    10 using HeuristicLab.Encodings.RealVectorEncoding;
     10using HeuristicLab.Encodings.IntegerVectorEncoding;
    1111using HeuristicLab.Operators;
    1212using HeuristicLab.Optimization;
     
    1818
    1919namespace HeuristicLab.Algorithms.EGO {
    20   [Item("Adaptive Sampling Algorithm (EGO)", "An adaptive sampling algorithm.")]
     20  [Item("Discrete Adaptive Sampling Algorithm (D-EGO)", "A discrete adaptive sampling algorithm.")]
    2121  [Creatable(CreatableAttribute.Categories.SingleSolutionAlgorithms, Priority = 150)]
    2222  [StorableClass]
    23   public class AdaptiveSamplingAlgorithm : HeuristicOptimizationEngineAlgorithm, IStorableContent {
     23  public class DiscreteAdaptiveSamplingAlgorithm : HeuristicOptimizationEngineAlgorithm, IStorableContent {
    2424    public string Filename { get; set; }
    2525
     
    8080    private BestAverageWorstQualityAnalyzer singleObjectiveQualityAnalyzer;
    8181    [Storable]
    82     private CorrelationAnalyzer correlationAnalyzer;
    83     [Storable]
    84     private EvaluatedSolutionsAnalyzer sampleAnalyzer;
     82    private DiscreteCorrelationAnalyzer correlationAnalyzer;
     83    [Storable]
     84    private DiscreteEvaluatedSolutionsAnalyzer sampleAnalyzer;
    8585    [Storable]
    8686    private ModelQualityAnalyzer modelAnalyzer;
     
    102102    #region Problem-dependent Operators
    103103    [Storable]
    104     private SampleCollector sampleCollector;
    105     [Storable]
    106     private InfillSolver infillSolver;
     104    private DiscreteSampleCollector sampleCollector;
     105    [Storable]
     106    private DiscreteInfillSolver infillSolver;
    107107    [Storable]
    108108    private SolutionsCreator infillSolutionsCreator;
     
    112112    #region Constructors
    113113    [StorableConstructor]
    114     protected AdaptiveSamplingAlgorithm(bool deserializing) : base(deserializing) { }
     114    protected DiscreteAdaptiveSamplingAlgorithm(bool deserializing) : base(deserializing) { }
    115115    [StorableHook(HookType.AfterDeserialization)]
    116116    private void AfterDeserialization() {
    117117      Initialize();
    118118    }
    119     protected AdaptiveSamplingAlgorithm(AdaptiveSamplingAlgorithm original, Cloner cloner) : base(original, cloner) {
     119    protected DiscreteAdaptiveSamplingAlgorithm(DiscreteAdaptiveSamplingAlgorithm original, Cloner cloner) : base(original, cloner) {
    120120      singleObjectiveQualityAnalyzer = cloner.Clone(original.singleObjectiveQualityAnalyzer);
    121121      evaluationsTerminator = cloner.Clone(original.evaluationsTerminator);
     
    134134    }
    135135    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() {
    139139
    140140      #region Add parameters
     
    148148        new PluginExpectedImprovement()
    149149      };
    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()
    154154      };
    155155      var model = new GaussianProcessRegression {
     
    194194      Operators.Add(modelbuilder);
    195195
    196       sampleCollector = new SampleCollector { Name = "Collect Sample" };
     196      sampleCollector = new DiscreteSampleCollector { Name = "Collect Sample" };
    197197      Operators.Add(sampleCollector);
    198198      infillSolutionsCreator = new SolutionsCreator { Name = "Create Adaptive Solutions" };
    199199      Operators.Add(infillSolutionsCreator);
    200       infillSolver = new InfillSolver();
     200      infillSolver = new DiscreteInfillSolver();
    201201      Operators.Add(infillSolver);
    202202
     
    230230      variableCreator.CollectedValues.Add(new ValueParameter<IRegressionSolution>(modelVariableName, "The regression solution representing the model for EGO", null));
    231231      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));
    233233      variableCreator.Successor = resultsCollector;
    234234
     
    301301      Operators.Add(singleObjectiveQualityAnalyzer);
    302302
    303       correlationAnalyzer = new CorrelationAnalyzer();
     303      correlationAnalyzer = new DiscreteCorrelationAnalyzer();
    304304      correlationAnalyzer.ModelParameter.ActualName = modelVariableName;
    305305      Operators.Add(correlationAnalyzer);
    306306
    307       sampleAnalyzer = new EvaluatedSolutionsAnalyzer();
     307      sampleAnalyzer = new DiscreteEvaluatedSolutionsAnalyzer();
    308308      sampleAnalyzer.PhaseParameter.ActualName = initialPhaseVariableName;
    309309      Operators.Add(sampleAnalyzer);
     
    354354    public override void Start(CancellationToken cancellationToken) {
    355355      ParameterizeProblemSpecificOperators();
    356       ((InfillProblem)InfillOptimizationAlgorithm.Problem).InfillCriterion = InfillCriterion;
     356      ((DiscreteInfillProblem)InfillOptimizationAlgorithm.Problem).InfillCriterion = InfillCriterion;
    357357      ParameterizeCancellableOperators(cancellationToken);
    358358      base.Start(cancellationToken);
     
    387387      singleObjectiveQualityAnalyzer.QualityParameter.Depth = 1;
    388388      correlationAnalyzer.QualityParameter.Depth = 1;
    389       correlationAnalyzer.RealVectorParameter.Depth = 1;
     389      correlationAnalyzer.IntegerVectorParameter.Depth = 1;
    390390      sampleAnalyzer.QualityParameter.Depth = 1;
    391       sampleAnalyzer.RealVectorParameter.Depth = 1;
     391      sampleAnalyzer.IntegerVectorParameter.Depth = 1;
    392392
    393393      if (SingleObjectiveProblem == null) return;
     
    418418      if (SingleObjectiveProblem == null) throw new ArgumentException("Adaptive sampling requires a single objective problem");
    419419      infillSolver.MaximizationParameter.ActualName = SingleObjectiveProblem.MaximizationParameter.Name;
    420       var rcreator = Problem.SolutionCreator as IRealVectorCreator;
    421       if (rcreator == null) throw new ArgumentException("Adaptive sampling requires real vectors 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");
    422422
    423423      infillSolver.LengthParameter.ActualName = rcreator.LengthParameter.ActualName;
     
    425425      infillSolver.LengthParameter.Value = rcreator.LengthParameter.Value;
    426426      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;
    430430      sampleCollector.QualityParameter.ActualName = SingleObjectiveProblem.Evaluator.QualityParameter.ActualName;
    431431
    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;
    434434    }
    435435    private void ParameterizeCancellableOperators(CancellationToken cancellation) {
     
    451451    }
    452452    private void OnInfillCriterionChanged(object sender, EventArgs e) {
    453       ((InfillProblem)InfillOptimizationAlgorithm.Problem).InfillCriterion = InfillCriterion;
     453      ((DiscreteInfillProblem)InfillOptimizationAlgorithm.Problem).InfillCriterion = InfillCriterion;
    454454    }
    455455    private void OnInfillAlgorithmChanged(object sender, EventArgs e) {
    456       InfillOptimizationAlgorithm.Problem = new InfillProblem { InfillCriterion = InfillCriterion };
     456      InfillOptimizationAlgorithm.Problem = new DiscreteInfillProblem { InfillCriterion = InfillCriterion };
    457457      InfillOptimizationAlgorithm.ProblemChanged -= OnInfillProblemChanged; //avoid double attaching
    458458      InfillOptimizationAlgorithm.ProblemChanged += OnInfillProblemChanged;
     
    461461      //enforce an infill problem for the infill optimization algorithm
    462462      InfillOptimizationAlgorithm.ProblemChanged -= OnInfillProblemChanged;
    463       InfillOptimizationAlgorithm.Problem = new InfillProblem { InfillCriterion = InfillCriterion };
     463      InfillOptimizationAlgorithm.Problem = new DiscreteInfillProblem { InfillCriterion = InfillCriterion };
    464464      InfillOptimizationAlgorithm.ProblemChanged += OnInfillProblemChanged;
    465465    }
  • branches/EfficientGlobalOptimization/HeuristicLab.Algorithms.EGO/DiscreteEGO/DiscreteCorrelationAnalyzer.cs

    r15340 r15343  
    2626using HeuristicLab.Core;
    2727using HeuristicLab.Data;
    28 using HeuristicLab.Encodings.RealVectorEncoding;
     28using HeuristicLab.Encodings.IntegerVectorEncoding;
    2929using HeuristicLab.Operators;
    3030using HeuristicLab.Optimization;
     
    3434
    3535namespace 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")]
    3737  [StorableClass]
    38   public class CorrelationAnalyzer : SingleSuccessorOperator, IAnalyzer, IResultsOperator {
     38  public class DiscreteCorrelationAnalyzer : SingleSuccessorOperator, IAnalyzer, IResultsOperator {
    3939    public override bool CanChangeName => true;
    4040    public bool EnabledByDefault => false;
    4141
    42     public IScopeTreeLookupParameter<RealVector> RealVectorParameter => (IScopeTreeLookupParameter<RealVector>)Parameters["RealVector"];
     42    public IScopeTreeLookupParameter<IntegerVector> IntegerVectorParameter => (IScopeTreeLookupParameter<IntegerVector>)Parameters["IntegerVector"];
    4343    public IScopeTreeLookupParameter<DoubleValue> QualityParameter => (IScopeTreeLookupParameter<DoubleValue>)Parameters["Quality"];
    4444    public ILookupParameter<IRegressionSolution> ModelParameter => (ILookupParameter<IRegressionSolution>)Parameters["Model"];
     
    4949
    5050    [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."));
    5555      Parameters.Add(new ScopeTreeLookupParameter<DoubleValue>("Quality", "The quality associated which this vector"));
    5656      Parameters.Add(new LookupParameter<IRegressionSolution>("Model", "The model of this iteration"));
     
    5959
    6060    public override IDeepCloneable Clone(Cloner cloner) {
    61       return new CorrelationAnalyzer(this, cloner);
     61      return new DiscreteCorrelationAnalyzer(this, cloner);
    6262    }
    6363
     
    6666      var results = ResultsParameter.ActualValue;
    6767      var q = QualityParameter.ActualValue.Select(x => x.Value).ToArray();
    68       var p = RealVectorParameter.ActualValue.ToArray();
     68      var p = IntegerVectorParameter.ActualValue.ToArray();
    6969      if (model == null) return base.Apply();
    7070      var plot = CreateScatterPlotResult(results);
  • branches/EfficientGlobalOptimization/HeuristicLab.Algorithms.EGO/DiscreteEGO/DiscreteEfficientGlobalOptimizationAlgorithm.cs

    r15340 r15343  
    2525using System.Threading;
    2626using HeuristicLab.Algorithms.DataAnalysis;
     27using HeuristicLab.Algorithms.OffspringSelectionGeneticAlgorithm;
    2728using HeuristicLab.Analysis;
    2829using HeuristicLab.Common;
    2930using HeuristicLab.Core;
    3031using HeuristicLab.Data;
    31 using HeuristicLab.Encodings.RealVectorEncoding;
     32using HeuristicLab.Encodings.IntegerVectorEncoding;
    3233using HeuristicLab.Optimization;
    3334using HeuristicLab.Parameters;
     
    4041  [StorableClass]
    4142  [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> {
    4445    #region Basic-Alg-Essentials
    4546    public override bool SupportsPause => true;
     
    9596    public IFixedValueParameter<BoolValue> RemoveDuplicatesParameter => Parameters[RemoveDuplicatesParamterName] as IFixedValueParameter<BoolValue>;
    9697    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>>;
    99100    #endregion
    100101
     
    111112    public bool SetSeedRandomly => SetSeedRandomlyParameter.Value.Value;
    112113    public int MaximalDatasetSize => MaximalDataSetSizeParameter.Value.Value;
    113     private IEnumerable<Tuple<RealVector, double>> DataSamples => Samples.Count > MaximalDatasetSize && MaximalDatasetSize > 0
     114    private IEnumerable<Tuple<IntegerVector, double>> DataSamples => Samples.Count > MaximalDatasetSize && MaximalDatasetSize > 0
    114115      ? Samples.Skip(Samples.Count - MaximalDatasetSize)
    115116      : Samples;
    116117    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;
    119120    #endregion
    120121
     
    123124    private IRandom Random = new MersenneTwister();
    124125    [Storable]
    125     private List<Tuple<RealVector, double>> Samples;
     126    private List<Tuple<IntegerVector, double>> Samples;
    126127    [Storable]
    127     private List<Tuple<RealVector, double>> InitialSamples;
     128    private List<Tuple<IntegerVector, double>> InitialSamples;
    128129    #endregion
    129130
     
    133134      set { ((DoubleValue)Results[BestQualityResultName].Value).Value = value; }
    134135    }
    135     private RealVector ResultsBestSolution {
    136       get { return (RealVector)Results[BestSolutionResultName].Value; }
     136    private IntegerVector ResultsBestSolution {
     137      get { return (IntegerVector)Results[BestSolutionResultName].Value; }
    137138      set { Results[BestSolutionResultName].Value = value; }
    138139    }
     
    157158    #region HLConstructors
    158159    [StorableConstructor]
    159     protected EfficientGlobalOptimizationAlgorithm(bool deserializing) : base(deserializing) { }
     160    protected DiscreteEfficientGlobalOptimizationAlgorithm(bool deserializing) : base(deserializing) { }
    160161    [StorableHook(HookType.AfterDeserialization)]
    161162    protected void AfterDeseialization() {
    162163      RegisterEventhandlers();
    163164    }
    164     protected EfficientGlobalOptimizationAlgorithm(EfficientGlobalOptimizationAlgorithm original, Cloner cloner) : base(original, cloner) {
     165    protected DiscreteEfficientGlobalOptimizationAlgorithm(DiscreteEfficientGlobalOptimizationAlgorithm original, Cloner cloner) : base(original, cloner) {
    165166      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();
    168169      RegisterEventhandlers();
    169170    }
    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() {
    172173      IProblemInstanceExporter dummy = new RegressionProblem(); //this variable is irrelevant
    173174      //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 referenced 
     175      //"new ValueParameter<IDataAnalysisAlgorithm<IRegressionProblem>>" requires no using-Statement, but nontheless it requires HeuristicLab.Problems.Instances to be referenced 
    175176      //Having HeuristicLab.Problems.Instances referenced but not used, causes the Essential-Unit-tests to fail.
    176177
    177       var cmaes = new CMAEvolutionStrategy.CMAEvolutionStrategy {
    178         MaximumGenerations = 300,
    179         PopulationSize = 50
     178      var cmaes = new OffspringSelectionGeneticAlgorithm.OffspringSelectionGeneticAlgorithm() {
     179        MaximumGenerations = new IntValue(300),
     180        PopulationSize = new IntValue(50)
    180181      };
    181182      var model = new GaussianProcessRegression {
     
    195196      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"));
    196197      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)"));
    198199      var eqi = new ExpectedQuantileImprovement();
    199200      eqi.MaxEvaluationsParameter.Value = MaximumEvaluationsParameter.Value;
    200201      var criteria = new ItemSet<IInfillCriterion> { new ExpectedImprovement(), new AugmentedExpectedImprovement(), new ExpectedQuality(), eqi, new MinimalQuantileCriterium(), new PluginExpectedImprovement() };
    201202      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()));
    204205      SetInfillProblem();
    205206      RegisterEventhandlers();
    206207    }
    207208    #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();
    210211    }
    211212    protected override void Initialize(CancellationToken cancellationToken) {
    212213      base.Initialize(cancellationToken);
    213214      //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?");
    218219
    219220      //random
    220221      if (SetSeedRandomly) SeedParameter.Value.Value = new System.Random().Next();
    221222      Random.Reset(Seed);
    222       Samples = InitialSamples?.ToList() ?? new List<Tuple<RealVector, double>>();
     223      Samples = InitialSamples?.ToList() ?? new List<Tuple<IntegerVector, double>>();
    223224
    224225      //results
    225226      Results.Add(new Result(IterationsResultName, new IntValue(0)));
    226227      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)));
    228229      Results.Add(new Result(BestQualityResultName, new DoubleValue(Problem.Maximization ? double.MinValue : double.MaxValue)));
    229230      Results.Add(new Result(RegressionSolutionResultName, typeof(IRegressionSolution)));
     
    241242      //initial samples
    242243      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);
    244245        foreach (var t in points) {
    245246          try {
    246247            Samples.Add(Evaluate(t));
    247248            cancellationToken.ThrowIfCancellationRequested();
    248           } finally {
     249          }
     250          finally {
    249251            Analyze();
    250252          }
     
    259261          for (var i = 0; i < GenerationSize; i++) {
    260262            var samplepoint = OptimizeInfillProblem(cancellationToken);
     263            if (RemoveDuplicates) {
     264
     265            }
    261266            var sample = Evaluate(samplepoint);
    262267            Samples.Add(sample);
     
    264269          }
    265270
    266         } finally {
     271        }
     272        finally {
    267273          Analyze();
    268274        }
     
    298304    }
    299305    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?");
    302308      infillProblem.InfillCriterion = InfillCriterion;
    303309    }
     
    326332    #region helpers
    327333    private IRegressionSolution BuildModel(CancellationToken cancellationToken) {
    328       var dataset = EgoUtilities.GetDataSet(DataSamples.ToList(), RemoveDuplicates);
     334      var dataset = EgoUtilities.GetDataSet(DataSamples.ToList());
    329335      var problemdata = new RegressionProblemData(dataset, dataset.VariableNames.Where(x => !x.Equals("output")), "output");
    330336      problemdata.TrainingPartition.Start = 0;
     
    363369            solution = sol;
    364370          }
    365         } catch (ArgumentException) { }
     371        }
     372        catch (ArgumentException) { }
    366373      }
    367374
     
    380387      return solution;
    381388    }
    382     private RealVector OptimizeInfillProblem(CancellationToken cancellationToken) {
     389    private IntegerVector OptimizeInfillProblem(CancellationToken cancellationToken) {
    383390      //parameterize and check InfillProblem
    384       var infillProblem = InfillOptimizationAlgorithm.Problem as InfillProblem;
     391      var infillProblem = InfillOptimizationAlgorithm.Problem as DiscreteInfillProblem;
    385392      if (infillProblem == null) throw new ArgumentException("InfillOptimizationAlgorithm does not have an InfillProblem.");
    386393      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;
    388395      infillProblem.Encoding.Bounds = enc.Bounds;
    389396      infillProblem.Encoding.Length = enc.Length;
     
    392399
    393400
    394       RealVector bestVector = null;
     401      IntegerVector bestVector = null;
    395402      var bestValue = infillProblem.Maximization ? double.NegativeInfinity : double.PositiveInfinity;
    396403      for (var i = 0; i < InfillOptimizationRestarts; i++) {
     
    399406        cancellationToken.ThrowIfCancellationRequested();
    400407        //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;
    405412        if (d == null || v == null) throw new ArgumentException("The InfillOptimizationAlgorithm did not return the expected result types");
    406413        //check for improvement
     
    456463    }
    457464
    458     private Individual GetIndividual(RealVector r) {
     465
     466
     467    private Individual GetIndividual(IntegerVector r) {
    459468      var scope = new Scope();
    460469      scope.Variables.Add(new Variable(Problem.Encoding.Name, r));
    461470      return new SingleEncodingIndividual(Problem.Encoding, scope);
    462471    }
    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));
    465474    }
    466475
    467476    private void SetInfillProblem() {
    468       InfillOptimizationAlgorithm.Problem = new InfillProblem { InfillCriterion = InfillCriterion };
     477      InfillOptimizationAlgorithm.Problem = new DiscreteInfillProblem { InfillCriterion = InfillCriterion };
    469478    }
    470479    #endregion
  • branches/EfficientGlobalOptimization/HeuristicLab.Algorithms.EGO/DiscreteEGO/DiscreteEvaluatedSolutionsAnalyzer.cs

    r15340 r15343  
    2626using HeuristicLab.Core;
    2727using HeuristicLab.Data;
    28 using HeuristicLab.Encodings.RealVectorEncoding;
     28using HeuristicLab.Encodings.IntegerVectorEncoding;
    2929using HeuristicLab.Operators;
    3030using HeuristicLab.Optimization;
     
    3333
    3434namespace 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")]
    3936  [StorableClass]
    40   public class EvaluatedSolutionsAnalyzer : SingleSuccessorOperator, IAnalyzer, IResultsOperator {
     37  public class DiscreteEvaluatedSolutionsAnalyzer : SingleSuccessorOperator, IAnalyzer, IResultsOperator {
    4138    public override bool CanChangeName => true;
    4239    public bool EnabledByDefault => false;
    4340
    44     public IScopeTreeLookupParameter<RealVector> RealVectorParameter => (IScopeTreeLookupParameter<RealVector>)Parameters["RealVector"];
     41    public IScopeTreeLookupParameter<IntegerVector> IntegerVectorParameter => (IScopeTreeLookupParameter<IntegerVector>)Parameters["IntegerVector"];
    4542    public IScopeTreeLookupParameter<DoubleValue> QualityParameter => (IScopeTreeLookupParameter<DoubleValue>)Parameters["Quality"];
    4643    public ILookupParameter<ResultCollection> ResultsParameter => (ILookupParameter<ResultCollection>)Parameters["Results"];
     
    5350
    5451    [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."));
    5956      Parameters.Add(new ScopeTreeLookupParameter<DoubleValue>("Quality", "The quality associated which this vector"));
    6057      Parameters.Add(new LookupParameter<BoolValue>("InitialPhase", "Whether the initial phase has finished"));
     
    6360
    6461    public override IDeepCloneable Clone(Cloner cloner) {
    65       return new EvaluatedSolutionsAnalyzer(this, cloner);
     62      return new DiscreteEvaluatedSolutionsAnalyzer(this, cloner);
    6663    }
    6764
    6865    public sealed override IOperation Apply() {
    69       var p = RealVectorParameter.ActualValue.ToArray();
     66      var p = IntegerVectorParameter.ActualValue.ToArray();
    7067      if (p.Length == 0 || p[0].Length > 2 || p[0].Length == 0) return base.Apply();
    7168      var results = ResultsParameter.ActualValue;
  • branches/EfficientGlobalOptimization/HeuristicLab.Algorithms.EGO/DiscreteEGO/DiscreteInfillProblem.cs

    r15340 r15343  
    2626using HeuristicLab.Core;
    2727using HeuristicLab.Data;
     28using HeuristicLab.Encodings.IntegerVectorEncoding;
    2829using HeuristicLab.Encodings.RealVectorEncoding;
    2930using HeuristicLab.Optimization;
     
    3334namespace HeuristicLab.Algorithms.EGO {
    3435  [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> {
    3738
    3839    public override bool Maximization => true;
     
    4748    private IInfillCriterion infillCriterion;
    4849
    49     public IInfillCriterion InfillCriterion
    50     {
     50    public IInfillCriterion InfillCriterion {
    5151      get { return infillCriterion; }
    52       set
    53       {
     52      set {
    5453        infillCriterion = value;
    55         infillCriterion.Encoding = Encoding;
     54        infillCriterion.Encoding = GetRealVectorEncoding(Encoding);
    5655      }
    5756    }
     
    6059    #region Constructors
    6160    [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) {
    6463      infillCriterion = cloner.Clone(original.infillCriterion);
    6564    }
    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); }
    6867    #endregion
    6968
    7069    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());
    7271    }
    7372    public override void Analyze(Individual[] individuals, double[] qualities, ResultCollection results, IRandom random) {
     
    7675      var newQuality = qualities[best];
    7776      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()));
    7978        results.Add(new Result(BestInfillQualityResultName, new DoubleValue(newQuality)));
    8079        return;
     
    8382      if (qold == null) throw new ArgumentException("Old best quality is not a double value. Conflicting Analyzers?");
    8483      if (qold.Value >= newQuality) return;
    85       results[BestInfillSolutionResultName].Value = (RealVector)individuals[best].RealVector().Clone();
     84      results[BestInfillSolutionResultName].Value = (IntegerVector)individuals[best].IntegerVector().Clone();
    8685      qold.Value = newQuality;
    8786    }
     
    8988      var bounds = Encoding.Bounds;
    9089      var michalewiczIteration = 0;
     90      var sigma = new DoubleArray(new double[] { 1.0 });
     91
    9192      while (true) {
    9293        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;
    10099          default: throw new NotImplementedException();
    101100        }
     
    108107      infillCriterion.RegressionSolution = model;
    109108      infillCriterion.ExpensiveMaximization = expensiveMaximization;
    110       infillCriterion.Encoding = Encoding;
     109      infillCriterion.Encoding = GetRealVectorEncoding(Encoding);
    111110      infillCriterion.Initialize();
    112111    }
    113112
    114113    #region helpers
    115     private static bool InBounds(RealVector r, DoubleMatrix bounds) {
     114    private static bool InBounds(IntegerVector r, IntMatrix bounds) {
    116115      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
    117127    }
    118128    #endregion
  • branches/EfficientGlobalOptimization/HeuristicLab.Algorithms.EGO/DiscreteEGO/DiscreteInfillSolver.cs

    r15340 r15343  
    2222using System;
    2323using System.Threading;
     24using System.Linq;
     25using System.Collections.Generic;
    2426using HeuristicLab.Common;
    2527using HeuristicLab.Core;
    2628using HeuristicLab.Data;
    27 using HeuristicLab.Encodings.RealVectorEncoding;
     29using HeuristicLab.Encodings.IntegerVectorEncoding;
    2830using HeuristicLab.Optimization;
    2931using HeuristicLab.Parameters;
     
    3234
    3335namespace 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")]
    3837  [StorableClass]
    39   public class InfillSolver : RealVectorCreator, ICancellableOperator {
     38  public class DiscreteInfillSolver : IntegerVectorCreator, ICancellableOperator {
    4039
    4140    public ILookupParameter<IAlgorithm> InfillOptimizationAlgorithmParamter => (ILookupParameter<IAlgorithm>)Parameters["InfillAlgorithm"];
     
    4443    public ILookupParameter<BoolValue> RemoveDuplicatesParameter => (ILookupParameter<BoolValue>)Parameters["RemoveDuplicates"];
    4544    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"];
    4746
    4847    public CancellationToken Cancellation { get; set; }
    4948
    5049    [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() {
    5453      Parameters.Add(new LookupParameter<IAlgorithm>("InfillAlgorithm", "The algorithm used to optimize the infill problem") { Hidden = true });
    5554      Parameters.Add(new LookupParameter<IRegressionSolution>("Model", "The RegressionSolution upon which the InfillProblem operates") { Hidden = true });
     
    5756      Parameters.Add(new LookupParameter<BoolValue>("RemoveDuplicates", "Whether duplicates shall be removed") { Hidden = true });
    5857      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 });
    6059    }
    6160
    6261    public override IDeepCloneable Clone(Cloner cloner) {
    63       return new InfillSolver(this, cloner);
     62      return new DiscreteInfillSolver(this, cloner);
    6463    }
    6564
    66     protected override RealVector Create(IRandom random, IntValue length, DoubleMatrix bounds) {
     65    protected override IntegerVector Create(IRandom random, IntValue length, IntMatrix bounds) {
    6766      var infillBounds = InfillBoundsParameter.ActualValue;
    6867      if (infillBounds != null && infillBounds.Rows > 0) {
     
    7574      var res = OptimizeInfillProblem(alg, model, max, bounds, length.Value, random);
    7675      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      }
    79105      return res;
    80106    }
    81107
    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;
    84119      if (infillProblem == null) throw new ArgumentException("The algortihm has no InfillProblem to solve");
    85120      infillProblem.Encoding.Length = length;
     
    87122      infillProblem.Initialize(model, maximization);
    88123      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;
    90125      algorithm.Runs.Clear();
    91126      return v;
    92127    }
    93128
    94     private static double GetMinDifference(IDataset data, RealVector r) {
     129    private static double GetMinDifference(IDataset data, IntegerVector r) {
    95130      var mind = double.MaxValue;
    96131      for (var i = 0; i < data.Rows; i++) {
  • branches/EfficientGlobalOptimization/HeuristicLab.Algorithms.EGO/DiscreteEGO/DiscreteSampleCollector.cs

    r15340 r15343  
    2323using HeuristicLab.Core;
    2424using HeuristicLab.Data;
    25 using HeuristicLab.Encodings.RealVectorEncoding;
     25using HeuristicLab.Encodings.IntegerVectorEncoding;
    2626using HeuristicLab.Operators;
    2727using HeuristicLab.Parameters;
     
    3030
    3131namespace 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")]
    3633  [StorableClass]
    37   public class SampleCollector : InstrumentedOperator {
     34  public class DiscreteSampleCollector : InstrumentedOperator {
    3835    public override bool CanChangeName => true;
    3936
    40     public ILookupParameter<RealVector> RealVectorParameter => (ILookupParameter<RealVector>)Parameters["RealVector"];
     37    public ILookupParameter<IntegerVector> IntegerVectorParameter => (ILookupParameter<IntegerVector>)Parameters["IntegerVector"];
    4138    public ILookupParameter<DoubleValue> QualityParameter => (ILookupParameter<DoubleValue>)Parameters["Quality"];
    4239    public ILookupParameter<ModifiableDataset> DatasetParameter => (ILookupParameter<ModifiableDataset>)Parameters["Dataset"];
    4340
    4441    [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."));
    4946      Parameters.Add(new LookupParameter<DoubleValue>("Quality", "The quality associated which this vector"));
    5047      Parameters.Add(new LookupParameter<ModifiableDataset>("Dataset", "The Dataset in wich new samples are stored."));
     
    5249
    5350    public override IDeepCloneable Clone(Cloner cloner) {
    54       return new SampleCollector(this, cloner);
     51      return new DiscreteSampleCollector(this, cloner);
    5552    }
    5653
    5754    public sealed override IOperation InstrumentedApply() {
    58       var vector = RealVectorParameter.ActualValue;
     55      var vector = IntegerVectorParameter.ActualValue;
    5956      var quality = QualityParameter.ActualValue.Value;
    6057      var data = DatasetParameter.ActualValue;
     
    7168
    7269
    73     private static void AddRow(ModifiableDataset data, RealVector vector, double quality) {
     70    private static void AddRow(ModifiableDataset data, IntegerVector vector, double quality) {
    7471      var row = new object[vector.Length + 1];
    7572      for (var i = 0; i < vector.Length; i++)
    76         row[i] = vector[i];
     73        row[i] = (double)vector[i];
    7774      row[vector.Length] = quality;
    7875      data.AddRow(row);
  • branches/EfficientGlobalOptimization/HeuristicLab.Algorithms.EGO/EfficientGlobalOptimizationAlgorithm.cs

    r15338 r15343  
    9696    public IFixedValueParameter<FileValue> InitialSamplesParameter => Parameters[InitialSamplesParameterName] as IFixedValueParameter<FileValue>;
    9797    public IValueParameter<RealVector> BaselineVectorParameter => Parameters[BaselineVectorParameterName] as IValueParameter<RealVector>;
    98     public IConstrainedValueParameter<IInitialSampling> InitialSamplingPlanParameter => Parameters[InitialSamplingPlanParamterName] as IConstrainedValueParameter<IInitialSampling>;
     98    public IConstrainedValueParameter<IInitialSampling<RealVector>> InitialSamplingPlanParameter => Parameters[InitialSamplingPlanParamterName] as IConstrainedValueParameter<IInitialSampling<RealVector>>;
    9999    #endregion
    100100
     
    116116    private bool RemoveDuplicates => RemoveDuplicatesParameter.Value.Value;
    117117    private RealVector BaselineVector => BaselineVectorParameter.Value;
    118     private IInitialSampling InitialSamplingPlan => InitialSamplingPlanParameter.Value;
     118    private IInitialSampling<RealVector> InitialSamplingPlan => InitialSamplingPlanParameter.Value;
    119119    #endregion
    120120
     
    200200      var criteria = new ItemSet<IInfillCriterion> { new ExpectedImprovement(), new AugmentedExpectedImprovement(), new ExpectedQuality(), eqi, new MinimalQuantileCriterium(), new PluginExpectedImprovement() };
    201201      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()));
     202      var intialSamplingPlans = new ItemSet<IInitialSampling<RealVector>> { new UniformRandomSampling(), new LatinHyperCubeDesignCreator() };
     203      Parameters.Add(new ConstrainedValueParameter<IInitialSampling<RealVector>>(InitialSamplingPlanParamterName, "Determies the initial samples from which the first model can be built.", intialSamplingPlans, intialSamplingPlans.First()));
    204204      SetInfillProblem();
    205205      RegisterEventhandlers();
     
    246246            Samples.Add(Evaluate(t));
    247247            cancellationToken.ThrowIfCancellationRequested();
    248           } finally {
     248          }
     249          finally {
    249250            Analyze();
    250251          }
     
    264265          }
    265266
    266         } finally {
     267        }
     268        finally {
    267269          Analyze();
    268270        }
     
    363365            solution = sol;
    364366          }
    365         } catch (ArgumentException) { }
     367        }
     368        catch (ArgumentException) { }
    366369      }
    367370
  • branches/EfficientGlobalOptimization/HeuristicLab.Algorithms.EGO/EgoUtilities.cs

    r15338 r15343  
    2727using HeuristicLab.Data;
    2828using HeuristicLab.Encodings.RealVectorEncoding;
     29using HeuristicLab.Encodings.IntegerVectorEncoding;
    2930using HeuristicLab.Optimization;
    3031using HeuristicLab.Problems.DataAnalysis;
     
    5455      return model.GetEstimatedValues(dataset, new[] { 0 }).First();
    5556    }
     57    public static double GetEstimation(this IRegressionModel model, IntegerVector r) {
     58      var dataset = GetDataSet(new[] { new Tuple<IntegerVector, double>(r, 0.0) });
     59      return model.GetEstimatedValues(dataset, new[] { 0 }).First();
     60    }
    5661    public static double GetVariance(this IConfidenceRegressionModel model, RealVector r) {
    5762      var dataset = GetDataSet(new[] { new Tuple<RealVector, double>(r, 0.0) }, false);
     63      return model.GetEstimatedVariances(dataset, new[] { 0 }).First();
     64    }
     65    public static double GetVariance(this IConfidenceRegressionModel model, IntegerVector r) {
     66      var dataset = GetDataSet(new[] { new Tuple<IntegerVector, double>(r, 0.0) });
    5867      return model.GetEstimatedVariances(dataset, new[] { 0 }).First();
    5968    }
     
    6170      return dataset.GetDoubleValue("input" + j, i);
    6271    }
     72    public static RealVector ToRealVector(this IntegerVector vector) {
     73      return new RealVector(vector.Select(x => (double)x).ToArray());
     74    }
     75
    6376
    6477    //Sub-ALgorithms
     
    8093    public static Dataset GetDataSet(IReadOnlyList<Tuple<RealVector, double>> samples, bool removeDuplicates) {
    8194      if (removeDuplicates) samples = RemoveDuplicates(samples); //TODO duplicate removal leads to incorrect uncertainty values in models
     95      var dimensions = samples[0].Item1.Length + 1;
     96      var data = new double[samples.Count, dimensions];
     97      var names = new string[dimensions - 1];
     98      for (var i = 0; i < names.Length; i++) names[i] = "input" + i;
     99      for (var j = 0; j < samples.Count; j++) {
     100        for (var i = 0; i < names.Length; i++) data[j, i] = samples[j].Item1[i];
     101        data[j, dimensions - 1] = samples[j].Item2;
     102      }
     103      return new Dataset(names.Concat(new[] { "output" }).ToArray(), data);
     104    }
     105    //overload for IntegerVectors does not support duplicate removal
     106    public static Dataset GetDataSet(IReadOnlyList<Tuple<IntegerVector, double>> samples) {
    82107      var dimensions = samples[0].Item1.Length + 1;
    83108      var data = new double[samples.Count, dimensions];
  • branches/EfficientGlobalOptimization/HeuristicLab.Algorithms.EGO/HeuristicLab.Algorithms.EGO-3.4.csproj

    r15338 r15343  
    3939      <HintPath>..\..\..\trunk\sources\bin\HeuristicLab.Algorithms.DataAnalysis-3.4.dll</HintPath>
    4040    </Reference>
     41    <Reference Include="HeuristicLab.Algorithms.OffspringSelectionGeneticAlgorithm-3.3, Version=3.3.0.0, Culture=neutral, PublicKeyToken=ba48961d6f65dcec, processorArchitecture=MSIL">
     42      <SpecificVersion>False</SpecificVersion>
     43      <HintPath>..\..\..\trunk\sources\bin\HeuristicLab.Algorithms.OffspringSelectionGeneticAlgorithm-3.3.dll</HintPath>
     44    </Reference>
    4145    <Reference Include="HeuristicLab.Analysis-3.3, Version=3.3.0.0, Culture=neutral, PublicKeyToken=ba48961d6f65dcec, processorArchitecture=MSIL">
    4246      <SpecificVersion>False</SpecificVersion>
     
    5862      <SpecificVersion>False</SpecificVersion>
    5963      <HintPath>..\..\..\trunk\sources\bin\HeuristicLab.Data-3.3.dll</HintPath>
     64    </Reference>
     65    <Reference Include="HeuristicLab.Encodings.IntegerVectorEncoding-3.3, Version=3.3.0.0, Culture=neutral, PublicKeyToken=ba48961d6f65dcec, processorArchitecture=MSIL">
     66      <SpecificVersion>False</SpecificVersion>
     67      <HintPath>..\..\..\trunk\sources\bin\HeuristicLab.Encodings.IntegerVectorEncoding-3.3.dll</HintPath>
    6068    </Reference>
    6169    <Reference Include="HeuristicLab.Encodings.PermutationEncoding-3.3, Version=3.3.0.0, Culture=neutral, PublicKeyToken=ba48961d6f65dcec, processorArchitecture=MSIL">
     
    107115  </ItemGroup>
    108116  <ItemGroup>
     117    <Compile Include="DiscreteEGO\DiscreteCorrelationAnalyzer.cs" />
     118    <Compile Include="DiscreteEGO\DiscreteAdaptiveSamplingAlgorithm.cs" />
     119    <Compile Include="DiscreteEGO\DiscreteEfficientGlobalOptimizationAlgorithm.cs" />
     120    <Compile Include="DiscreteEGO\DiscreteInfillSolver.cs" />
     121    <Compile Include="DiscreteEGO\DiscreteSampleCollector.cs" />
     122    <Compile Include="DiscreteEGO\DiscreteEvaluatedSolutionsAnalyzer.cs" />
    109123    <Compile Include="EgoUtilities.cs" />
    110124    <Compile Include="EfficientGlobalOptimizationAlgorithm.cs" />
     
    133147    <Compile Include="Operators\SampleCollector.cs" />
    134148    <Compile Include="Plugin.cs" />
     149    <Compile Include="DiscreteEGO\DiscreteInfillProblem.cs" />
    135150    <Compile Include="Problems\InfillProblem.cs" />
    136151    <Compile Include="Properties\AssemblyInfo.cs" />
    137152    <Compile Include="SamplingMethods\LatinHyperCubeDesignOLD.cs" />
    138153    <Compile Include="SamplingMethods\LatinHyperCubeDesignCreator.cs" />
     154    <Compile Include="SamplingMethods\UniformRandomDiscreteSampling.cs" />
    139155    <Compile Include="SamplingMethods\UniformRandomSampling.cs" />
    140156  </ItemGroup>
  • branches/EfficientGlobalOptimization/HeuristicLab.Algorithms.EGO/Interfaces/IInfillCriterion.cs

    r15064 r15343  
    3232    RealVectorEncoding Encoding { get; set; }
    3333    double Evaluate(RealVector vector);
    34     //bool Maximization();
    3534    void Initialize();
    3635  }
  • branches/EfficientGlobalOptimization/HeuristicLab.Algorithms.EGO/Interfaces/IInitialSampling.cs

    r14833 r15343  
    2222// ReSharper disable once CheckNamespace
    2323using HeuristicLab.Core;
    24 using HeuristicLab.Encodings.RealVectorEncoding;
     24using HeuristicLab.Optimization;
    2525
    2626namespace HeuristicLab.Algorithms.EGO {
    27   public interface IInitialSampling : INamedItem {
    28     RealVector[] GetSamples(int noSamples, RealVector[] existingSamples, RealVectorEncoding encoding, IRandom random);
     27  public interface IInitialSampling<T> : INamedItem where T : class {
     28    T[] GetSamples(int noSamples, T[] existingSamples, IEncoding encoding, IRandom random);
    2929  }
    3030}
  • branches/EfficientGlobalOptimization/HeuristicLab.Algorithms.EGO/Operators/EvaluatedSolutionsAnalyzer.cs

    r15338 r15343  
    3333
    3434namespace HeuristicLab.Algorithms.EGO {
    35   /// <summary>
    36   /// A base class for operators that manipulate real-valued vectors.
    37   /// </summary>
    3835  [Item("EvaluatedSolutionsAnalyzer", "Displays the evaluated Solutions for one or two dimensional problems")]
    3936  [StorableClass]
  • branches/EfficientGlobalOptimization/HeuristicLab.Algorithms.EGO/Operators/InfillSolver.cs

    r15338 r15343  
    3232
    3333namespace HeuristicLab.Algorithms.EGO {
    34   /// <summary>
    35   /// A base class for operators that manipulate real-valued vectors.
    36   /// </summary>
    3734  [Item("InfillSolver", "A RealVectorCreator that creates candidates by optimizing an infill-subproblem")]
    3835  [StorableClass]
  • branches/EfficientGlobalOptimization/HeuristicLab.Algorithms.EGO/Operators/ModelBuilder.cs

    r15338 r15343  
    3232using HeuristicLab.Persistence.Default.CompositeSerializers.Storable;
    3333using HeuristicLab.Problems.DataAnalysis;
    34 using HeuristicLab.Problems.SurrogateProblem;
    3534
    3635namespace HeuristicLab.Algorithms.EGO {
    37   /// <summary>
    38   /// A base class for operators that manipulate real-valued vectors.
    39   /// </summary>
    4036  [Item("ModelBuilder", "Builds a model from a dataset and a given RegressionAlgorithm")]
    4137  [StorableClass]
     
    120116        solution = SanitizeGaussianProcess(oldSolution as GaussianProcessRegressionSolution, solution as GaussianProcessRegressionSolution, Cancellation);
    121117
    122       if (regressionAlgorithm is M5RegressionTree && oldSolution != null)
    123         solution = SanitizeM5Regression(oldSolution.Model as M5Model, solution, random, Cancellation);
     118      //if (regressionAlgorithm is M5RegressionTree && oldSolution != null) solution = SanitizeM5Regression(oldSolution.Model as M5Model, solution, random, Cancellation);
    124119
    125120
     
    129124    }
    130125
    131     private static IRegressionSolution SanitizeM5Regression(M5Model oldmodel, IRegressionSolution newSolution, IRandom random, CancellationToken cancellation) {
    132       var problemdata = newSolution.ProblemData;
    133       oldmodel.UpdateLeafModels(problemdata, problemdata.AllIndices, random, cancellation);
    134       var oldSolution = oldmodel.CreateRegressionSolution(problemdata);
    135       var magicDecision = newSolution.TrainingRSquared < oldSolution.TrainingRSquared - 0.05;
    136       return magicDecision ? newSolution : oldmodel.CreateRegressionSolution(problemdata);
    137     }
     126    //private static IRegressionSolution SanitizeM5Regression(M5Model oldmodel, IRegressionSolution newSolution, IRandom random, CancellationToken cancellation) {
     127    //  var problemdata = newSolution.ProblemData;
     128    //  oldmodel.UpdateLeafModels(problemdata, problemdata.AllIndices, random, cancellation);
     129    //  var oldSolution = oldmodel.CreateRegressionSolution(problemdata);
     130    //  var magicDecision = newSolution.TrainingRSquared < oldSolution.TrainingRSquared - 0.05;
     131    //  return magicDecision ? newSolution : oldmodel.CreateRegressionSolution(problemdata);
     132    //}
    138133
    139134    //try creating a model with old hyperparameters and new dataset;
     
    150145          newSolution = sol;
    151146        }
    152       } catch (ArgumentException) { }
     147      }
     148      catch (ArgumentException) { }
    153149      return newSolution;
    154150    }
  • branches/EfficientGlobalOptimization/HeuristicLab.Algorithms.EGO/Operators/ModelQualityAnalyzer.cs

    r15338 r15343  
    3030
    3131namespace HeuristicLab.Algorithms.EGO {
    32   /// <summary>
    33   /// A base class for operators that manipulate real-valued vectors.
    34   /// </summary>
    3532  [Item("ModelQualityAnalyzer", "Collects RealVectors into a modifiablbe dataset")]
    3633  [StorableClass]
  • branches/EfficientGlobalOptimization/HeuristicLab.Algorithms.EGO/Operators/SampleCollector.cs

    r15064 r15343  
    3030
    3131namespace HeuristicLab.Algorithms.EGO {
    32   /// <summary>
    33   /// A base class for operators that manipulate real-valued vectors.
    34   /// </summary>
    3532  [Item("SampleCollector", "Collects RealVectors into a modifiablbe dataset")]
    3633  [StorableClass]
     
    5956      var quality = QualityParameter.ActualValue.Value;
    6057      var data = DatasetParameter.ActualValue;
    61 
    6258      if (data.Columns != vector.Length + 1) {
    6359        if (data.Columns != 0 || data.Rows != 0) throw new OperatorExecutionException(this, "dataset columns do not match samplesize+1");
     
    7066    }
    7167
    72 
    7368    private static void AddRow(ModifiableDataset data, RealVector vector, double quality) {
    7469      var row = new object[vector.Length + 1];
     
    7873      data.AddRow(row);
    7974    }
    80 
    81 
    82 
    8375  }
    8476}
  • branches/EfficientGlobalOptimization/HeuristicLab.Algorithms.EGO/SamplingMethods/LatinHyperCubeDesignCreator.cs

    r15064 r15343  
    2626using HeuristicLab.Core;
    2727using HeuristicLab.Data;
     28using HeuristicLab.Optimization;
    2829using HeuristicLab.Encodings.PermutationEncoding;
    2930using HeuristicLab.Encodings.RealVectorEncoding;
     
    3637  [StorableClass]
    3738  [Item("LatinHyperCubeDesignCreator", "A latin hypercube sampling strategy for real valued optimization")]
    38   public class LatinHyperCubeDesignCreator : RealVectorCreator, IInitialSampling {
     39  public class LatinHyperCubeDesignCreator : RealVectorCreator, IInitialSampling<RealVector> {
    3940    private IValueLookupParameter<IntValue> DesignSize => (IValueLookupParameter<IntValue>)Parameters["DesignSize"];
    4041    [Storable]
     
    5455    }
    5556
    56     public RealVector[] GetSamples(int noSamples, RealVector[] existingSamples, RealVectorEncoding encoding, IRandom random) {
    57       return GetSamples(random, encoding.Length, encoding.Bounds, noSamples);
     57    public RealVector[] GetSamples(int noSamples, RealVector[] existingSamples, IEncoding encoding, IRandom random) {
     58      var enc = encoding as RealVectorEncoding;
     59
     60
     61      return GetSamples(random, enc.Length, enc.Bounds, noSamples);
    5862    }
    5963
  • branches/EfficientGlobalOptimization/HeuristicLab.Algorithms.EGO/SamplingMethods/UniformRandomDiscreteSampling.cs

    r15340 r15343  
    2222using HeuristicLab.Common;
    2323using HeuristicLab.Core;
    24 using HeuristicLab.Encodings.RealVectorEncoding;
     24using HeuristicLab.Optimization;
     25using HeuristicLab.Encodings.IntegerVectorEncoding;
    2526using HeuristicLab.Persistence.Default.CompositeSerializers.Storable;
    2627
     
    2930
    3031  [StorableClass]
    31   [Item("UniformRandomSampling", "A uniform random sampling strategy for real valued optimization")]
    32   public class UniformRandomSampling : ParameterizedNamedItem, IInitialSampling {
     32  [Item("UniformRandomDiscreteSampling", "A uniform random sampling strategy for real valued optimization")]
     33  public class UniformRandomDiscreteSampling : ParameterizedNamedItem, IInitialSampling<IntegerVector> {
    3334
    3435    #region HL-Constructors, Serialization and Cloning
    3536    [StorableConstructor]
    36     protected UniformRandomSampling(bool deserializing) : base(deserializing) { }
    37     protected UniformRandomSampling(UniformRandomSampling original, Cloner cloner) : base(original, cloner) { }
    38     public UniformRandomSampling() {
     37    protected UniformRandomDiscreteSampling(bool deserializing) : base(deserializing) { }
     38    protected UniformRandomDiscreteSampling(UniformRandomDiscreteSampling original, Cloner cloner) : base(original, cloner) { }
     39    public UniformRandomDiscreteSampling() {
    3940    }
    4041    public override IDeepCloneable Clone(Cloner cloner) {
    41       return new UniformRandomSampling(this, cloner);
     42      return new UniformRandomDiscreteSampling(this, cloner);
    4243    }
    4344
    44     public RealVector[] GetSamples(int noSamples, RealVector[] existingSamples, RealVectorEncoding encoding, IRandom random) {
    45       var res = new RealVector[noSamples];
     45    public IntegerVector[] GetSamples(int noSamples, IntegerVector[] existingSamples, IEncoding encoding, IRandom random) {
     46      var enc = encoding as IntegerVectorEncoding;
     47      var res = new IntegerVector[noSamples];
    4648      for (var i = 0; i < noSamples; i++) {
    47         var r = new RealVector(encoding.Length);
     49        var r = new IntegerVector(enc.Length);
    4850        res[i] = r;
    49         for (var j = 0; j < encoding.Length; j++) {
    50           var b = j % encoding.Bounds.Rows;
    51           r[j] = UniformRandom(encoding.Bounds[b, 0], encoding.Bounds[b, 1], random);
     51        for (var j = 0; j < enc.Length; j++) {
     52          var b = j % enc.Bounds.Rows;
     53          r[j] = UniformRandom(enc.Bounds[b, 0], enc.Bounds[b, 1], random);
    5254        }
    5355      }
    5456      return res;
    5557    }
    56     private static double UniformRandom(double min, double max, IRandom rand) {
    57       return rand.NextDouble() * (max - min) + min;
     58    private static int UniformRandom(int min, int max, IRandom rand) {
     59      return rand.Next(min, max + 1);  //TODO check wether max is inclusive or exclusive
    5860    }
    5961  }
  • branches/EfficientGlobalOptimization/HeuristicLab.Algorithms.EGO/SamplingMethods/UniformRandomSampling.cs

    r15064 r15343  
    2222using HeuristicLab.Common;
    2323using HeuristicLab.Core;
     24using HeuristicLab.Optimization;
    2425using HeuristicLab.Encodings.RealVectorEncoding;
    2526using HeuristicLab.Persistence.Default.CompositeSerializers.Storable;
     
    3031  [StorableClass]
    3132  [Item("UniformRandomSampling", "A uniform random sampling strategy for real valued optimization")]
    32   public class UniformRandomSampling : ParameterizedNamedItem, IInitialSampling {
     33  public class UniformRandomSampling : ParameterizedNamedItem, IInitialSampling<RealVector> {
    3334
    3435    #region HL-Constructors, Serialization and Cloning
     
    4243    }
    4344
    44     public RealVector[] GetSamples(int noSamples, RealVector[] existingSamples, RealVectorEncoding encoding, IRandom random) {
     45    public RealVector[] GetSamples(int noSamples, RealVector[] existingSamples, IEncoding encoding, IRandom random) {
     46      var enc = encoding as RealVectorEncoding;
    4547      var res = new RealVector[noSamples];
    4648      for (var i = 0; i < noSamples; i++) {
    47         var r = new RealVector(encoding.Length);
     49        var r = new RealVector(enc.Length);
    4850        res[i] = r;
    49         for (var j = 0; j < encoding.Length; j++) {
    50           var b = j % encoding.Bounds.Rows;
    51           r[j] = UniformRandom(encoding.Bounds[b, 0], encoding.Bounds[b, 1], random);
     51        for (var j = 0; j < enc.Length; j++) {
     52          var b = j % enc.Bounds.Rows;
     53          r[j] = UniformRandom(enc.Bounds[b, 0], enc.Bounds[b, 1], random);
    5254        }
    5355      }
Note: See TracChangeset for help on using the changeset viewer.