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

Last change on this file since 9698 was 9698, checked in by mkommend, 6 years ago

#2082: Improved error handling and correct matlab license file.

File size: 6.5 KB
Line 
1#region License Information
2/* HeuristicLab
3 * Copyright (C) 2002-2013 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.Linq;
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 Scilab 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 InitializationScriptParameterName = "InitializationScript";
39
40    #region parameters
41    public ILookupParameter<StringValue> QualityVariableParameter {
42      get { return (ILookupParameter<StringValue>)Parameters[QualityVariableParameterName]; }
43    }
44    public ILookupParameter<TextFile> MatlabEvaluationScriptParameter {
45      get { return (ILookupParameter<TextFile>)Parameters[MatlabEvaluationScriptParameterName]; }
46    }
47    public IFixedValueParameter<TextFile> InitializationScriptParameter {
48      get { return (IFixedValueParameter<TextFile>)Parameters[InitializationScriptParameterName]; }
49    }
50    #endregion
51
52    public TextFile InitializationScript {
53      get { return InitializationScriptParameter.Value; }
54    }
55
56    [StorableConstructor]
57    private MatlabParameterVectorEvaluator(bool deserializing) : base(deserializing) { }
58    private MatlabParameterVectorEvaluator(MatlabParameterVectorEvaluator original, Cloner cloner)
59      : base(original, cloner) {
60    }
61    public override IDeepCloneable Clone(Cloner cloner) {
62      return new MatlabParameterVectorEvaluator(this, cloner);
63    }
64
65    public MatlabParameterVectorEvaluator()
66      : base() {
67      Parameters.Add(new LookupParameter<StringValue>(QualityVariableParameterName, "The name of the quality variable of the Matlab script."));
68      Parameters.Add(new LookupParameter<TextFile>(MatlabEvaluationScriptParameterName, "The path to the Matlab evaluation script."));
69      Parameters.Add(new FixedValueParameter<TextFile>(InitializationScriptParameterName, "The path to a Matlab script the should be execute before the evaluation starts.", new TextFile()));
70    }
71
72
73    private MLApp.IMLApp matLabConnector;
74    public override void InitializeState() {
75      base.InitializeState();
76
77      Type matlabtype = Type.GetTypeFromProgID("matlab.application.single");
78      matLabConnector = (MLApp.IMLApp)Activator.CreateInstance(matlabtype);
79
80      if (string.IsNullOrEmpty(InitializationScript.Value)) return;
81      if (!InitializationScript.Exists()) throw new FileNotFoundException(string.Format("The initialization script \"{0}\" cannot be found.", InitializationScript.Value));
82      string result = matLabConnector.Execute(string.Format("run({0});", InitializationScript.Value));
83      //if (result != 0) ThrowSciLabException(InitializationScript.Value, result);
84    }
85
86    public override void ClearState() {
87      base.ClearState();
88      matLabConnector.Quit();
89    }
90
91    private readonly object locker = new object();
92    public override IOperation Apply() {
93      var evaluationScript = MatlabEvaluationScriptParameter.ActualValue;
94      if (string.IsNullOrEmpty(evaluationScript.Value)) throw new FileNotFoundException("The evaluation script in the problem is not set.");
95      if (!evaluationScript.Exists()) throw new FileNotFoundException(string.Format("The evaluation script \"{0}\" cannot be found.", evaluationScript.Value));
96
97      lock (locker) {
98        string result;
99        var parameterVector = ParameterVectorParameter.ActualValue;
100        var parameterNames = ParameterNamesParameter.ActualValue;
101        if (parameterNames.Any(string.IsNullOrEmpty)) throw new ArgumentException("Not all parameter names are provided.");
102
103        for (int i = 0; i < ProblemSizeParameter.ActualValue.Value; i++) {
104          matLabConnector.PutWorkspaceData(parameterNames[i], "base", parameterVector[i]);
105        }
106
107        string script = MatlabEvaluationScriptParameter.ActualValue.Value;
108        result = matLabConnector.Execute(string.Format("run({0});", script));
109        //if (result != 0) ThrowSciLabException(script, result);
110
111        string qualityVariableName = QualityVariableParameter.ActualValue.Value;
112        var quality = matLabConnector.GetVariable(qualityVariableName, "base");
113        //if (values == null) throw new InvalidOperationException(string.Format("Could not find the variable \"{0}\" in the Scilab workspace, that should hold the quality value.", qualityVariableName));
114
115        if (double.IsNaN(quality)) quality = double.MaxValue;
116        if (double.IsInfinity(quality)) quality = double.MaxValue;
117
118        QualityParameter.ActualValue = new DoubleValue(quality);
119        return base.Apply();
120      }
121    }
122
123    //private void ThrowSciLabException(string fileName, int errorCode) {
124    //  const string code = "errorMsg = lasterror();";
125    //  int result = DotNetScilab.Scilab.Instance.SendScilabJob(code);
126    //  if (result != 0) throw new InvalidOperationException(string.Format("An error occured during the execution of the Scilab script {0}.", fileName));
127
128    //  string errorMessage = DotNetScilab.Scilab.Instance.readNamedMatrixOfString("errorMsg")[0];
129
130    //  string message = string.Format("The error {1} occured during the execution of the Scilab script {0}. \r\n\r\n {2}", fileName, errorCode, errorMessage);
131    //  throw new InvalidOperationException(message);
132    //}
133  }
134}
Note: See TracBrowser for help on using the repository browser.