Free cookie consent management tool by TermsFeed Policy Generator

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

Last change on this file since 17928 was 17180, checked in by swagner, 5 years ago

#2875: Removed years in copyrights

File size: 7.9 KB
Line 
1#region License Information
2/* HeuristicLab
3 * Copyright (C) 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 HEAL.Attic;
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  [StorableType("B0EEB2BC-B35E-47AC-93DE-8B2C0EFF8650")]
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(StorableConstructorFlag _) : base(_) { }
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          if (!string.IsNullOrEmpty(initializationScript.Value)) {
95            result = scilab.execScilabScript(initializationScript.Value);
96            if (result != 0) ThrowSciLabException(initializationScript.Value, result);
97          }
98        } else if (!startedScilab) {
99          throw new InvalidOperationException("Could not run multiple optimization algorithms in parallel.");
100        }
101
102        var parameterVector = ParameterVectorParameter.ActualValue;
103        var parameterNames = ParameterNamesParameter.ActualValue;
104        if (parameterNames.Any(string.IsNullOrEmpty)) throw new ArgumentException("Not all parameter names are provided. Change the 'ParameterNames' parameter in the 'Problem' tab.");
105        if (ProblemSizeParameter.ActualValue.Value != parameterVector.Length || ProblemSizeParameter.ActualValue.Value != parameterNames.Length)
106          throw new ArgumentException("The size of the parameter vector or the parameter names vector does not match the problem size.");
107
108        for (int i = 0; i < ProblemSizeParameter.ActualValue.Value; i++) {
109          result = scilab.createNamedMatrixOfDouble(parameterNames[i], 1, 1, new double[] { parameterVector[i] });
110          if (result != 0) ThrowSciLabException("setting parameter " + parameterNames[i], result);
111        }
112
113        string script = ScilabEvaluationScriptParameter.ActualValue.Value;
114        result = scilab.execScilabScript(script);
115        if (result != 0) ThrowSciLabException(script, result);
116
117        string qualityVariableName = QualityVariableParameter.ActualValue.Value;
118        double[] values = scilab.readNamedMatrixOfDouble(qualityVariableName);
119        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));
120        double quality = values[0];
121
122        var worstQualityValue = MaximizationParameter.ActualValue.Value ? double.MinValue : double.MaxValue;
123        if (double.IsNaN(quality)) quality = worstQualityValue;
124        if (double.IsInfinity(quality)) quality = worstQualityValue;
125
126        QualityParameter.ActualValue = new DoubleValue(quality);
127        return base.Apply();
128      }
129    }
130
131    public override void ClearState() {
132      base.ClearState();
133      if (startedScilab)
134        scilab = null;
135      startedScilab = false;
136    }
137
138    private void ThrowSciLabException(string fileName, int errorCode) {
139      const string code = "errorMsg = lasterror();";
140      int result = scilab.SendScilabJob(code);
141      if (result != 0) throw new InvalidOperationException(string.Format("An error occured during the execution of the Scilab script {0}.", fileName));
142
143      string errorMessage = scilab.readNamedMatrixOfString("errorMsg")[0];
144
145      string message = string.Format("The error {1} occured during the execution of the Scilab script {0}. "
146        + Environment.NewLine + Environment.NewLine + " {2}", fileName, errorCode, errorMessage);
147      throw new InvalidOperationException(message);
148    }
149  }
150}
Note: See TracBrowser for help on using the repository browser.