Free cookie consent management tool by TermsFeed Policy Generator

source: branches/irace/HeuristicLab.Problems.ExternalEvaluation.Matlab/3.3/MatlabParameterVectorEvaluator.cs @ 11813

Last change on this file since 11813 was 11094, checked in by gkronber, 10 years ago

#2082: fixed a few strings while reviewing the source code of the MATLAB problem.

File size: 6.7 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 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        matLabConnector.Execute("exit");
73      }
74      catch (COMException) { }
75      finally {
76        matLabConnector = null;
77      }
78
79      changedDirectory = false;
80      base.ClearState();
81    }
82
83    private MLApp.MLApp matLabConnector;
84    private bool changedDirectory = false;
85    private readonly object locker = new object();
86
87    public override IOperation Apply() {
88      lock (locker) {
89        var initializationScript = MatlabInitializationScriptParameter.ActualValue;
90        if (!string.IsNullOrEmpty(initializationScript.Value) && !initializationScript.Exists())
91          throw new FileNotFoundException(string.Format("The initialization script \"{0}\" cannot be found.", initializationScript.Value));
92
93        var evaluationScript = MatlabEvaluationScriptParameter.ActualValue;
94        if (string.IsNullOrEmpty(evaluationScript.Value))
95          throw new FileNotFoundException("The evaluation script in the problem is not set.");
96        if (!evaluationScript.Exists())
97          throw new FileNotFoundException(string.Format("The evaluation script \"{0}\" cannot be found.", evaluationScript.Value));
98
99        string result;
100        if (matLabConnector == null) {
101          Type matlabtype = Type.GetTypeFromProgID("matlab.application.single");
102          matLabConnector = (MLApp.MLApp)Activator.CreateInstance(matlabtype);
103          matLabConnector.Visible = 0;
104
105          if (!string.IsNullOrEmpty(initializationScript.Value)) {
106            var directoryName = Path.GetDirectoryName(initializationScript.Value);
107            if (string.IsNullOrEmpty(directoryName)) directoryName = Environment.CurrentDirectory;
108            result = matLabConnector.Execute(string.Format("cd '{0}'", directoryName));
109            if (!string.IsNullOrEmpty(result)) throw new InvalidOperationException(result);
110
111            result = matLabConnector.Execute(Path.GetFileNameWithoutExtension(initializationScript.Value));
112            if (!string.IsNullOrEmpty(result)) throw new InvalidOperationException(result);
113          }
114        }
115
116        if (!changedDirectory) {
117          var directoryName = Path.GetDirectoryName(evaluationScript.Value);
118          if (string.IsNullOrEmpty(directoryName)) directoryName = Environment.CurrentDirectory;
119          result = matLabConnector.Execute(string.Format("cd '{0}'", directoryName));
120          if (!string.IsNullOrEmpty(result)) throw new InvalidOperationException(result);
121          changedDirectory = true;
122        }
123
124        var parameterVector = ParameterVectorParameter.ActualValue;
125        var parameterNames = ParameterNamesParameter.ActualValue;
126
127        for (int i = 0; i < ProblemSizeParameter.ActualValue.Value; i++) {
128          matLabConnector.PutWorkspaceData(parameterNames[i], "base", parameterVector[i]);
129        }
130
131        result = matLabConnector.Execute(Path.GetFileNameWithoutExtension(evaluationScript.Value));
132        if (!string.IsNullOrEmpty(result)) throw new InvalidOperationException(result);
133
134        string qualityVariableName = QualityVariableParameter.ActualValue.Value;
135        var quality = matLabConnector.GetVariable(qualityVariableName, "base");
136
137        if (double.IsNaN(quality)) quality = double.MaxValue;
138        if (double.IsInfinity(quality)) quality = double.MaxValue;
139
140        QualityParameter.ActualValue = new DoubleValue(quality);
141        return base.Apply();
142      }
143    }
144  }
145}
146
Note: See TracBrowser for help on using the repository browser.