Free cookie consent management tool by TermsFeed Policy Generator

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

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

added possibility to create input variables in modeling database (ticket #759)

File size: 14.7 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    private readonly string connection;
35    public DatabaseService(string connection) {
36      this.connection = connection;
37      Connect();
38      if (!ctx.DatabaseExists())
39        ctx.CreateDatabase();
40    }
41
42    public void EmptyDatabase() {
43      ctx.Connection.Dispose();
44      ctx.DeleteDatabase();
45      Connect();
46      ctx.CreateDatabase();
47    }
48
49    private ModelingDataContext ctx;
50    public void Connect() {
51      if (ctx != null)
52        Disconnect();
53
54      ctx = new ModelingDataContext(connection);
55      DataLoadOptions dlo = new DataLoadOptions();
56      dlo.LoadWith<ModelResult>(mr => mr.Result);
57      dlo.LoadWith<ModelMetaData>(mmd => mmd.MetaData);
58      dlo.LoadWith<InputVariableResult>(ir => ir.Variable);
59      dlo.LoadWith<InputVariableResult>(ir => ir.Result);
60      dlo.LoadWith<Model>(m => m.TargetVariable);
61      dlo.LoadWith<Model>(m => m.Algorithm);
62      ctx.LoadOptions = dlo;
63    }
64
65    public void Disconnect() {
66      if (ctx == null)
67        return;
68      ctx.Connection.Dispose();
69      ctx.Dispose();
70      ctx = null;
71    }
72
73    public IEnumerable<IModel> GetAllModels() {
74      return ctx.Models.ToList().Cast<IModel>();
75    }
76
77    public IEnumerable<IVariable> GetAllVariables() {
78      return ctx.Variables.ToList().Cast<IVariable>();
79    }
80
81    public IEnumerable<IResult> GetAllResults() {
82      return ctx.Results.ToList().Cast<IResult>();
83    }
84
85    public IEnumerable<IResult> GetAllResultsForInputVariables() {
86      return (from ir in ctx.InputVariableResults select ir.Result).Distinct().ToList().Cast<IResult>();
87    }
88
89    public IEnumerable<IMetaData> GetAllMetaData() {
90      return ctx.MetaData.ToList().Cast<IMetaData>();
91    }
92
93    public IEnumerable<IAlgorithm> GetAllAlgorithms() {
94      return ctx.Algorithms.ToList().Cast<IAlgorithm>();
95    }
96
97    public IModel CreateModel(ModelType modelType, IAlgorithm algorithm, IVariable targetVariable,
98int trainingSamplesStart, int trainingSamplesEnd, int validationSamplesStart, int validationSamplesEnd, int testSamplesStart, int testSamplesEnd) {
99      return CreateModel(null, modelType, algorithm, targetVariable, trainingSamplesStart, trainingSamplesEnd, validationSamplesStart, validationSamplesEnd, testSamplesStart, testSamplesEnd);
100    }
101
102    public IModel CreateModel(string modelName, ModelType modelType, IAlgorithm algorithm, IVariable targetVariable,
103     int trainingSamplesStart, int trainingSamplesEnd, int validationSamplesStart, int validationSamplesEnd, int testSamplesStart, int testSamplesEnd) {
104      Variable target = (Variable)targetVariable;
105      Algorithm algo = (Algorithm)algorithm;
106      Model model = new Model(target, algo, modelType);
107      model.Name = modelName;
108      model.TrainingSamplesStart = trainingSamplesStart;
109      model.TrainingSamplesEnd = trainingSamplesEnd;
110      model.ValidationSamplesStart = validationSamplesStart;
111      model.ValidationSamplesEnd = validationSamplesEnd;
112      model.TestSamplesStart = testSamplesStart;
113      model.TestSamplesEnd = testSamplesEnd;
114
115      return model;
116    }
117
118    public void PersistModel(IModel model) {
119      using (ModelingDataContext ctx = new ModelingDataContext(connection)) {
120        Model m = (Model)model;
121        Model orginal = ctx.Models.GetOriginalEntityState(m);
122        if (orginal == null)
123          ctx.Models.Attach(m);
124        ctx.Refresh(RefreshMode.KeepCurrentValues, m);
125        ctx.SubmitChanges();
126      }
127    }
128
129    public void DeleteModel(IModel model) {
130      Model m = (Model)model;
131      ctx.ModelData.DeleteAllOnSubmit(ctx.ModelData.Where(x => x.Model == m));
132      ctx.ModelMetaData.DeleteAllOnSubmit(ctx.ModelMetaData.Where(x => x.Model == m));
133      ctx.ModelResults.DeleteAllOnSubmit(ctx.ModelResults.Where(x => x.Model == m));
134      ctx.InputVariableResults.DeleteAllOnSubmit(ctx.InputVariableResults.Where(x => x.Model == m));
135      ctx.InputVariables.DeleteAllOnSubmit(ctx.InputVariables.Where(x => x.Model == m));
136      Model orginal = ctx.Models.GetOriginalEntityState(m);
137      if (orginal == null)
138        ctx.Models.Attach(m);
139      ctx.Models.DeleteOnSubmit(m);
140      ctx.SubmitChanges();
141    }
142
143    public Dataset GetDataset() {
144      if (ctx.Problems.Count() != 1)
145        throw new InvalidOperationException("Could not get dataset. No or more than one problems are persisted in the database.");
146      Problem problem = ctx.Problems.Single();
147      return problem.Dataset;
148    }
149
150    public void PersistProblem(Dataset dataset) {
151      Problem problem;
152      using (ModelingDataContext ctx = new ModelingDataContext(connection)) {
153        if (ctx.Problems.Count() != 0)
154          throw new InvalidOperationException("Could not persist dataset. A dataset is already saved in the database.");
155        problem = new Problem(dataset);
156        ctx.Problems.InsertOnSubmit(problem);
157        foreach (string variable in dataset.VariableNames) {
158          ctx.Variables.InsertOnSubmit(new Variable(variable));
159        }
160        ctx.SubmitChanges();
161      }
162    }
163
164    public IVariable GetVariable(string variableName) {
165      var variables = ctx.Variables.Where(v => v.Name == variableName);
166      if (variables.Count() != 1)
167        throw new ArgumentException("Zero or more than one variable with the name " + variableName + " are persisted in the database.");
168      return variables.Single();
169    }
170
171    public IPredictor GetModelPredictor(IModel model) {
172      var data = (from md in ctx.ModelData
173                  where md.Model == model
174                  select md);
175      if (data.Count() != 1)
176        throw new ArgumentException("No predictor persisted for given model!");
177      return (IPredictor)PersistenceManager.RestoreFromGZip(data.Single().Data);
178    }
179
180    public void PersistPredictor(IModel model, IPredictor predictor) {
181      Model m = (Model)model;
182      using (ModelingDataContext ctx = new ModelingDataContext(connection)) {
183        ctx.ModelData.DeleteAllOnSubmit(ctx.ModelData.Where(x => x.Model == m));
184        ctx.ModelResults.DeleteAllOnSubmit(ctx.ModelResults.Where(x => x.Model == m));
185        ctx.InputVariableResults.DeleteAllOnSubmit(ctx.InputVariableResults.Where(x => x.Model == m));
186        ctx.InputVariables.DeleteAllOnSubmit(ctx.InputVariables.Where(x => x.Model == m));
187
188        ctx.ModelData.InsertOnSubmit(new ModelData(m, PersistenceManager.SaveToGZip(predictor)));
189        foreach (string variableName in predictor.GetInputVariables())
190          ctx.InputVariables.InsertOnSubmit(new InputVariable(m, (Variable)GetVariable(variableName)));
191
192        ctx.SubmitChanges();
193      }
194    }
195
196    public IAlgorithm GetOrPersistAlgorithm(string algorithmName) {
197      Algorithm algorithm;
198      using (ModelingDataContext ctx = new ModelingDataContext(connection)) {
199        var algorithms = ctx.Algorithms.Where(algo => algo.Name == algorithmName);
200        if (algorithms.Count() == 0) {
201          algorithm = new Algorithm(algorithmName, "");
202          ctx.Algorithms.InsertOnSubmit(algorithm);
203          ctx.SubmitChanges();
204        } else if (algorithms.Count() == 1)
205          algorithm = algorithms.Single();
206        else
207          throw new ArgumentException("Could not get Algorithm. More than one algorithm with the name " + algorithmName + " are saved in database.");
208      }
209      return algorithm;
210    }
211
212    public IResult GetOrPersistResult(string resultName) {
213      Result result;
214      using (ModelingDataContext ctx = new ModelingDataContext(connection)) {
215        var results = ctx.Results.Where(r => r.Name == resultName);
216        if (results.Count() == 0) {
217          result = new Result(resultName);
218          ctx.Results.InsertOnSubmit(result);
219          ctx.SubmitChanges();
220        } else if (results.Count() == 1)
221          result = results.Single();
222        else
223          throw new ArgumentException("Could not get result. More than one result with the name " + resultName + " are saved in database.");
224      }
225      return result;
226    }
227
228    public IMetaData GetOrPersistMetaData(string metaDataName) {
229      MetaData metadata;
230      using (ModelingDataContext ctx = new ModelingDataContext(connection)) {
231        var md = ctx.MetaData.Where(r => r.Name == metaDataName);
232        if (md.Count() == 0) {
233          metadata = new MetaData(metaDataName);
234          ctx.MetaData.InsertOnSubmit(metadata);
235          ctx.SubmitChanges();
236        } else if (md.Count() == 1)
237          metadata = md.Single();
238        else
239          throw new ArgumentException("Could not get metadata. More than one metadata with the name " + metaDataName + " are saved in database.");
240      }
241      return metadata;
242    }
243
244    public IEnumerable<IModelResult> GetModelResults(IModel model) {
245      return ctx.ModelResults.Where(mr => mr.Model == model).Cast<IModelResult>();
246    }
247    public IEnumerable<IInputVariableResult> GetInputVariableResults(IModel model) {
248      return ctx.InputVariableResults.Where(ivr => ivr.Model == model).Cast<IInputVariableResult>();
249    }
250    public IEnumerable<IModelMetaData> GetModelMetaData(IModel model) {
251      return ctx.ModelMetaData.Where(md => md.Model == model).Cast<IModelMetaData>();
252    }
253
254    public IModelResult CreateModelResult(IModel model, IResult result, double value) {
255      Model m = (Model)model;
256      Result r = (Result)result;
257      return new ModelResult(m, r, value);
258    }
259
260    public void PersistModelResults(IModel model,IEnumerable<IModelResult> modelResults) {
261      using (ModelingDataContext ctx = new ModelingDataContext(connection)) {
262        ctx.ModelResults.DeleteAllOnSubmit(GetModelResults(model).Cast<ModelResult>());
263        ctx.ModelResults.InsertAllOnSubmit(modelResults.Cast<ModelResult>());
264        ctx.SubmitChanges();
265      }
266    }
267
268    public IInputVariable CreateInputVariable(IModel model, IVariable variable) {
269      InputVariable inputVariable = new InputVariable((Model)model, (Variable)variable);
270      return inputVariable;
271    }
272
273    public IInputVariableResult CreateInputVariableResult(IInputVariable inputVariable, IResult result, double value) {
274      InputVariable i = (InputVariable)inputVariable;
275      Result r = (Result)result;
276      return new InputVariableResult(i, r, value);
277    }
278
279    public void PersistInputVariableResults(IModel model,IEnumerable<IInputVariableResult> inputVariableResults) {
280      using (ModelingDataContext ctx = new ModelingDataContext(connection)) {
281        ctx.InputVariableResults.DeleteAllOnSubmit(GetInputVariableResults(model).Cast<InputVariableResult>());
282        ctx.InputVariableResults.InsertAllOnSubmit(inputVariableResults.Cast<InputVariableResult>());
283        ctx.SubmitChanges();
284      }
285    }
286
287    public IModelMetaData CreateModelMetaData(IModel model, IMetaData metadata, double value) {
288      Model m = (Model)model;
289      MetaData md = (MetaData)metadata;
290      return new ModelMetaData(m, md, value);
291    }
292
293    public void PersistModelMetaData(IModel model, IEnumerable<IModelMetaData> modelMetaData) {
294      using (ModelingDataContext ctx = new ModelingDataContext(connection)) {
295        ctx.ModelMetaData.DeleteAllOnSubmit(GetModelMetaData(model).Cast<ModelMetaData>());
296        ctx.ModelMetaData.InsertAllOnSubmit(modelMetaData.Cast<ModelMetaData>());
297        ctx.SubmitChanges();
298      }
299    }
300
301    public IModel Persist(HeuristicLab.Modeling.IAlgorithm algorithm) {
302      if (ctx.Problems.Count() == 0)
303        PersistProblem(algorithm.Dataset);
304      return Persist(algorithm.Model, algorithm.Name, algorithm.Description);
305    }
306
307    public IModel Persist(HeuristicLab.Modeling.IAnalyzerModel model, string algorithmName, string algorithmDescription) {
308      Algorithm algorithm = (Algorithm) GetOrPersistAlgorithm(algorithmName);
309      Variable targetVariable  = (Variable)GetVariable (model.TargetVariable);
310
311      Model m = (Model)CreateModel(model.Type, algorithm, targetVariable, model.TrainingSamplesStart, model.TrainingSamplesEnd,
312        model.ValidationSamplesStart, model.ValidationSamplesEnd, model.TestSamplesStart, model.TestSamplesEnd);
313      PersistModel(m);
314      PersistPredictor(m, model.Predictor);
315
316      using (ModelingDataContext ctx = new ModelingDataContext(connection)) {
317        foreach (KeyValuePair<string, double> pair in model.MetaData) {
318          MetaData metaData = (MetaData)GetOrPersistMetaData(pair.Key);
319          ctx.ModelMetaData.InsertOnSubmit(new ModelMetaData(m, metaData, pair.Value));
320        }
321        ctx.SubmitChanges();
322      }
323
324      using (ModelingDataContext ctx = new ModelingDataContext(connection)) {
325        foreach (KeyValuePair<ModelingResult, double> pair in model.Results) {
326          Result result = (Result)GetOrPersistResult(pair.Key.ToString());
327          ctx.ModelResults.InsertOnSubmit(new ModelResult(m, result, pair.Value));
328        }
329        ctx.SubmitChanges();
330      }
331
332      using (ModelingDataContext ctx = new ModelingDataContext(connection)) {
333        foreach (InputVariable variable in ctx.InputVariables.Where(iv => iv.Model == m)) {
334          foreach (KeyValuePair<ModelingResult, double> variableResult in model.GetVariableResults(variable.Variable.Name)) {
335            Result result = (Result)GetOrPersistResult(variableResult.Key.ToString());
336            ctx.InputVariableResults.InsertOnSubmit(new InputVariableResult(variable, result, variableResult.Value));
337          }
338        }
339        ctx.SubmitChanges();
340      }
341
342      //if connected to database return inserted model
343      if (this.ctx != null)
344        return this.ctx.Models.Where(x => x.Id == m.Id).Single();
345      return null;
346    }
347  }
348}
Note: See TracBrowser for help on using the repository browser.