Free cookie consent management tool by TermsFeed Policy Generator

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

Last change on this file since 2530 was 2530, checked in by mkommend, 14 years ago

changed modeling database backend to use a shared read connection => notification by exception if another program is connected to the database (ticket #759)

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