Free cookie consent management tool by TermsFeed Policy Generator

source: trunk/sources/HeuristicLab.CEDMA.Server/3.3/SimpleDispatcher.cs @ 2227

Last change on this file since 2227 was 2223, checked in by mkommend, 15 years ago

reintegrated branch new heuristic.modeling database backend (ticket #712)

File size: 10.0 KB
RevLine 
[1044]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 System.ServiceModel.Description;
30using System.Linq;
31using HeuristicLab.CEDMA.Core;
[1053]32using HeuristicLab.Data;
[1060]33using HeuristicLab.Core;
[1857]34using HeuristicLab.Modeling;
[2223]35using HeuristicLab.Modeling.Database;
[1044]36
37namespace HeuristicLab.CEDMA.Server {
[1873]38  public class SimpleDispatcher : DispatcherBase {
[2119]39    private class AlgorithmConfiguration {
40      public string name;
41      public int targetVariable;
42      public List<int> inputVariables;
43    }
44
[2223]45    private Random random;   
[2119]46    private Dictionary<int, List<AlgorithmConfiguration>> finishedAndDispatchedRuns;
[1873]47
[2223]48    public SimpleDispatcher(IModelingDatabase database, Problem problem)
49      : base(database, problem) {     
[1217]50      random = new Random();
[2119]51      finishedAndDispatchedRuns = new Dictionary<int, List<AlgorithmConfiguration>>();
[1873]52      PopulateFinishedRuns();
[1044]53    }
54
[2223]55    public override HeuristicLab.Modeling.IAlgorithm SelectAndConfigureAlgorithm(int targetVariable, int[] inputVariables, Problem problem) {
[1857]56      DiscoveryService ds = new DiscoveryService();
[2223]57      HeuristicLab.Modeling.IAlgorithm[] algos = ds.GetInstances<HeuristicLab.Modeling.IAlgorithm>();
58      HeuristicLab.Modeling.IAlgorithm selectedAlgorithm = null;
[2119]59      switch (problem.LearningTask) {
[1857]60        case LearningTask.Regression: {
61            var regressionAlgos = algos.Where(a => (a as IClassificationAlgorithm) == null && (a as ITimeSeriesAlgorithm) == null);
[2119]62            selectedAlgorithm = ChooseDeterministic(targetVariable, inputVariables, regressionAlgos) ?? ChooseStochastic(regressionAlgos);
[1873]63            break;
[1857]64          }
65        case LearningTask.Classification: {
66            var classificationAlgos = algos.Where(a => (a as IClassificationAlgorithm) != null);
[2119]67            selectedAlgorithm = ChooseDeterministic(targetVariable, inputVariables, classificationAlgos) ?? ChooseStochastic(classificationAlgos);
[1873]68            break;
[1857]69          }
70        case LearningTask.TimeSeries: {
71            var timeSeriesAlgos = algos.Where(a => (a as ITimeSeriesAlgorithm) != null);
[2119]72            selectedAlgorithm = ChooseDeterministic(targetVariable, inputVariables, timeSeriesAlgos) ?? ChooseStochastic(timeSeriesAlgos);
[1873]73            break;
[1857]74          }
75      }
[2119]76
77
[1873]78      if (selectedAlgorithm != null) {
[2152]79        SetProblemParameters(selectedAlgorithm, problem, targetVariable, inputVariables);
[2119]80        AddDispatchedRun(targetVariable, inputVariables, selectedAlgorithm.Name);
[1873]81      }
82      return selectedAlgorithm;
[1044]83    }
84
[2223]85    private HeuristicLab.Modeling.IAlgorithm ChooseDeterministic(int targetVariable, int[] inputVariables, IEnumerable<HeuristicLab.Modeling.IAlgorithm> algos) {
[1873]86      var deterministicAlgos = algos
87        .Where(a => (a as IStochasticAlgorithm) == null)
[2119]88        .Where(a => AlgorithmFinishedOrDispatched(targetVariable, inputVariables, a.Name) == false);
[1873]89
90      if (deterministicAlgos.Count() == 0) return null;
91      return deterministicAlgos.ElementAt(random.Next(deterministicAlgos.Count()));
92    }
93
[2223]94    private HeuristicLab.Modeling.IAlgorithm ChooseStochastic(IEnumerable<HeuristicLab.Modeling.IAlgorithm> regressionAlgos) {
[1873]95      var stochasticAlgos = regressionAlgos.Where(a => (a as IStochasticAlgorithm) != null);
96      if (stochasticAlgos.Count() == 0) return null;
97      return stochasticAlgos.ElementAt(random.Next(stochasticAlgos.Count()));
98    }
99
100    private void PopulateFinishedRuns() {
[2223]101      //Dictionary<Entity, Entity> processedModels = new Dictionary<Entity, Entity>();
102      //var datasetBindings = store
103      //  .Query(
104      //  "?Dataset <" + Ontology.InstanceOf + "> <" + Ontology.TypeDataSet + "> .", 0, 1)
105      //  .Select(x => (Entity)x.Get("Dataset"));
[2012]106
[2223]107      //if (datasetBindings.Count() > 0) {
108      //  var datasetEntity = datasetBindings.ElementAt(0);
[1873]109
[2223]110      //  DataSet ds = new DataSet(store, datasetEntity);
111      //  var result = store
112      //    .Query(
113      //    "?Model <" + Ontology.TargetVariable + "> ?TargetVariable ." + Environment.NewLine +
114      //    "?Model <" + Ontology.Name + "> ?AlgoName .",
115      //    0, 1000)
116      //    .Select(x => new Resource[] { (Literal)x.Get("TargetVariable"), (Literal)x.Get("AlgoName"), (Entity)x.Get("Model") });
[2012]117
[2223]118      //  foreach (Resource[] row in result) {
119      //    Entity model = ((Entity)row[2]);
120      //    if (!processedModels.ContainsKey(model)) {
121      //      processedModels.Add(model, model);
[2049]122
[2223]123      //      string targetVariable = (string)((Literal)row[0]).Value;
124      //      string algoName = (string)((Literal)row[1]).Value;
125      //      int targetVariableIndex = ds.Problem.Dataset.GetVariableIndex(targetVariable);
[2119]126
[2223]127      //      var inputVariableLiterals = store
128      //        .Query(
129      //          "<" + model.Uri + "> <" + Ontology.HasInputVariable + "> ?InputVariable ." + Environment.NewLine +
130      //          "?InputVariable <" + Ontology.Name + "> ?Name .",
131      //          0, 1000)
132      //        .Select(x => (Literal)x.Get("Name"))
133      //        .Select(l => (string)l.Value)
134      //        .Distinct();
[2119]135
[2223]136      //      List<int> inputVariables = new List<int>();
137      //      foreach (string variableName in inputVariableLiterals) {
138      //        int variableIndex = ds.Problem.Dataset.GetVariableIndex(variableName);
139      //        inputVariables.Add(variableIndex);
140      //      }
141      //      if (!AlgorithmFinishedOrDispatched(targetVariableIndex, inputVariables.ToArray(), algoName)) {
142      //        AddDispatchedRun(targetVariableIndex, inputVariables.ToArray(), algoName);
143      //      }
144      //    }
145      //  }
146      //}
[1873]147    }
148
[2223]149    private void SetProblemParameters(HeuristicLab.Modeling.IAlgorithm algo, Problem problem, int targetVariable, int[] inputVariables) {
[2119]150      algo.Dataset = problem.Dataset;
151      algo.TargetVariable = targetVariable;
152      algo.ProblemInjector.GetVariable("TrainingSamplesStart").GetValue<IntData>().Data = problem.TrainingSamplesStart;
153      algo.ProblemInjector.GetVariable("TrainingSamplesEnd").GetValue<IntData>().Data = problem.TrainingSamplesEnd;
154      algo.ProblemInjector.GetVariable("ValidationSamplesStart").GetValue<IntData>().Data = problem.ValidationSamplesStart;
155      algo.ProblemInjector.GetVariable("ValidationSamplesEnd").GetValue<IntData>().Data = problem.ValidationSamplesEnd;
156      algo.ProblemInjector.GetVariable("TestSamplesStart").GetValue<IntData>().Data = problem.TestSamplesStart;
157      algo.ProblemInjector.GetVariable("TestSamplesEnd").GetValue<IntData>().Data = problem.TestSamplesEnd;
158      ItemList<IntData> allowedFeatures = algo.ProblemInjector.GetVariable("AllowedFeatures").GetValue<ItemList<IntData>>();
[2130]159      foreach (int inputVariable in inputVariables) {
160        if (inputVariable != targetVariable) {
161          allowedFeatures.Add(new IntData(inputVariable));
162        }
163      }
[2119]164
165      if (problem.LearningTask == LearningTask.TimeSeries) {
166        algo.ProblemInjector.GetVariable("Autoregressive").GetValue<BoolData>().Data = problem.AutoRegressive;
167        algo.ProblemInjector.GetVariable("MinTimeOffset").GetValue<IntData>().Data = problem.MinTimeOffset;
168        algo.ProblemInjector.GetVariable("MaxTimeOffset").GetValue<IntData>().Data = problem.MaxTimeOffset;
[2130]169        if (problem.AutoRegressive) {
170          allowedFeatures.Add(new IntData(targetVariable));
171        }
[2119]172      } else if (problem.LearningTask == LearningTask.Classification) {
173        ItemList<DoubleData> classValues = algo.ProblemInjector.GetVariable("TargetClassValues").GetValue<ItemList<DoubleData>>();
174        foreach (double classValue in GetDifferentClassValues(problem.Dataset, targetVariable)) classValues.Add(new DoubleData(classValue));
175      }
176    }
177
178    private IEnumerable<double> GetDifferentClassValues(HeuristicLab.DataAnalysis.Dataset dataset, int targetVariable) {
179      return Enumerable.Range(0, dataset.Rows).Select(x => dataset.GetValue(x, targetVariable)).Distinct();
180    }
181
182    private void AddDispatchedRun(int targetVariable, int[] inputVariables, string algoName) {
[2012]183      if (!finishedAndDispatchedRuns.ContainsKey(targetVariable)) {
[2119]184        finishedAndDispatchedRuns[targetVariable] = new List<AlgorithmConfiguration>();
[1873]185      }
[2119]186      AlgorithmConfiguration conf = new AlgorithmConfiguration();
187      conf.name = algoName;
188      conf.inputVariables = new List<int>(inputVariables);
189      conf.targetVariable = targetVariable;
190      finishedAndDispatchedRuns[targetVariable].Add(conf);
[1873]191    }
192
[2119]193    private bool AlgorithmFinishedOrDispatched(int targetVariable, int[] inputVariables, string algoName) {
[1873]194      return
[2012]195        finishedAndDispatchedRuns.ContainsKey(targetVariable) &&
[2119]196        finishedAndDispatchedRuns[targetVariable].Any(x => targetVariable == x.targetVariable &&
197                                                           algoName == x.name &&
198                                                           inputVariables.Count() == x.inputVariables.Count() &&
199                                                           inputVariables.All(v => x.inputVariables.Contains(v)));
[1873]200    }
[1044]201  }
202}
Note: See TracBrowser for help on using the repository browser.