Free cookie consent management tool by TermsFeed Policy Generator

source: branches/OaaS/HeuristicLab.Services.Optimization.Controller/HiveScenarioManager.cs @ 8506

Last change on this file since 8506 was 8506, checked in by fschoepp, 10 years ago

#1888:

  • Web project now creates custom html for each type we want to enter / display
  • Added endpointConfigurationName to HiveServiceLocator (because Web Project contains more than one endpoint configuration)
  • Removed logging statement from ConfigurationService to prevent exception during failure of loading ConfigurationSettings
  • ApplicationManager: Changed default implementation to WebApplicationManager (instead of LightWeight) for testing purposes within Web Project
  • WebApplicationManager: The application manager which returns plugin descriptors from the currently loaded assemblies (instead of LightweightAppManager)
  • HiveService: Fixed a transaction bug
  • IControllerService: Created a method to dispatch Scenarios to certain IScenarioManager (in this case HiveScenarioManager)
  • Added more mappable types to ControllerModel
  • PlaceholderControllerService dispatches all Scenarios to the HiveScenarioManager
  • Web project now dispatches the scenario to the controller after pressing "Run Job"
File size: 6.1 KB
Line 
1using System;
2using System.Collections.Generic;
3using System.Linq;
4using System.Text;
5using HeuristicLab.Services.Optimization.ControllerService.Interfaces;
6using HeuristicLab.Optimization;
7using HeuristicLab.Algorithms.GeneticAlgorithm;
8using HeuristicLab.Problems.TravelingSalesman;
9using HeuristicLab;
10using System.Reflection;
11using HeuristicLab.Services.Optimization.ControllerService.Model;
12using HeuristicLab.Core;
13using System.Collections;
14using HeuristicLab.Clients.Hive;
15using System.Threading;
16
17namespace HeuristicLab.Services.Optimization.ControllerService {
18  public class HiveScenarioManager : IScenarioManager {
19    public object MapControllerDataType(object model, Parameter param) {
20      switch (param.Type) {
21        case ParameterType.Boolean:
22          return (param.Value as Model.BoolValue).Value;
23        case ParameterType.Integer:
24          return Convert.ToInt32((param.Value as Model.DecimalValue).Value);         
25        case ParameterType.Percent:       
26        case ParameterType.Decimal:
27          return (param.Value as Model.DecimalValue).Value;
28        case ParameterType.DecimalMatrix:
29          return Utility.ToMultiD(((param.Value as Model.DecimalMatrix).Value));
30        case ParameterType.DecimalVector:
31          return (param.Value as Model.DecimalVector).Value;
32        case ParameterType.Type:
33          //TODO handle type correctly!
34          var typeValue = param.Value as Model.TypeValue;
35         
36          IProblem problem = model as IProblem;
37          IAlgorithm algoModel = model as IAlgorithm;
38          if (problem == null && algoModel != null) {
39            problem = algoModel.Problem;
40          }
41
42          if (problem != null) {
43            var toselect = problem.Operators.OfType<IOperator>().FirstOrDefault(x => x.Name == typeValue.Value);
44            if (toselect != null) {
45              return toselect;
46            }
47          }
48         
49          string parameterPropertyName = typeValue.Name.EndsWith("Parameter") ? typeValue.Name : typeValue.Name + "Parameter";
50          var parameterProperty = model.GetType().GetProperty(parameterPropertyName);
51          if (parameterProperty != null) {
52            var parameterPropertyValue = parameterProperty.GetGetMethod().Invoke(model, null);
53            var vvProp = parameterPropertyValue.GetType().GetProperty("ValidValues");
54            if (vvProp != null) {
55              //http://stackoverflow.com/questions/245607/how-is-generic-covariance-contra-variance-implemented-in-c-sharp-4-0 because of covariance declared in IEnumerable
56              var options = vvProp.GetGetMethod().Invoke(parameterPropertyValue, null) as IEnumerable<IItem>;
57              if (options != null) {
58                var result = options.FirstOrDefault(x => x.ItemName == typeValue.Value);
59                if (result != null)
60                  return result;
61              }
62            }
63          }
64
65          Type type = null;
66          foreach (var asm in AppDomain.CurrentDomain.GetAssemblies()) {
67            type = asm.GetType(typeValue.Value);
68            if (type != null)
69              break;
70          }
71         
72          return Activator.CreateInstance(type);
73      }
74      return null;
75    }
76
77    public object CreateHLObjectForType(object obj, Type type, Parameter prop) {
78      var value = MapControllerDataType(obj, prop);
79      if (prop.Type == ParameterType.Type)
80        return value;
81
82      if (type == typeof(HeuristicLab.Encodings.PermutationEncoding.Permutation)) {
83        double[] input = value as double[];
84        int[] arr = new int[input.Length];
85        for (int i = 0; i < input.Length; i++) {
86          arr[i] = Convert.ToInt32(input[i]);
87        }
88        var valueObj = new HeuristicLab.Encodings.PermutationEncoding.Permutation(Encodings.PermutationEncoding.PermutationTypes.RelativeUndirected, arr);
89        return valueObj;
90      }
91      var propertyGetter = obj.GetType().GetProperty(prop.Value.Name).GetGetMethod();       
92      return Activator.CreateInstance(propertyGetter.ReturnType, value);
93    }
94
95    private void MapProperty(object model, Parameter prop) {
96      var propertyGetter = model.GetType().GetProperty(prop.Value.Name).GetGetMethod();
97      var propertySetter = model.GetType().GetProperty(prop.Value.Name).GetSetMethod();
98      var value = propertyGetter.Invoke(model, null);
99      var valueProperty = value != null ? value.GetType().GetProperty("Value") : null;
100      if (propertySetter != null) {
101        var instance = CreateHLObjectForType(model, propertyGetter.ReturnType, prop);
102        propertySetter.Invoke(model, new object[] { instance });
103      }
104      else if (valueProperty != null) {       
105        valueProperty.GetSetMethod().Invoke(value, new object[] { MapControllerDataType(model, prop) });
106      }
107      else {
108        Console.WriteLine("Failed to handle property!");
109      }
110    }
111
112    public void DispatchScenario(Model.OptimizationScenario scenario) {
113      Experiment experiment = new Experiment();
114      var problem = new TravelingSalesmanProblem();
115      foreach (var prop in scenario.InputParameters.Items) {
116        MapProperty(problem, prop);
117      }
118
119      var algo = new GeneticAlgorithm();
120      algo.Problem = problem;     
121      foreach (var prop in scenario.AlgorithmParameters.Items) {
122        MapProperty(algo, prop);
123      }
124
125      experiment.Optimizers.Add(algo);
126      SendExperimentToHive(experiment);
127    }
128
129    private void SendExperimentToHive(Experiment exp) {
130      var job = new RefreshableJob();
131      job.IsAllowedPrivileged = true;     
132      job.Job.Name = "Web Scheduled Traveling Salesman Job";
133      job.Job.ResourceNames = "TESTGROUP";
134      job.RefreshAutomatically = false;
135      job.HiveTasks.Add(new OptimizerHiveTask(exp));
136      HiveServiceLocator.Instance.Username = "fschoeppl";
137      HiveServiceLocator.Instance.Password = "fschoeppl";
138      HiveServiceLocator.Instance.EndpointConfigurationName = "WSHttpBinding_IHiveService";
139     
140      HiveClient.StartJob((ex) => {
141        Console.WriteLine(ex.StackTrace);
142      }, job, new CancellationToken());
143
144      job.StopResultPolling();
145    }
146  }
147}
Note: See TracBrowser for help on using the repository browser.