Free cookie consent management tool by TermsFeed Policy Generator

source: trunk/sources/HeuristicLab.Modeling.Database.SQLServerCompact/3.2/DatabaseService.cs @ 2229

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

added license information (ticket #712)

File size: 10.4 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.Linq;
25using System.Reflection;
26
27using HeuristicLab.Core;
28using HeuristicLab.DataAnalysis;
29using HeuristicLab.Data;
30using System.Data.Linq;
31
32namespace HeuristicLab.Modeling.Database.SQLServerCompact {
33  public class DatabaseService : IModelingDatabase {
34
35    private readonly string connection;
36    public DatabaseService(string connection) {
37      this.connection = connection;
38      Connect();
39      if (!ctx.DatabaseExists())
40        ctx.CreateDatabase();
41    }
42
43    private void EmptyDatabase() {
44      ctx.DeleteDatabase();
45      ctx.CreateDatabase();
46    }
47
48    private ModelingDataContext ctx;
49    public void Connect() {
50      if (ctx != null)
51        return;
52
53      ctx = new ModelingDataContext(connection);
54      DataLoadOptions dlo = new DataLoadOptions();
55      dlo.LoadWith<ModelResult>(mr => mr.Result);
56      dlo.LoadWith<InputVariableResult>(ir => ir.Variable);
57      dlo.LoadWith<InputVariableResult>(ir => ir.Result);
58      dlo.LoadWith<Model>(m => m.TargetVariable);
59      ctx.LoadOptions = dlo;
60    }
61
62    public void Disconnect() {
63      if (ctx == null)
64        return;
65      ctx.Dispose();
66      ctx = null;
67    }
68
69    public void Persist(HeuristicLab.Modeling.IAlgorithm algorithm) {
70      int trainingSamplesStart = ((IntData)algorithm.Engine.GlobalScope.GetVariableValue("TrainingSamplesStart", false)).Data;
71      int trainingSamplesEnd = ((IntData)algorithm.Engine.GlobalScope.GetVariableValue("TrainingSamplesEnd", false)).Data;
72      int validationSamplesStart = ((IntData)algorithm.Engine.GlobalScope.GetVariableValue("ValidationSamplesStart", false)).Data;
73      int validationSamplesEnd = ((IntData)algorithm.Engine.GlobalScope.GetVariableValue("ValidationSamplesEnd", false)).Data;
74      int testSamplesStart = ((IntData)algorithm.Engine.GlobalScope.GetVariableValue("TestSamplesStart", false)).Data;
75      int testSamplesEnd = ((IntData)algorithm.Engine.GlobalScope.GetVariableValue("TestSamplesEnd", false)).Data;
76
77      GetOrCreateProblem(algorithm.Dataset);
78      Dictionary<string, Variable> variables = GetAllVariables();
79      Algorithm algo = GetOrCreateAlgorithm(algorithm.Name, algorithm.Description);
80      Variable target = variables[algorithm.Model.TargetVariable];
81      Model model;
82
83      using (ModelingDataContext ctx = new ModelingDataContext(connection)) {
84        model = new Model(target, algo);
85        model.TrainingSamplesStart = trainingSamplesStart;
86        model.TrainingSamplesEnd = trainingSamplesEnd;
87        model.ValidationSamplesStart = validationSamplesStart;
88        model.ValidationSamplesEnd = validationSamplesEnd;
89        model.TestSamplesStart = testSamplesStart;
90        model.TestSamplesEnd = testSamplesEnd;
91
92        ctx.Models.InsertOnSubmit(model);
93
94        ctx.SubmitChanges();
95      }
96
97      using (ModelingDataContext ctx = new ModelingDataContext(connection)) {
98        ctx.ModelData.InsertOnSubmit(new ModelData(model, PersistenceManager.SaveToGZip(algorithm.Model.Data)));
99      }
100
101      using (ModelingDataContext ctx = new ModelingDataContext(connection)) {
102        foreach (string inputVariable in algorithm.Model.InputVariables) {
103          ctx.InputVariables.InsertOnSubmit(new InputVariable(model, variables[inputVariable]));
104        }
105        ctx.SubmitChanges();
106      }
107
108      using (ModelingDataContext ctx = new ModelingDataContext(connection)) {
109        //get all double properties to save as modelResult
110        IEnumerable<PropertyInfo> modelResultInfos = algorithm.Model.GetType().GetProperties().Where(
111          info => info.PropertyType == typeof(double));
112        foreach (PropertyInfo modelResultInfo in modelResultInfos) {
113          Result result = GetOrCreateResult(modelResultInfo.Name);
114          double value = (double)modelResultInfo.GetValue(algorithm.Model, null);
115          ctx.ModelResults.InsertOnSubmit(new ModelResult(model, result, value));
116        }
117        ctx.SubmitChanges();
118      }
119
120      using (ModelingDataContext ctx = new ModelingDataContext(connection)) {
121        IEnumerable<MethodInfo> inputVariableResultInfos = algorithm.Model.GetType().GetMethods().Where(
122          info => info.GetParameters().Count() == 1 &&
123             info.GetParameters()[0].ParameterType == typeof(string) &&
124             info.GetParameters()[0].Name == "variableName" &&
125             info.ReturnParameter.ParameterType == typeof(double) &&
126             info.Name.StartsWith("Get"));
127        foreach (MethodInfo inputVariableResultInfo in inputVariableResultInfos) {
128          Result result = GetOrCreateResult(inputVariableResultInfo.Name.Substring(3));
129          foreach (InputVariable variable in ctx.InputVariables.Where(iv => iv.Model == model)) {
130            double value = (double)inputVariableResultInfo.Invoke(algorithm.Model, new object[] { variable.Variable.Name });
131            ctx.InputVariableResults.InsertOnSubmit(new InputVariableResult(variable, result, value));
132          }
133        }
134        ctx.SubmitChanges();
135      }
136
137    }
138
139    #region Problem
140
141    public Dataset GetDataset() {
142      if (ctx.Problems.Count() != 1)
143        throw new InvalidOperationException("Could not get dataset. No or more than one problems are persisted in the database.");
144
145      Problem problem = ctx.Problems.Single();
146      return problem.Dataset;
147
148    }
149
150    public Problem GetOrCreateProblem(Dataset dataset) {
151      Problem problem;
152      if (ctx.Problems.Count() == 0)
153        problem = PersistProblem(dataset);
154      else
155        problem = ctx.Problems.Single();
156      if (problem.Dataset.ToString() != dataset.ToString())
157        throw new InvalidOperationException("Could not persist dataset. The database already contains a different dataset.");
158      return problem;
159    }
160
161    private Problem PersistProblem(Dataset dataset) {
162      Problem problem;
163      using (ModelingDataContext ctx = new ModelingDataContext(connection)) {
164        if (ctx.Problems.Count() != 0)
165          throw new InvalidOperationException("Could not persist dataset. A dataset is already saved in the database.");
166        problem = new Problem(dataset);
167        ctx.Problems.InsertOnSubmit(problem);
168        foreach (string variable in dataset.VariableNames) {
169          ctx.Variables.InsertOnSubmit(new Variable(variable));
170        }
171        ctx.SubmitChanges();
172      }
173      return problem;
174    }
175
176    #endregion
177
178    #region Algorithm
179    public Algorithm GetOrCreateAlgorithm(string name, string description) {
180      Algorithm algorithm;
181      using (ModelingDataContext ctx = new ModelingDataContext(connection)) {
182        var algorithms = from algo in ctx.Algorithms
183                         where algo.Name == name && algo.Description == description
184                         select algo;
185        if (algorithms.Count() == 0) {
186          algorithm = new Algorithm(name, description);
187          ctx.Algorithms.InsertOnSubmit(algorithm);
188          ctx.SubmitChanges();
189        } else if (algorithms.Count() == 1)
190          algorithm = algorithms.Single();
191        else
192          throw new ArgumentException("Could not get Algorithm. More than one algorithm with the name " + name + " are saved in database.");
193      }
194      return algorithm;
195    }
196    #endregion
197
198    #region Variables
199    public Dictionary<string, Variable> GetAllVariables() {
200      Dictionary<string, Variable> dict = new Dictionary<string, Variable>();
201      dict = ctx.Variables.ToDictionary<Variable, string>(delegate(Variable v) { return v.Name; });
202      return dict;
203    }
204    #endregion
205
206    #region Result
207    public Result GetOrCreateResult(string name) {
208      Result result;
209      using (ModelingDataContext ctx = new ModelingDataContext(connection)) {
210        var results = from r in ctx.Results
211                      where r.Name == name
212                      select r;
213        if (results.Count() == 0) {
214          result = new Result(name);
215          ctx.Results.InsertOnSubmit(result);
216          ctx.SubmitChanges();
217        } else if (results.Count() == 1)
218          result = results.Single();
219        else
220          throw new ArgumentException("Could not get result. More than one result with the name " + name + " are saved in database.");
221      }
222      return result;
223    }
224
225    public IEnumerable<IResult> GetAllResults() {
226      return ctx.Results.ToList().Cast<IResult>();
227    }
228
229    public IEnumerable<IResult> GetAllResultsForInputVariables() {
230      return (from ir in ctx.InputVariableResults select ir.Result).Distinct().ToList().Cast<IResult>();
231    }
232
233    #endregion
234
235    #region ModelResult
236    public IEnumerable<IModelResult> GetModelResults(IModel model) {
237      var results = from result in ctx.ModelResults
238                    where result.Model == model
239                    select result;
240      return results.ToList().Cast<IModelResult>();
241    }
242    #endregion
243
244    #region InputVariableResults
245    public IEnumerable<IInputVariableResult> GetInputVariableResults(IModel model) {
246      var inputResults = from ir in ctx.InputVariableResults
247                         where ir.Model == model
248                         select ir;
249      return inputResults.ToList().Cast<IInputVariableResult>();
250    }
251
252    #endregion
253
254    #region Model
255    public IEnumerable<IModel> GetAllModels() {
256      return ctx.Models.ToList().Cast<IModel>();
257    }
258
259    public byte[] GetModelData(IModel model) {
260      var data = (from md in ctx.ModelData
261                  where md.Model == model
262                  select md);
263      if (data.Count() == 0)
264        return null;
265      return data.Single().Data;
266    }
267    #endregion
268
269  }
270}
Note: See TracBrowser for help on using the repository browser.