Free cookie consent management tool by TermsFeed Policy Generator

source: branches/OaaS/HeuristicLab.Services.Optimization.ControllerService.Tests/Program.cs @ 9032

Last change on this file since 9032 was 8817, checked in by fschoepp, 12 years ago

#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 size: 11.0 KB
Line 
1using System;
2using System.Collections.Generic;
3using System.Linq;
4using System.Text;
5using HeuristicLab.Services.Optimization.ControllerService.Interfaces;
6using HeuristicLab.Problems.TravelingSalesman;
7using System.Reflection;
8using System.IO;
9using Microsoft.Scripting.Hosting;
10using IronPython.Hosting;
11using HeuristicLab.Algorithms.GeneticAlgorithm;
12using HeuristicLab.Persistence.Core;
13using HeuristicLab.Core;
14
15namespace HeuristicLab.Services.Optimization.ControllerService.Tests {
16  class Program {
17    static void Main(string[] args) {
18      Console.WriteLine(AppDomain.CurrentDomain.BaseDirectory);   
19      //TestScenarioParser();
20      TestCodeDOM();
21      //TestPython();
22      //TestOtis();
23      //TestJobResults();
24    }
25
26    static void TestJobResults() {
27      IScenarioManager manager = new HiveScenarioManager();
28      Console.WriteLine("Press key to continue");
29      Console.ReadKey();
30      IList<Model.Run> results = manager.GetJobResults(new Model.User() { Password = "fschoeppl", Username = "fschoeppl" }, "cfd0cd8d-76a5-4bf6-bfcb-53fbfe3efe24");
31      foreach (var run in results) {
32        Console.WriteLine(run);
33      }
34    }
35
36    static void TestStorable() {
37      TravelingSalesmanProblem tsp = new TravelingSalesmanProblem();
38      GeneticAlgorithm algo = new GeneticAlgorithm();
39      algo.Problem = tsp;
40
41     
42    }
43
44    static void TestCodeDOM() {
45      ScenarioParser parser = new ScenarioParser();
46      var scen = parser.GetByName("Traveling Salesman Problem");
47      TravelingSalesmanProblem tsp = new TravelingSalesmanProblem();
48      GeneticAlgorithm algo = new GeneticAlgorithm();
49      algo.Problem = tsp;
50
51      // http://stackoverflow.com/questions/3188882/compile-and-run-dynamic-code-without-generating-exe
52      using (var csCodeProvider = new Microsoft.CSharp.CSharpCodeProvider()) {               
53
54        var cp = new System.CodeDom.Compiler.CompilerParameters() {
55            GenerateInMemory = true
56          };
57
58        var loadedAssemblies = AppDomain.CurrentDomain.GetAssemblies().ToList();
59        var loadedPaths = loadedAssemblies.Select(a => a.Location).ToArray();
60
61        var referencedPaths = Directory.GetFiles(AppDomain.CurrentDomain.BaseDirectory, "*.dll");
62        foreach (var loadedAssembly in referencedPaths) {
63          cp.ReferencedAssemblies.Add(loadedAssembly);         
64        }
65        cp.ReferencedAssemblies.Add("System.dll");
66
67        tsp.BestKnownQuality = HLMapper.ConvertToDoubleValue(scen.InputParameters.FindByName("BestKnownQuality"));
68       
69        var res = csCodeProvider.CompileAssemblyFromSource(
70         cp
71         ,
72          @"using System;
73            using System.Collections.Generic;
74            using System.Linq;
75            using System.Text;
76            using HeuristicLab.Data;
77            using HeuristicLab.Services.Optimization.ControllerService.Model;
78            using HeuristicLab.Optimization;
79            using HeuristicLab.Services.Optimization.ControllerService;
80            using HeuristicLab.Algorithms.GeneticAlgorithm;
81            using HeuristicLab.Problems.TravelingSalesman;
82            public class TSPScenarioMapper : IScenarioMapper {
83              public void MapScenario(OptimizationScenario scenario, IAlgorithm algorithm) {
84                Console.WriteLine(""Mapping scenario!"");
85                var ga = algorithm as GeneticAlgorithm;
86                var problem = algorithm.Problem as TravelingSalesmanProblem;
87               
88                problem.BestKnownQuality = HLMapper.ConvertToDoubleValue(scenario.InputParameters.FindByName(""BestKnownQuality""));
89                problem.BestKnownSolution = HLMapper.ConvertToPermutation(scenario.InputParameters.FindByName(""BestKnownSolution""));
90                problem.Coordinates = HLMapper.ConvertToDoubleMatrix(scenario.InputParameters.FindByName(""Coordinates""));
91                var evalParam = HLMapper.GetStringValue(scenario.InputParameters.FindByName(""EvaluatorParameter""));
92                if (evalParam == ""HeuristicLab.Problems.TravelingSalesman.TSPRoundedEuclideanPathEvaluator"") {
93                  problem.EvaluatorParameter.Value = new TSPRoundedEuclideanPathEvaluator();
94                }
95                else if (evalParam == ""HeuristicLab.Problems.TravelingSalesman.TSPGeoPathEvaluator"") {
96                  problem.EvaluatorParameter.Value = new TSPGeoPathEvaluator();
97                }
98                else {
99                  problem.EvaluatorParameter.Value = new TSPEuclideanPathEvaluator();
100                }
101                problem.UseDistanceMatrix = HLMapper.ConvertToBoolValue(scenario.InputParameters.FindByName(""UseDistanceMatrix""));
102                Console.WriteLine(""Mapping algorithm..."");
103                ga.Mutator = HLMapper.FindInItemSet<HeuristicLab.Optimization.IManipulator>(ga.MutatorParameter.ValidValues, scenario.AlgorithmParameters.FindByName(""Mutator""));
104                ga.CrossoverParameter.Value = HLMapper.FindOperator<HeuristicLab.Optimization.ICrossover>(problem, scenario.AlgorithmParameters.FindByName(""CrossoverParameter""));
105                ga.Elites = HLMapper.ConvertToIntValue(scenario.AlgorithmParameters.FindByName(""Elites""));
106                ga.MaximumGenerations = HLMapper.ConvertToIntValue(scenario.AlgorithmParameters.FindByName(""MaximumGenerations""));
107                ga.MutationProbability = HLMapper.ConvertToPercentValue(scenario.AlgorithmParameters.FindByName(""MutationProbability""));               
108                ga.PopulationSize = HLMapper.ConvertToIntValue(scenario.AlgorithmParameters.FindByName(""PopulationSize""));
109                ga.Seed = HLMapper.ConvertToIntValue(scenario.AlgorithmParameters.FindByName(""Seed""));
110                ga.Selector = HLMapper.FindInItemSet<HeuristicLab.Optimization.ISelector>(ga.SelectorParameter.ValidValues, scenario.AlgorithmParameters.FindByName(""Selector""));
111                ga.SetSeedRandomly = HLMapper.ConvertToBoolValue(scenario.AlgorithmParameters.FindByName(""SetSeedRandomly""));
112              }
113            }"
114        );       
115
116        foreach (var error in res.Errors) {
117          Console.WriteLine(error);
118        }       
119       
120        var type = res.CompiledAssembly.GetType("TSPScenarioMapper");
121        var mapper = Activator.CreateInstance(type) as IScenarioMapper;
122        mapper.MapScenario(scen, algo);
123      }     
124    }
125
126    static void TestPython() {
127      ScenarioParser parser = new ScenarioParser();
128      var scen = parser.GetByName("Traveling Salesman Problem");
129      //TravelingSalesmanProblem tsp = new TravelingSalesmanProblem();
130      //GeneticAlgorithm algo = new GeneticAlgorithm();
131      //algo.Problem = tsp;
132      var rt = Python.CreateRuntime();
133      // workaround to load all referenced assemblies into the current AppDomain
134      var loadedAssemblies = AppDomain.CurrentDomain.GetAssemblies().ToList();
135      var loadedPaths = loadedAssemblies.Select(a => a.Location).ToArray();
136
137      var referencedPaths = Directory.GetFiles(AppDomain.CurrentDomain.BaseDirectory, "*.dll");
138      var toLoad = referencedPaths.Where(r => !loadedPaths.Contains(r, StringComparer.InvariantCultureIgnoreCase)).ToList();
139      toLoad.ForEach(path => loadedAssemblies.Add(AppDomain.CurrentDomain.Load(AssemblyName.GetAssemblyName(path))));
140
141      foreach (var assm in AppDomain.CurrentDomain.GetAssemblies()) {               
142        rt.LoadAssembly(assm); 
143      }
144     
145      /*var scope = rt.CreateScope();
146      scope.SetVariable("source", scen);
147      scope.SetVariable("target", tsp);*/
148      var engine = rt.GetEngine("py");
149      char op = ' ';
150      while (op != 'q') {
151        try {
152          TravelingSalesmanProblem tsp = new TravelingSalesmanProblem();
153          GeneticAlgorithm algo = new GeneticAlgorithm();
154          algo.Problem = tsp;
155          Console.WriteLine("\n\n===============================================================");
156          var script = engine.CreateScriptSourceFromFile(System.Configuration.ConfigurationManager.AppSettings["scenarioPath"] + @"\mapping.py");         
157          var scope = engine.CreateScope();
158          scope.SetVariable("source", scen);
159          scope.SetVariable("problem", tsp);
160          scope.SetVariable("algorithm", algo);         
161          script.Execute(scope);                   
162        }
163        catch (Exception e) {
164          Console.WriteLine(e);
165        }
166        Console.WriteLine("Hit 'q' to quit...");
167        op = Console.ReadKey().KeyChar;
168      }
169
170      /*dynamic script = rt.UseFile("C:/temp/scenarios/mapping.py");
171      script.SetVariable("source", scen);
172      script.SetVariable("target", tsp);
173     
174
175      script.mapObjects(scen, tsp);*/
176     
177    }
178
179    static void TestOtis() {
180      Console.WriteLine();
181      Otis.Configuration cfg = new Otis.Configuration();
182      Model.DecimalValue dv = new Model.DecimalValue();
183      dv.Value = 100;
184      Console.WriteLine(dv);
185      Console.WriteLine(typeof(HeuristicLab.Data.DoubleValue).AssemblyQualifiedName);
186      Console.WriteLine(typeof(System.Double).AssemblyQualifiedName);
187
188      // workaround to load all referenced assemblies into the current AppDomain
189      var loadedAssemblies = AppDomain.CurrentDomain.GetAssemblies().ToList();
190      var loadedPaths = loadedAssemblies.Select(a => a.Location).ToArray();
191
192      var referencedPaths = Directory.GetFiles(AppDomain.CurrentDomain.BaseDirectory, "*.dll");
193      var toLoad = referencedPaths.Where(r => !loadedPaths.Contains(r, StringComparer.InvariantCultureIgnoreCase)).ToList();
194      toLoad.ForEach(path => loadedAssemblies.Add(AppDomain.CurrentDomain.Load(AssemblyName.GetAssemblyName(path))));
195     
196      foreach (var assm in AppDomain.CurrentDomain.GetAssemblies()) {
197        //cfg.AddAssembly(assm);
198        cfg.AddAssemblyReference(assm);       
199      }
200      //cfg.AddAssemblyReference("HeuristicLab.Data-3.3, Version=3.3.0.0, Culture=neutral, PublicKeyToken=ba48961d6f65dcec");
201      //cfg.AddAssemblyReference("HeuristicLab.Data-3.3.dll");
202      cfg.AddXmlFile(System.Configuration.ConfigurationManager.AppSettings["scenarioPath"] + @"\mapping.tsp.xml");
203
204      Otis.IAssembler<TravelingSalesmanProblem,Model.OptimizationScenario> asm = cfg.GetAssembler<TravelingSalesmanProblem,Model.OptimizationScenario>();
205      ScenarioParser parser = new ScenarioParser();
206      var scen = parser.GetByName("Traveling Salesman Problem");
207      TravelingSalesmanProblem tsp = new TravelingSalesmanProblem();
208      //tsp.BestKnownQuality = new Data.DoubleValue();
209      asm.Assemble(ref tsp, ref scen);
210      Console.WriteLine(tsp.BestKnownQuality);     
211    }
212
213    static void TestMapping() {
214    }
215
216    // template for mapping Model.OptimizationScenario & e.g. TSP
217    static void TestScenarioParser() {
218      ScenarioParser parser = new ScenarioParser();
219      var scen = parser.GetByName("Traveling Salesman Problem");
220      TravelingSalesmanProblem tsp = new TravelingSalesmanProblem();
221      // proceed with mapping between scen and tsp
222    }
223  }
224}
Note: See TracBrowser for help on using the repository browser.