source: trunk/sources/HeuristicLab.Problems.ExternalEvaluation.Scilab/3.3/ScilabParameterVectorEvaluator.cs @ 11076

Last change on this file since 11076 was 11076, checked in by gkronber, 5 years ago

#2171: made some changes while reviewing the code.

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