Free cookie consent management tool by TermsFeed Policy Generator

source: branches/2925_AutoDiffForDynamicalModels/HeuristicLab.Problems.DynamicalSystemsModelling/3.3/OdeParameterIdentification.cs @ 16597

Last change on this file since 16597 was 16597, checked in by gkronber, 5 years ago

#2925: made some adaptations while debugging parameter identification for dynamical models

File size: 11.7 KB
Line 
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
22using System;
23using System.Linq;
24using System.Threading;
25using HeuristicLab.Algorithms.DataAnalysis;
26using HeuristicLab.Common;
27using HeuristicLab.Core;
28using HeuristicLab.Data;
29using HeuristicLab.Encodings.SymbolicExpressionTreeEncoding;
30using HeuristicLab.Parameters;
31using HeuristicLab.Persistence.Default.CompositeSerializers.Storable;
32using HeuristicLab.Problems.DataAnalysis;
33using HeuristicLab.Problems.DataAnalysis.Symbolic;
34using HeuristicLab.Random;
35using System.Collections.Generic;
36
37namespace 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      if (SetSeedRandomly) Seed = (new System.Random()).Next();
143      var rand = new MersenneTwister((uint)Seed);
144      if (InitializeParametersRandomly) {
145        throw new NotImplementedException();
146        // var qualityTable = new DataTable("RMSE table");
147        // qualityTable.VisualProperties.YAxisLogScale = true;
148        // var trainRMSERow = new DataRow("RMSE (train)");
149        // trainRMSERow.VisualProperties.ChartType = DataRowVisualProperties.DataRowChartType.Points;
150        // var testRMSERow = new DataRow("RMSE test");
151        // testRMSERow.VisualProperties.ChartType = DataRowVisualProperties.DataRowChartType.Points;
152        //
153        // qualityTable.Rows.Add(trainRMSERow);
154        // qualityTable.Rows.Add(testRMSERow);
155        // Results.Add(new Result(qualityTable.Name, qualityTable.Name + " for all restarts", qualityTable));
156
157        // CreateSolution(Problem, ModelStructure.ToArray(), Iterations, rand);
158        //
159        // for (int r = 0; r < Restarts; r++) {
160        //   CreateSolution(Problem, ModelStructure.ToArray(), Iterations, rand);
161        //   trainRMSERow.Values.Add(solution.TrainingRootMeanSquaredError);
162        //   testRMSERow.Values.Add(solution.TestRootMeanSquaredError);
163        //   if (solution.TrainingRootMeanSquaredError < bestSolution.TrainingRootMeanSquaredError) {
164        //     bestSolution = solution;
165        //   }
166        // }
167      } else {
168        CreateSolution(Problem, ModelStructure.ToArray(), Iterations, rand);
169      }
170
171      // Results.Add(new Result(RegressionSolutionResultName, "The nonlinear regression solution.", bestSolution));
172      // 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)));
173      // 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)));
174
175    }
176
177    public void CreateSolution(Problem problem, string[] modelStructure, int maxIterations, IRandom rand) {
178      var parser = new InfixExpressionParser();
179      var trees = modelStructure.Select(expr => Convert(parser.Parse(expr))).ToArray();
180      var names = problem.Encoding.Encodings.Select(enc => enc.Name).ToArray();
181      if (trees.Length != names.Length) throw new ArgumentException("The number of expressions must match the number of target variables exactly");
182
183      var scope = new Scope();
184      for (int i = 0; i < names.Length; i++) {
185        scope.Variables.Add(new Core.Variable(names[i], trees[i]));
186      }
187      var ind = problem.Encoding.GetIndividual(scope);
188      var quality = problem.Evaluate(ind, rand);
189      problem.Analyze(new[] { ind }, new[] { quality }, Results, rand);
190    }
191
192    private ISymbolicExpressionTree Convert(ISymbolicExpressionTree tree) {
193      return new SymbolicExpressionTree(Convert(tree.Root));
194    }
195
196
197    // for translation from symbolic expressions to simple symbols
198    private static Dictionary<Type, string> sym2str = new Dictionary<Type, string>() {
199      {typeof(Addition), "+" },
200      {typeof(Subtraction), "-" },
201      {typeof(Multiplication), "*" },
202      {typeof(Sine), "sin" },
203      {typeof(Cosine), "cos" },
204      {typeof(Square), "sqr" },
205    };
206
207    private ISymbolicExpressionTreeNode Convert(ISymbolicExpressionTreeNode node) {
208      if (sym2str.ContainsKey(node.Symbol.GetType())) {
209        var children = node.Subtrees.Select(st => Convert(st)).ToArray();
210        return Make(sym2str[node.Symbol.GetType()], children);
211      } else if (node.Symbol is ProgramRootSymbol) {
212        var child = Convert(node.GetSubtree(0));
213        node.RemoveSubtree(0);
214        node.AddSubtree(child);
215        return node;
216      } else if (node.Symbol is StartSymbol) {
217        var child = Convert(node.GetSubtree(0));
218        node.RemoveSubtree(0);
219        node.AddSubtree(child);
220        return node;
221      } else if (node.Symbol is Division) {
222        var children = node.Subtrees.Select(st => Convert(st)).ToArray();
223        if (children.Length == 1) {
224          return Make("%", new[] { new SimpleSymbol("θ", 0).CreateTreeNode(), children[0] });
225        } else if (children.Length != 2) throw new ArgumentException("Division is not supported for multiple arguments");
226        else return Make("%", children);
227      } else if (node.Symbol is Constant) {
228        return new SimpleSymbol("θ", 0).CreateTreeNode();
229      } else if (node.Symbol is DataAnalysis.Symbolic.Variable) {
230        var varNode = node as VariableTreeNode;
231        if (!varNode.Weight.IsAlmost(1.0)) throw new ArgumentException("Variable weights are not supported");
232        return new SimpleSymbol(varNode.VariableName, 0).CreateTreeNode();
233      } else throw new ArgumentException("Unsupported symbol: " + node.Symbol.Name);
234    }
235
236    private ISymbolicExpressionTreeNode Make(string op, ISymbolicExpressionTreeNode[] children) {
237      if (children.Length == 1) {
238        var s = new SimpleSymbol(op, 1).CreateTreeNode();
239        s.AddSubtree(children.First());
240        return s;
241      } else {
242        var s = new SimpleSymbol(op, 2).CreateTreeNode();
243        var c0 = children[0];
244        var c1 = children[1];
245        s.AddSubtree(c0);
246        s.AddSubtree(c1);
247        for (int i = 2; i < children.Length; i++) {
248          var sn = new SimpleSymbol(op, 2).CreateTreeNode();
249          sn.AddSubtree(s);
250          sn.AddSubtree(children[i]);
251          s = sn;
252        }
253        return s;
254      }
255    }
256    #endregion
257  }
258}
Note: See TracBrowser for help on using the repository browser.