Free cookie consent management tool by TermsFeed Policy Generator

source: branches/HeuristicLab.ExternalEvaluation Scientific/HeuristicLab.Problems.ExternalEvaluation.Matlab/3.3/MatlabParameterVectorEvaluator.cs @ 10594

Last change on this file since 10594 was 10594, checked in by mkommend, 10 years ago

#2082: Updated copyright and used Environment.NewLine instead of \r\n.

File size: 6.4 KB
Line 
1#region License Information
2/* HeuristicLab
3 * Copyright (C) 2002-2014 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.IO;
24using HeuristicLab.Common;
25using HeuristicLab.Core;
26using HeuristicLab.Data;
27using HeuristicLab.Parameters;
28using HeuristicLab.Persistence.Default.CompositeSerializers.Storable;
29using HeuristicLab.Problems.ParameterOptimization;
30
31namespace HeuristicLab.Problems.ExternalEvaluation.Matlab {
32  [Item("MATLABParameterVectorEvaluator", "An evaluator which takes a parameter vector and returns a quality value, calculated by a Scilab script.")]
33  [StorableClass]
34  public sealed class MatlabParameterVectorEvaluator : ParameterVectorEvaluator {
35    private const string QualityVariableParameterName = "QualityVariableName";
36    private const string MatlabEvaluationScriptParameterName = "MATLABEvaluationScript";
37    private const string InitializationScriptParameterName = "InitializationScript";
38
39    #region parameters
40    public ILookupParameter<StringValue> QualityVariableParameter {
41      get { return (ILookupParameter<StringValue>)Parameters[QualityVariableParameterName]; }
42    }
43    public ILookupParameter<TextFileValue> MatlabEvaluationScriptParameter {
44      get { return (ILookupParameter<TextFileValue>)Parameters[MatlabEvaluationScriptParameterName]; }
45    }
46    public IFixedValueParameter<TextFileValue> InitializationScriptParameter {
47      get { return (IFixedValueParameter<TextFileValue>)Parameters[InitializationScriptParameterName]; }
48    }
49    #endregion
50
51    public TextFileValue InitializationScript {
52      get { return InitializationScriptParameter.Value; }
53    }
54
55    [StorableConstructor]
56    private MatlabParameterVectorEvaluator(bool deserializing) : base(deserializing) { }
57    private MatlabParameterVectorEvaluator(MatlabParameterVectorEvaluator original, Cloner cloner)
58      : base(original, cloner) {
59    }
60    public override IDeepCloneable Clone(Cloner cloner) {
61      return new MatlabParameterVectorEvaluator(this, cloner);
62    }
63
64    public MatlabParameterVectorEvaluator()
65      : base() {
66      Parameters.Add(new LookupParameter<StringValue>(QualityVariableParameterName, "The name of the quality variable calculated in the MATLAB script."));
67      Parameters.Add(new LookupParameter<TextFileValue>(MatlabEvaluationScriptParameterName, "The path to the MATLAB evaluation script."));
68      Parameters.Add(new FixedValueParameter<TextFileValue>(InitializationScriptParameterName, "The path to a MATLAB script the should be execute before the evaluation starts.", new TextFileValue()));
69    }
70
71    private MLApp.MLApp matLabConnector;
72    public override void InitializeState() {
73      base.InitializeState();
74      changedDirectory = false;
75
76      if (matLabConnector == null) {
77        Type matlabtype = Type.GetTypeFromProgID("matlab.application.single");
78        matLabConnector = (MLApp.MLApp)Activator.CreateInstance(matlabtype);
79        matLabConnector.Visible = 0;
80      }
81
82      if (string.IsNullOrEmpty(InitializationScript.Value)) return;
83      if (!InitializationScript.Exists()) throw new FileNotFoundException(string.Format("The initialization script \"{0}\" cannot be found.", InitializationScript.Value));
84
85      string initScript = InitializationScript.Value;
86      var directoryName = Path.GetDirectoryName(initScript);
87      string result = matLabConnector.Execute(string.Format("cd '{0}'", directoryName));
88      if (!string.IsNullOrEmpty(result)) throw new InvalidOperationException(result);
89
90      result = matLabConnector.Execute(Path.GetFileNameWithoutExtension(initScript));
91      if (!string.IsNullOrEmpty(result)) throw new InvalidOperationException(result);
92    }
93
94    public override void ClearState() {
95      matLabConnector.Execute("clear");
96      changedDirectory = false;
97      base.ClearState();
98    }
99
100    private bool changedDirectory = false;
101    private readonly object locker = new object();
102    public override IOperation Apply() {
103      var evaluationScript = MatlabEvaluationScriptParameter.ActualValue;
104      if (string.IsNullOrEmpty(evaluationScript.Value)) throw new FileNotFoundException("The evaluation script in the problem is not set.");
105      if (!evaluationScript.Exists()) throw new FileNotFoundException(string.Format("The evaluation script \"{0}\" cannot be found.", evaluationScript.Value));
106
107      lock (locker) {
108        if (matLabConnector == null) InitializeState();
109
110        string result;
111        string script = evaluationScript.Value;
112
113        if (!changedDirectory) {
114          var directoryName = Path.GetDirectoryName(script);
115          result = matLabConnector.Execute(string.Format("cd '{0}'", directoryName));
116          if (!string.IsNullOrEmpty(result)) throw new InvalidOperationException(result);
117          changedDirectory = true;
118        }
119
120        var parameterVector = ParameterVectorParameter.ActualValue;
121        var parameterNames = ParameterNamesParameter.ActualValue;
122
123        for (int i = 0; i < ProblemSizeParameter.ActualValue.Value; i++) {
124          matLabConnector.PutWorkspaceData(parameterNames[i], "base", parameterVector[i]);
125        }
126
127        result = matLabConnector.Execute(Path.GetFileNameWithoutExtension(script));
128        if (!string.IsNullOrEmpty(result)) throw new InvalidOperationException(result);
129
130        string qualityVariableName = QualityVariableParameter.ActualValue.Value;
131        var quality = matLabConnector.GetVariable(qualityVariableName, "base");
132
133        if (double.IsNaN(quality)) quality = double.MaxValue;
134        if (double.IsInfinity(quality)) quality = double.MaxValue;
135
136        QualityParameter.ActualValue = new DoubleValue(quality);
137        return base.Apply();
138      }
139    }
140  }
141}
142
Note: See TracBrowser for help on using the repository browser.