1 | using System;
|
---|
2 | using System.Linq;
|
---|
3 | using HEAL.Attic;
|
---|
4 | using HeuristicLab.Common;
|
---|
5 | using HeuristicLab.Core;
|
---|
6 | using HeuristicLab.Encodings.SymbolicExpressionTreeEncoding;
|
---|
7 | using HeuristicLab.Optimization;
|
---|
8 | using HeuristicLab.Parameters;
|
---|
9 | using HeuristicLab.PluginInfrastructure;
|
---|
10 | using HeuristicLab.Problems.Instances;
|
---|
11 | using HeuristicLab.Problems.Instances.DataAnalysis;
|
---|
12 |
|
---|
13 | namespace HeuristicLab.Problems.DataAnalysis.Symbolic.Regression {
|
---|
14 | [StorableType("7464E84B-65CC-440A-91F0-9FA920D730F9")]
|
---|
15 | [Item(Name = "Structured Symbolic Regression Single Objective Problem (single-objective)", Description = "A problem with a structural definition and unfixed subfunctions.")]
|
---|
16 | [Creatable(CreatableAttribute.Categories.GeneticProgrammingProblems, Priority = 150)]
|
---|
17 | public class StructuredSymbolicRegressionSingleObjectiveProblem : SingleObjectiveBasicProblem<MultiEncoding>, IRegressionProblem, IProblemInstanceConsumer<IRegressionProblemData> {
|
---|
18 |
|
---|
19 | #region Constants
|
---|
20 | private const string TreeEvaluatorParameterName = "TreeEvaluator";
|
---|
21 | private const string ProblemDataParameterName = "ProblemData";
|
---|
22 | private const string StructureTemplateParameterName = "Structure Template";
|
---|
23 | private const string InterpreterParameterName = "Interpreter";
|
---|
24 | private const string EstimationLimitsParameterName = "EstimationLimits";
|
---|
25 | private const string BestTrainingSolutionParameterName = "Best Training Solution";
|
---|
26 |
|
---|
27 | private const string SymbolicExpressionTreeName = "SymbolicExpressionTree";
|
---|
28 |
|
---|
29 | private const string StructureTemplateDescriptionText =
|
---|
30 | "Enter your expression as string in infix format into the empty input field.\n" +
|
---|
31 | "By checking the \"Apply Linear Scaling\" checkbox you can add the relevant scaling terms to your expression.\n" +
|
---|
32 | "After entering the expression click parse to build the tree.\n" +
|
---|
33 | "To edit the defined sub-functions, click on the corresponding-colored node in the tree view.\n" +
|
---|
34 | "Check the info box besides the input field for more information.";
|
---|
35 | #endregion
|
---|
36 |
|
---|
37 | #region Parameters
|
---|
38 | public IConstrainedValueParameter<SymbolicRegressionSingleObjectiveEvaluator> TreeEvaluatorParameter => (IConstrainedValueParameter<SymbolicRegressionSingleObjectiveEvaluator>)Parameters[TreeEvaluatorParameterName];
|
---|
39 | public IValueParameter<IRegressionProblemData> ProblemDataParameter => (IValueParameter<IRegressionProblemData>)Parameters[ProblemDataParameterName];
|
---|
40 | public IFixedValueParameter<StructureTemplate> StructureTemplateParameter => (IFixedValueParameter<StructureTemplate>)Parameters[StructureTemplateParameterName];
|
---|
41 | public IValueParameter<ISymbolicDataAnalysisExpressionTreeInterpreter> InterpreterParameter => (IValueParameter<ISymbolicDataAnalysisExpressionTreeInterpreter>)Parameters[InterpreterParameterName];
|
---|
42 | public IFixedValueParameter<DoubleLimit> EstimationLimitsParameter => (IFixedValueParameter<DoubleLimit>)Parameters[EstimationLimitsParameterName];
|
---|
43 | public IResultParameter<ISymbolicRegressionSolution> BestTrainingSolutionParameter => (IResultParameter<ISymbolicRegressionSolution>)Parameters[BestTrainingSolutionParameterName];
|
---|
44 | #endregion
|
---|
45 |
|
---|
46 | #region Properties
|
---|
47 |
|
---|
48 | public IRegressionProblemData ProblemData {
|
---|
49 | get => ProblemDataParameter.Value;
|
---|
50 | set {
|
---|
51 | ProblemDataParameter.Value = value;
|
---|
52 | ProblemDataChanged?.Invoke(this, EventArgs.Empty);
|
---|
53 | }
|
---|
54 | }
|
---|
55 |
|
---|
56 | public SymbolicRegressionSingleObjectiveEvaluator TreeEvaluator => TreeEvaluatorParameter.Value;
|
---|
57 |
|
---|
58 | public StructureTemplate StructureTemplate => StructureTemplateParameter.Value;
|
---|
59 |
|
---|
60 | public ISymbolicDataAnalysisExpressionTreeInterpreter Interpreter => InterpreterParameter.Value;
|
---|
61 |
|
---|
62 | IParameter IDataAnalysisProblem.ProblemDataParameter => ProblemDataParameter;
|
---|
63 | IDataAnalysisProblemData IDataAnalysisProblem.ProblemData => ProblemData;
|
---|
64 |
|
---|
65 | public DoubleLimit EstimationLimits => EstimationLimitsParameter.Value;
|
---|
66 |
|
---|
67 | public override bool Maximization => false;
|
---|
68 | #endregion
|
---|
69 |
|
---|
70 | #region EventHandlers
|
---|
71 | public event EventHandler ProblemDataChanged;
|
---|
72 | #endregion
|
---|
73 |
|
---|
74 | #region Constructors & Cloning
|
---|
75 | public StructuredSymbolicRegressionSingleObjectiveProblem() {
|
---|
76 | var provider = new PhysicsInstanceProvider();
|
---|
77 | var descriptor = new SheetBendingProcess();
|
---|
78 | var problemData = provider.LoadData(descriptor);
|
---|
79 | var shapeConstraintProblemData = new ShapeConstrainedRegressionProblemData(problemData);
|
---|
80 |
|
---|
81 | var structureTemplate = new StructureTemplate();
|
---|
82 |
|
---|
83 | var evaluators = new ItemSet<SymbolicRegressionSingleObjectiveEvaluator>(
|
---|
84 | ApplicationManager.Manager.GetInstances<SymbolicRegressionSingleObjectiveEvaluator>()
|
---|
85 | .Where(x => x.Maximization == Maximization));
|
---|
86 |
|
---|
87 | Parameters.Add(new ConstrainedValueParameter<SymbolicRegressionSingleObjectiveEvaluator>(
|
---|
88 | TreeEvaluatorParameterName,
|
---|
89 | evaluators,
|
---|
90 | evaluators.First()));
|
---|
91 |
|
---|
92 | Parameters.Add(new ValueParameter<IRegressionProblemData>(
|
---|
93 | ProblemDataParameterName,
|
---|
94 | shapeConstraintProblemData));
|
---|
95 |
|
---|
96 | Parameters.Add(new FixedValueParameter<StructureTemplate>(
|
---|
97 | StructureTemplateParameterName,
|
---|
98 | StructureTemplateDescriptionText,
|
---|
99 | structureTemplate));
|
---|
100 |
|
---|
101 | Parameters.Add(new ValueParameter<ISymbolicDataAnalysisExpressionTreeInterpreter>(
|
---|
102 | InterpreterParameterName,
|
---|
103 | new SymbolicDataAnalysisExpressionTreeBatchInterpreter()) { Hidden = true });
|
---|
104 |
|
---|
105 | Parameters.Add(new FixedValueParameter<DoubleLimit>(
|
---|
106 | EstimationLimitsParameterName,
|
---|
107 | new DoubleLimit(double.NegativeInfinity, double.PositiveInfinity)) { Hidden = true });
|
---|
108 |
|
---|
109 | Parameters.Add(new ResultParameter<ISymbolicRegressionSolution>(BestTrainingSolutionParameterName, "") { Hidden = true });
|
---|
110 |
|
---|
111 | this.EvaluatorParameter.Hidden = true;
|
---|
112 |
|
---|
113 | Operators.Add(new SymbolicDataAnalysisVariableFrequencyAnalyzer());
|
---|
114 | Operators.Add(new MinAverageMaxSymbolicExpressionTreeLengthAnalyzer());
|
---|
115 | Operators.Add(new SymbolicExpressionSymbolFrequencyAnalyzer());
|
---|
116 |
|
---|
117 | RegisterEventHandlers();
|
---|
118 | StructureTemplate.Template =
|
---|
119 | "(" +
|
---|
120 | "(210000 / (210000 + h)) * ((sigma_y * t * t) / (wR * Rt * t)) + " +
|
---|
121 | "PlasticHardening(_) - Elasticity(_)" +
|
---|
122 | ")" +
|
---|
123 | " * C(_)";
|
---|
124 | }
|
---|
125 |
|
---|
126 | public StructuredSymbolicRegressionSingleObjectiveProblem(StructuredSymbolicRegressionSingleObjectiveProblem original, Cloner cloner) : base(original, cloner) {
|
---|
127 | RegisterEventHandlers();
|
---|
128 | }
|
---|
129 |
|
---|
130 | public override IDeepCloneable Clone(Cloner cloner) =>
|
---|
131 | new StructuredSymbolicRegressionSingleObjectiveProblem(this, cloner);
|
---|
132 |
|
---|
133 | [StorableConstructor]
|
---|
134 | protected StructuredSymbolicRegressionSingleObjectiveProblem(StorableConstructorFlag _) : base(_) { }
|
---|
135 |
|
---|
136 |
|
---|
137 | [StorableHook(HookType.AfterDeserialization)]
|
---|
138 | private void AfterDeserialization() {
|
---|
139 | RegisterEventHandlers();
|
---|
140 | }
|
---|
141 |
|
---|
142 | #endregion
|
---|
143 |
|
---|
144 | private void RegisterEventHandlers() {
|
---|
145 | if (StructureTemplate != null) {
|
---|
146 | StructureTemplate.Changed += OnTemplateChanged;
|
---|
147 | }
|
---|
148 |
|
---|
149 | ProblemDataParameter.ValueChanged += ProblemDataParameterValueChanged;
|
---|
150 | }
|
---|
151 |
|
---|
152 | private void ProblemDataParameterValueChanged(object sender, EventArgs e) {
|
---|
153 | StructureTemplate.Reset();
|
---|
154 | // InfoBox for Reset?
|
---|
155 | }
|
---|
156 |
|
---|
157 | private void OnTemplateChanged(object sender, EventArgs args) {
|
---|
158 | SetupEncoding();
|
---|
159 | }
|
---|
160 |
|
---|
161 | private void SetupEncoding() {
|
---|
162 | foreach (var e in Encoding.Encodings.ToArray())
|
---|
163 | Encoding.Remove(e);
|
---|
164 |
|
---|
165 | foreach (var subFunction in StructureTemplate.SubFunctions) {
|
---|
166 | subFunction.SetupVariables(ProblemData.AllowedInputVariables);
|
---|
167 | // to prevent the same encoding twice
|
---|
168 | if (Encoding.Encodings.Any(x => x.Name == subFunction.Name)) continue; // duplicate subfunction
|
---|
169 |
|
---|
170 | var encoding = new SymbolicExpressionTreeEncoding(
|
---|
171 | subFunction.Name,
|
---|
172 | subFunction.Grammar,
|
---|
173 | subFunction.MaximumSymbolicExpressionTreeLength,
|
---|
174 | subFunction.MaximumSymbolicExpressionTreeDepth);
|
---|
175 | Encoding.Add(encoding);
|
---|
176 | }
|
---|
177 |
|
---|
178 | //set multi manipulator as default manipulator for all encoding parts
|
---|
179 | var manipulator = (IParameterizedItem)Encoding.Operators.OfType<MultiEncodingManipulator>().FirstOrDefault();
|
---|
180 | if (manipulator != null) {
|
---|
181 | foreach (var param in manipulator.Parameters.OfType<ConstrainedValueParameter<IManipulator>>()) {
|
---|
182 | var m = param.ValidValues.OfType<MultiSymbolicExpressionTreeManipulator>().FirstOrDefault();
|
---|
183 | param.Value = m == null ? param.ValidValues.First() : m;
|
---|
184 | }
|
---|
185 | }
|
---|
186 | }
|
---|
187 |
|
---|
188 | public override void Analyze(Individual[] individuals, double[] qualities, ResultCollection results, IRandom random) {
|
---|
189 | base.Analyze(individuals, qualities, results, random);
|
---|
190 |
|
---|
191 | var best = GetBestIndividual(individuals, qualities).Item1;
|
---|
192 |
|
---|
193 | if (!results.ContainsKey(BestTrainingSolutionParameter.ActualName)) {
|
---|
194 | results.Add(new Result(BestTrainingSolutionParameter.ActualName, typeof(SymbolicRegressionSolution)));
|
---|
195 | }
|
---|
196 |
|
---|
197 | var tree = (ISymbolicExpressionTree)best[SymbolicExpressionTreeName];
|
---|
198 |
|
---|
199 | var model = new SymbolicRegressionModel(ProblemData.TargetVariable, tree, Interpreter);
|
---|
200 | var solution = model.CreateRegressionSolution(ProblemData);
|
---|
201 |
|
---|
202 | results[BestTrainingSolutionParameter.ActualName].Value = solution;
|
---|
203 | }
|
---|
204 |
|
---|
205 |
|
---|
206 | public override double Evaluate(Individual individual, IRandom random) {
|
---|
207 | var templateTree = StructureTemplate.Tree;
|
---|
208 | if (templateTree == null)
|
---|
209 | throw new ArgumentException("No structure template defined!");
|
---|
210 |
|
---|
211 | var tree = BuildTree(templateTree, individual);
|
---|
212 |
|
---|
213 | // NMSEConstraintsEvaluator sets linear scaling terms itself
|
---|
214 | if (StructureTemplate.ApplyLinearScaling && !(TreeEvaluator is NMSESingleObjectiveConstraintsEvaluator)) {
|
---|
215 | AdjustLinearScalingParams(ProblemData, tree, Interpreter);
|
---|
216 | }
|
---|
217 |
|
---|
218 | individual[SymbolicExpressionTreeName] = tree;
|
---|
219 |
|
---|
220 | return TreeEvaluator.Evaluate(
|
---|
221 | tree, ProblemData,
|
---|
222 | ProblemData.TrainingIndices,
|
---|
223 | Interpreter,
|
---|
224 | StructureTemplate.ApplyLinearScaling,
|
---|
225 | EstimationLimits.Lower,
|
---|
226 | EstimationLimits.Upper);
|
---|
227 | }
|
---|
228 |
|
---|
229 | private static void AdjustLinearScalingParams(IRegressionProblemData problemData, ISymbolicExpressionTree tree, ISymbolicDataAnalysisExpressionTreeInterpreter interpreter) {
|
---|
230 | var offsetNode = tree.Root.GetSubtree(0).GetSubtree(0);
|
---|
231 | var scalingNode = offsetNode.Subtrees.Where(x => !(x is NumberTreeNode)).First();
|
---|
232 |
|
---|
233 | var offsetNumberNode = (NumberTreeNode)offsetNode.Subtrees.Where(x => x is NumberTreeNode).First();
|
---|
234 | var scalingNumberNode = (NumberTreeNode)scalingNode.Subtrees.Where(x => x is NumberTreeNode).First();
|
---|
235 |
|
---|
236 | var estimatedValues = interpreter.GetSymbolicExpressionTreeValues(tree, problemData.Dataset, problemData.TrainingIndices);
|
---|
237 | var targetValues = problemData.Dataset.GetDoubleValues(problemData.TargetVariable, problemData.TrainingIndices);
|
---|
238 |
|
---|
239 | OnlineLinearScalingParameterCalculator.Calculate(estimatedValues, targetValues, out double a, out double b, out OnlineCalculatorError error);
|
---|
240 | if (error == OnlineCalculatorError.None) {
|
---|
241 | offsetNumberNode.Value = a;
|
---|
242 | scalingNumberNode.Value = b;
|
---|
243 | }
|
---|
244 | }
|
---|
245 |
|
---|
246 | private static ISymbolicExpressionTree BuildTree(ISymbolicExpressionTree template, Individual individual) {
|
---|
247 | var resolvedTree = (ISymbolicExpressionTree)template.Clone();
|
---|
248 |
|
---|
249 | // build main tree
|
---|
250 | foreach (var subFunctionTreeNode in resolvedTree.IterateNodesPrefix().OfType<SubFunctionTreeNode>()) {
|
---|
251 | var subFunctionTree = individual.SymbolicExpressionTree(subFunctionTreeNode.Name);
|
---|
252 |
|
---|
253 | // extract function tree
|
---|
254 | var subTree = subFunctionTree.Root.GetSubtree(0) // StartSymbol
|
---|
255 | .GetSubtree(0); // First Symbol
|
---|
256 | subTree = (ISymbolicExpressionTreeNode)subTree.Clone();
|
---|
257 | subFunctionTreeNode.AddSubtree(subTree);
|
---|
258 | }
|
---|
259 | return resolvedTree;
|
---|
260 | }
|
---|
261 |
|
---|
262 |
|
---|
263 | public void Load(IRegressionProblemData data) {
|
---|
264 | ProblemData = data;
|
---|
265 | }
|
---|
266 | }
|
---|
267 | }
|
---|