Free cookie consent management tool by TermsFeed Policy Generator

source: branches/HeuristicLab.ExternalEvaluation Scientific/HeuristicLab.Problems.ExternalEvaluation.Scilab/3.3/ScilabParameterVectorEvaluator.cs @ 10595

Last change on this file since 10595 was 10595, checked in by mkommend, 9 years ago

#2082: Implemented reviewer comments for the Scilab parameter optimization problem & evaluator.

File size: 7.0 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.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.Scilab {
33  [Item("SciLabParameterVectorEvaluator", "An evaluator which takes a parameter vector and returns a quality value, calculated by a Scilab script.")]
34  [StorableClass]
35  public sealed class ScilabParameterVectorEvaluator : ParameterVectorEvaluator {
36    private const string QualityVariableParameterName = "QualityVariableName";
37    private const string ScilabEvaluationScriptParameterName = "ScilabEvaluationScript";
38    private const string ScilabInitializationScriptParameterName = "ScilabInitializationScript";
39
40    #region parameters
41    public ILookupParameter<StringValue> QualityVariableParameter {
42      get { return (ILookupParameter<StringValue>)Parameters[QualityVariableParameterName]; }
43    }
44    public ILookupParameter<TextFileValue> ScilabEvaluationScriptParameter {
45      get { return (ILookupParameter<TextFileValue>)Parameters[ScilabEvaluationScriptParameterName]; }
46    }
47    public ILookupParameter<TextFileValue> ScilabInitializationScriptParameter {
48      get { return (ILookupParameter<TextFileValue>)Parameters[ScilabInitializationScriptParameterName]; }
49    }
50    #endregion
51
52    [StorableConstructor]
53    private ScilabParameterVectorEvaluator(bool deserializing) : base(deserializing) { }
54    private ScilabParameterVectorEvaluator(ScilabParameterVectorEvaluator original, Cloner cloner)
55      : base(original, cloner) {
56    }
57    public override IDeepCloneable Clone(Cloner cloner) {
58      return new ScilabParameterVectorEvaluator(this, cloner);
59    }
60
61    public ScilabParameterVectorEvaluator()
62      : base() {
63      Parameters.Add(new LookupParameter<StringValue>(QualityVariableParameterName, "The name of the quality variable of the Scilab script."));
64      Parameters.Add(new LookupParameter<TextFileValue>(ScilabEvaluationScriptParameterName, "The path to the Scilab evaluation script."));
65      Parameters.Add(new LookupParameter<TextFileValue>(ScilabInitializationScriptParameterName, "The path to a Scilab script the should be execute before the evaluation starts."));
66    }
67
68    private readonly object locker = new object();
69    private static DotNetScilab.Scilab scilab = null;
70    private bool startedScilab = false;
71
72    public override IOperation Apply() {
73      var evaluationScript = ScilabEvaluationScriptParameter.ActualValue;
74      if (string.IsNullOrEmpty(evaluationScript.Value)) throw new FileNotFoundException("The evaluation script in the problem is not set.");
75      if (!evaluationScript.Exists()) throw new FileNotFoundException(string.Format("The evaluation script \"{0}\" cannot be found.", evaluationScript.Value));
76
77      var initializationScript = ScilabInitializationScriptParameter.ActualValue;
78      if (!string.IsNullOrEmpty(initializationScript.Value) && !initializationScript.Exists()) throw new FileNotFoundException(string.Format("The initialization script \"{0}\" cannot be found.", initializationScript.Value));
79
80      int result;
81      //Scilab is used via a c++ wrapper that calls static methods. Hence it is not possible to parallelize the evaluation.
82      lock (locker) {
83        //initialize scilab and execute initialization script
84        if (scilab == null) {
85          startedScilab = true;
86          scilab = new DotNetScilab.Scilab(false);
87          if (!string.IsNullOrEmpty(initializationScript.Value)) {
88            result = DotNetScilab.Scilab.Instance.execScilabScript(initializationScript.Value);
89            if (result != 0) ThrowSciLabException(initializationScript.Value, result);
90          }
91        } else if (!startedScilab) {
92          throw new InvalidOperationException("Could not run multiple optimization algorithms in parallel.");
93        }
94
95        var parameterVector = ParameterVectorParameter.ActualValue;
96        var parameterNames = ParameterNamesParameter.ActualValue;
97        if (parameterNames.Any(string.IsNullOrEmpty)) throw new ArgumentException("Not all parameter names are provided.");
98
99        for (int i = 0; i < ProblemSizeParameter.ActualValue.Value; i++) {
100          result = scilab.createNamedMatrixOfDouble(parameterNames[i], 1, 1, new double[] { parameterVector[i] });
101          if (result != 0) ThrowSciLabException("setting parameter " + parameterNames[i], result);
102        }
103
104        string script = ScilabEvaluationScriptParameter.ActualValue.Value;
105        result = scilab.execScilabScript(script);
106        if (result != 0) ThrowSciLabException(script, result);
107
108        string qualityVariableName = QualityVariableParameter.ActualValue.Value;
109        double[] values = scilab.readNamedMatrixOfDouble(qualityVariableName);
110        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));
111        double quality = values[0];
112
113        if (double.IsNaN(quality)) quality = double.MaxValue;
114        if (double.IsInfinity(quality)) quality = double.MaxValue;
115
116        QualityParameter.ActualValue = new DoubleValue(quality);
117        return base.Apply();
118      }
119    }
120
121    public override void ClearState() {
122      base.ClearState();
123      if (startedScilab)
124        scilab = null;
125      startedScilab = false;
126    }
127
128    private void ThrowSciLabException(string fileName, int errorCode) {
129      const string code = "errorMsg = lasterror();";
130      int result = DotNetScilab.Scilab.Instance.SendScilabJob(code);
131      if (result != 0) throw new InvalidOperationException(string.Format("An error occured during the execution of the Scilab script {0}.", fileName));
132
133      string errorMessage = DotNetScilab.Scilab.Instance.readNamedMatrixOfString("errorMsg")[0];
134
135      string message = string.Format("The error {1} occured during the execution of the Scilab script {0}. "
136        + Environment.NewLine + Environment.NewLine + " {2}", fileName, errorCode, errorMessage);
137      throw new InvalidOperationException(message);
138    }
139  }
140}
Note: See TracBrowser for help on using the repository browser.