Free cookie consent management tool by TermsFeed Policy Generator

source: trunk/sources/HeuristicLab.Problems.ExternalEvaluation.Matlab/3.3/MatlabParameterVectorEvaluator.cs @ 15405

Last change on this file since 15405 was 14185, checked in by swagner, 8 years ago

#2526: Updated year of copyrights in license headers

File size: 6.8 KB
RevLine 
[9690]1#region License Information
2/* HeuristicLab
[14185]3 * Copyright (C) 2002-2016 Heuristic and Evolutionary Algorithms Laboratory (HEAL)
[9690]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;
[11033]24using System.Runtime.InteropServices;
[9690]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 {
[11094]33  [Item("MATLABParameterVectorEvaluator", "An evaluator which takes a parameter vector and returns a quality value, calculated by a MATLAB script.")]
[9690]34  [StorableClass]
35  public sealed class MatlabParameterVectorEvaluator : ParameterVectorEvaluator {
36    private const string QualityVariableParameterName = "QualityVariableName";
[9748]37    private const string MatlabEvaluationScriptParameterName = "MATLABEvaluationScript";
[11028]38    private const string MatlabInitializationScriptParameterName = "MATLABInitializationScript";
[9690]39
40    #region parameters
41    public ILookupParameter<StringValue> QualityVariableParameter {
42      get { return (ILookupParameter<StringValue>)Parameters[QualityVariableParameterName]; }
43    }
[9715]44    public ILookupParameter<TextFileValue> MatlabEvaluationScriptParameter {
45      get { return (ILookupParameter<TextFileValue>)Parameters[MatlabEvaluationScriptParameterName]; }
[9690]46    }
[11028]47    public ILookupParameter<TextFileValue> MatlabInitializationScriptParameter {
48      get { return (ILookupParameter<TextFileValue>)Parameters[MatlabInitializationScriptParameterName]; }
[9690]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() {
[9748]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."));
[11094]65      Parameters.Add(new LookupParameter<TextFileValue>(MatlabInitializationScriptParameterName, "The path to a MATLAB script for initialization that should be executed once when the algorithm starts."));
[9690]66    }
67
68
69    public override void ClearState() {
[11033]70      //mkommend: necessary because matlabConnector.Quit() does not work
71      try {
[12494]72        if (matLabConnector != null)
73          matLabConnector.Execute("exit");
74      } catch (COMException) { } finally {
[11033]75        matLabConnector = null;
76      }
77
[9715]78      changedDirectory = false;
[9690]79      base.ClearState();
80    }
81
[11028]82    private MLApp.MLApp matLabConnector;
[9715]83    private bool changedDirectory = false;
[9690]84    private readonly object locker = new object();
[11028]85
[9690]86    public override IOperation Apply() {
87      lock (locker) {
[11028]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
[11033]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;
[11028]103
[11033]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);
[11028]109
[11033]110            result = matLabConnector.Execute(Path.GetFileNameWithoutExtension(initializationScript.Value));
111            if (!string.IsNullOrEmpty(result)) throw new InvalidOperationException(result);
112          }
[11028]113        }
114
[9715]115        if (!changedDirectory) {
[11028]116          var directoryName = Path.GetDirectoryName(evaluationScript.Value);
[11033]117          if (string.IsNullOrEmpty(directoryName)) directoryName = Environment.CurrentDirectory;
[9748]118          result = matLabConnector.Execute(string.Format("cd '{0}'", directoryName));
[9715]119          if (!string.IsNullOrEmpty(result)) throw new InvalidOperationException(result);
120          changedDirectory = true;
121        }
122
[9690]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
[11028]130        result = matLabConnector.Execute(Path.GetFileNameWithoutExtension(evaluationScript.Value));
[9715]131        if (!string.IsNullOrEmpty(result)) throw new InvalidOperationException(result);
[9690]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}
[9715]145
Note: See TracBrowser for help on using the repository browser.