Free cookie consent management tool by TermsFeed Policy Generator

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

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

Copied refactored plugin infrastructure from branch and merged changeset r2586:2589 from branch into the trunk. #799

File size: 12.5 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;
[1053]31using HeuristicLab.Data;
[1060]32using HeuristicLab.Core;
[1857]33using HeuristicLab.Modeling;
[2223]34using HeuristicLab.Modeling.Database;
[2375]35using HeuristicLab.DataAnalysis;
[2566]36using HeuristicLab.GP.Interfaces;
37using HeuristicLab.GP;
38using HeuristicLab.GP.StructureIdentification;
[1044]39
40namespace HeuristicLab.CEDMA.Server {
[2375]41  public class SimpleDispatcher : IDispatcher, IViewable {
[2119]42    private class AlgorithmConfiguration {
43      public string name;
[2375]44      public ProblemSpecification problemSpecification;
[2119]45    }
46
[2375]47    internal event EventHandler Changed;
48
[2290]49    private IModelingDatabase database;
50    public IModelingDatabase Database {
51      get {
52        return database;
53      }
54    }
55
[2375]56    private Dataset dataset;
57    public Dataset Dataset {
[2290]58      get {
[2375]59        return dataset;
[2290]60      }
61    }
62
63    public IEnumerable<string> TargetVariables {
64      get {
[2375]65        return Enumerable.Range(0, Dataset.Columns).Select(x => Dataset.GetVariableName(x));
[2290]66      }
67    }
68
[2375]69    public IEnumerable<string> Variables {
[2290]70      get {
71        return TargetVariables;
72      }
73    }
74
[2375]75    private HeuristicLab.Modeling.IAlgorithm[] defaultAlgorithms;
76    public IEnumerable<HeuristicLab.Modeling.IAlgorithm> GetAlgorithms(LearningTask task) {
77      switch (task) {
78        case LearningTask.Regression: {
79            return defaultAlgorithms.Where(a => (a as IClassificationAlgorithm) == null && (a as ITimeSeriesAlgorithm) == null);
80          }
81        case LearningTask.Classification: {
82            return defaultAlgorithms.Where(a => (a as IClassificationAlgorithm) != null);
83          }
84        case LearningTask.TimeSeries: {
85            return defaultAlgorithms.Where(a => (a as ITimeSeriesAlgorithm) != null);
86          }
87        default: {
88            return new HeuristicLab.Modeling.IAlgorithm[] { };
89          }
[2290]90      }
91    }
92
[2375]93    private Random random;
94    private Dictionary<string, ProblemSpecification> problemSpecifications;
95    private Dictionary<string, List<HeuristicLab.Modeling.IAlgorithm>> algorithms;
96    public IEnumerable<HeuristicLab.Modeling.IAlgorithm> GetAllowedAlgorithms(string targetVariable) {
97      if (algorithms.ContainsKey(targetVariable))
98        return algorithms[targetVariable];
99      else return new HeuristicLab.Modeling.IAlgorithm[] { };
[2290]100    }
[2375]101    private Dictionary<string, bool> activeVariables;
102    public IEnumerable<string> AllowedTargetVariables {
103      get { return activeVariables.Where(x => x.Value).Select(x => x.Key); }
104    }
105    private Dictionary<string, List<AlgorithmConfiguration>> finishedAndDispatchedRuns;
[2290]106    private object locker = new object();
[1873]107
[2375]108    public SimpleDispatcher(IModelingDatabase database, Dataset dataset) {
109      this.dataset = dataset;
[2290]110      this.database = database;
[2375]111      dataset.Changed += (sender, args) => FireChanged();
112      random = new Random();
[2290]113
[2375]114      activeVariables = new Dictionary<string, bool>();
115      problemSpecifications = new Dictionary<string, ProblemSpecification>();
116      algorithms = new Dictionary<string, List<HeuristicLab.Modeling.IAlgorithm>>();
117      finishedAndDispatchedRuns = new Dictionary<string, List<AlgorithmConfiguration>>();
118
[2591]119     
120      defaultAlgorithms = ApplicationManager.Manager.GetInstances<HeuristicLab.Modeling.IAlgorithm>().ToArray();
[2290]121
[2375]122      // PopulateFinishedRuns();
[1044]123    }
124
[2290]125    public HeuristicLab.Modeling.IAlgorithm GetNextJob() {
126      lock (locker) {
[2422]127        if (activeVariables.Where(x => x.Value == true).Count() > 0) {
128          string[] targetVariables = (from pair in activeVariables
129                                      where pair.Value == true
130                                      select pair.Key).ToArray();
[2375]131          string targetVariable = SelectTargetVariable(targetVariables);
132          HeuristicLab.Modeling.IAlgorithm selectedAlgorithm = SelectAndConfigureAlgorithm(targetVariable);
[2290]133
134          return selectedAlgorithm;
135        } else return null;
[1857]136      }
[2290]137    }
[2119]138
[2375]139    public virtual string SelectTargetVariable(string[] targetVariables) {
[2290]140      return targetVariables[random.Next(targetVariables.Length)];
141    }
[2119]142
[2375]143    public HeuristicLab.Modeling.IAlgorithm SelectAndConfigureAlgorithm(string targetVariable) {
[2290]144      HeuristicLab.Modeling.IAlgorithm selectedAlgorithm = null;
145      var possibleAlgos =
[2375]146        algorithms[targetVariable]
147        .Where(x =>
148          ((x is IStochasticAlgorithm) || !AlgorithmFinishedOrDispatched(problemSpecifications[targetVariable], x.Name)));
[2290]149      if (possibleAlgos.Count() > 0) selectedAlgorithm = possibleAlgos.ElementAt(random.Next(possibleAlgos.Count()));
[1873]150      if (selectedAlgorithm != null) {
[2377]151        // create a clone of the algorithm template before setting the parameters
[2422]152        selectedAlgorithm = (HeuristicLab.Modeling.IAlgorithm)selectedAlgorithm.Clone();
[2375]153        SetProblemParameters(selectedAlgorithm, problemSpecifications[targetVariable]);
[2290]154        if (!(selectedAlgorithm is IStochasticAlgorithm))
[2375]155          AddDispatchedRun(problemSpecifications[targetVariable], selectedAlgorithm.Name);
[1873]156      }
157      return selectedAlgorithm;
[1044]158    }
159
[2375]160    //private void PopulateFinishedRuns() {
161    //  var dispatchedAlgos = from model in Database.GetAllModels()
162    //                        select new {
163    //                          TargetVariable = model.TargetVariable.Name,
164    //                          Algorithm = model.Algorithm.Name,
165    //                          InputVariables = Database.GetInputVariableResults(model).Select(x => x.Variable.Name).Distinct(),
166    //                        };
167    //  foreach (var algo in dispatchedAlgos) {
168    //    ProblemSpecification spec = new ProblemSpecification();
169    //    spec.TargetVariable = algo.TargetVariable;
170    //    foreach (string variable in algo.InputVariables) spec.AddInputVariable(variable);
171    //    AddDispatchedRun(spec, algo.Algorithm);
172    //  }
173    //}
[1873]174
[2375]175    private void SetProblemParameters(HeuristicLab.Modeling.IAlgorithm algo, ProblemSpecification spec) {
176      algo.Dataset = spec.Dataset;
[2440]177      algo.TargetVariable = spec.TargetVariable;
[2375]178      algo.TrainingSamplesStart = spec.TrainingSamplesStart;
179      algo.TrainingSamplesEnd = spec.TrainingSamplesEnd;
180      algo.ValidationSamplesStart = spec.ValidationSamplesStart;
181      algo.ValidationSamplesEnd = spec.ValidationSamplesEnd;
182      algo.TestSamplesStart = spec.TestSamplesStart;
183      algo.TestSamplesEnd = spec.TestSamplesEnd;
[2440]184      List<string> allowedFeatures = new List<string>();
[2375]185      foreach (string inputVariable in spec.InputVariables) {
186        if (inputVariable != spec.TargetVariable) {
[2440]187          allowedFeatures.Add(inputVariable);
[2130]188        }
189      }
[2119]190
[2375]191      if (spec.LearningTask == LearningTask.TimeSeries) {
[2366]192        ITimeSeriesAlgorithm timeSeriesAlgo = (ITimeSeriesAlgorithm)algo;
[2375]193        timeSeriesAlgo.MinTimeOffset = spec.MinTimeOffset;
194        timeSeriesAlgo.MaxTimeOffset = spec.MaxTimeOffset;
[2422]195        timeSeriesAlgo.TrainingSamplesStart = spec.TrainingSamplesStart - spec.MinTimeOffset + 1; // first possible index is 1 because of differential symbol
[2375]196        if (spec.AutoRegressive) {
[2440]197          allowedFeatures.Add(spec.TargetVariable);
[2130]198        }
[2119]199      }
[2375]200      algo.AllowedVariables = allowedFeatures;
[2566]201
202      IGeneticProgrammingAlgorithm structIdAlgo = algo as IGeneticProgrammingAlgorithm;
203      if (structIdAlgo != null) {
204        var funLib = SelectRandomFunctionLibrary();
205        structIdAlgo.FunctionLibraryInjector = funLib;
206      }
[2119]207    }
208
[2566]209    private IOperator SelectRandomFunctionLibrary() {
[2591]210      var injectors = from injector in ApplicationManager.Manager.GetInstances<FunctionLibraryInjectorBase>()
[2566]211                      where injector.GetType().GetCustomAttributes(typeof(SymbolicRegressionFunctionLibraryInjectorAttribute), true).Count() > 0
212                      select injector;
[2119]213
[2566]214      return injectors.ElementAt(random.Next(injectors.Count()));
215    }
216
217
[2375]218    private void AddDispatchedRun(ProblemSpecification specification, string algorithm) {
[2119]219      AlgorithmConfiguration conf = new AlgorithmConfiguration();
[2375]220      conf.name = algorithm;
221      conf.problemSpecification = new ProblemSpecification(specification);
222      if (!finishedAndDispatchedRuns.ContainsKey(specification.TargetVariable))
223        finishedAndDispatchedRuns.Add(specification.TargetVariable, new List<AlgorithmConfiguration>());
224      finishedAndDispatchedRuns[specification.TargetVariable].Add(conf);
[1873]225    }
226
[2375]227    private bool AlgorithmFinishedOrDispatched(ProblemSpecification specification, string algoName) {
[1873]228      return
[2375]229        finishedAndDispatchedRuns.ContainsKey(specification.TargetVariable) &&
230        finishedAndDispatchedRuns[specification.TargetVariable].Any(x =>
[2119]231                                                           algoName == x.name &&
[2375]232                                                           specification.Equals(x.problemSpecification));
[1873]233    }
[2290]234
[2375]235    internal void EnableTargetVariable(string name) {
236      activeVariables[name] = true;
[2290]237    }
238
[2375]239    internal void DisableTargetVariable(string name) {
240      activeVariables[name] = false;
[2290]241    }
242
[2375]243    public void EnableAlgorithm(string targetVariable, HeuristicLab.Modeling.IAlgorithm algo) {
244      if (!algorithms.ContainsKey(targetVariable)) algorithms.Add(targetVariable, new List<HeuristicLab.Modeling.IAlgorithm>());
[2422]245      if (!algorithms[targetVariable].Contains(algo))
246        algorithms[targetVariable].Add(algo);
[2290]247    }
248
[2375]249    public void DisableAlgorithm(string targetVariable, HeuristicLab.Modeling.IAlgorithm algo) {
250      algorithms[targetVariable].Remove(algo);
[2290]251    }
252
[2375]253    public ProblemSpecification GetProblemSpecification(string targetVariable) {
254      if (!problemSpecifications.ContainsKey(targetVariable))
255        problemSpecifications[targetVariable] = CreateDefaultProblemSpecification(targetVariable);
256
257      return problemSpecifications[targetVariable];
[2290]258    }
259
[2375]260    private ProblemSpecification CreateDefaultProblemSpecification(string targetVariable) {
261      ProblemSpecification spec = new ProblemSpecification();
262      spec.Dataset = dataset;
263      spec.TargetVariable = targetVariable;
264      spec.LearningTask = LearningTask.Regression;
265      int targetColumn = dataset.GetVariableIndex(targetVariable);
266      // find index of first correct target value
267      int firstValueIndex;
268      for (firstValueIndex = 0; firstValueIndex < dataset.Rows; firstValueIndex++) {
269        double x = dataset.GetValue(firstValueIndex, targetColumn);
270        if (!(double.IsNaN(x) || double.IsInfinity(x))) break;
[2290]271      }
[2375]272      // find index of last correct target value
273      int lastValueIndex;
274      for (lastValueIndex = dataset.Rows - 1; lastValueIndex > firstValueIndex; lastValueIndex--) {
275        double x = dataset.GetValue(lastValueIndex, targetColumn);
276        if (!(double.IsNaN(x) || double.IsInfinity(x))) break;
277      }
278
279      int validTargetRange = lastValueIndex - firstValueIndex;
280      spec.TrainingSamplesStart = firstValueIndex;
281      spec.TrainingSamplesEnd = firstValueIndex + (int)Math.Floor(validTargetRange * 0.5);
282      spec.ValidationSamplesStart = spec.TrainingSamplesEnd;
283      spec.ValidationSamplesEnd = firstValueIndex + (int)Math.Floor(validTargetRange * 0.75);
284      spec.TestSamplesStart = spec.ValidationSamplesEnd;
285      spec.TestSamplesEnd = lastValueIndex;
286      return spec;
[2290]287    }
288
[2375]289    public void FireChanged() {
[2290]290      if (Changed != null) Changed(this, new EventArgs());
291    }
292
293    #region IViewable Members
294
295    public virtual IView CreateView() {
296      return new DispatcherView(this);
297    }
298
299    #endregion
[1044]300  }
301}
Note: See TracBrowser for help on using the repository browser.