1 | using System;
|
---|
2 | using HeuristicLab.Common;
|
---|
3 | using HeuristicLab.Core;
|
---|
4 | using HeuristicLab.Data;
|
---|
5 | using HeuristicLab.Encodings.SymbolicExpressionTreeEncoding;
|
---|
6 | using HeuristicLab.Operators;
|
---|
7 | using HeuristicLab.Parameters;
|
---|
8 | using HeuristicLab.PluginInfrastructure;
|
---|
9 |
|
---|
10 | namespace HeuristicLab.Problems.GrammaticalOptimization {
|
---|
11 | // this type is not storable because we use a func<ITree,double> for evaluation, which references back to the original grammatical optimization problem
|
---|
12 | [NonDiscoverableType]
|
---|
13 | [Item("GrammaticalOptimizationEvaluator", "Evaluator for grammatical optimization problems (using a symbolic expression tree encoding).")]
|
---|
14 | public class GrammaticalOptimizationEvaluator : SingleSuccessorOperator, IGrammaticalOptimizationEvaluator {
|
---|
15 | public event Action<string, double> SolutionEvaluated;
|
---|
16 |
|
---|
17 | public ILookupParameter<DoubleValue> QualityParameter {
|
---|
18 | get { return (ILookupParameter<DoubleValue>)Parameters["Quality"]; }
|
---|
19 | }
|
---|
20 | public ILookupParameter<ISymbolicExpressionTree> SymbolicExpressionTreeParameter {
|
---|
21 | get { return (ILookupParameter<ISymbolicExpressionTree>)Parameters["SymbolicExpressionTree"]; }
|
---|
22 | }
|
---|
23 |
|
---|
24 | private Func<string, double> evalFunc;
|
---|
25 | private Func<ISymbolicExpressionTree, string> toStringFunc;
|
---|
26 |
|
---|
27 | public GrammaticalOptimizationEvaluator(GrammaticalOptimizationEvaluator original, Cloner cloner)
|
---|
28 | : base(original, cloner) {
|
---|
29 | this.evalFunc = original.evalFunc;
|
---|
30 | }
|
---|
31 |
|
---|
32 | public GrammaticalOptimizationEvaluator(Func<ISymbolicExpressionTree, string> toStringFunc, Func<string, double> evalFunc)
|
---|
33 | : base() {
|
---|
34 | Parameters.Add(new LookupParameter<DoubleValue>("Quality"));
|
---|
35 | Parameters.Add(new LookupParameter<ISymbolicExpressionTree>("SymbolicExpressionTree"));
|
---|
36 | this.evalFunc = evalFunc;
|
---|
37 | this.toStringFunc = toStringFunc;
|
---|
38 | }
|
---|
39 |
|
---|
40 | public override IDeepCloneable Clone(Cloner cloner) {
|
---|
41 | return new GrammaticalOptimizationEvaluator(this, cloner);
|
---|
42 | }
|
---|
43 |
|
---|
44 | public override IOperation Apply() {
|
---|
45 | var tree = SymbolicExpressionTreeParameter.ActualValue;
|
---|
46 | var sentence = toStringFunc(tree);
|
---|
47 | var q = evalFunc(sentence);
|
---|
48 | QualityParameter.ActualValue = new DoubleValue(q);
|
---|
49 |
|
---|
50 | RaiseSolutionEvaluated(sentence, q);
|
---|
51 |
|
---|
52 | return base.Apply();
|
---|
53 | }
|
---|
54 |
|
---|
55 | private void RaiseSolutionEvaluated(string sentence, double quality) {
|
---|
56 | var handler = SolutionEvaluated;
|
---|
57 | if (handler != null) handler(sentence, quality);
|
---|
58 | }
|
---|
59 | }
|
---|
60 | }
|
---|