Changeset 5207


Ignore:
Timestamp:
01/04/11 02:18:27 (12 years ago)
Author:
cneumuel
Message:

#1215

  • lots of memory-consumption improvements
  • validValues -> validTypes (this saves memory!)
  • changed manipulators; modifications are less significant, out-of-bound-values are resampled instead of set to lower or upper bound
  • changed the way a base-level algorithm gets executed -> introduced AlgorithmExecutor
Location:
branches/HeuristicLab.MetaOptimization
Files:
1 added
18 edited

Legend:

Unmodified
Added
Removed
  • branches/HeuristicLab.MetaOptimization/HeuristicLab.MetaOptimization.Test/HeuristicLab.MetaOptimization.Test.csproj

    r5184 r5207  
    176176      <HintPath>..\..\..\..\..\..\..\Program Files\HeuristicLab 3.3\HeuristicLab.Optimizer-3.3.dll</HintPath>
    177177    </Reference>
     178    <Reference Include="HeuristicLab.ParallelEngine-3.3">
     179      <HintPath>..\..\..\..\..\..\..\Program Files\HeuristicLab 3.3\HeuristicLab.ParallelEngine-3.3.dll</HintPath>
     180    </Reference>
    178181    <Reference Include="HeuristicLab.Parameters-3.3">
    179182      <HintPath>..\..\..\..\..\..\..\Program Files\HeuristicLab 3.3\HeuristicLab.Parameters-3.3.dll</HintPath>
     
    322325    <Compile Include="Program.cs" />
    323326    <Compile Include="Properties\AssemblyInfo.cs" />
     327    <Compile Include="TableBuilder.cs" />
    324328  </ItemGroup>
    325329  <ItemGroup>
  • branches/HeuristicLab.MetaOptimization/HeuristicLab.MetaOptimization.Test/Program.cs

    r5184 r5207  
    1818using HeuristicLab.Selection;
    1919using HeuristicLab.Parameters;
     20using HeuristicLab.Operators;
     21using System.Diagnostics;
     22using HeuristicLab.Encodings.RealVectorEncoding;
    2023
    2124namespace HeuristicLab.MetaOptimization.Test {
    2225  class Program {
    23     private static int metaAlgorithmPopulationSize = 10;
    24     private static int metaAlgorithmMaxGenerations = 10;
    25     private static int metaProblemRepetitions = 1;
    26 
    27     private static int baseAlgorithmMaxGenerations = 10;
     26    private static int metaAlgorithmPopulationSize = 50;
     27    private static int metaAlgorithmMaxGenerations = 30;
     28    private static int metaProblemRepetitions = 5;
     29    private static int baseAlgorithmMaxGenerations = 1000;
     30
     31    //private static int metaAlgorithmPopulationSize = 10;
     32    //private static int metaAlgorithmMaxGenerations = 20;
     33    //private static int metaProblemRepetitions = 3;
     34    //private static int baseAlgorithmMaxGenerations = 10;
    2835
    2936    static void Main(string[] args) {
     37      //TestTableBuilder();
    3038      //TestShorten();
    3139
    3240      //TestIntSampling();
    33       //TestDoubleSampling();
     41      //TestDoubleSampling(); return;
    3442      //TestTypeDiscovery();
    3543      //TestOperators();
     
    3947      //TestEnumeratorCollectionEnumerator();
    4048      //TestCombinations4();
     49      //TestAlgorithmPerformanceIssue();
    4150
    4251      GeneticAlgorithm baseLevelAlgorithm = new GeneticAlgorithm();
     52
     53      MetaOptimizationProblem metaOptimizationProblem = new MetaOptimizationProblem();
     54      metaOptimizationProblem.Repetitions = new IntValue(metaProblemRepetitions);
     55      //GeneticAlgorithm metaLevelAlgorithm = GetMetaGA(metaOptimizationProblem);
     56      GeneticAlgorithm metaLevelAlgorithm = GetParallelMetaGA(metaOptimizationProblem);
     57      //EvolutionStrategy metaLevelAlgorithm = GetMetaES(metaOptimizationProblem);
     58
     59      IValueConfiguration algorithmVc = SetupGAAlgorithm(baseLevelAlgorithm, metaOptimizationProblem);
     60
     61      //TestToString(algorithmVc);
     62
     63
     64      //Console.WriteLine("Press enter to start");
     65      //Console.ReadLine();
     66      //TestConfiguration(algorithmVc, baseLevelAlgorithm);
     67
     68      //Console.WriteLine("Press enter to start");
     69      //Console.ReadLine();
     70      TestOptimization(metaLevelAlgorithm);
     71
     72      //TestMemoryLeak(metaLevelAlgorithm);
     73
     74      Console.ReadLine();
     75    }
     76
     77    private static void TestAlgorithmPerformanceIssue() {
     78      ContentManager.Initialize(new PersistenceContentManager());
     79      Queue<TimeSpan> latestExecutionTimes = new Queue<TimeSpan>();
     80      int size = 10;
     81
     82      GeneticAlgorithm ga = new GeneticAlgorithm();
     83      ga.PopulationSize.Value = 3;
     84      ga.MaximumGenerations.Value = 1;
     85      ga.Engine = new SequentialEngine.SequentialEngine();
    4386
    4487      MetaOptimizationProblem metaOptimizationProblem = new MetaOptimizationProblem();
    4588      metaOptimizationProblem.Repetitions = new IntValue(metaProblemRepetitions);
    4689      GeneticAlgorithm metaLevelAlgorithm = GetMetaGA(metaOptimizationProblem);
    47       //EvolutionStrategy metaLevelAlgorithm = GetMetaES(metaOptimizationProblem);
    48 
    49       IValueConfiguration algorithmVc = SetupGAAlgorithm(baseLevelAlgorithm, metaOptimizationProblem);
    50 
    51       //TestToString(algorithmVc);
    52 
    53 
    54       //Console.WriteLine("Press enter to start");
    55       //Console.ReadLine();
    56       //TestConfiguration(algorithmVc, baseLevelAlgorithm);
    57 
    58       //Console.WriteLine("Press enter to start");
    59       //Console.ReadLine();
    60       TestOptimization(metaLevelAlgorithm);
    61 
    62       //TestMemoryLeak(metaLevelAlgorithm);
    63 
    64       Console.ReadLine();
    65     }
    66 
    67     private static void TestToString(IValueConfiguration algorithmVc) {
     90      ParameterConfigurationTree algorithmVc = SetupGAAlgorithm(ga, metaOptimizationProblem);
     91      Stopwatch sw = new Stopwatch();
     92
     93      for (int i = 0; i < 1000; i++) {
     94        sw.Start();
     95        GeneticAlgorithm clonedGa = (GeneticAlgorithm)ga.Clone();
     96        clonedGa.Name = "CLONED GA";
     97        algorithmVc.Parameterize(clonedGa);
     98        clonedGa.Prepare(true);
     99        var executor = new AlgorithmExecutor(clonedGa);
     100        executor.StartSync();
     101        sw.Stop();
     102        latestExecutionTimes.Enqueue(sw.Elapsed);
     103        Console.WriteLine("{0}: {1} ({2})", i, sw.Elapsed, latestExecutionTimes.Count > size ? TimeSpan.FromMilliseconds(latestExecutionTimes.Average(t => t.TotalMilliseconds)).ToString() : "-");
     104        if (latestExecutionTimes.Count > size) {
     105          latestExecutionTimes.Dequeue();
     106        }
     107        sw.Reset();
     108      }
     109    }
     110
     111    private static void TestTableBuilder() {
     112      TableBuilder tb = new TableBuilder("column_1", "col2", "col3");
     113      tb.AppendRow("1", "humpi", "0.23124");
     114      tb.AppendRow("2", "sf", "0.23124");
     115      tb.AppendRow("5", "humpi dampti", "0.224");
     116      tb.AppendRow("10", "egon asdf", "0.4");
     117      tb.AppendRow("15", "MichaelizcMultiVfds", "0.23124564");
     118      Console.WriteLine(tb.ToString());
     119    }
     120
     121    private static void TestToInfoString(IValueConfiguration algorithmVc) {
    68122      var random = new MersenneTwister();
    69123      Console.WriteLine(algorithmVc.ParameterInfoString);
     
    154208      }
    155209      Console.WriteLine("You are about to create {0} algorithms.", count);
    156      
     210
    157211      Experiment experiment = vc.GenerateExperiment(ga);
    158212      //foreach (var opt in experiment.Optimizers) {
     
    170224    private static void TestOperators() {
    171225      IRandom random = new MersenneTwister();
    172       ParameterConfigurationManipulator manip = new ParameterConfigurationManipulator();
    173 
    174       manip.IntValueManipulatorParameter.ActualValue = new UniformIntValueManipulator();
    175       manip.DoubleValueManipulatorParameter.ActualValue = new NormalDoubleValueManipulator();
    176226
    177227      var doubleRange = new DoubleValueRange(new DoubleValue(0), new DoubleValue(100), new DoubleValue(0.1));
    178228      using (var sw = new StreamWriter("out-DoubleValue.txt")) {
    179229        for (int i = 0; i < 10000; i++) {
    180           var val = new DoubleValue(50);
     230          var val = new DoubleValue(90);
    181231          NormalDoubleValueManipulator.ApplyStatic(random, val, doubleRange);
    182232
     
    244294      metaLevelAlgorithm.Problem = metaOptimizationProblem;
    245295      metaLevelAlgorithm.Engine = new SequentialEngine.SequentialEngine();
    246      
     296
    247297      metaLevelAlgorithm.Mutator = ((OptionalConstrainedValueParameter<IManipulator>)((IAlgorithm)metaLevelAlgorithm).Parameters["Mutator"]).ValidValues.Last();
    248      
     298
    249299      metaLevelAlgorithm.MutationProbability.Value = 0.15;
     300
     301      return metaLevelAlgorithm;
     302    }
     303
     304    private static GeneticAlgorithm GetParallelMetaGA(MetaOptimizationProblem metaOptimizationProblem) {
     305      GeneticAlgorithm metaLevelAlgorithm = GetMetaGA(metaOptimizationProblem);
     306
     307      UniformSubScopesProcessor uniformSubScopesProcessor =
     308        (HeuristicLab.Operators.UniformSubScopesProcessor)
     309        ((HeuristicLab.Operators.AlgorithmOperator)metaLevelAlgorithm.OperatorGraph.Operators.ElementAt(2)).OperatorGraph.Operators.ElementAt(8);
     310      uniformSubScopesProcessor.Parallel.Value = true;
     311
     312      metaLevelAlgorithm.Engine = new ParallelEngine.ParallelEngine();
    250313
    251314      return metaLevelAlgorithm;
     
    265328    }
    266329
    267     private static IValueConfiguration SetupGAAlgorithm(GeneticAlgorithm baseLevelAlgorithm, MetaOptimizationProblem metaOptimizationProblem) {
     330    private static ParameterConfigurationTree SetupGAAlgorithm(GeneticAlgorithm baseLevelAlgorithm, MetaOptimizationProblem metaOptimizationProblem) {
    268331      baseLevelAlgorithm.Problem = new HeuristicLab.Problems.TestFunctions.SingleObjectiveTestFunctionProblem();
    269332      baseLevelAlgorithm.MaximumGenerations.Value = baseAlgorithmMaxGenerations;
    270333
    271334      metaOptimizationProblem.Algorithm = baseLevelAlgorithm;
    272       IValueConfiguration algorithmVc = metaOptimizationProblem.ParameterConfigurationTree;
     335      ParameterConfigurationTree algorithmVc = metaOptimizationProblem.ParameterConfigurationTree;
    273336
    274337      metaOptimizationProblem.Problems.Add(new HeuristicLab.Problems.TestFunctions.SingleObjectiveTestFunctionProblem() {
     
    276339        ProblemSize = new IntValue(500)
    277340      });
    278       metaOptimizationProblem.Problems.Add(new HeuristicLab.Problems.TestFunctions.SingleObjectiveTestFunctionProblem() {
    279         Evaluator = new GriewankEvaluator(),
    280         ProblemSize = new IntValue(1000)
    281       });
    282 
    283       ConfigurePopulationSize(algorithmVc, 0, 10, 1);
    284       //ConfigureMutationRate(algorithmVc, 0.0, 1.0, 0.01);
    285       //ConfigureMutationOperator(algorithmVc);
     341      //metaOptimizationProblem.Problems.Add(new HeuristicLab.Problems.TestFunctions.SingleObjectiveTestFunctionProblem() {
     342      //  Evaluator = new GriewankEvaluator(),
     343      //  ProblemSize = new IntValue(1000)
     344      //});
     345
     346      ConfigurePopulationSize(algorithmVc, 0, 100, 1);
     347      ConfigureMutationRate(algorithmVc, 0.0, 1.0, 0.01);
     348      ConfigureMutationOperator(algorithmVc);
    286349      ConfigureElites(algorithmVc, 0, 10, 1);
    287       //ConfigureSelectionOperator(algorithmVc, true);
     350      ConfigureSelectionOperator(algorithmVc, true);
    288351      return algorithmVc;
    289352    }
     
    393456
    394457      groupSizePc.ValueConfigurations.First().Optimize = true;
    395       groupSizePc.ValueConfigurations.First().RangeConstraint.LowerBound = new IntValue(2);
     458      groupSizePc.ValueConfigurations.First().RangeConstraint.LowerBound = new IntValue(0);
    396459      groupSizePc.ValueConfigurations.First().RangeConstraint.UpperBound = new IntValue(10);
    397460      groupSizePc.ValueConfigurations.First().RangeConstraint.StepSize = new IntValue(1);
     
    441504
    442505        StringBuilder sb1 = new StringBuilder();
    443         sb1.AppendLine(string.Format("Meta.PopulationSize: {0}", metaAlgorithmPopulationSize));
    444         sb1.AppendLine(string.Format("Meta.MaxGenerations: {0}", metaAlgorithmMaxGenerations));
    445         sb1.AppendLine(string.Format("Meta.Repetitions   : {0}", metaProblemRepetitions));
    446         sb1.AppendLine(string.Format("Base.MaxGenerations: {0}", baseAlgorithmMaxGenerations));
     506        sb1.AppendFormat("Meta.PopulationSize: {0}\n", metaAlgorithmPopulationSize);
     507        sb1.AppendFormat("Meta.MaxGenerations: {0}\n", metaAlgorithmMaxGenerations);
     508        sb1.AppendFormat("Meta.Repetitions   : {0}\n", metaProblemRepetitions);
     509        sb1.AppendFormat("Meta.MutProb       : {0}\n", ((GeneticAlgorithm)metaLevelAlgorithm).MutationProbability.Value);
     510        sb1.AppendFormat("Base.MaxGenerations: {0}\n", baseAlgorithmMaxGenerations);
     511        sb1.AppendLine("Problems:");
     512        foreach (var prob in ((MetaOptimizationProblem)metaLevelAlgorithm.Problem).Problems) {
     513          sb1.Append(prob.Name);
     514          var sotf = prob as SingleObjectiveTestFunctionProblem;
     515          if (sotf != null) {
     516            sb1.AppendFormat(" {0}", sotf.ProblemSize.Value);
     517          }
     518          sb1.AppendLine();
     519        }
    447520        sw.WriteLine(sb1.ToString());
    448521        Console.WriteLine(sb1.ToString());
     
    463536
    464537            sb.AppendLine(metaLevelAlgorithm.ExecutionState.ToString());
    465             foreach (var result in metaLevelAlgorithm.Results) {
     538            var rsClone = (ResultCollection)metaLevelAlgorithm.Results.Clone();
     539            foreach (var result in rsClone) {
    466540              sb.AppendLine(result.ToString());
    467541              if (result.Name == "Population") {
     
    469543                var orderedRuns = rc.OrderBy(x => x.Results["RunsAverageQuality"]);
    470544
    471                 sb.AppendLine("Qual.  PoSi MutRa Eli SelOp MutOp");
     545                TableBuilder tb = new TableBuilder("AvgQual", "AvgET", "PoSi", "MutRa", "Eli", "SelOp", "MutOp", "NrSelSubScopes");
    472546                foreach (IRun run in orderedRuns) {
    473547                  string selector;
     
    478552                  }
    479553
    480                   sb.AppendLine(string.Format("{0} {1} {2} {3} {4} {5}",
    481                     ((DoubleValue)run.Results["RunsAverageQuality"]).Value.ToString("#0.00").PadLeft(7, ' '),
    482                     ((IntValue)run.Parameters["PopulationSize"]).Value.ToString().PadLeft(3, ' ').PadRight(3, ' '),
    483                     ((DoubleValue)run.Parameters["MutationProbability"]).Value.ToString("0.00").PadLeft(5, ' '),
    484                     ((IntValue)run.Parameters["Elites"]).Value.ToString().PadLeft(3, ' '),
    485                     Shorten(selector, 20).PadRight(20, ' '),
    486                     run.Parameters.ContainsKey("Mutator") ? run.Parameters["Mutator"].ToString() : "null"));
     554                  tb.AppendRow(
     555                    ((DoubleValue)run.Results["RunsAverageQuality"]).Value.ToString("#0.00"),
     556                    run.Results["RunsAverageExecutionTime"].ToString(),
     557                    ((IntValue)run.Parameters["PopulationSize"]).Value.ToString(),
     558                    ((DoubleValue)run.Parameters["MutationProbability"]).Value.ToString("0.00"),
     559                    ((IntValue)run.Parameters["Elites"]).Value.ToString(),
     560                    Shorten(selector, 20),
     561                    Shorten(run.Parameters.ContainsKey("Mutator") ? run.Parameters["Mutator"].ToString() : "null", 40),
     562                    ((ISelector)run.Parameters["Selector"]).NumberOfSelectedSubScopesParameter.Value.ToString());
    487563                }
     564                sb.AppendLine(tb.ToString());
    488565              }
    489566            } // foreach
    490             Console.Clear();
     567            //Console.Clear();
    491568            Console.WriteLine(sb.ToString());
    492569            sw.WriteLine(sb.ToString());
    493570            currentGeneration = ((IntValue)metaLevelAlgorithm.Results["Generations"].Value).Value;
    494571          } // if
    495           if (i % 30 == 0) GC.Collect();
     572          //if (i % 30 == 0) GC.Collect();
    496573          i++;
    497574        } while (metaLevelAlgorithm.ExecutionState != ExecutionState.Stopped);
     
    545622      int lower = 10;
    546623      int upper = 20;
    547       int stepsize = 7;
     624      int stepsize = 1;
    548625      for (int i = 0; i < 100; i++) {
    549626        int val;
     
    631708      int i = 0;
    632709      bool ok = false;
    633       while(!ok && i < enumerators.Count) {
    634         if(enumerators[i].MoveNext()) {
     710      while (!ok && i < enumerators.Count) {
     711        if (enumerators[i].MoveNext()) {
    635712          ok = true;
    636713        } else {
     
    640717
    641718      if (ok) {
    642         for (int k = i-1; k >= 0; k--) {
     719        for (int k = i - 1; k >= 0; k--) {
    643720          enumerators[k].Reset();
    644721          enumerators[k].MoveNext();
  • branches/HeuristicLab.MetaOptimization/HeuristicLab.MetaOptimization.sln

    r5110 r5207  
    1212    HeuristicLab.MetaOptimization.vsmdi = HeuristicLab.MetaOptimization.vsmdi
    1313    Local.testsettings = Local.testsettings
     14    Performance1.psess = Performance1.psess
    1415    PreBuildEvent.cmd = PreBuildEvent.cmd
    1516    TraceAndTestImpact.testsettings = TraceAndTestImpact.testsettings
  • branches/HeuristicLab.MetaOptimization/HeuristicLab.Problems.MetaOptimization.Views/3.3/ValueConfigurationViews/ValueView.cs

    r5110 r5207  
    4646
    4747    private void setValueButton_Click(object sender, EventArgs e) {
    48       var withoutNullValue = Content.ValidValues.Where(x => !(x is NullValue));
    49       var objectSelectorDialog = new ObjectSelectorDialog<IItem>(withoutNullValue.GroupBy(x => ApplicationManager.Manager.GetDeclaringPlugin(x.GetType()).Name));
     48      var typesWithoutNullValue = Content.ValidTypes.Where(x => x != typeof(NullValue));
     49      var instances = typesWithoutNullValue.Select(x => (IItem)Activator.CreateInstance(x));
     50      var groupedInstances = instances.GroupBy(x => ApplicationManager.Manager.GetDeclaringPlugin(x.GetType()).Name);
     51
     52      var objectSelectorDialog = new ObjectSelectorDialog<IItem>(groupedInstances);
    5053      if (objectSelectorDialog.ShowDialog(this) == DialogResult.OK) {
    5154        try {
  • branches/HeuristicLab.MetaOptimization/HeuristicLab.Problems.MetaOptimization/3.3/Encoding/Crossovers/ParameterConfigurationCrossover.cs

    r5184 r5207  
    88using HeuristicLab.Parameters;
    99using HeuristicLab.Persistence.Default.CompositeSerializers.Storable;
     10using System;
    1011
    1112namespace HeuristicLab.Problems.MetaOptimization {
     
    5758      ParameterConfigurationTree child2 = (ParameterConfigurationTree)ParentsParameter.ActualValue[1];
    5859
    59       //child1.Cross(child2, RandomParameter.ActualValue);
    60       //this.ChildParameter.ActualValue = child1;
    61 
    6260      child1.Cross(RandomParameter.ActualValue, child2, Cross, this);
    6361      this.ChildParameter.ActualValue = child1;
  • branches/HeuristicLab.MetaOptimization/HeuristicLab.Problems.MetaOptimization/3.3/Encoding/ParameterConfigurationTree.cs

    r5184 r5207  
    177177
    178178    public override void Parameterize(IParameterizedItem item) {
     179      this.parameters.Clear();
    179180      base.Parameterize(item);
    180       this.parameters.Clear();
    181181      ((IAlgorithm)item).CollectParameterValues(this.Parameters);
    182182    }
  • branches/HeuristicLab.MetaOptimization/HeuristicLab.Problems.MetaOptimization/3.3/Encoding/ParameterConfigurations/ParameterConfiguration.cs

    r5184 r5207  
    1010using HeuristicLab.PluginInfrastructure;
    1111using System.Text;
     12using System.Reflection;
    1213
    1314namespace HeuristicLab.Problems.MetaOptimization {
    1415  [StorableClass]
    1516  public class ParameterConfiguration : Item, IParameterConfiguration, IStorableContent {
    16     public bool IsOptimizable { 
    17       get { return true; } 
     17    public bool IsOptimizable {
     18      get { return true; }
    1819    }
    1920
     
    5859
    5960    [Storable]
    60     protected IItemSet<IItem> validValues;
    61     public IItemSet<IItem> ValidValues {
    62       get { return validValues; }
     61    protected Type[] validTypes;
     62    public Type[] ValidTypes {
     63      get { return validTypes; }
    6364      protected set {
    64         if (this.validValues != value) {
    65           this.validValues = value;
     65        if (this.validTypes != value) {
     66          this.validTypes = value;
    6667        }
    6768      }
     
    124125      this.parameterDataType = valueParameter.GetType();
    125126      this.valueDataType = valueParameter.DataType;
    126       this.validValues = GetValidValues(valueParameter);
     127      this.validTypes = GetValidTypes(valueParameter).ToArray();
    127128      this.IsNullable = valueParameter.ItemName.StartsWith("Optional");
    128129      if (IsNullable) {
    129         validValues.Add(new NullValue());
    130       }
    131       this.ValueConfigurations = new CheckedValueConfigurationCollection(this.validValues);
    132       this.ActualValue = new ConstrainedValue(valueParameter.Value, valueParameter.DataType, this.ValidValues, this.IsNullable);
     130        validTypes = new List<Type>(validTypes) { typeof(NullValue) }.ToArray();
     131      }
     132      this.ValueConfigurations = new CheckedValueConfigurationCollection(this.validTypes);
     133      this.ActualValue = new ConstrainedValue(valueParameter.Value != null ? (IItem)valueParameter.Value.Clone() : null, valueParameter.DataType, this.ValidTypes, this.IsNullable);
    133134      if (Optimize) {
    134135        PopulateValueConfigurations();
     
    139140    [StorableConstructor]
    140141    protected ParameterConfiguration(bool deserializing) { }
    141     protected ParameterConfiguration(ParameterConfiguration original, Cloner cloner) : base(original, cloner) {
     142    protected ParameterConfiguration(ParameterConfiguration original, Cloner cloner)
     143      : base(original, cloner) {
    142144      this.parameterName = original.ParameterName;
    143145      this.parameterDataType = original.parameterDataType;
    144146      this.valueDataType = original.ValueDataType;
    145       this.validValues = cloner.Clone(original.ValidValues);
     147      this.validTypes = original.validTypes.ToArray();
    146148      this.valueConfigurations = cloner.Clone(original.ValueConfigurations);
    147149      this.ActualValue = cloner.Clone(original.ActualValue);
     
    180182
    181183    private void PopulateValueConfigurations() {
    182       foreach (IItem validValue in this.validValues) {
    183         if (validValue is NullValue) {
     184      foreach (Type t in this.validTypes) {
     185        if (t == typeof(NullValue)) {
    184186          this.ValueConfigurations.Add(new NullValueConfiguration());
    185187        } else {
    186188          IItem val;
    187           if (ActualValue.Value != null && ActualValue.ValueDataType == validValue.GetType()) {
     189          if (ActualValue.Value != null && ActualValue.ValueDataType == t) {
    188190            val = ActualValue.Value; // use existing value for that type (if available)
    189191          } else {
    190             val = validValue;
     192            val = (IItem)Activator.CreateInstance(t);
    191193          }
    192194          this.ValueConfigurations.Add(new ValueConfiguration(val, val.GetType()), true);
     
    195197    }
    196198
    197     private IItemSet<IItem> GetValidValues(IValueParameter parameter) {
    198       if (IsSubclassOfRawGeneric(typeof(OptionalConstrainedValueParameter<>), parameter.GetType())) {
    199         var x = (IEnumerable)parameter.GetType().GetProperty("ValidValues").GetValue(parameter, new object[] { });
    200         return new ItemSet<IItem>(x.Cast<IItem>());
    201       } else {
    202         return new ItemSet<IItem>(ApplicationManager.Manager.GetInstances(valueDataType).Select(x => (IItem)x).OrderBy(x => x.ItemName));
    203       }
     199    private IEnumerable<Type> GetValidTypes(IValueParameter parameter) {
     200      //if (IsSubclassOfRawGeneric(typeof(OptionalConstrainedValueParameter<>), parameter.GetType())) {
     201      //  var x = (IEnumerable)parameter.GetType().GetProperty("ValidValues").GetValue(parameter, new object[] { });
     202      //  return new ItemSet<IItem>(x.Cast<IItem>());
     203      //} else {
     204      //  return new ItemSet<IItem>(ApplicationManager.Manager.GetInstances(valueDataType).Select(x => (IItem)x).OrderBy(x => x.ItemName));
     205      //}
     206      return ApplicationManager.Manager.GetTypes(valueDataType, true);
    204207    }
    205208
     
    278281      if (handler != null) handler(sender, e);
    279282    }
    280    
     283
    281284    public virtual event EventHandler IsOptimizableChanged;
    282285    private void OnIsOptimizableChanged() {
     
    333336        }
    334337      }
    335       parameter.Value = this.ActualValue.Value;
     338      var clonedValue = this.ActualValue.Value != null ? (IItem)this.ActualValue.Value.Clone() : null;
     339      AdaptValidValues(parameter, clonedValue);
     340      parameter.Value = clonedValue;
     341    }
     342
     343    /// <summary>
     344    /// Adds value to the ValidValues of the parameter if they don't contain the value
     345    /// </summary>
     346    private void AdaptValidValues(IValueParameter parameter, IItem value) {
     347      // this requires some tricky reflection, because the type is unknown at runtime so parameter.ValidValues cannot be casted to Collection<?>
     348      if (IsSubclassOfRawGeneric(typeof(OptionalConstrainedValueParameter<>), parameter.GetType())) {
     349        var validValues = parameter.GetType().GetProperty("ValidValues").GetValue(parameter, new object[] { });
     350        Type validValuesType = validValues.GetType();
     351
     352        var containsMethod = validValuesType.GetMethod("Contains");
     353        if (!(bool)containsMethod.Invoke(validValues, new object[] { value })) {
     354          var addMethod = validValuesType.GetMethod("Add");
     355          addMethod.Invoke(validValues, new object[] { value });
     356        }
     357      }
    336358    }
    337359
  • branches/HeuristicLab.MetaOptimization/HeuristicLab.Problems.MetaOptimization/3.3/Encoding/RangeConstraints/ConstrainedValue.cs

    r5112 r5207  
    3333
    3434    [Storable]
    35     protected IItemSet<IItem> validValues;
    36     public IItemSet<IItem> ValidValues {
    37       get { return validValues; }
     35    protected Type[] validTypes;
     36    public Type[] ValidTypes {
     37      get { return validTypes; }
    3838      protected set {
    39         if (this.validValues != value) {
    40           this.validValues = value;
     39        if (this.validTypes != value) {
     40          this.validTypes = value;
    4141        }
    4242      }
     
    6565    [StorableConstructor]
    6666    protected ConstrainedValue(bool deserializing) : base(deserializing) { }
    67     public ConstrainedValue(IItem value, Type valueDataType, IItemSet<IItem> validValues, bool isNullable) {
     67    public ConstrainedValue(IItem value, Type valueDataType, Type[] validTypes, bool isNullable) {
    6868      this.Value = value;
    6969      this.ValueDataType = valueDataType;
    70       this.ValidValues = validValues;
     70      this.ValidTypes = validTypes;
    7171      this.isNullable = isNullable;
    7272    }
     
    7474      this.valueDataType = original.valueDataType;
    7575      this.Value = cloner.Clone(original.value);
    76       this.ValidValues = cloner.Clone(original.ValidValues);
     76      if(original.ValidTypes != null) this.ValidTypes = original.ValidTypes.ToArray();
    7777      this.isNullable = original.isNullable;
    7878    }
  • branches/HeuristicLab.MetaOptimization/HeuristicLab.Problems.MetaOptimization/3.3/Encoding/RangeConstraints/DoubleValueRange.cs

    r5184 r5207  
    2525      do {
    2626        val = Math.Round((random.NextDouble() * (UpperBound.Value - LowerBound.Value) + LowerBound.Value) / StepSize.Value, 0) * StepSize.Value;
    27       } while (val < LowerBound.Value || val > UpperBound.Value);
     27      } while (!IsInRange(val));
    2828      return new DoubleValue(val);
    2929    }
    3030
    31     public void Fix(DoubleValue value) {
    32       // apply stepsize
     31    public void ApplyStepSize(DoubleValue value) {
    3332      value.Value = ((int)Math.Round(value.Value / this.StepSize.Value, 0)) * this.StepSize.Value;
     33    }
    3434
    35       // repair bounds
    36       if (value.Value > this.UpperBound.Value) value.Value = this.UpperBound.Value;
    37       if (value.Value < this.LowerBound.Value) value.Value = this.LowerBound.Value;
     35    public bool IsInRange(double value) {
     36      return value <= this.UpperBound.Value && value >= this.LowerBound.Value;
    3837    }
    3938
    4039    public override IEnumerable<DoubleValue> GetCombinations() {
    4140      var solutions = new List<DoubleValue>();
    42       double value = ((int)Math.Round(LowerBound.Value / StepSize.Value, 0)) * StepSize.Value;
    43       if (value < LowerBound.Value) value += StepSize.Value;
     41      double value = LowerBound.Value;
    4442
    4543      while (value <= UpperBound.Value) {
  • branches/HeuristicLab.MetaOptimization/HeuristicLab.Problems.MetaOptimization/3.3/Encoding/RangeConstraints/IntValueRange.cs

    r5184 r5207  
    2525      do {
    2626        val = random.Next(LowerBound.Value / StepSize.Value, UpperBound.Value / StepSize.Value + 1) * StepSize.Value;
    27       } while (val < LowerBound.Value || val > UpperBound.Value);
     27      } while (!IsInRange(val));
    2828      return new IntValue(val);
    2929    }
    3030
    31     public void Fix(IntValue value) {
    32       // apply stepsize
     31    public void ApplyStepSize(IntValue value) {
    3332      value.Value = ((int)Math.Round(value.Value / (double)this.StepSize.Value, 0)) * this.StepSize.Value;
     33    }
    3434
    35       // repair bounds
    36       if (value.Value > this.UpperBound.Value) value.Value = this.UpperBound.Value;
    37       if (value.Value < this.LowerBound.Value) value.Value = this.LowerBound.Value;
     35    public bool IsInRange(int value) {
     36      return value <= this.UpperBound.Value && value >= this.LowerBound.Value;
    3837    }
    3938
    4039    public override IEnumerable<IntValue> GetCombinations() {
    4140      var solutions = new List<IntValue>();
    42       int value = (this.LowerBound.Value / StepSize.Value) * StepSize.Value;
    43       if (value < this.LowerBound.Value) value += StepSize.Value;
     41      int value = this.LowerBound.Value;
    4442
    4543      while (value <= this.UpperBound.Value) {
  • branches/HeuristicLab.MetaOptimization/HeuristicLab.Problems.MetaOptimization/3.3/Encoding/RangeConstraints/PercentValueRange.cs

    r5184 r5207  
    2525      do {
    2626        val = Math.Round((random.NextDouble() * (UpperBound.Value - LowerBound.Value) + LowerBound.Value) / StepSize.Value, 0) * StepSize.Value;
    27       } while (val < LowerBound.Value || val > UpperBound.Value);
     27      } while (!IsInRange(val));
    2828      return new PercentValue(val);
    2929    }
     
    3333    }
    3434
     35    public void ApplyStepSize(PercentValue value) {
     36      value.Value = ((int)Math.Round(value.Value / this.StepSize.Value, 0)) * this.StepSize.Value;
     37    }
     38
     39    public bool IsInRange(double value) {
     40      return value <= this.UpperBound.Value && value >= this.LowerBound.Value;
     41    }
     42
    3543    public override IEnumerable<PercentValue> GetCombinations() {
    3644      var solutions = new List<PercentValue>();
    37       double value = ((int)Math.Round(LowerBound.Value / StepSize.Value, 0)) * StepSize.Value;
    38       if (value < LowerBound.Value) value += StepSize.Value;
     45      double value = LowerBound.Value;
    3946
    4047      while (value <= UpperBound.Value) {
  • branches/HeuristicLab.MetaOptimization/HeuristicLab.Problems.MetaOptimization/3.3/Encoding/ValueConfigurations/CheckedValueConfigurationCollection.cs

    r5112 r5207  
    2424    }
    2525
    26     public CheckedValueConfigurationCollection(IItemSet<IItem> validValues) {
    27       this.validValues = validValues;
     26    public CheckedValueConfigurationCollection(IEnumerable<Type> validTypes) {
     27      this.validValues = new ItemSet<IItem>();
     28      foreach (Type t in validTypes) {
     29        this.validValues.Add((IItem)Activator.CreateInstance(t));
     30      }
    2831      RegisterEvents();
    2932    }
  • branches/HeuristicLab.MetaOptimization/HeuristicLab.Problems.MetaOptimization/3.3/Encoding/ValueConfigurations/ValueConfiguration.cs

    r5184 r5207  
    6060      set {
    6161        if (this.actualValue != value) {
    62           RegisterActualValueEvents();
     62          DeregisterActualValueEvents();
    6363          ClearParameterConfigurations();
    6464          this.actualValue = value;
     
    6666          OnValueChanged();
    6767          OnToStringChanged();
    68           DeregisterActualValueEvents();
     68          RegisterActualValueEvents();
    6969        }
    7070      }
     
    8787    public ValueConfiguration(IItem value, Type valueDataType) {
    8888      this.ParameterConfigurations = new ItemList<IParameterConfiguration>();
    89       var validValues = new ItemSet<IItem>(ApplicationManager.Manager.GetInstances(valueDataType).Select(x => (IItem)x).OrderBy(x => x.ItemName));
    90       this.ActualValue = new ConstrainedValue(value, valueDataType, validValues, false);
     89      var validTypes = ApplicationManager.Manager.GetTypes(valueDataType).OrderBy(x => x.Name).ToArray();
     90      this.ActualValue = new ConstrainedValue(value, valueDataType, validTypes, false);
    9191      this.IsOptimizable = true;
    9292      if (actualValue.ValueDataType == typeof(IntValue)) {
  • branches/HeuristicLab.MetaOptimization/HeuristicLab.Problems.MetaOptimization/3.3/Evaluators/ParameterConfigurationEvaluator.cs

    r5184 r5207  
    1010using HeuristicLab.Persistence.Default.CompositeSerializers.Storable;
    1111using System.Collections.Generic;
     12using HeuristicLab.Algorithms.GeneticAlgorithm;
     13using System.Threading.Tasks;
     14using System.Diagnostics;
     15using System.Reflection;
    1216
    1317namespace HeuristicLab.Problems.MetaOptimization {
     
    1822  [StorableClass]
    1923  public class ParameterConfigurationEvaluator : SingleSuccessorOperator, IParameterConfigurationEvaluator {
    20     private bool algorithmStopped;
    21     private bool algorithmExceptionOccured;
     24    private const double PenaltyQuality = 100000.0; // todo: use something better
    2225
    2326    public ILookupParameter<DoubleValue> QualityParameter {
     
    5457    protected ParameterConfigurationEvaluator(ParameterConfigurationEvaluator original, Cloner cloner)
    5558      : base(original, cloner) {
    56       this.algorithmStopped = original.algorithmStopped;
    5759    }
    5860    public override IDeepCloneable Clone(Cloner cloner) {
     
    6163
    6264    public override IOperation Apply() {
    63       EngineAlgorithm algorithm = AlgorithmParameter.ActualValue;
     65      EngineAlgorithm algorithm = (EngineAlgorithm)AlgorithmParameter.ActualValue.Clone();
    6466      IItemList<ISingleObjectiveProblem> problems = ProblemsParameter.ActualValue;
    6567
    6668      // set parameters
    6769      ParameterConfigurationParameter.ActualValue.Parameterize(algorithm);
    68       algorithm.Problem = problems.First();
    6970      algorithm.StoreAlgorithmInEachRun = false;
    70 
    71       algorithmStopped = false;
    72       algorithmExceptionOccured = false;
    73       algorithm.Stopped += new EventHandler(algorithm_Stopped);
    74       algorithm.Paused += new EventHandler(algorithm_Paused);
    75       algorithm.ExceptionOccurred += new EventHandler<EventArgs<Exception>>(algorithm_ExceptionOccurred);
    7671
    7772      List<double> qualities = new List<double>();
     
    8176
    8277      foreach (ISingleObjectiveProblem problem in problems) {
    83         algorithm.Problem = problem;
     78        algorithm.Problem = (IProblem)problem.Clone();
    8479
    8580        for (int i = 0; i < Repetitions.Value; i++) {
    8681          algorithm.Prepare();
    87           algorithm.Start();
    88           while (!algorithmStopped) {
    89             Thread.Sleep(200); // wait for algorithm to complete; do not rely on Algorithm.ExecutionState here, because change of ExecutionState happens before Run is added (which causes problems because Algorithm might get cloned when its started already)
    90           }
    9182
    92           if (algorithmExceptionOccured) {
     83          AlgorithmExecutor executor = new AlgorithmExecutor(algorithm);
     84          executor.StartSync();
     85
     86          if (algorithm.ExecutionState == ExecutionState.Paused) {
    9387            // this parametercombination was bad. set penalty for this solution
    94             qualities.Add(double.MaxValue); // todo: respect Maximization
     88            qualities.Add(PenaltyQuality); // todo: respect Maximization; problem: this messes up average value; solution: use currently worst quality*2
    9589            executionTimes.Add(algorithm.ExecutionTime);
    9690          } else {
     
    10397            algorithm.Runs.Last().Parameters.Add("Problem", problem);
    10498          }
    105           algorithmStopped = false;
    106           algorithmExceptionOccured = false;
    10799        }
    108100      }
    109 
    110       algorithm.Stopped -= new EventHandler(algorithm_Stopped);
    111       algorithm.Paused -= new EventHandler(algorithm_Paused);
    112       algorithm.ExceptionOccurred -= new EventHandler<EventArgs<Exception>>(algorithm_ExceptionOccurred);
    113101      algorithm.Prepare();
    114102
     
    130118    }
    131119
    132     private void algorithm_Paused(object sender, EventArgs e) {
    133       algorithmStopped = true;
    134     }
    135 
    136     private void algorithm_Stopped(object sender, EventArgs e) {
    137       algorithmStopped = true;
    138     }
    139 
    140     void algorithm_ExceptionOccurred(object sender, EventArgs<Exception> e) {
    141       algorithmExceptionOccured = true;
    142     }
    143 
    144120    public static double Variance(IEnumerable<double> source) {
    145121      double avg = source.Average();
     
    151127      return Math.Sqrt(source.Variance());
    152128    }
     129  }
    153130
     131  public class AlgorithmExecutor {
     132    private EngineAlgorithm algorithm;
     133    private AutoResetEvent waitHandle = new AutoResetEvent(false);
    154134
     135    public AlgorithmExecutor(EngineAlgorithm algorithm) {
     136      this.algorithm = algorithm;
     137    }
     138
     139    public void StartSync() {
     140      algorithm.Stopped += new EventHandler(algorithm_Stopped);
     141      algorithm.Paused += new EventHandler(algorithm_Paused);
     142      algorithm.Start();
     143      waitHandle.WaitOne();
     144      waitHandle.Dispose();
     145      algorithm.Stopped -= new EventHandler(algorithm_Stopped);
     146      algorithm.Paused -= new EventHandler(algorithm_Paused);
     147    }
     148
     149    void algorithm_Paused(object sender, EventArgs e) {
     150      waitHandle.Set();
     151    }
     152
     153    void algorithm_Stopped(object sender, EventArgs e) {
     154      waitHandle.Set();
     155    }
    155156  }
    156157}
  • branches/HeuristicLab.MetaOptimization/HeuristicLab.Problems.MetaOptimization/3.3/Interfaces/IParameterConfiguration.cs

    r5144 r5207  
    1010    Type ParameterDataType { get; }
    1111    ICheckedValueConfigurationCollection ValueConfigurations { get; }
    12     IItemSet<IItem> ValidValues { get; }
     12    Type[] ValidTypes { get; }
    1313    int ActualValueConfigurationIndex { get; set; }
    1414
  • branches/HeuristicLab.MetaOptimization/HeuristicLab.Problems.MetaOptimization/3.3/Operators/Manipulators/NormalDoubleValueManipulator.cs

    r5111 r5207  
    3636
    3737    public static void ApplyStatic(IRandom random, DoubleValue value, DoubleValueRange range) {
    38       var vector = new RealVector(new double[] { value.Value });
    39       var strategy = new RealVector(new double[] { (range.UpperBound.Value - range.LowerBound.Value) / 5});
    40       NormalAllPositionsManipulator.Apply(random, vector, strategy);
    41       value.Value = vector[0];
    42       range.Fix(value);
     38      bool ok = false;
     39      RealVector strategy = new RealVector(new double[] { (range.UpperBound.Value - range.LowerBound.Value) / 15});
     40      RealVector vector = new RealVector(1);
     41      double val = value.Value;
     42
     43      while (!ok) {
     44        vector[0] = val;
     45        NormalAllPositionsManipulator.Apply(random, vector, strategy);
     46        value.Value = vector[0];
     47        range.ApplyStepSize(value);
     48        ok = range.IsInRange(value.Value);
     49      }
    4350    }
    4451  }
  • branches/HeuristicLab.MetaOptimization/HeuristicLab.Problems.MetaOptimization/3.3/Operators/Manipulators/UniformDoubleValueManipulator.cs

    r5111 r5207  
    3636
    3737    public static void ApplyStatic(IRandom random, DoubleValue value, DoubleValueRange range) {
    38       var vector = new RealVector(new double[] { value.Value });
     38      bool ok = false;
     39      var vector = new RealVector(1);
    3940      var bounds = new DoubleMatrix(1, 2);
    4041      bounds[0, 0] = range.LowerBound.Value;
    4142      bounds[0, 1] = range.UpperBound.Value;
    42       UniformOnePositionManipulator.Apply(random, vector, bounds);
    43       value.Value = vector[0];
    44       range.Fix(value);
     43      double val = value.Value;
     44
     45      while (!ok) {
     46        vector[0] = val;
     47        UniformOnePositionManipulator.Apply(random, vector, bounds);
     48        value.Value = vector[0];
     49        range.ApplyStepSize(value);
     50        ok = range.IsInRange(value.Value);
     51      }
    4552    }
    4653  }
  • branches/HeuristicLab.MetaOptimization/HeuristicLab.Problems.MetaOptimization/3.3/Operators/Manipulators/UniformIntValueManipulator.cs

    r5111 r5207  
    3737
    3838    public static void ApplyStatic(IRandom random, IntValue value, IntValueRange range) {
     39      bool ok = false;
    3940      var vector = new IntegerVector(new int[] { value.Value });
    40       UniformOnePositionManipulator.Apply(random, vector, range.LowerBound, new IntValue(range.UpperBound.Value + 1));
    41       value.Value = vector[0];
    42       range.Fix(value);
     41      int val = value.Value;
     42
     43      while (!ok) {
     44        vector[0] = val;
     45        UniformOnePositionManipulator.Apply(random, vector, range.LowerBound, new IntValue(range.UpperBound.Value + 1));
     46        value.Value = vector[0];
     47        range.ApplyStepSize(value);
     48        ok = range.IsInRange(value.Value);
     49      }
    4350    }
    4451  }
Note: See TracChangeset for help on using the changeset viewer.