Free cookie consent management tool by TermsFeed Policy Generator

Ignore:
Timestamp:
10/17/12 10:57:14 (12 years ago)
Author:
fschoepp
Message:

#1888:

  • Added a parser for independent scenarios (using the model of the optimization backend)
  • Optimization scenario sample can be found in mappings folder of the web project.
  • Added IScenarioMapper interface which provides functionality to map from the optimization data model to a backend model (e.g. Heuristic Lab data model)
  • Implementations of IScenarioMapper have to be provided as C# code (strings) which will be compiled by using a CSharpCodeProvider. Once compiled, the implementations of the IScenarioMapper are being cached within the platform for further usage.
  • Fixed a bug in web template DecimalMatrix (using i instead of j)
  • Added missing thumprint of localhost certificate to the optimization web project (ServiceConfiguration.Local.cscfg / ServiceConfiguration.Cloud.cscfg)
  • Test project now provides following test cases: Mapping types using IronPython and mapping types using Otis
File:
1 edited

Legend:

Unmodified
Added
Removed
  • branches/OaaS/HeuristicLab.Services.Optimization.Controller/HiveScenarioManager.cs

    r8545 r8817  
    1515using System.Threading;
    1616using HeuristicLab.Data;
     17using System.IO;
    1718
    1819namespace HeuristicLab.Services.Optimization.ControllerService {
    1920  public class HiveScenarioManager : IScenarioManager {
    20     public object MapControllerDataType(object model, Parameter param) {
    21       switch (param.Type) {
    22         case ParameterType.Boolean:
    23           return (param.Value as Model.BoolValue).Value;
    24         case ParameterType.Integer:
    25           return Convert.ToInt32((param.Value as Model.DecimalValue).Value);         
    26         case ParameterType.Percent:       
    27         case ParameterType.Decimal:
    28           return (param.Value as Model.DecimalValue).Value;
    29         case ParameterType.DecimalMatrix:
    30           return Utility.ToMultiD(((param.Value as Model.DecimalMatrix).Value));
    31         case ParameterType.DecimalVector:
    32           return (param.Value as Model.DecimalVector).Value;
    33         case ParameterType.Type:
    34           //TODO handle type correctly!
    35           var typeValue = param.Value as Model.TypeValue;
    36          
    37           IProblem problem = model as IProblem;
    38           IAlgorithm algoModel = model as IAlgorithm;
    39           if (problem == null && algoModel != null) {
    40             problem = algoModel.Problem;
    41           }
    42 
    43           if (problem != null) {
    44             var toselect = problem.Operators.OfType<IOperator>().FirstOrDefault(x => x.Name == typeValue.Value);
    45             if (toselect != null) {
    46               return toselect;
    47             }
    48           }
    49          
    50           string parameterPropertyName = typeValue.Name.EndsWith("Parameter") ? typeValue.Name : typeValue.Name + "Parameter";
    51           var parameterProperty = model.GetType().GetProperty(parameterPropertyName);
    52           if (parameterProperty != null) {
    53             var parameterPropertyValue = parameterProperty.GetGetMethod().Invoke(model, null);
    54             var vvProp = parameterPropertyValue.GetType().GetProperty("ValidValues");
    55             if (vvProp != null) {
    56               //http://stackoverflow.com/questions/245607/how-is-generic-covariance-contra-variance-implemented-in-c-sharp-4-0 because of covariance declared in IEnumerable
    57               var options = vvProp.GetGetMethod().Invoke(parameterPropertyValue, null) as IEnumerable<IItem>;
    58               if (options != null) {
    59                 var result = options.FirstOrDefault(x => x.ItemName == typeValue.Value);
    60                 if (result != null)
    61                   return result;
    62               }
    63             }
    64           }
    65 
    66           Type type = null;
    67           foreach (var asm in AppDomain.CurrentDomain.GetAssemblies()) {
    68             type = asm.GetType(typeValue.Value);
    69             if (type != null)
    70               break;
    71           }
    72          
    73           return Activator.CreateInstance(type);
    74       }
    75       return null;
    76     }
    77 
    78     public object CreateHLObjectForType(object obj, Type type, Parameter prop) {
    79       var value = MapControllerDataType(obj, prop);
    80       if (prop.Type == ParameterType.Type)
    81         return value;
    82 
    83       if (type == typeof(HeuristicLab.Encodings.PermutationEncoding.Permutation)) {
    84         double[] input = value as double[];
    85         int[] arr = new int[input.Length];
    86         for (int i = 0; i < input.Length; i++) {
    87           arr[i] = Convert.ToInt32(input[i]);
    88         }
    89         var valueObj = new HeuristicLab.Encodings.PermutationEncoding.Permutation(Encodings.PermutationEncoding.PermutationTypes.RelativeUndirected, arr);
    90         return valueObj;
    91       }
    92       var propertyGetter = obj.GetType().GetProperty(prop.Value.Name).GetGetMethod();       
    93       return Activator.CreateInstance(propertyGetter.ReturnType, value);
    94     }
    95 
    96     private void MapProperty(object model, Parameter prop) {
    97       var propertyGetter = model.GetType().GetProperty(prop.Value.Name).GetGetMethod();
    98       var propertySetter = model.GetType().GetProperty(prop.Value.Name).GetSetMethod();
    99       var value = propertyGetter.Invoke(model, null);
    100       var valueProperty = value != null ? value.GetType().GetProperty("Value") : null;
    101       if (propertySetter != null) {
    102         var instance = CreateHLObjectForType(model, propertyGetter.ReturnType, prop);
    103         propertySetter.Invoke(model, new object[] { instance });
    104       }
    105       else if (valueProperty != null) {       
    106         valueProperty.GetSetMethod().Invoke(value, new object[] { MapControllerDataType(model, prop) });
    107       }
    108       else {
    109         Console.WriteLine("Failed to handle property!");
    110       }
     21    private static IScenarioMapper tspMapper;
     22    private static object lockable;
     23
     24    static HiveScenarioManager() {
     25      lockable = new object();
    11126    }
    11227
     
    11429      Experiment experiment = new Experiment();
    11530      var problem = new TravelingSalesmanProblem();
    116       foreach (var prop in scenario.InputParameters.Items) {
    117         MapProperty(problem, prop);
    118       }
    119 
    12031      var algo = new GeneticAlgorithm();
    12132      algo.Problem = problem;     
    122       foreach (var prop in scenario.AlgorithmParameters.Items) {
    123         MapProperty(algo, prop);
    124       }
     33     
     34      MapExperiment(scenario, algo);
    12535
    12636      experiment.Optimizers.Add(algo);
    12737      SendExperimentToHive(user, experiment);
     38    }
     39
     40    static public string AssemblyDirectory {
     41      get {
     42        string codeBase = Assembly.GetExecutingAssembly().CodeBase;
     43        UriBuilder uri = new UriBuilder(codeBase);
     44        string path = Uri.UnescapeDataString(uri.Path);
     45        return Path.GetDirectoryName(path);
     46      }
     47    }
     48
     49    private IScenarioMapper GetMapper(Model.OptimizationScenario scenario) {
     50      if (tspMapper == null) {
     51        lock (lockable) {
     52          if (tspMapper != null)
     53            return tspMapper;
     54         
     55          // http://stackoverflow.com/questions/3188882/compile-and-run-dynamic-code-without-generating-exe
     56          using (var csCodeProvider = new Microsoft.CSharp.CSharpCodeProvider()) {
     57            var cp = new System.CodeDom.Compiler.CompilerParameters() {
     58              GenerateInMemory = true
     59            };
     60
     61            var referencedPaths = Directory.GetFiles(AssemblyDirectory, "*.dll");
     62            foreach (var loadedAssembly in referencedPaths) {
     63              cp.ReferencedAssemblies.Add(loadedAssembly);
     64            }
     65            cp.ReferencedAssemblies.Add("System.dll");
     66            cp.ReferencedAssemblies.Add("System.Core.dll");
     67            cp.ReferencedAssemblies.Add("System.Data.dll");
     68            cp.ReferencedAssemblies.Add("System.Xml.dll");
     69            cp.ReferencedAssemblies.Add("System.Xml.Linq.dll");
     70
     71            var res = csCodeProvider.CompileAssemblyFromSource(
     72              cp,
     73            @"using System;
     74              using System.Collections.Generic;
     75              using System.Linq;
     76              using System.Text;
     77              using HeuristicLab.Data;
     78              using HeuristicLab.Services.Optimization.ControllerService.Model;
     79              using HeuristicLab.Optimization;
     80              using HeuristicLab.Services.Optimization.ControllerService;
     81              using HeuristicLab.Algorithms.GeneticAlgorithm;
     82              using HeuristicLab.Problems.TravelingSalesman;
     83              public class TSPScenarioMapper : IScenarioMapper {
     84                public void MapScenario(OptimizationScenario scenario, IAlgorithm algorithm) {
     85                  Console.WriteLine(""Mapping scenario!"");
     86                  var ga = algorithm as GeneticAlgorithm;
     87                  var problem = algorithm.Problem as TravelingSalesmanProblem;
     88                 
     89                  problem.BestKnownQuality = HLMapper.ConvertToDoubleValue(scenario.InputParameters.FindByName(""BestKnownQuality""));
     90                  problem.BestKnownSolution = HLMapper.ConvertToPermutation(scenario.InputParameters.FindByName(""BestKnownSolution""));
     91                  problem.Coordinates = HLMapper.ConvertToDoubleMatrix(scenario.InputParameters.FindByName(""Coordinates""));
     92                  var evalParam = HLMapper.GetStringValue(scenario.InputParameters.FindByName(""EvaluatorParameter""));
     93                  if (evalParam == ""HeuristicLab.Problems.TravelingSalesman.TSPRoundedEuclideanPathEvaluator"") {
     94                    problem.EvaluatorParameter.Value = new TSPRoundedEuclideanPathEvaluator();
     95                  }
     96                  else if (evalParam == ""HeuristicLab.Problems.TravelingSalesman.TSPGeoPathEvaluator"") {
     97                    problem.EvaluatorParameter.Value = new TSPGeoPathEvaluator();
     98                  }
     99                  else {
     100                    problem.EvaluatorParameter.Value = new TSPEuclideanPathEvaluator();
     101                  }
     102                  problem.UseDistanceMatrix = HLMapper.ConvertToBoolValue(scenario.InputParameters.FindByName(""UseDistanceMatrix""));
     103                  Console.WriteLine(""Mapping algorithm..."");
     104                  ga.Mutator = HLMapper.FindInItemSet<HeuristicLab.Optimization.IManipulator>(ga.MutatorParameter.ValidValues, scenario.AlgorithmParameters.FindByName(""Mutator""));
     105                  ga.CrossoverParameter.Value = HLMapper.FindOperator<HeuristicLab.Optimization.ICrossover>(problem, scenario.AlgorithmParameters.FindByName(""CrossoverParameter""));
     106                  ga.Elites = HLMapper.ConvertToIntValue(scenario.AlgorithmParameters.FindByName(""Elites""));
     107                  ga.MaximumGenerations = HLMapper.ConvertToIntValue(scenario.AlgorithmParameters.FindByName(""MaximumGenerations""));
     108                  ga.MutationProbability = HLMapper.ConvertToPercentValue(scenario.AlgorithmParameters.FindByName(""MutationProbability""));               
     109                  ga.PopulationSize = HLMapper.ConvertToIntValue(scenario.AlgorithmParameters.FindByName(""PopulationSize""));
     110                  ga.Seed = HLMapper.ConvertToIntValue(scenario.AlgorithmParameters.FindByName(""Seed""));
     111                  ga.Selector = HLMapper.FindInItemSet<HeuristicLab.Optimization.ISelector>(ga.SelectorParameter.ValidValues, scenario.AlgorithmParameters.FindByName(""Selector""));
     112                  ga.SetSeedRandomly = HLMapper.ConvertToBoolValue(scenario.AlgorithmParameters.FindByName(""SetSeedRandomly""));
     113                }
     114              }"
     115            );
     116
     117            foreach (var error in res.Errors) {
     118              Console.WriteLine(error);
     119            }
     120
     121            var type = res.CompiledAssembly.GetType("TSPScenarioMapper");
     122            tspMapper = Activator.CreateInstance(type) as IScenarioMapper;
     123          } // using
     124        } // lock       
     125       } // if
     126       return tspMapper;
     127     } 
     128
     129    private void MapExperiment(Model.OptimizationScenario scenario, IAlgorithm algorithm) {     
     130      IScenarioMapper mapper = GetMapper(scenario);
     131      mapper.MapScenario(scenario, algorithm);     
    128132    }
    129133
     
    246250      return runs;
    247251    }
     252
     253    //TODO: We might need images / +++
    248254    private Parameter MapHiveDataType(string name, IItem item) {
    249255      Parameter result = new Parameter();
Note: See TracChangeset for help on using the changeset viewer.