1 | using System;
|
---|
2 | using System.Collections.Generic;
|
---|
3 | using System.Linq;
|
---|
4 | using System.Text;
|
---|
5 | using HeuristicLab.Services.Optimization.ControllerService.Interfaces;
|
---|
6 | using HeuristicLab.Optimization;
|
---|
7 | using HeuristicLab.Algorithms.GeneticAlgorithm;
|
---|
8 | using HeuristicLab.Problems.TravelingSalesman;
|
---|
9 | using HeuristicLab;
|
---|
10 | using System.Reflection;
|
---|
11 | using HeuristicLab.Services.Optimization.ControllerService.Model;
|
---|
12 | using HeuristicLab.Core;
|
---|
13 | using System.Collections;
|
---|
14 | using HeuristicLab.Clients.Hive;
|
---|
15 | using System.Threading;
|
---|
16 | using HeuristicLab.Data;
|
---|
17 | using System.IO;
|
---|
18 |
|
---|
19 | namespace HeuristicLab.Services.Optimization.ControllerService {
|
---|
20 | public class HiveScenarioManager : IScenarioManager {
|
---|
21 | private static IScenarioMapper tspMapper;
|
---|
22 | private static object lockable;
|
---|
23 |
|
---|
24 | static HiveScenarioManager() {
|
---|
25 | lockable = new object();
|
---|
26 | }
|
---|
27 |
|
---|
28 | public void DispatchScenario(Model.User user, Model.OptimizationScenario scenario) {
|
---|
29 | Experiment experiment = new Experiment();
|
---|
30 | var problem = new TravelingSalesmanProblem();
|
---|
31 | var algo = new GeneticAlgorithm();
|
---|
32 | algo.Problem = problem;
|
---|
33 |
|
---|
34 | MapExperiment(scenario, algo);
|
---|
35 |
|
---|
36 | experiment.Optimizers.Add(algo);
|
---|
37 | 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);
|
---|
132 | }
|
---|
133 |
|
---|
134 | private void SendExperimentToHive(Model.User user, Experiment exp) {
|
---|
135 | var job = new RefreshableJob();
|
---|
136 | job.IsAllowedPrivileged = true;
|
---|
137 | job.Job.Name = "Web Scheduled Traveling Salesman Job";
|
---|
138 | job.Job.ResourceNames = "TESTGROUP";
|
---|
139 | job.RefreshAutomatically = false;
|
---|
140 | job.HiveTasks.Add(new OptimizerHiveTask(exp));
|
---|
141 | HiveServiceLocator.Instance.Username = user.Username;
|
---|
142 | HiveServiceLocator.Instance.Password = user.Password;
|
---|
143 | HiveServiceLocator.Instance.EndpointConfigurationName = "WSHttpBinding_IHiveService";
|
---|
144 |
|
---|
145 | HiveClient.StartJob((ex) => {
|
---|
146 | Console.WriteLine(ex.StackTrace);
|
---|
147 | }, job, new CancellationToken());
|
---|
148 |
|
---|
149 | job.StopResultPolling();
|
---|
150 | }
|
---|
151 |
|
---|
152 |
|
---|
153 | public IList<Model.Job> GetJobs(User user) {
|
---|
154 | HiveServiceLocator.Instance.Username = user.Username;
|
---|
155 | HiveServiceLocator.Instance.Password = user.Password;
|
---|
156 | HiveServiceLocator.Instance.EndpointConfigurationName = "WSHttpBinding_IHiveService";
|
---|
157 | var jobsLoaded = HiveServiceLocator.Instance.CallHiveService<IEnumerable<HeuristicLab.Clients.Hive.Job>>(s => s.GetJobs());
|
---|
158 | IList<Model.Job> jobs = new List<Model.Job>();
|
---|
159 |
|
---|
160 | foreach (var job in jobsLoaded) {
|
---|
161 | jobs.Add(ConvertJob(user, job));
|
---|
162 | }
|
---|
163 | return jobs;
|
---|
164 | }
|
---|
165 |
|
---|
166 | private Model.Job ConvertJob(User user, HeuristicLab.Clients.Hive.Job job)
|
---|
167 | {
|
---|
168 | var waitingJobs = job.JobCount - job.CalculatingCount - job.FinishedCount;
|
---|
169 | Model.JobState? state = null;
|
---|
170 | var jobTasks = HiveServiceLocator.Instance.CallHiveService<IEnumerable<HeuristicLab.Clients.Hive.LightweightTask>>(s => s.GetLightweightJobTasks(job.Id));
|
---|
171 |
|
---|
172 | foreach (var task in jobTasks) {
|
---|
173 | switch (task.State) {
|
---|
174 | case TaskState.Aborted:
|
---|
175 | state = JobState.Aborted;
|
---|
176 | break;
|
---|
177 | case TaskState.Failed:
|
---|
178 | state = JobState.Failed;
|
---|
179 | break;
|
---|
180 | }
|
---|
181 | }
|
---|
182 | if (!state.HasValue) {
|
---|
183 | if (job.CalculatingCount > 0)
|
---|
184 | state = JobState.Calculating;
|
---|
185 | else if (waitingJobs > 0)
|
---|
186 | state = JobState.Waiting;
|
---|
187 | else
|
---|
188 | state = JobState.Finished;
|
---|
189 | }
|
---|
190 | return new Model.Job() { Id = job.Id.ToString(), Name = job.Name, Resource = job.ResourceNames, State = state.Value };
|
---|
191 | }
|
---|
192 |
|
---|
193 |
|
---|
194 | public Model.Job GetJob(User user, string id) {
|
---|
195 | HiveServiceLocator.Instance.Username = user.Username;
|
---|
196 | HiveServiceLocator.Instance.Password = user.Password;
|
---|
197 | HiveServiceLocator.Instance.EndpointConfigurationName = "WSHttpBinding_IHiveService";
|
---|
198 | var guid = Guid.Parse(id);
|
---|
199 | return ConvertJob(user, HiveServiceLocator.Instance.CallHiveService<HeuristicLab.Clients.Hive.Job>(s => s.GetJob(guid)));
|
---|
200 | }
|
---|
201 |
|
---|
202 |
|
---|
203 | public void DeleteJob(User user, string id) {
|
---|
204 | HiveServiceLocator.Instance.Username = user.Username;
|
---|
205 | HiveServiceLocator.Instance.Password = user.Password;
|
---|
206 | HiveServiceLocator.Instance.EndpointConfigurationName = "WSHttpBinding_IHiveService";
|
---|
207 | var guid = Guid.Parse(id);
|
---|
208 | HiveServiceLocator.Instance.CallHiveService(s => s.DeleteJob(guid));
|
---|
209 | }
|
---|
210 |
|
---|
211 | public IList<Model.Run> GetJobResults(User user, string id) {
|
---|
212 | HiveServiceLocator.Instance.Username = user.Username;
|
---|
213 | HiveServiceLocator.Instance.Password = user.Password;
|
---|
214 | HiveServiceLocator.Instance.EndpointConfigurationName = "WSHttpBinding_IHiveService";
|
---|
215 | var guid = Guid.Parse(id);
|
---|
216 | var jobTasks = HiveServiceLocator.Instance.CallHiveService<IEnumerable<HeuristicLab.Clients.Hive.LightweightTask>>(s => s.GetLightweightJobTasks(guid));
|
---|
217 |
|
---|
218 | IList<Guid> taskIds = new List<Guid>();
|
---|
219 | foreach (var task in jobTasks) {
|
---|
220 | taskIds.Add(task.Id);
|
---|
221 | }
|
---|
222 | TaskDownloader downloader = new TaskDownloader(taskIds);
|
---|
223 | downloader.StartAsync();
|
---|
224 | while (!downloader.IsFinished) {
|
---|
225 | Thread.Sleep(500);
|
---|
226 |
|
---|
227 | if (downloader.IsFaulted) {
|
---|
228 | throw downloader.Exception;
|
---|
229 | }
|
---|
230 | }
|
---|
231 | IDictionary<Guid, HiveTask> hiveTasks = downloader.Results;
|
---|
232 | IList<Model.Run> runs = new List<Model.Run>();
|
---|
233 | foreach (var keyTask in hiveTasks.Keys) {
|
---|
234 | var oht = hiveTasks[keyTask] as OptimizerHiveTask;
|
---|
235 | if (oht != null) {
|
---|
236 | foreach (var run in oht.ItemTask.Item.Runs) {
|
---|
237 | Model.Run taskRun = new Model.Run();
|
---|
238 | taskRun.Id = taskRun.Name = run.Name;
|
---|
239 | IList<Parameter> resultValues = new List<Model.Parameter>();
|
---|
240 | foreach (var key in run.Results.Keys) {
|
---|
241 | var value = run.Results[key];
|
---|
242 | Parameter result = MapHiveDataType(key, value);
|
---|
243 | resultValues.Add(result);
|
---|
244 | }
|
---|
245 | taskRun.Results = resultValues;
|
---|
246 | runs.Add(taskRun);
|
---|
247 | }
|
---|
248 | }
|
---|
249 | }
|
---|
250 | return runs;
|
---|
251 | }
|
---|
252 |
|
---|
253 | //TODO: We might need images / +++
|
---|
254 | private Parameter MapHiveDataType(string name, IItem item) {
|
---|
255 | Parameter result = new Parameter();
|
---|
256 | result.Type = ParameterType.String;
|
---|
257 | if (item is IStringConvertibleValue) {
|
---|
258 | var value = (item as IStringConvertibleValue).GetValue();
|
---|
259 | result.Value = new HeuristicLab.Services.Optimization.ControllerService.Model.StringValue() { Name = name, Value = value };
|
---|
260 | }
|
---|
261 | else if (item is IStringConvertibleValueTuple) {
|
---|
262 | var value1 = (item as IStringConvertibleValueTuple).Item1.GetValue();
|
---|
263 | var value2 = (item as IStringConvertibleValueTuple).Item2.GetValue();
|
---|
264 | result.Value = new HeuristicLab.Services.Optimization.ControllerService.Model.StringValue() { Name = name, Value = "{" + value1 + ", " + value2 + "}" };
|
---|
265 | }
|
---|
266 | else if (item is IStringConvertibleArray) {
|
---|
267 | StringBuilder sb = new StringBuilder();
|
---|
268 | var array = item as IStringConvertibleArray;
|
---|
269 | if (array.Length == 0) {
|
---|
270 | sb.Append("[ ]");
|
---|
271 | } else {
|
---|
272 | sb.Append("[");
|
---|
273 | for (int i=0; i < array.Length - 1; i++) {
|
---|
274 | sb.Append(array.GetValue(i)).Append(", ");
|
---|
275 | }
|
---|
276 | sb.Append(array.GetValue(array.Length - 1));
|
---|
277 | sb.Append(" ]");
|
---|
278 | }
|
---|
279 | var value = sb.ToString();
|
---|
280 | result.Value = new HeuristicLab.Services.Optimization.ControllerService.Model.StringValue() { Name = name, Value = value };
|
---|
281 | }
|
---|
282 | else if (item is IStringConvertibleMatrix) {
|
---|
283 | StringBuilder sb = new StringBuilder();
|
---|
284 | var matrix = item as IStringConvertibleMatrix;
|
---|
285 | if (matrix.Rows == 0 || matrix.Columns == 0) {
|
---|
286 | sb.Append("[ ]");
|
---|
287 | }
|
---|
288 | else {
|
---|
289 | sb.Append("[ ");
|
---|
290 | for (int r = 0; r < matrix.Rows; r++) {
|
---|
291 | sb.Append("( ");
|
---|
292 | for (int c = 0; c < matrix.Columns - 1; c++) {
|
---|
293 | sb.Append(matrix.GetValue(r, c)).Append(", ");
|
---|
294 | }
|
---|
295 | sb.Append(matrix.GetValue(r, matrix.Columns - 1)).Append(r < matrix.Rows - 1 ? " ), " : " )");
|
---|
296 | }
|
---|
297 | sb.Append(" ]");
|
---|
298 | }
|
---|
299 | var value = sb.ToString();
|
---|
300 | result.Value = new HeuristicLab.Services.Optimization.ControllerService.Model.StringValue() { Name = name, Value = value };
|
---|
301 | }
|
---|
302 | else {
|
---|
303 | result.Value = new HeuristicLab.Services.Optimization.ControllerService.Model.StringValue() { Name = name, Value = "Cannot be displayed as string" };
|
---|
304 | }
|
---|
305 | return result;
|
---|
306 | }
|
---|
307 | }
|
---|
308 | }
|
---|