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

Last change on this file since 16603 was 16603, checked in by gkronber, 2 years ago

#2925: scaling of residuals to target variance and update constant values directly in the tree

File size: 9.0 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 => 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    #endregion
192  }
193}
Note: See TracBrowser for help on using the repository browser.