[18061] | 1 | using System;
|
---|
| 2 | using System.Collections.Generic;
|
---|
| 3 | using System.Linq;
|
---|
| 4 | using System.Text;
|
---|
| 5 | using System.Threading.Tasks;
|
---|
| 6 | using HeuristicLab.Core;
|
---|
| 7 | using HeuristicLab.Optimization;
|
---|
| 8 | using HEAL.Attic;
|
---|
| 9 | using HeuristicLab.Common;
|
---|
| 10 | using HeuristicLab.Problems.Instances;
|
---|
| 11 | using HeuristicLab.Parameters;
|
---|
| 12 | using HeuristicLab.Data;
|
---|
[18062] | 13 | using HeuristicLab.Encodings.SymbolicExpressionTreeEncoding;
|
---|
[18061] | 14 |
|
---|
[18063] | 15 | namespace HeuristicLab.Problems.DataAnalysis.Symbolic.Regression {
|
---|
[18061] | 16 | [StorableType("7464E84B-65CC-440A-91F0-9FA920D730F9")]
|
---|
[18063] | 17 | [Item(Name = "Structured Symbolic Regression Single Objective Problem (single-objective)", Description = "A problem with a structural definition and unfixed subfunctions.")]
|
---|
| 18 | [Creatable(CreatableAttribute.Categories.GeneticProgrammingProblems, Priority = 150)]
|
---|
[18061] | 19 | public class StructuredSymbolicRegressionSingleObjectiveProblem : SingleObjectiveBasicProblem<MultiEncoding>, IRegressionProblem, IProblemInstanceConsumer<RegressionProblemData> {
|
---|
| 20 |
|
---|
| 21 | #region Constants
|
---|
| 22 | private const string ProblemDataParameterName = "ProblemData";
|
---|
| 23 | private const string StructureDefinitionParameterName = "Structure Definition";
|
---|
[18063] | 24 | private const string StructureTemplateParameterName = "Structure Template";
|
---|
[18061] | 25 | #endregion
|
---|
| 26 |
|
---|
| 27 | #region Parameter
|
---|
| 28 | public IValueParameter<IRegressionProblemData> ProblemDataParameter => (IValueParameter<IRegressionProblemData>)Parameters[ProblemDataParameterName];
|
---|
| 29 | public IFixedValueParameter<StringValue> StructureDefinitionParameter => (IFixedValueParameter<StringValue>)Parameters[StructureDefinitionParameterName];
|
---|
[18063] | 30 | public IFixedValueParameter<StructureTemplate> StructureTemplateParameter => (IFixedValueParameter<StructureTemplate>)Parameters[StructureTemplateParameterName];
|
---|
[18061] | 31 | #endregion
|
---|
| 32 |
|
---|
| 33 | #region Properties
|
---|
| 34 | public IRegressionProblemData ProblemData {
|
---|
| 35 | get => ProblemDataParameter.Value;
|
---|
| 36 | set {
|
---|
| 37 | ProblemDataParameter.Value = value;
|
---|
| 38 | ProblemDataChanged?.Invoke(this, EventArgs.Empty);
|
---|
| 39 | }
|
---|
| 40 | }
|
---|
| 41 |
|
---|
| 42 | public string StructureDefinition {
|
---|
| 43 | get => StructureDefinitionParameter.Value.Value;
|
---|
| 44 | set => StructureDefinitionParameter.Value.Value = value;
|
---|
| 45 | }
|
---|
| 46 |
|
---|
[18063] | 47 | public StructureTemplate StructureTemplate {
|
---|
| 48 | get => StructureTemplateParameter.Value;
|
---|
| 49 | }
|
---|
| 50 |
|
---|
[18071] | 51 | public ISymbolicDataAnalysisExpressionTreeInterpreter Interpreter { get; } = new SymbolicDataAnalysisExpressionTreeInterpreter();
|
---|
| 52 |
|
---|
[18061] | 53 | IParameter IDataAnalysisProblem.ProblemDataParameter => ProblemDataParameter;
|
---|
| 54 | IDataAnalysisProblemData IDataAnalysisProblem.ProblemData => ProblemData;
|
---|
| 55 |
|
---|
[18066] | 56 | public override bool Maximization => true;
|
---|
[18061] | 57 | #endregion
|
---|
| 58 |
|
---|
| 59 | #region EventHandlers
|
---|
| 60 | public event EventHandler ProblemDataChanged;
|
---|
| 61 | #endregion
|
---|
| 62 |
|
---|
| 63 | #region Constructors & Cloning
|
---|
| 64 | public StructuredSymbolicRegressionSingleObjectiveProblem() {
|
---|
[18062] | 65 | var problemData = new ShapeConstrainedRegressionProblemData();
|
---|
| 66 |
|
---|
[18065] | 67 | var structureTemplate = new StructureTemplate();
|
---|
[18066] | 68 | structureTemplate.Changed += OnTemplateChanged;
|
---|
[18065] | 69 |
|
---|
[18066] | 70 | Parameters.Add(new ValueParameter<IRegressionProblemData>(ProblemDataParameterName, problemData));
|
---|
[18065] | 71 | Parameters.Add(new FixedValueParameter<StructureTemplate>(StructureTemplateParameterName, structureTemplate));
|
---|
[18066] | 72 |
|
---|
[18061] | 73 | }
|
---|
| 74 |
|
---|
[18063] | 75 | public StructuredSymbolicRegressionSingleObjectiveProblem(StructuredSymbolicRegressionSingleObjectiveProblem original, Cloner cloner) { }
|
---|
[18061] | 76 |
|
---|
| 77 | [StorableConstructor]
|
---|
[18063] | 78 | protected StructuredSymbolicRegressionSingleObjectiveProblem(StorableConstructorFlag _) : base(_) { }
|
---|
[18065] | 79 | #endregion
|
---|
[18061] | 80 |
|
---|
[18065] | 81 | #region Cloning
|
---|
[18061] | 82 | public override IDeepCloneable Clone(Cloner cloner) =>
|
---|
| 83 | new StructuredSymbolicRegressionSingleObjectiveProblem(this, cloner);
|
---|
| 84 | #endregion
|
---|
| 85 |
|
---|
[18066] | 86 | private void OnTemplateChanged(object sender, EventArgs args) {
|
---|
[18068] | 87 | SetupStructureTemplate();
|
---|
| 88 | }
|
---|
| 89 |
|
---|
| 90 | private void SetupStructureTemplate() {
|
---|
[18066] | 91 | foreach (var e in Encoding.Encodings.ToArray())
|
---|
| 92 | Encoding.Remove(e);
|
---|
| 93 |
|
---|
[18068] | 94 | foreach (var f in StructureTemplate.SubFunctions.Values) {
|
---|
| 95 | SetupVariables(f);
|
---|
| 96 | if(!Encoding.Encodings.Any(x => x.Name == f.Name)) // to prevent the same encoding twice
|
---|
| 97 | Encoding.Add(new SymbolicExpressionTreeEncoding(f.Name, f.Grammar, f.MaximumSymbolicExpressionTreeLength, f.MaximumSymbolicExpressionTreeDepth));
|
---|
[18066] | 98 | }
|
---|
| 99 | }
|
---|
| 100 |
|
---|
| 101 | public override void Analyze(Individual[] individuals, double[] qualities, ResultCollection results, IRandom random) {
|
---|
| 102 | base.Analyze(individuals, qualities, results, random);
|
---|
| 103 |
|
---|
| 104 | int bestIdx = 0;
|
---|
| 105 | double bestQuality = Maximization ? double.MinValue : double.MaxValue;
|
---|
| 106 | for(int idx = 0; idx < qualities.Length; ++idx) {
|
---|
| 107 | if((Maximization && qualities[idx] > bestQuality) ||
|
---|
| 108 | (!Maximization && qualities[idx] < bestQuality)) {
|
---|
| 109 | bestQuality = qualities[idx];
|
---|
| 110 | bestIdx = idx;
|
---|
| 111 | }
|
---|
| 112 | }
|
---|
| 113 |
|
---|
[18071] | 114 | if (results.TryGetValue("Best Tree", out IResult result)) {
|
---|
| 115 | var tree = BuildTree(individuals[bestIdx]);
|
---|
| 116 | AdjustLinearScalingParams(tree, Interpreter);
|
---|
| 117 | result.Value = tree;
|
---|
| 118 | }
|
---|
| 119 | else {
|
---|
| 120 | var tree = BuildTree(individuals[bestIdx]);
|
---|
| 121 | AdjustLinearScalingParams(tree, Interpreter);
|
---|
| 122 | results.Add(new Result("Best Tree", tree));
|
---|
| 123 | }
|
---|
| 124 |
|
---|
[18066] | 125 | }
|
---|
| 126 |
|
---|
[18065] | 127 | public override double Evaluate(Individual individual, IRandom random) {
|
---|
[18066] | 128 | var tree = BuildTree(individual);
|
---|
[18071] | 129 |
|
---|
| 130 | AdjustLinearScalingParams(tree, Interpreter);
|
---|
[18066] | 131 | var estimationInterval = ProblemData.VariableRanges.GetInterval(ProblemData.TargetVariable);
|
---|
| 132 | var quality = SymbolicRegressionSingleObjectivePearsonRSquaredEvaluator.Calculate(
|
---|
[18071] | 133 | Interpreter, tree,
|
---|
[18066] | 134 | estimationInterval.LowerBound, estimationInterval.UpperBound,
|
---|
| 135 | ProblemData, ProblemData.TrainingIndices, false);
|
---|
| 136 |
|
---|
| 137 | return quality;
|
---|
| 138 | }
|
---|
| 139 |
|
---|
[18071] | 140 | private void AdjustLinearScalingParams(ISymbolicExpressionTree tree, ISymbolicDataAnalysisExpressionTreeInterpreter interpreter) {
|
---|
| 141 | var offsetNode = tree.Root.GetSubtree(0).GetSubtree(0);
|
---|
| 142 | var scalingNode = offsetNode.Subtrees.Where(x => !(x is ConstantTreeNode)).First();
|
---|
| 143 |
|
---|
| 144 | var offsetConstantNode = (ConstantTreeNode)offsetNode.Subtrees.Where(x => x is ConstantTreeNode).First();
|
---|
| 145 | var scalingConstantNode = (ConstantTreeNode)scalingNode.Subtrees.Where(x => x is ConstantTreeNode).First();
|
---|
| 146 |
|
---|
| 147 | var estimatedValues = interpreter.GetSymbolicExpressionTreeValues(tree, ProblemData.Dataset, ProblemData.TrainingIndices);
|
---|
| 148 | var targetValues = ProblemData.Dataset.GetDoubleValues(ProblemData.TargetVariable, ProblemData.TrainingIndices);
|
---|
| 149 |
|
---|
| 150 | OnlineLinearScalingParameterCalculator.Calculate(estimatedValues, targetValues, out double a, out double b, out OnlineCalculatorError error);
|
---|
| 151 | if(error == OnlineCalculatorError.None) {
|
---|
| 152 | offsetConstantNode.Value = a;
|
---|
| 153 | scalingConstantNode.Value = b;
|
---|
| 154 | }
|
---|
| 155 | }
|
---|
| 156 |
|
---|
[18066] | 157 | private ISymbolicExpressionTree BuildTree(Individual individual) {
|
---|
[18065] | 158 | var templateTree = (ISymbolicExpressionTree)StructureTemplate.Tree.Clone();
|
---|
[18066] | 159 |
|
---|
[18065] | 160 | // build main tree
|
---|
| 161 | foreach (var n in templateTree.IterateNodesPrefix()) {
|
---|
[18066] | 162 | if (n.Symbol is SubFunctionSymbol) {
|
---|
| 163 | var subFunctionTreeNode = n as SubFunctionTreeNode;
|
---|
[18068] | 164 | var subFunctionTree = individual.SymbolicExpressionTree(subFunctionTreeNode.Name);
|
---|
[18071] | 165 | //var parent = n.Parent;
|
---|
[18062] | 166 |
|
---|
[18066] | 167 | // remove SubFunctionTreeNode
|
---|
[18071] | 168 | //parent.RemoveSubtree(parent.IndexOfSubtree(subFunctionTreeNode));
|
---|
[18065] | 169 |
|
---|
[18066] | 170 | // add new tree
|
---|
| 171 | var subTree = subFunctionTree.Root.GetSubtree(0) // Start
|
---|
| 172 | .GetSubtree(0); // Offset
|
---|
[18071] | 173 | //parent.AddSubtree(subTree);
|
---|
| 174 | subFunctionTreeNode.AddSubtree(subTree);
|
---|
[18065] | 175 | }
|
---|
| 176 | }
|
---|
[18066] | 177 | return templateTree;
|
---|
[18061] | 178 | }
|
---|
| 179 |
|
---|
[18068] | 180 | private void SetupVariables(SubFunction subFunction) {
|
---|
| 181 | var varSym = (Variable)subFunction.Grammar.GetSymbol("Variable");
|
---|
| 182 | if (varSym == null) {
|
---|
| 183 | varSym = new Variable();
|
---|
| 184 | subFunction.Grammar.AddSymbol(varSym);
|
---|
| 185 | }
|
---|
| 186 |
|
---|
| 187 | var allVariables = ProblemData.InputVariables.Select(x => x.Value);
|
---|
| 188 | var allInputs = allVariables.Where(x => x != ProblemData.TargetVariable);
|
---|
| 189 |
|
---|
| 190 | // set all variables
|
---|
| 191 | varSym.AllVariableNames = allVariables;
|
---|
| 192 |
|
---|
| 193 | // set all allowed variables
|
---|
| 194 | if (subFunction.Arguments.Contains("_")) {
|
---|
| 195 | varSym.VariableNames = allInputs;
|
---|
| 196 | } else {
|
---|
| 197 | var vars = new List<string>();
|
---|
| 198 | var exceptions = new List<Exception>();
|
---|
| 199 | foreach (var arg in subFunction.Arguments) {
|
---|
| 200 | if (allInputs.Contains(arg))
|
---|
| 201 | vars.Add(arg);
|
---|
| 202 | else
|
---|
| 203 | exceptions.Add(new ArgumentException($"The argument '{arg}' for sub-function '{subFunction.Name}' is not a valid variable."));
|
---|
| 204 | }
|
---|
| 205 | if (exceptions.Any())
|
---|
| 206 | throw new AggregateException(exceptions);
|
---|
| 207 | varSym.VariableNames = vars;
|
---|
| 208 | }
|
---|
| 209 |
|
---|
| 210 | varSym.Enabled = true;
|
---|
| 211 | }
|
---|
| 212 |
|
---|
[18061] | 213 | public void Load(RegressionProblemData data) {
|
---|
| 214 | ProblemData = data;
|
---|
[18068] | 215 | SetupStructureTemplate();
|
---|
[18061] | 216 | }
|
---|
| 217 | }
|
---|
| 218 | }
|
---|