Free cookie consent management tool by TermsFeed Policy Generator

source: branches/HeuristicLab.Modeling Database Backend/sources/HeuristicLab.CEDMA.Server/3.3/SimpleDispatcher.cs @ 2193

Last change on this file since 2193 was 2193, checked in by gkronber, 15 years ago

Added problem view for the cedma server. #712

File size: 10.1 KB
Line 
1#region License Information
2/* HeuristicLab
3 * Copyright (C) 2002-2008 Heuristic and Evolutionary Algorithms Laboratory (HEAL)
4 *
5 * This file is part of HeuristicLab.
6 *
7 * HeuristicLab is free software: you can redistribute it and/or modify
8 * it under the terms of the GNU General Public License as published by
9 * the Free Software Foundation, either version 3 of the License, or
10 * (at your option) any later version.
11 *
12 * HeuristicLab is distributed in the hope that it will be useful,
13 * but WITHOUT ANY WARRANTY; without even the implied warranty of
14 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
15 * GNU General Public License for more details.
16 *
17 * You should have received a copy of the GNU General Public License
18 * along with HeuristicLab. If not, see <http://www.gnu.org/licenses/>.
19 */
20#endregion
21
22using System;
23using System.Collections.Generic;
24using System.Text;
25using System.Windows.Forms;
26using HeuristicLab.PluginInfrastructure;
27using System.Net;
28using System.ServiceModel;
29using HeuristicLab.CEDMA.DB.Interfaces;
30using HeuristicLab.CEDMA.DB;
31using System.ServiceModel.Description;
32using System.Linq;
33using HeuristicLab.CEDMA.Core;
34using HeuristicLab.GP.StructureIdentification;
35using HeuristicLab.Data;
36using HeuristicLab.Core;
37using HeuristicLab.Modeling;
38using HeuristicLab.Modeling.Database;
39
40namespace HeuristicLab.CEDMA.Server {
41  public class SimpleDispatcher : DispatcherBase {
42    private class AlgorithmConfiguration {
43      public string name;
44      public int targetVariable;
45      public List<int> inputVariables;
46    }
47
48    private Random random;   
49    private Dictionary<int, List<AlgorithmConfiguration>> finishedAndDispatchedRuns;
50
51    public SimpleDispatcher(IModelingDatabase database, Problem problem)
52      : base(database, problem) {     
53      random = new Random();
54      finishedAndDispatchedRuns = new Dictionary<int, List<AlgorithmConfiguration>>();
55      PopulateFinishedRuns();
56    }
57
58    public override HeuristicLab.Modeling.IAlgorithm SelectAndConfigureAlgorithm(int targetVariable, int[] inputVariables, Problem problem) {
59      DiscoveryService ds = new DiscoveryService();
60      HeuristicLab.Modeling.IAlgorithm[] algos = ds.GetInstances<HeuristicLab.Modeling.IAlgorithm>();
61      HeuristicLab.Modeling.IAlgorithm selectedAlgorithm = null;
62      switch (problem.LearningTask) {
63        case LearningTask.Regression: {
64            var regressionAlgos = algos.Where(a => (a as IClassificationAlgorithm) == null && (a as ITimeSeriesAlgorithm) == null);
65            selectedAlgorithm = ChooseDeterministic(targetVariable, inputVariables, regressionAlgos) ?? ChooseStochastic(regressionAlgos);
66            break;
67          }
68        case LearningTask.Classification: {
69            var classificationAlgos = algos.Where(a => (a as IClassificationAlgorithm) != null);
70            selectedAlgorithm = ChooseDeterministic(targetVariable, inputVariables, classificationAlgos) ?? ChooseStochastic(classificationAlgos);
71            break;
72          }
73        case LearningTask.TimeSeries: {
74            var timeSeriesAlgos = algos.Where(a => (a as ITimeSeriesAlgorithm) != null);
75            selectedAlgorithm = ChooseDeterministic(targetVariable, inputVariables, timeSeriesAlgos) ?? ChooseStochastic(timeSeriesAlgos);
76            break;
77          }
78      }
79
80
81      if (selectedAlgorithm != null) {
82        SetProblemParameters(selectedAlgorithm, problem, targetVariable, inputVariables);
83        AddDispatchedRun(targetVariable, inputVariables, selectedAlgorithm.Name);
84      }
85      return selectedAlgorithm;
86    }
87
88    private HeuristicLab.Modeling.IAlgorithm ChooseDeterministic(int targetVariable, int[] inputVariables, IEnumerable<HeuristicLab.Modeling.IAlgorithm> algos) {
89      var deterministicAlgos = algos
90        .Where(a => (a as IStochasticAlgorithm) == null)
91        .Where(a => AlgorithmFinishedOrDispatched(targetVariable, inputVariables, a.Name) == false);
92
93      if (deterministicAlgos.Count() == 0) return null;
94      return deterministicAlgos.ElementAt(random.Next(deterministicAlgos.Count()));
95    }
96
97    private HeuristicLab.Modeling.IAlgorithm ChooseStochastic(IEnumerable<HeuristicLab.Modeling.IAlgorithm> regressionAlgos) {
98      var stochasticAlgos = regressionAlgos.Where(a => (a as IStochasticAlgorithm) != null);
99      if (stochasticAlgos.Count() == 0) return null;
100      return stochasticAlgos.ElementAt(random.Next(stochasticAlgos.Count()));
101    }
102
103    private void PopulateFinishedRuns() {
104      //Dictionary<Entity, Entity> processedModels = new Dictionary<Entity, Entity>();
105      //var datasetBindings = store
106      //  .Query(
107      //  "?Dataset <" + Ontology.InstanceOf + "> <" + Ontology.TypeDataSet + "> .", 0, 1)
108      //  .Select(x => (Entity)x.Get("Dataset"));
109
110      //if (datasetBindings.Count() > 0) {
111      //  var datasetEntity = datasetBindings.ElementAt(0);
112
113      //  DataSet ds = new DataSet(store, datasetEntity);
114      //  var result = store
115      //    .Query(
116      //    "?Model <" + Ontology.TargetVariable + "> ?TargetVariable ." + Environment.NewLine +
117      //    "?Model <" + Ontology.Name + "> ?AlgoName .",
118      //    0, 1000)
119      //    .Select(x => new Resource[] { (Literal)x.Get("TargetVariable"), (Literal)x.Get("AlgoName"), (Entity)x.Get("Model") });
120
121      //  foreach (Resource[] row in result) {
122      //    Entity model = ((Entity)row[2]);
123      //    if (!processedModels.ContainsKey(model)) {
124      //      processedModels.Add(model, model);
125
126      //      string targetVariable = (string)((Literal)row[0]).Value;
127      //      string algoName = (string)((Literal)row[1]).Value;
128      //      int targetVariableIndex = ds.Problem.Dataset.GetVariableIndex(targetVariable);
129
130      //      var inputVariableLiterals = store
131      //        .Query(
132      //          "<" + model.Uri + "> <" + Ontology.HasInputVariable + "> ?InputVariable ." + Environment.NewLine +
133      //          "?InputVariable <" + Ontology.Name + "> ?Name .",
134      //          0, 1000)
135      //        .Select(x => (Literal)x.Get("Name"))
136      //        .Select(l => (string)l.Value)
137      //        .Distinct();
138
139      //      List<int> inputVariables = new List<int>();
140      //      foreach (string variableName in inputVariableLiterals) {
141      //        int variableIndex = ds.Problem.Dataset.GetVariableIndex(variableName);
142      //        inputVariables.Add(variableIndex);
143      //      }
144      //      if (!AlgorithmFinishedOrDispatched(targetVariableIndex, inputVariables.ToArray(), algoName)) {
145      //        AddDispatchedRun(targetVariableIndex, inputVariables.ToArray(), algoName);
146      //      }
147      //    }
148      //  }
149      //}
150    }
151
152    private void SetProblemParameters(HeuristicLab.Modeling.IAlgorithm algo, Problem problem, int targetVariable, int[] inputVariables) {
153      algo.Dataset = problem.Dataset;
154      algo.TargetVariable = targetVariable;
155      algo.ProblemInjector.GetVariable("TrainingSamplesStart").GetValue<IntData>().Data = problem.TrainingSamplesStart;
156      algo.ProblemInjector.GetVariable("TrainingSamplesEnd").GetValue<IntData>().Data = problem.TrainingSamplesEnd;
157      algo.ProblemInjector.GetVariable("ValidationSamplesStart").GetValue<IntData>().Data = problem.ValidationSamplesStart;
158      algo.ProblemInjector.GetVariable("ValidationSamplesEnd").GetValue<IntData>().Data = problem.ValidationSamplesEnd;
159      algo.ProblemInjector.GetVariable("TestSamplesStart").GetValue<IntData>().Data = problem.TestSamplesStart;
160      algo.ProblemInjector.GetVariable("TestSamplesEnd").GetValue<IntData>().Data = problem.TestSamplesEnd;
161      ItemList<IntData> allowedFeatures = algo.ProblemInjector.GetVariable("AllowedFeatures").GetValue<ItemList<IntData>>();
162      foreach (int inputVariable in inputVariables) {
163        if (inputVariable != targetVariable) {
164          allowedFeatures.Add(new IntData(inputVariable));
165        }
166      }
167
168      if (problem.LearningTask == LearningTask.TimeSeries) {
169        algo.ProblemInjector.GetVariable("Autoregressive").GetValue<BoolData>().Data = problem.AutoRegressive;
170        algo.ProblemInjector.GetVariable("MinTimeOffset").GetValue<IntData>().Data = problem.MinTimeOffset;
171        algo.ProblemInjector.GetVariable("MaxTimeOffset").GetValue<IntData>().Data = problem.MaxTimeOffset;
172        if (problem.AutoRegressive) {
173          allowedFeatures.Add(new IntData(targetVariable));
174        }
175      } else if (problem.LearningTask == LearningTask.Classification) {
176        ItemList<DoubleData> classValues = algo.ProblemInjector.GetVariable("TargetClassValues").GetValue<ItemList<DoubleData>>();
177        foreach (double classValue in GetDifferentClassValues(problem.Dataset, targetVariable)) classValues.Add(new DoubleData(classValue));
178      }
179    }
180
181    private IEnumerable<double> GetDifferentClassValues(HeuristicLab.DataAnalysis.Dataset dataset, int targetVariable) {
182      return Enumerable.Range(0, dataset.Rows).Select(x => dataset.GetValue(x, targetVariable)).Distinct();
183    }
184
185    private void AddDispatchedRun(int targetVariable, int[] inputVariables, string algoName) {
186      if (!finishedAndDispatchedRuns.ContainsKey(targetVariable)) {
187        finishedAndDispatchedRuns[targetVariable] = new List<AlgorithmConfiguration>();
188      }
189      AlgorithmConfiguration conf = new AlgorithmConfiguration();
190      conf.name = algoName;
191      conf.inputVariables = new List<int>(inputVariables);
192      conf.targetVariable = targetVariable;
193      finishedAndDispatchedRuns[targetVariable].Add(conf);
194    }
195
196    private bool AlgorithmFinishedOrDispatched(int targetVariable, int[] inputVariables, string algoName) {
197      return
198        finishedAndDispatchedRuns.ContainsKey(targetVariable) &&
199        finishedAndDispatchedRuns[targetVariable].Any(x => targetVariable == x.targetVariable &&
200                                                           algoName == x.name &&
201                                                           inputVariables.Count() == x.inputVariables.Count() &&
202                                                           inputVariables.All(v => x.inputVariables.Contains(v)));
203    }
204  }
205}
Note: See TracBrowser for help on using the repository browser.