using System; using HeuristicLab.Common; using HeuristicLab.Core; using HeuristicLab.Data; using HeuristicLab.Encodings.SymbolicExpressionTreeEncoding; using HeuristicLab.Operators; using HeuristicLab.Parameters; using HeuristicLab.Persistence.Default.CompositeSerializers.Storable; using HeuristicLab.PluginInfrastructure; namespace HeuristicLab.Problems.GrammaticalOptimization { [NonDiscoverableType] [StorableClass] [Item("GenericSymbExprEvaluator", "Evaluator for grammatical optimization problems (using a symbolic expression tree encoding).")] public class GenericSymbExprEvaluator : SingleSuccessorOperator, IGenericSymbExprEvaluator { public event Action SolutionEvaluated; public ILookupParameter QualityParameter { get { return (ILookupParameter)Parameters["Quality"]; } } public ILookupParameter SymbolicExpressionTreeParameter { get { return (ILookupParameter)Parameters["SymbolicExpressionTree"]; } } // cannot save these (eval won't work when loaded from file private Func evalFunc; private Func toStringFunc; [StorableConstructor] private GenericSymbExprEvaluator(bool deserializing) : base(deserializing) { } public GenericSymbExprEvaluator(GenericSymbExprEvaluator original, Cloner cloner) : base(original, cloner) { this.evalFunc = original.evalFunc; } public GenericSymbExprEvaluator(Func toStringFunc, Func evalFunc) : base() { Parameters.Add(new LookupParameter("Quality")); Parameters.Add(new LookupParameter("SymbolicExpressionTree")); this.evalFunc = evalFunc; this.toStringFunc = toStringFunc; } public override IDeepCloneable Clone(Cloner cloner) { return new GenericSymbExprEvaluator(this, cloner); } public override IOperation Apply() { var tree = SymbolicExpressionTreeParameter.ActualValue; var sentence = toStringFunc(tree); var q = evalFunc(sentence); QualityParameter.ActualValue = new DoubleValue(q); RaiseSolutionEvaluated(sentence, q); return base.Apply(); } private void RaiseSolutionEvaluated(string sentence, double quality) { var handler = SolutionEvaluated; if (handler != null) handler(sentence, quality); } } }