Free cookie consent management tool by TermsFeed Policy Generator

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

Last change on this file since 10605 was 10605, checked in by mkommend, 10 years ago

#2171: Added new ParameterOptimizationProblem and the external evaluation with Scilab to the trunk.

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