Free cookie consent management tool by TermsFeed Policy Generator

source: branches/ProblemRefactoring/HeuristicLab.Problems.ExternalEvaluation.Matlab/3.3/MatlabParameterVectorEvaluator.cs @ 13741

Last change on this file since 13741 was 12494, checked in by gkronber, 9 years ago

#2403: added a null check in the MatlabParameterVectorEvaluator to prevent exceptions when clearstate is called

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