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
RevLine 
[2229]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;
[2185]23using System.Collections.Generic;
24using System.Linq;
25using System.Reflection;
26
27using HeuristicLab.Core;
28using HeuristicLab.DataAnalysis;
29using HeuristicLab.Data;
[2194]30using System.Data.Linq;
[2185]31
[2194]32namespace HeuristicLab.Modeling.Database.SQLServerCompact {
[2185]33  public class DatabaseService : IModelingDatabase {
34    private readonly string connection;
35    public DatabaseService(string connection) {
36      this.connection = connection;
[2221]37      Connect();
38      if (!ctx.DatabaseExists())
[2344]39        ctx.CreateDatabase();
[2185]40    }
41
[2333]42    public void EmptyDatabase() {
[2339]43      ctx.Connection.Dispose();
[2221]44      ctx.DeleteDatabase();
[2339]45      Connect();
[2221]46      ctx.CreateDatabase();
[2185]47    }
48
[2221]49    private ModelingDataContext ctx;
50    public void Connect() {
51      if (ctx != null)
[2339]52        Disconnect();
[2221]53
54      ctx = new ModelingDataContext(connection);
55      DataLoadOptions dlo = new DataLoadOptions();
56      dlo.LoadWith<ModelResult>(mr => mr.Result);
[2355]57      dlo.LoadWith<ModelMetaData>(mmd => mmd.MetaData);
[2221]58      dlo.LoadWith<InputVariableResult>(ir => ir.Variable);
59      dlo.LoadWith<InputVariableResult>(ir => ir.Result);
60      dlo.LoadWith<Model>(m => m.TargetVariable);
[2370]61      dlo.LoadWith<Model>(m => m.Algorithm);
[2221]62      ctx.LoadOptions = dlo;
63    }
64
65    public void Disconnect() {
66      if (ctx == null)
67        return;
[2339]68      ctx.Connection.Dispose();
[2221]69      ctx.Dispose();
70      ctx = null;
71    }
72
[2382]73    public IEnumerable<IModel> GetAllModels() {
74      return ctx.Models.ToList().Cast<IModel>();
[2271]75    }
76
[2382]77    public IEnumerable<IVariable> GetAllVariables() {
78      return ctx.Variables.ToList().Cast<IVariable>();
79    }
[2185]80
[2382]81    public IEnumerable<IResult> GetAllResults() {
82      return ctx.Results.ToList().Cast<IResult>();
83    }
[2185]84
[2382]85    public IEnumerable<IResult> GetAllResultsForInputVariables() {
86      return (from ir in ctx.InputVariableResults select ir.Result).Distinct().ToList().Cast<IResult>();
87    }
[2203]88
[2382]89    public IEnumerable<IMetaData> GetAllMetaData() {
90      return ctx.MetaData.ToList().Cast<IMetaData>();
91    }
[2203]92
[2382]93    public IEnumerable<IAlgorithm> GetAllAlgorithms() {
94      return ctx.Algorithms.ToList().Cast<IAlgorithm>();
95    }
[2217]96
[2382]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    }
[2185]101
[2382]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;
[2185]114
[2382]115      return model;
116    }
[2344]117
[2382]118    public void PersistModel(IModel model) {
[2203]119      using (ModelingDataContext ctx = new ModelingDataContext(connection)) {
[2382]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);
[2185]125        ctx.SubmitChanges();
126      }
[2382]127    }
[2314]128
[2382]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();
[2185]141    }
142
143    public Dataset GetDataset() {
[2221]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;
[2185]148    }
149
[2382]150    public void PersistProblem(Dataset dataset) {
[2185]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
[2382]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    }
[2185]170
[2382]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) {
[2185]197      Algorithm algorithm;
198      using (ModelingDataContext ctx = new ModelingDataContext(connection)) {
[2382]199        var algorithms = ctx.Algorithms.Where(algo => algo.Name == algorithmName);
[2185]200        if (algorithms.Count() == 0) {
[2382]201          algorithm = new Algorithm(algorithmName, "");
[2185]202          ctx.Algorithms.InsertOnSubmit(algorithm);
203          ctx.SubmitChanges();
204        } else if (algorithms.Count() == 1)
205          algorithm = algorithms.Single();
206        else
[2382]207          throw new ArgumentException("Could not get Algorithm. More than one algorithm with the name " + algorithmName + " are saved in database.");
[2185]208      }
209      return algorithm;
210    }
[2278]211
[2382]212    public IResult GetOrPersistResult(string resultName) {
[2185]213      Result result;
214      using (ModelingDataContext ctx = new ModelingDataContext(connection)) {
[2382]215        var results = ctx.Results.Where(r => r.Name == resultName);
[2185]216        if (results.Count() == 0) {
[2382]217          result = new Result(resultName);
[2185]218          ctx.Results.InsertOnSubmit(result);
219          ctx.SubmitChanges();
220        } else if (results.Count() == 1)
221          result = results.Single();
222        else
[2382]223          throw new ArgumentException("Could not get result. More than one result with the name " + resultName + " are saved in database.");
[2185]224      }
225      return result;
226    }
227
[2382]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;
[2190]242    }
243
244    public IEnumerable<IModelResult> GetModelResults(IModel model) {
[2382]245      return ctx.ModelResults.Where(mr => mr.Model == model).Cast<IModelResult>();
[2190]246    }
[2205]247    public IEnumerable<IInputVariableResult> GetInputVariableResults(IModel model) {
[2382]248      return ctx.InputVariableResults.Where(ivr => ivr.Model == model).Cast<IInputVariableResult>();
[2205]249    }
[2355]250    public IEnumerable<IModelMetaData> GetModelMetaData(IModel model) {
[2382]251      return ctx.ModelMetaData.Where(md => md.Model == model).Cast<IModelMetaData>();
[2355]252    }
253
[2382]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);
[2355]258    }
259
[2382]260    public void PersistModelResults(IModel model,IEnumerable<IModelResult> modelResults) {
[2355]261      using (ModelingDataContext ctx = new ModelingDataContext(connection)) {
[2382]262        ctx.ModelResults.DeleteAllOnSubmit(GetModelResults(model).Cast<ModelResult>());
263        ctx.ModelResults.InsertAllOnSubmit(modelResults.Cast<ModelResult>());
264        ctx.SubmitChanges();
[2355]265      }
266    }
267
[2384]268    public IInputVariable CreateInputVariable(IModel model, IVariable variable) {
269      InputVariable inputVariable = new InputVariable((Model)model, (Variable)variable);
270      return inputVariable;
271    }
272
[2382]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    }
[2355]278
[2382]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      }
[2190]285    }
[2217]286
[2382]287    public IModelMetaData CreateModelMetaData(IModel model, IMetaData metadata, double value) {
[2326]288      Model m = (Model)model;
[2382]289      MetaData md = (MetaData)metadata;
290      return new ModelMetaData(m, md, value);
[2326]291    }
292
[2382]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      }
[2217]299    }
[2292]300
[2382]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);
[2326]305    }
306
[2382]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;
[2292]346    }
[2185]347  }
348}
Note: See TracBrowser for help on using the repository browser.