Free cookie consent management tool by TermsFeed Policy Generator

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

Last change on this file was 16663, checked in by gkronber, 6 years ago

#2925: adapted to work with new persistence

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;
36using HEAL.Attic;
37
38namespace HeuristicLab.Problems.DynamicalSystemsModelling {
39  [Item("OdeParameterIdentification", "TODO")]
40  [Creatable(CreatableAttribute.Categories.DataAnalysisRegression, Priority = 120)]
41  [StorableType("93C151A2-9579-4013-9E67-7611F9378962")]
42  public sealed class OdeParameterIdentification : FixedDataAnalysisAlgorithm<Problem> {
43    private const string RegressionSolutionResultName = "Regression solution";
44    private const string ModelStructureParameterName = "Model structure";
45    private const string IterationsParameterName = "Iterations";
46    private const string RestartsParameterName = "Restarts";
47    private const string SetSeedRandomlyParameterName = "SetSeedRandomly";
48    private const string SeedParameterName = "Seed";
49    private const string InitParamsRandomlyParameterName = "InitializeParametersRandomly";
50
51    public IValueParameter<StringArray> ModelStructureParameter {
52      get { return (IValueParameter<StringArray>)Parameters[ModelStructureParameterName]; }
53    }
54    public IFixedValueParameter<IntValue> IterationsParameter {
55      get { return (IFixedValueParameter<IntValue>)Parameters[IterationsParameterName]; }
56    }
57
58    public IFixedValueParameter<BoolValue> SetSeedRandomlyParameter {
59      get { return (IFixedValueParameter<BoolValue>)Parameters[SetSeedRandomlyParameterName]; }
60    }
61
62    public IFixedValueParameter<IntValue> SeedParameter {
63      get { return (IFixedValueParameter<IntValue>)Parameters[SeedParameterName]; }
64    }
65
66    public IFixedValueParameter<IntValue> RestartsParameter {
67      get { return (IFixedValueParameter<IntValue>)Parameters[RestartsParameterName]; }
68    }
69
70    public IFixedValueParameter<BoolValue> InitParametersRandomlyParameter {
71      get { return (IFixedValueParameter<BoolValue>)Parameters[InitParamsRandomlyParameterName]; }
72    }
73
74    public StringArray ModelStructure {
75      get { return ModelStructureParameter.Value; }
76      set { ModelStructureParameter.Value = value; }
77    }
78
79    public int Iterations {
80      get { return IterationsParameter.Value.Value; }
81      set { IterationsParameter.Value.Value = value; }
82    }
83
84    public int Restarts {
85      get { return RestartsParameter.Value.Value; }
86      set { RestartsParameter.Value.Value = value; }
87    }
88
89    public int Seed {
90      get { return SeedParameter.Value.Value; }
91      set { SeedParameter.Value.Value = value; }
92    }
93
94    public bool SetSeedRandomly {
95      get { return SetSeedRandomlyParameter.Value.Value; }
96      set { SetSeedRandomlyParameter.Value.Value = value; }
97    }
98
99    public bool InitializeParametersRandomly {
100      get { return InitParametersRandomlyParameter.Value.Value; }
101      set { InitParametersRandomlyParameter.Value.Value = value; }
102    }
103
104    [StorableConstructor]
105    private OdeParameterIdentification(StorableConstructorFlag _) : base(_) { }
106    private OdeParameterIdentification(OdeParameterIdentification original, Cloner cloner)
107      : base(original, cloner) {
108    }
109    public OdeParameterIdentification()
110      : base() {
111      Problem = new Problem();
112      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" })));
113      Parameters.Add(new FixedValueParameter<IntValue>(IterationsParameterName, "The maximum number of iterations for constants optimization.", new IntValue(200)));
114      Parameters.Add(new FixedValueParameter<IntValue>(RestartsParameterName, "The number of independent random restarts (>0)", new IntValue(10)));
115      Parameters.Add(new FixedValueParameter<IntValue>(SeedParameterName, "The PRNG seed value.", new IntValue()));
116      Parameters.Add(new FixedValueParameter<BoolValue>(SetSeedRandomlyParameterName, "Switch to determine if the random number seed should be initialized randomly.", new BoolValue(true)));
117      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)));
118
119      SetParameterHiddenState();
120
121      InitParametersRandomlyParameter.Value.ValueChanged += (sender, args) => {
122        SetParameterHiddenState();
123      };
124    }
125
126    private void SetParameterHiddenState() {
127      var hide = !InitializeParametersRandomly;
128      RestartsParameter.Hidden = hide;
129      SeedParameter.Hidden = hide;
130      SetSeedRandomlyParameter.Hidden = hide;
131    }
132
133    [StorableHook(HookType.AfterDeserialization)]
134    private void AfterDeserialization() {
135    }
136
137    public override IDeepCloneable Clone(Cloner cloner) {
138      return new OdeParameterIdentification(this, cloner);
139    }
140
141    #region nonlinear regression
142    protected override void Run(CancellationToken cancellationToken) {
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 => 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    #endregion
193  }
194}
Note: See TracBrowser for help on using the repository browser.