Free cookie consent management tool by TermsFeed Policy Generator

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

#2745 added discretized EGO-version for use with IntegerVectors

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  
    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);
Note: See TracChangeset for help on using the changeset viewer.