1 | #region License Information
|
---|
2 | /* HeuristicLab
|
---|
3 | * Copyright (C) 2002-2018 Heuristic and Evolutionary Algorithms Laboratory (HEAL)
|
---|
4 | *
|
---|
5 | * This file is part of HeuristicLab.
|
---|
6 | *
|
---|
7 | * HeuristicLab is free software: you can redistribute it and/or modify
|
---|
8 | * it under the terms of the GNU General Public License as published by
|
---|
9 | * the Free Software Foundation, either version 3 of the License, or
|
---|
10 | * (at your option) any later version.
|
---|
11 | *
|
---|
12 | * HeuristicLab is distributed in the hope that it will be useful,
|
---|
13 | * but WITHOUT ANY WARRANTY; without even the implied warranty of
|
---|
14 | * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
|
---|
15 | * GNU General Public License for more details.
|
---|
16 | *
|
---|
17 | * You should have received a copy of the GNU General Public License
|
---|
18 | * along with HeuristicLab. If not, see <http://www.gnu.org/licenses/>.
|
---|
19 | */
|
---|
20 | #endregion
|
---|
21 |
|
---|
22 | using System;
|
---|
23 | using System.Linq;
|
---|
24 | using System.Threading;
|
---|
25 | using HeuristicLab.Algorithms.DataAnalysis;
|
---|
26 | using HeuristicLab.Common;
|
---|
27 | using HeuristicLab.Core;
|
---|
28 | using HeuristicLab.Data;
|
---|
29 | using HeuristicLab.Encodings.SymbolicExpressionTreeEncoding;
|
---|
30 | using HeuristicLab.Parameters;
|
---|
31 | using HeuristicLab.Persistence.Default.CompositeSerializers.Storable;
|
---|
32 | using HeuristicLab.Problems.DataAnalysis;
|
---|
33 | using HeuristicLab.Problems.DataAnalysis.Symbolic;
|
---|
34 | using HeuristicLab.Random;
|
---|
35 | using System.Collections.Generic;
|
---|
36 |
|
---|
37 | namespace HeuristicLab.Problems.DynamicalSystemsModelling {
|
---|
38 | [Item("OdeParameterIdentification", "TODO")]
|
---|
39 | [Creatable(CreatableAttribute.Categories.DataAnalysisRegression, Priority = 120)]
|
---|
40 | [StorableClass]
|
---|
41 | public sealed class OdeParameterIdentification : FixedDataAnalysisAlgorithm<Problem> {
|
---|
42 | private const string RegressionSolutionResultName = "Regression solution";
|
---|
43 | private const string ModelStructureParameterName = "Model structure";
|
---|
44 | private const string IterationsParameterName = "Iterations";
|
---|
45 | private const string RestartsParameterName = "Restarts";
|
---|
46 | private const string SetSeedRandomlyParameterName = "SetSeedRandomly";
|
---|
47 | private const string SeedParameterName = "Seed";
|
---|
48 | private const string InitParamsRandomlyParameterName = "InitializeParametersRandomly";
|
---|
49 |
|
---|
50 | public IValueParameter<StringArray> ModelStructureParameter {
|
---|
51 | get { return (IValueParameter<StringArray>)Parameters[ModelStructureParameterName]; }
|
---|
52 | }
|
---|
53 | public IFixedValueParameter<IntValue> IterationsParameter {
|
---|
54 | get { return (IFixedValueParameter<IntValue>)Parameters[IterationsParameterName]; }
|
---|
55 | }
|
---|
56 |
|
---|
57 | public IFixedValueParameter<BoolValue> SetSeedRandomlyParameter {
|
---|
58 | get { return (IFixedValueParameter<BoolValue>)Parameters[SetSeedRandomlyParameterName]; }
|
---|
59 | }
|
---|
60 |
|
---|
61 | public IFixedValueParameter<IntValue> SeedParameter {
|
---|
62 | get { return (IFixedValueParameter<IntValue>)Parameters[SeedParameterName]; }
|
---|
63 | }
|
---|
64 |
|
---|
65 | public IFixedValueParameter<IntValue> RestartsParameter {
|
---|
66 | get { return (IFixedValueParameter<IntValue>)Parameters[RestartsParameterName]; }
|
---|
67 | }
|
---|
68 |
|
---|
69 | public IFixedValueParameter<BoolValue> InitParametersRandomlyParameter {
|
---|
70 | get { return (IFixedValueParameter<BoolValue>)Parameters[InitParamsRandomlyParameterName]; }
|
---|
71 | }
|
---|
72 |
|
---|
73 | public StringArray ModelStructure {
|
---|
74 | get { return ModelStructureParameter.Value; }
|
---|
75 | set { ModelStructureParameter.Value = value; }
|
---|
76 | }
|
---|
77 |
|
---|
78 | public int Iterations {
|
---|
79 | get { return IterationsParameter.Value.Value; }
|
---|
80 | set { IterationsParameter.Value.Value = value; }
|
---|
81 | }
|
---|
82 |
|
---|
83 | public int Restarts {
|
---|
84 | get { return RestartsParameter.Value.Value; }
|
---|
85 | set { RestartsParameter.Value.Value = value; }
|
---|
86 | }
|
---|
87 |
|
---|
88 | public int Seed {
|
---|
89 | get { return SeedParameter.Value.Value; }
|
---|
90 | set { SeedParameter.Value.Value = value; }
|
---|
91 | }
|
---|
92 |
|
---|
93 | public bool SetSeedRandomly {
|
---|
94 | get { return SetSeedRandomlyParameter.Value.Value; }
|
---|
95 | set { SetSeedRandomlyParameter.Value.Value = value; }
|
---|
96 | }
|
---|
97 |
|
---|
98 | public bool InitializeParametersRandomly {
|
---|
99 | get { return InitParametersRandomlyParameter.Value.Value; }
|
---|
100 | set { InitParametersRandomlyParameter.Value.Value = value; }
|
---|
101 | }
|
---|
102 |
|
---|
103 | [StorableConstructor]
|
---|
104 | private OdeParameterIdentification(bool deserializing) : base(deserializing) { }
|
---|
105 | private OdeParameterIdentification(OdeParameterIdentification original, Cloner cloner)
|
---|
106 | : base(original, cloner) {
|
---|
107 | }
|
---|
108 | public OdeParameterIdentification()
|
---|
109 | : base() {
|
---|
110 | Problem = new Problem();
|
---|
111 | Parameters.Add(new ValueParameter<StringArray>(ModelStructureParameterName, "The function for which the parameters must be fit (only numeric constants are tuned).", new StringArray(new string[] { "1.0 * x*x + 0.0" })));
|
---|
112 | Parameters.Add(new FixedValueParameter<IntValue>(IterationsParameterName, "The maximum number of iterations for constants optimization.", new IntValue(200)));
|
---|
113 | Parameters.Add(new FixedValueParameter<IntValue>(RestartsParameterName, "The number of independent random restarts (>0)", new IntValue(10)));
|
---|
114 | Parameters.Add(new FixedValueParameter<IntValue>(SeedParameterName, "The PRNG seed value.", new IntValue()));
|
---|
115 | Parameters.Add(new FixedValueParameter<BoolValue>(SetSeedRandomlyParameterName, "Switch to determine if the random number seed should be initialized randomly.", new BoolValue(true)));
|
---|
116 | Parameters.Add(new FixedValueParameter<BoolValue>(InitParamsRandomlyParameterName, "Switch to determine if the real-valued model parameters should be initialized randomly in each restart.", new BoolValue(false)));
|
---|
117 |
|
---|
118 | SetParameterHiddenState();
|
---|
119 |
|
---|
120 | InitParametersRandomlyParameter.Value.ValueChanged += (sender, args) => {
|
---|
121 | SetParameterHiddenState();
|
---|
122 | };
|
---|
123 | }
|
---|
124 |
|
---|
125 | private void SetParameterHiddenState() {
|
---|
126 | var hide = !InitializeParametersRandomly;
|
---|
127 | RestartsParameter.Hidden = hide;
|
---|
128 | SeedParameter.Hidden = hide;
|
---|
129 | SetSeedRandomlyParameter.Hidden = hide;
|
---|
130 | }
|
---|
131 |
|
---|
132 | [StorableHook(HookType.AfterDeserialization)]
|
---|
133 | private void AfterDeserialization() {
|
---|
134 | }
|
---|
135 |
|
---|
136 | public override IDeepCloneable Clone(Cloner cloner) {
|
---|
137 | return new OdeParameterIdentification(this, cloner);
|
---|
138 | }
|
---|
139 |
|
---|
140 | #region nonlinear regression
|
---|
141 | protected override void Run(CancellationToken cancellationToken) {
|
---|
142 | IRegressionSolution bestSolution = null;
|
---|
143 | if (SetSeedRandomly) Seed = (new System.Random()).Next();
|
---|
144 | var rand = new MersenneTwister((uint)Seed);
|
---|
145 | if (InitializeParametersRandomly) {
|
---|
146 | throw new NotImplementedException();
|
---|
147 | // var qualityTable = new DataTable("RMSE table");
|
---|
148 | // qualityTable.VisualProperties.YAxisLogScale = true;
|
---|
149 | // var trainRMSERow = new DataRow("RMSE (train)");
|
---|
150 | // trainRMSERow.VisualProperties.ChartType = DataRowVisualProperties.DataRowChartType.Points;
|
---|
151 | // var testRMSERow = new DataRow("RMSE test");
|
---|
152 | // testRMSERow.VisualProperties.ChartType = DataRowVisualProperties.DataRowChartType.Points;
|
---|
153 | //
|
---|
154 | // qualityTable.Rows.Add(trainRMSERow);
|
---|
155 | // qualityTable.Rows.Add(testRMSERow);
|
---|
156 | // Results.Add(new Result(qualityTable.Name, qualityTable.Name + " for all restarts", qualityTable));
|
---|
157 |
|
---|
158 | // CreateSolution(Problem, ModelStructure.ToArray(), Iterations, rand);
|
---|
159 | //
|
---|
160 | // for (int r = 0; r < Restarts; r++) {
|
---|
161 | // CreateSolution(Problem, ModelStructure.ToArray(), Iterations, rand);
|
---|
162 | // trainRMSERow.Values.Add(solution.TrainingRootMeanSquaredError);
|
---|
163 | // testRMSERow.Values.Add(solution.TestRootMeanSquaredError);
|
---|
164 | // if (solution.TrainingRootMeanSquaredError < bestSolution.TrainingRootMeanSquaredError) {
|
---|
165 | // bestSolution = solution;
|
---|
166 | // }
|
---|
167 | // }
|
---|
168 | } else {
|
---|
169 | CreateSolution(Problem, ModelStructure.ToArray(), Iterations, rand);
|
---|
170 | }
|
---|
171 |
|
---|
172 | // Results.Add(new Result(RegressionSolutionResultName, "The nonlinear regression solution.", bestSolution));
|
---|
173 | // Results.Add(new Result("Root mean square error (train)", "The root of the mean of squared errors of the regression solution on the training set.", new DoubleValue(bestSolution.TrainingRootMeanSquaredError)));
|
---|
174 | // Results.Add(new Result("Root mean square error (test)", "The root of the mean of squared errors of the regression solution on the test set.", new DoubleValue(bestSolution.TestRootMeanSquaredError)));
|
---|
175 |
|
---|
176 | }
|
---|
177 |
|
---|
178 | public void CreateSolution(Problem problem, string[] modelStructure, int maxIterations, IRandom rand) {
|
---|
179 | var parser = new InfixExpressionParser();
|
---|
180 | var trees = modelStructure.Select(expr => Convert(parser.Parse(expr))).ToArray();
|
---|
181 | var names = problem.Encoding.Encodings.Select(enc => enc.Name).ToArray();
|
---|
182 | if (trees.Length != names.Length) throw new ArgumentException("The number of expressions must match the number of target variables exactly");
|
---|
183 |
|
---|
184 | var scope = new Scope();
|
---|
185 | for (int i = 0; i < names.Length; i++) {
|
---|
186 | scope.Variables.Add(new Core.Variable(names[i], trees[i]));
|
---|
187 | }
|
---|
188 | var ind = problem.Encoding.GetIndividual(scope);
|
---|
189 | var quality = problem.Evaluate(ind, rand);
|
---|
190 | problem.Analyze(new[] { ind }, new[] { quality }, Results, rand);
|
---|
191 | }
|
---|
192 |
|
---|
193 | private ISymbolicExpressionTree Convert(ISymbolicExpressionTree tree) {
|
---|
194 | return new SymbolicExpressionTree(Convert(tree.Root));
|
---|
195 | }
|
---|
196 |
|
---|
197 |
|
---|
198 | // for translation from symbolic expressions to simple symbols
|
---|
199 | private static Dictionary<Type, string> sym2str = new Dictionary<Type, string>() {
|
---|
200 | {typeof(Addition), "+" },
|
---|
201 | {typeof(Subtraction), "-" },
|
---|
202 | {typeof(Multiplication), "*" },
|
---|
203 | {typeof(Sine), "sin" },
|
---|
204 | {typeof(Cosine), "cos" },
|
---|
205 | {typeof(Square), "sqr" },
|
---|
206 | };
|
---|
207 |
|
---|
208 | private ISymbolicExpressionTreeNode Convert(ISymbolicExpressionTreeNode node) {
|
---|
209 | if (sym2str.ContainsKey(node.Symbol.GetType())) {
|
---|
210 | var children = node.Subtrees.Select(st => Convert(st)).ToArray();
|
---|
211 | return Make(sym2str[node.Symbol.GetType()], children);
|
---|
212 | } else if (node.Symbol is ProgramRootSymbol) {
|
---|
213 | var child = Convert(node.GetSubtree(0));
|
---|
214 | node.RemoveSubtree(0);
|
---|
215 | node.AddSubtree(child);
|
---|
216 | return node;
|
---|
217 | } else if (node.Symbol is StartSymbol) {
|
---|
218 | var child = Convert(node.GetSubtree(0));
|
---|
219 | node.RemoveSubtree(0);
|
---|
220 | node.AddSubtree(child);
|
---|
221 | return node;
|
---|
222 | } else if (node.Symbol is Division) {
|
---|
223 | var children = node.Subtrees.Select(st => Convert(st)).ToArray();
|
---|
224 | if (children.Length == 1) {
|
---|
225 | return Make("%", new[] { new SimpleSymbol("θ", 0).CreateTreeNode(), children[0] });
|
---|
226 | } else if (children.Length != 2) throw new ArgumentException("Division is not supported for multiple arguments");
|
---|
227 | else return Make("%", children);
|
---|
228 | } else if (node.Symbol is Constant) {
|
---|
229 | return new SimpleSymbol("θ", 0).CreateTreeNode();
|
---|
230 | } else if (node.Symbol is DataAnalysis.Symbolic.Variable) {
|
---|
231 | var varNode = node as VariableTreeNode;
|
---|
232 | if (!varNode.Weight.IsAlmost(1.0)) throw new ArgumentException("Variable weights are not supported");
|
---|
233 | return new SimpleSymbol(varNode.VariableName, 0).CreateTreeNode();
|
---|
234 | } else throw new ArgumentException("Unsupported symbol: " + node.Symbol.Name);
|
---|
235 | }
|
---|
236 |
|
---|
237 | private ISymbolicExpressionTreeNode Make(string op, ISymbolicExpressionTreeNode[] children) {
|
---|
238 | if (children.Length == 1) {
|
---|
239 | var s = new SimpleSymbol(op, 1).CreateTreeNode();
|
---|
240 | s.AddSubtree(children.First());
|
---|
241 | return s;
|
---|
242 | } else {
|
---|
243 | var s = new SimpleSymbol(op, 2).CreateTreeNode();
|
---|
244 | var c0 = children[0];
|
---|
245 | var c1 = children[1];
|
---|
246 | s.AddSubtree(c0);
|
---|
247 | s.AddSubtree(c1);
|
---|
248 | for (int i = 2; i < children.Length; i++) {
|
---|
249 | var sn = new SimpleSymbol(op, 2).CreateTreeNode();
|
---|
250 | sn.AddSubtree(s);
|
---|
251 | sn.AddSubtree(children[i]);
|
---|
252 | s = sn;
|
---|
253 | }
|
---|
254 | return s;
|
---|
255 | }
|
---|
256 | }
|
---|
257 | #endregion
|
---|
258 | }
|
---|
259 | }
|
---|