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