- Timestamp:
- 12/11/21 12:26:27 (3 years ago)
- Location:
- branches/3140_NumberSymbol
- Files:
-
- 17 edited
- 2 moved
Legend:
- Unmodified
- Added
- Removed
-
branches/3140_NumberSymbol/HeuristicLab.Algorithms.DataAnalysis/3.4/GaussianProcess/GaussianProcessCovarianceOptimizationProblem.cs
r17180 r18113 97 97 98 98 private const string ProblemDataParameterName = "ProblemData"; 99 private const string ConstantOptIterationsParameterName = "Constantoptimization steps";99 private const string ParameterOptIterationsParameterName = "Parameter optimization steps"; 100 100 private const string RestartsParameterName = "Restarts"; 101 101 … … 108 108 get { return (IValueParameter<IRegressionProblemData>)Parameters[ProblemDataParameterName]; } 109 109 } 110 public IFixedValueParameter<IntValue> ConstantOptIterationsParameter {111 get { return (IFixedValueParameter<IntValue>)Parameters[ ConstantOptIterationsParameterName]; }110 public IFixedValueParameter<IntValue> ParameterOptIterationsParameter { 111 get { return (IFixedValueParameter<IntValue>)Parameters[ParameterOptIterationsParameterName]; } 112 112 } 113 113 public IFixedValueParameter<IntValue> RestartsParameter { … … 124 124 IDataAnalysisProblemData IDataAnalysisProblem.ProblemData { get { return ProblemData; } } 125 125 126 public int ConstantOptIterations {127 get { return ConstantOptIterationsParameter.Value.Value; }128 set { ConstantOptIterationsParameter.Value.Value = value; }126 public int ParameterOptIterations { 127 get { return ParameterOptIterationsParameter.Value.Value; } 128 set { ParameterOptIterationsParameter.Value.Value = value; } 129 129 } 130 130 … … 153 153 : base() { 154 154 Parameters.Add(new ValueParameter<IRegressionProblemData>(ProblemDataParameterName, "The data for the regression problem", new RegressionProblemData())); 155 Parameters.Add(new FixedValueParameter<IntValue>( ConstantOptIterationsParameterName, "Number of optimization steps for hyperparameter values", new IntValue(50)));156 Parameters.Add(new FixedValueParameter<IntValue>(RestartsParameterName, "The number of random restarts for constantoptimization.", new IntValue(10)));155 Parameters.Add(new FixedValueParameter<IntValue>(ParameterOptIterationsParameterName, "Number of optimization steps for hyperparameter values", new IntValue(50))); 156 Parameters.Add(new FixedValueParameter<IntValue>(RestartsParameterName, "The number of random restarts for parameter optimization.", new IntValue(10))); 157 157 Parameters["Restarts"].Hidden = true; 158 158 var g = new SimpleSymbolicExpressionGrammar(); … … 236 236 double epsx = 0; 237 237 double stpmax = 1; 238 int maxits = ConstantOptIterations;238 int maxits = ParameterOptIterations; 239 239 alglib.mincgstate state; 240 240 alglib.mincgreport rep; … … 384 384 [StorableHook(HookType.AfterDeserialization)] 385 385 private void AfterDeserialization() { 386 if (!Parameters.ContainsKey(ParameterOptIterationsParameterName)) { 387 if (Parameters.ContainsKey("Constant optimization steps")) { 388 Parameters.Add(new FixedValueParameter<IntValue>(ParameterOptIterationsParameterName, "Number of optimization steps for hyperparameter values", (IntValue)Parameters["Constant optimization steps"].ActualValue)); 389 Parameters.Remove("Constant optimization steps"); 390 } else { 391 Parameters.Add(new FixedValueParameter<IntValue>(ParameterOptIterationsParameterName, "Number of optimization steps for hyperparameter values", new IntValue(50))); 392 } 393 } 386 394 } 387 395 -
branches/3140_NumberSymbol/HeuristicLab.Algorithms.DataAnalysis/3.4/NonlinearRegression/NonlinearRegression.cs
r18100 r18113 263 263 } 264 264 265 if (!SymbolicRegression ConstantOptimizationEvaluator.CanOptimizeConstants(tree)) throw new ArgumentException("The optimizer does not support the specified model structure.");265 if (!SymbolicRegressionParameterOptimizationEvaluator.CanOptimizeParameters(tree)) throw new ArgumentException("The optimizer does not support the specified model structure."); 266 266 267 267 // initialize constants randomly … … 275 275 var interpreter = new SymbolicDataAnalysisExpressionTreeLinearInterpreter(); 276 276 277 SymbolicRegression ConstantOptimizationEvaluator.OptimizeConstants(interpreter, tree, problemData, problemData.TrainingIndices,277 SymbolicRegressionParameterOptimizationEvaluator.OptimizeParameters(interpreter, tree, problemData, problemData.TrainingIndices, 278 278 applyLinearScaling: applyLinearScaling, maxIterations: maxIterations, 279 updateVariableWeights: false, update ConstantsInTree: true);279 updateVariableWeights: false, updateParametersInTree: true); 280 280 281 281 var model = new SymbolicRegressionModel(problemData.TargetVariable, tree, (ISymbolicDataAnalysisExpressionTreeInterpreter)interpreter.Clone()); -
branches/3140_NumberSymbol/HeuristicLab.Problems.DataAnalysis.Symbolic.Regression.Views/3.4/InteractiveSymbolicRegressionSolutionSimplifierView.cs
r17430 r18113 42 42 43 43 var tree = Content?.Model?.SymbolicExpressionTree; 44 btnOptimizeConstants.Enabled = tree != null && SymbolicRegression ConstantOptimizationEvaluator.CanOptimizeConstants(tree);44 btnOptimizeConstants.Enabled = tree != null && SymbolicRegressionParameterOptimizationEvaluator.CanOptimizeParameters(tree); 45 45 } 46 46 … … 64 64 do { 65 65 prevResult = result; 66 result = SymbolicRegression ConstantOptimizationEvaluator.OptimizeConstants(model.Interpreter, tree, regressionProblemData, regressionProblemData.TrainingIndices,66 result = SymbolicRegressionParameterOptimizationEvaluator.OptimizeParameters(model.Interpreter, tree, regressionProblemData, regressionProblemData.TrainingIndices, 67 67 applyLinearScaling: true, maxIterations: constOptIterations, updateVariableWeights: true, lowerEstimationLimit: model.LowerEstimationLimit, upperEstimationLimit: model.UpperEstimationLimit, 68 68 iterationCallback: (args, func, obj) => { -
branches/3140_NumberSymbol/HeuristicLab.Problems.DataAnalysis.Symbolic.Regression/3.4/HeuristicLab.Problems.DataAnalysis.Symbolic.Regression-3.4.csproj
r18053 r18113 129 129 <Compile Include="Plugin.cs" /> 130 130 <Compile Include="ShapeConstraintsAnalyzer.cs" /> 131 <Compile Include="SingleObjective\ ConstantOptimizationAnalyzer.cs" />131 <Compile Include="SingleObjective\ParameterOptimizationAnalyzer.cs" /> 132 132 <Compile Include="SingleObjective\Evaluators\NMSESingleObjectiveConstraintsEvaluator.cs" /> 133 133 <Compile Include="SingleObjective\Evaluators\SymbolicRegressionMeanRelativeErrorEvaluator.cs" /> … … 142 142 <Compile Include="SingleObjective\Evaluators\SymbolicRegressionSingleObjectiveMaxAbsoluteErrorEvaluator.cs" /> 143 143 <Compile Include="SingleObjective\Evaluators\SymbolicRegressionSingleObjectiveMeanAbsoluteErrorEvaluator.cs" /> 144 <Compile Include="SingleObjective\Evaluators\SymbolicRegression ConstantOptimizationEvaluator.cs" />144 <Compile Include="SingleObjective\Evaluators\SymbolicRegressionParameterOptimizationEvaluator.cs" /> 145 145 <Compile Include="SingleObjective\SymbolicRegressionSingleObjectiveOverfittingAnalyzer.cs" /> 146 146 <Compile Include="SymbolicRegressionModel.cs" /> -
branches/3140_NumberSymbol/HeuristicLab.Problems.DataAnalysis.Symbolic.Regression/3.4/MultiObjective/NMSEMultiObjectiveConstraintsEvaluator.cs
r18100 r18113 90 90 var applyLinearScaling = ApplyLinearScalingParameter.ActualValue.Value; 91 91 92 if (Use ConstantOptimization) {93 SymbolicRegression ConstantOptimizationEvaluator.OptimizeConstants(interpreter, tree, problemData, rows,92 if (UseParameterOptimization) { 93 SymbolicRegressionParameterOptimizationEvaluator.OptimizeParameters(interpreter, tree, problemData, rows, 94 94 false, 95 ConstantOptimizationIterations,96 ConstantOptimizationUpdateVariableWeights,95 ParameterOptimizationIterations, 96 ParameterOptimizationUpdateVariableWeights, 97 97 estimationLimits.Lower, 98 98 estimationLimits.Upper); -
branches/3140_NumberSymbol/HeuristicLab.Problems.DataAnalysis.Symbolic.Regression/3.4/MultiObjective/PearsonRSquaredAverageSimilarityEvaluator.cs
r17180 r18113 76 76 var applyLinearScaling = ApplyLinearScalingParameter.ActualValue.Value; 77 77 78 if (Use ConstantOptimization) {79 SymbolicRegression ConstantOptimizationEvaluator.OptimizeConstants(interpreter, solution, problemData, rows, applyLinearScaling, ConstantOptimizationIterations, updateVariableWeights: ConstantOptimizationUpdateVariableWeights, lowerEstimationLimit: estimationLimits.Lower, upperEstimationLimit: estimationLimits.Upper);78 if (UseParameterOptimization) { 79 SymbolicRegressionParameterOptimizationEvaluator.OptimizeParameters(interpreter, solution, problemData, rows, applyLinearScaling, ParameterOptimizationIterations, updateVariableWeights: ParameterOptimizationUpdateVariableWeights, lowerEstimationLimit: estimationLimits.Lower, upperEstimationLimit: estimationLimits.Upper); 80 80 } 81 81 -
branches/3140_NumberSymbol/HeuristicLab.Problems.DataAnalysis.Symbolic.Regression/3.4/MultiObjective/PearsonRSquaredNestedTreeSizeEvaluator.cs
r17180 r18113 54 54 var applyLinearScaling = ApplyLinearScalingParameter.ActualValue.Value; 55 55 56 if (Use ConstantOptimization) {57 SymbolicRegression ConstantOptimizationEvaluator.OptimizeConstants(interpreter, solution, problemData, rows, applyLinearScaling, ConstantOptimizationIterations, updateVariableWeights: ConstantOptimizationUpdateVariableWeights,lowerEstimationLimit: estimationLimits.Lower, upperEstimationLimit: estimationLimits.Upper);56 if (UseParameterOptimization) { 57 SymbolicRegressionParameterOptimizationEvaluator.OptimizeParameters(interpreter, solution, problemData, rows, applyLinearScaling, ParameterOptimizationIterations, updateVariableWeights: ParameterOptimizationUpdateVariableWeights,lowerEstimationLimit: estimationLimits.Lower, upperEstimationLimit: estimationLimits.Upper); 58 58 } 59 59 -
branches/3140_NumberSymbol/HeuristicLab.Problems.DataAnalysis.Symbolic.Regression/3.4/MultiObjective/PearsonRSquaredNumberOfVariablesEvaluator.cs
r17180 r18113 54 54 var applyLinearScaling = ApplyLinearScalingParameter.ActualValue.Value; 55 55 56 if (Use ConstantOptimization) {57 SymbolicRegression ConstantOptimizationEvaluator.OptimizeConstants(interpreter, solution, problemData, rows, applyLinearScaling, ConstantOptimizationIterations, updateVariableWeights: ConstantOptimizationUpdateVariableWeights, lowerEstimationLimit: estimationLimits.Lower, upperEstimationLimit: estimationLimits.Upper);56 if (UseParameterOptimization) { 57 SymbolicRegressionParameterOptimizationEvaluator.OptimizeParameters(interpreter, solution, problemData, rows, applyLinearScaling, ParameterOptimizationIterations, updateVariableWeights: ParameterOptimizationUpdateVariableWeights, lowerEstimationLimit: estimationLimits.Lower, upperEstimationLimit: estimationLimits.Upper); 58 58 } 59 59 double[] qualities = Calculate(SymbolicDataAnalysisTreeInterpreterParameter.ActualValue, solution, EstimationLimitsParameter.ActualValue.Lower, EstimationLimitsParameter.ActualValue.Upper, ProblemDataParameter.ActualValue, rows, ApplyLinearScalingParameter.ActualValue.Value, DecimalPlaces); -
branches/3140_NumberSymbol/HeuristicLab.Problems.DataAnalysis.Symbolic.Regression/3.4/MultiObjective/PearsonRSquaredTreeComplexityEvaluator.cs
r17180 r18113 53 53 var applyLinearScaling = ApplyLinearScalingParameter.ActualValue.Value; 54 54 55 if (Use ConstantOptimization) {56 SymbolicRegression ConstantOptimizationEvaluator.OptimizeConstants(interpreter, solution, problemData, rows, applyLinearScaling, ConstantOptimizationIterations, updateVariableWeights: ConstantOptimizationUpdateVariableWeights, lowerEstimationLimit: estimationLimits.Lower, upperEstimationLimit: estimationLimits.Upper);55 if (UseParameterOptimization) { 56 SymbolicRegressionParameterOptimizationEvaluator.OptimizeParameters(interpreter, solution, problemData, rows, applyLinearScaling, ParameterOptimizationIterations, updateVariableWeights: ParameterOptimizationUpdateVariableWeights, lowerEstimationLimit: estimationLimits.Lower, upperEstimationLimit: estimationLimits.Upper); 57 57 } 58 58 double[] qualities = Calculate(interpreter, solution, estimationLimits.Lower, estimationLimits.Upper, problemData, rows, applyLinearScaling, DecimalPlaces); -
branches/3140_NumberSymbol/HeuristicLab.Problems.DataAnalysis.Symbolic.Regression/3.4/MultiObjective/SymbolicRegressionMultiObjectiveEvaluator.cs
r17180 r18113 31 31 public abstract class SymbolicRegressionMultiObjectiveEvaluator : SymbolicDataAnalysisMultiObjectiveEvaluator<IRegressionProblemData>, ISymbolicRegressionMultiObjectiveEvaluator { 32 32 private const string DecimalPlacesParameterName = "Decimal Places"; 33 private const string Use ConstantOptimizationParameterName = "Use constantoptimization";34 private const string ConstantOptimizationIterationsParameterName = "Constantoptimization iterations";33 private const string UseParameterOptimizationParameterName = "Use parameter optimization"; 34 private const string ParameterOptimizationIterationsParameterName = "Parameter optimization iterations"; 35 35 36 private const string ConstantOptimizationUpdateVariableWeightsParameterName =37 " Constantoptimization update variable weights";36 private const string ParameterOptimizationUpdateVariableWeightsParameterName = 37 "Parameter optimization update variable weights"; 38 38 39 39 public IFixedValueParameter<IntValue> DecimalPlacesParameter { 40 40 get { return (IFixedValueParameter<IntValue>)Parameters[DecimalPlacesParameterName]; } 41 41 } 42 public IFixedValueParameter<BoolValue> Use ConstantOptimizationParameter {43 get { return (IFixedValueParameter<BoolValue>)Parameters[Use ConstantOptimizationParameterName]; }42 public IFixedValueParameter<BoolValue> UseParameterOptimizationParameter { 43 get { return (IFixedValueParameter<BoolValue>)Parameters[UseParameterOptimizationParameterName]; } 44 44 } 45 45 46 public IFixedValueParameter<IntValue> ConstantOptimizationIterationsParameter {47 get { return (IFixedValueParameter<IntValue>)Parameters[ ConstantOptimizationIterationsParameterName]; }46 public IFixedValueParameter<IntValue> ParameterOptimizationIterationsParameter { 47 get { return (IFixedValueParameter<IntValue>)Parameters[ParameterOptimizationIterationsParameterName]; } 48 48 } 49 49 50 public IFixedValueParameter<BoolValue> ConstantOptimizationUpdateVariableWeightsParameter {51 get { return (IFixedValueParameter<BoolValue>)Parameters[ ConstantOptimizationUpdateVariableWeightsParameterName]; }50 public IFixedValueParameter<BoolValue> ParameterOptimizationUpdateVariableWeightsParameter { 51 get { return (IFixedValueParameter<BoolValue>)Parameters[ParameterOptimizationUpdateVariableWeightsParameterName]; } 52 52 } 53 53 … … 56 56 set { DecimalPlacesParameter.Value.Value = value; } 57 57 } 58 public bool Use ConstantOptimization {59 get { return Use ConstantOptimizationParameter.Value.Value; }60 set { Use ConstantOptimizationParameter.Value.Value = value; }58 public bool UseParameterOptimization { 59 get { return UseParameterOptimizationParameter.Value.Value; } 60 set { UseParameterOptimizationParameter.Value.Value = value; } 61 61 } 62 public int ConstantOptimizationIterations {63 get { return ConstantOptimizationIterationsParameter.Value.Value; }64 set { ConstantOptimizationIterationsParameter.Value.Value = value; }62 public int ParameterOptimizationIterations { 63 get { return ParameterOptimizationIterationsParameter.Value.Value; } 64 set { ParameterOptimizationIterationsParameter.Value.Value = value; } 65 65 } 66 public bool ConstantOptimizationUpdateVariableWeights {67 get { return ConstantOptimizationUpdateVariableWeightsParameter.Value.Value; }68 set { ConstantOptimizationUpdateVariableWeightsParameter.Value.Value = value; }66 public bool ParameterOptimizationUpdateVariableWeights { 67 get { return ParameterOptimizationUpdateVariableWeightsParameter.Value.Value; } 68 set { ParameterOptimizationUpdateVariableWeightsParameter.Value.Value = value; } 69 69 } 70 70 … … 78 78 : base() { 79 79 Parameters.Add(new FixedValueParameter<IntValue>(DecimalPlacesParameterName, "The number of decimal places used for rounding the quality values.", new IntValue(5)) { Hidden = true }); 80 Parameters.Add(new FixedValueParameter<BoolValue>(Use ConstantOptimizationParameterName, "", new BoolValue(false)));81 Parameters.Add(new FixedValueParameter<IntValue>( ConstantOptimizationIterationsParameterName, "The number of iterations constantoptimization should be applied.", new IntValue(5)));82 Parameters.Add(new FixedValueParameter<BoolValue>( ConstantOptimizationUpdateVariableWeightsParameterName, "Determines if the variable weights in the tree should be optimized during constantoptimization.", new BoolValue(true)) { Hidden = true });80 Parameters.Add(new FixedValueParameter<BoolValue>(UseParameterOptimizationParameterName, "", new BoolValue(false))); 81 Parameters.Add(new FixedValueParameter<IntValue>(ParameterOptimizationIterationsParameterName, "The number of iterations parameter optimization should be applied.", new IntValue(5))); 82 Parameters.Add(new FixedValueParameter<BoolValue>(ParameterOptimizationUpdateVariableWeightsParameterName, "Determines if the variable weights in the tree should be optimized during parameter optimization.", new BoolValue(true)) { Hidden = true }); 83 83 } 84 84 85 85 [StorableHook(HookType.AfterDeserialization)] 86 86 private void AfterDeserialization() { 87 if (!Parameters.ContainsKey(UseConstantOptimizationParameterName)) { 88 Parameters.Add(new FixedValueParameter<BoolValue>(UseConstantOptimizationParameterName, "", new BoolValue(false))); 87 if (!Parameters.ContainsKey(UseParameterOptimizationParameterName)) { 88 if (Parameters.ContainsKey("Use constant optimization")) { 89 Parameters.Add(new FixedValueParameter<BoolValue>(UseParameterOptimizationParameterName, "", (BoolValue)Parameters["Use constant optimization"].ActualValue)); 90 Parameters.Remove("Use constant optimization"); 91 } else { 92 Parameters.Add(new FixedValueParameter<BoolValue>(UseParameterOptimizationParameterName, "", new BoolValue(false))); 93 } 89 94 } 95 90 96 if (!Parameters.ContainsKey(DecimalPlacesParameterName)) { 91 97 Parameters.Add(new FixedValueParameter<IntValue>(DecimalPlacesParameterName, "The number of decimal places used for rounding the quality values.", new IntValue(-1)) { Hidden = true }); 92 98 } 93 if (!Parameters.ContainsKey(ConstantOptimizationIterationsParameterName)) { 94 Parameters.Add(new FixedValueParameter<IntValue>(ConstantOptimizationIterationsParameterName, "The number of iterations constant optimization should be applied.", new IntValue(5))); 99 if (!Parameters.ContainsKey(ParameterOptimizationIterationsParameterName)) { 100 if (Parameters.ContainsKey("Constant optimization iterations")) { 101 Parameters.Add(new FixedValueParameter<IntValue>(ParameterOptimizationIterationsParameterName, "The number of iterations parameter optimization should be applied.", (IntValue)Parameters["Constant optimization iterations"].ActualValue)); 102 Parameters.Remove("Constant optimization iterations"); 103 } else { 104 Parameters.Add(new FixedValueParameter<IntValue>(ParameterOptimizationIterationsParameterName, "The number of iterations parameter optimization should be applied.", new IntValue(5))); 105 } 95 106 } 96 if (!Parameters.ContainsKey(ConstantOptimizationUpdateVariableWeightsParameterName)) { 97 Parameters.Add(new FixedValueParameter<BoolValue>(ConstantOptimizationUpdateVariableWeightsParameterName, "Determines if the variable weights in the tree should be optimized during constant optimization.", new BoolValue(true))); 107 if (!Parameters.ContainsKey(ParameterOptimizationUpdateVariableWeightsParameterName)) { 108 if (Parameters.ContainsKey("Constant optimization update variable weights")) { 109 Parameters.Add(new FixedValueParameter<BoolValue>(ParameterOptimizationUpdateVariableWeightsParameterName, "Determines if the variable weights in the tree should be optimized during parameter optimization.", 110 (BoolValue)Parameters["Constant optimization update variable weights"].ActualValue)); 111 Parameters.Remove("Constant optimization update variable weights"); 112 } else { 113 Parameters.Add(new FixedValueParameter<BoolValue>(ParameterOptimizationUpdateVariableWeightsParameterName, "Determines if the variable weights in the tree should be optimized during parameter optimization.", new BoolValue(true))); 114 } 98 115 } 99 116 } -
branches/3140_NumberSymbol/HeuristicLab.Problems.DataAnalysis.Symbolic.Regression/3.4/MultiObjective/SymbolicRegressionMultiObjectiveMeanSquaredErrorTreeSizeEvaluator.cs
r17180 r18113 53 53 var applyLinearScaling = ApplyLinearScalingParameter.ActualValue.Value; 54 54 55 if (Use ConstantOptimization) {56 SymbolicRegression ConstantOptimizationEvaluator.OptimizeConstants(interpreter, solution, problemData, rows, applyLinearScaling, ConstantOptimizationIterations, updateVariableWeights: ConstantOptimizationUpdateVariableWeights, lowerEstimationLimit: estimationLimits.Lower, upperEstimationLimit: estimationLimits.Upper);55 if (UseParameterOptimization) { 56 SymbolicRegressionParameterOptimizationEvaluator.OptimizeParameters(interpreter, solution, problemData, rows, applyLinearScaling, ParameterOptimizationIterations, updateVariableWeights: ParameterOptimizationUpdateVariableWeights, lowerEstimationLimit: estimationLimits.Lower, upperEstimationLimit: estimationLimits.Upper); 57 57 } 58 58 -
branches/3140_NumberSymbol/HeuristicLab.Problems.DataAnalysis.Symbolic.Regression/3.4/MultiObjective/SymbolicRegressionMultiObjectivePearsonRSquaredTreeSizeEvaluator.cs
r17180 r18113 53 53 var applyLinearScaling = ApplyLinearScalingParameter.ActualValue.Value; 54 54 55 if (Use ConstantOptimization) {56 SymbolicRegression ConstantOptimizationEvaluator.OptimizeConstants(interpreter, solution, problemData, rows, applyLinearScaling, ConstantOptimizationIterations, updateVariableWeights: ConstantOptimizationUpdateVariableWeights, lowerEstimationLimit: estimationLimits.Lower, upperEstimationLimit: estimationLimits.Upper);55 if (UseParameterOptimization) { 56 SymbolicRegressionParameterOptimizationEvaluator.OptimizeParameters(interpreter, solution, problemData, rows, applyLinearScaling, ParameterOptimizationIterations, updateVariableWeights: ParameterOptimizationUpdateVariableWeights, lowerEstimationLimit: estimationLimits.Lower, upperEstimationLimit: estimationLimits.Upper); 57 57 } 58 58 double[] qualities = Calculate(SymbolicDataAnalysisTreeInterpreterParameter.ActualValue, solution, EstimationLimitsParameter.ActualValue.Lower, EstimationLimitsParameter.ActualValue.Upper, ProblemDataParameter.ActualValue, rows, ApplyLinearScalingParameter.ActualValue.Value, DecimalPlaces); -
branches/3140_NumberSymbol/HeuristicLab.Problems.DataAnalysis.Symbolic.Regression/3.4/SingleObjective/Evaluators/NMSESingleObjectiveConstraintsEvaluator.cs
r18100 r18113 46 46 (IFixedValueParameter<BoolValue>)Parameters[OptimizeParametersParameterName]; 47 47 48 public IFixedValueParameter<IntValue> ConstantOptimizationIterationsParameter =>48 public IFixedValueParameter<IntValue> ParameterOptimizationIterationsParameter => 49 49 (IFixedValueParameter<IntValue>)Parameters[ParameterOptimizationIterationsParameterName]; 50 50 … … 62 62 } 63 63 64 public int ConstantOptimizationIterations {65 get => ConstantOptimizationIterationsParameter.Value.Value;66 set => ConstantOptimizationIterationsParameter.Value.Value = value;64 public int ParameterOptimizationIterations { 65 get => ParameterOptimizationIterationsParameter.Value.Value; 66 set => ParameterOptimizationIterationsParameter.Value.Value = value; 67 67 } 68 68 … … 109 109 110 110 [StorableHook(HookType.AfterDeserialization)] 111 private void AfterDeserialization() { } 111 private void AfterDeserialization() { 112 if (!Parameters.ContainsKey(ParameterOptimizationIterationsParameterName)) { 113 if (Parameters.ContainsKey("ParameterOptimizationIterations")) { 114 Parameters.Add(new FixedValueParameter<IntValue>(ParameterOptimizationIterationsParameterName, "Define how many parameter optimization steps should be performed (default: 10).", (IntValue)Parameters["ParameterOptimizationIterations"].ActualValue)); 115 Parameters.Remove("ParameterOptimizationIterations"); 116 } else { 117 Parameters.Add(new FixedValueParameter<IntValue>(ParameterOptimizationIterationsParameterName, "Define how many parameter optimization steps should be performed (default: 10).", new IntValue(10))); 118 } 119 } 120 121 } 112 122 113 123 public override IDeepCloneable Clone(Cloner cloner) { … … 126 136 127 137 if (OptimizeParameters) { 128 SymbolicRegression ConstantOptimizationEvaluator.OptimizeConstants(interpreter, tree, problemData, rows,129 false, ConstantOptimizationIterations, true,138 SymbolicRegressionParameterOptimizationEvaluator.OptimizeParameters(interpreter, tree, problemData, rows, 139 false, ParameterOptimizationIterations, true, 130 140 estimationLimits.Lower, estimationLimits.Upper); 131 141 } else { -
branches/3140_NumberSymbol/HeuristicLab.Problems.DataAnalysis.Symbolic.Regression/3.4/SingleObjective/Evaluators/SymbolicRegressionParameterOptimizationEvaluator.cs
r18112 r18113 32 32 33 33 namespace HeuristicLab.Problems.DataAnalysis.Symbolic.Regression { 34 [Item(" Constant Optimization Evaluator", "Calculates Pearson R² of a symbolic regression solution and optimizes the constantused.")]34 [Item("Parameter Optimization Evaluator", "Calculates Pearson R² of a symbolic regression solution and optimizes the parameters used.")] 35 35 [StorableType("24B68851-036D-4446-BD6F-3823E9028FF4")] 36 public class SymbolicRegression ConstantOptimizationEvaluator : SymbolicRegressionSingleObjectiveEvaluator {37 private const string ConstantOptimizationIterationsParameterName = "ConstantOptimizationIterations";38 private const string ConstantOptimizationImprovementParameterName = "ConstantOptimizationImprovement";39 private const string ConstantOptimizationProbabilityParameterName = "ConstantOptimizationProbability";40 private const string ConstantOptimizationRowsPercentageParameterName = "ConstantOptimizationRowsPercentage";41 private const string Update ConstantsInTreeParameterName = "UpdateConstantsInSymbolicExpressionTree";36 public class SymbolicRegressionParameterOptimizationEvaluator : SymbolicRegressionSingleObjectiveEvaluator { 37 private const string ParameterOptimizationIterationsParameterName = "ParameterOptimizationIterations"; 38 private const string ParameterOptimizationImprovementParameterName = "ParameterOptimizationImprovement"; 39 private const string ParameterOptimizationProbabilityParameterName = "ParameterOptimizationProbability"; 40 private const string ParameterOptimizationRowsPercentageParameterName = "ParameterOptimizationRowsPercentage"; 41 private const string UpdateParametersInTreeParameterName = "UpdateParametersInSymbolicExpressionTree"; 42 42 private const string UpdateVariableWeightsParameterName = "Update Variable Weights"; 43 43 44 private const string FunctionEvaluationsResultParameterName = " Constants Optimization Function Evaluations";45 private const string GradientEvaluationsResultParameterName = " Constants Optimization Gradient Evaluations";44 private const string FunctionEvaluationsResultParameterName = "Parameters Optimization Function Evaluations"; 45 private const string GradientEvaluationsResultParameterName = "Parameters Optimization Gradient Evaluations"; 46 46 private const string CountEvaluationsParameterName = "Count Function and Gradient Evaluations"; 47 47 48 public IFixedValueParameter<IntValue> ConstantOptimizationIterationsParameter {49 get { return (IFixedValueParameter<IntValue>)Parameters[ ConstantOptimizationIterationsParameterName]; }50 } 51 public IFixedValueParameter<DoubleValue> ConstantOptimizationImprovementParameter {52 get { return (IFixedValueParameter<DoubleValue>)Parameters[ ConstantOptimizationImprovementParameterName]; }53 } 54 public IFixedValueParameter<PercentValue> ConstantOptimizationProbabilityParameter {55 get { return (IFixedValueParameter<PercentValue>)Parameters[ ConstantOptimizationProbabilityParameterName]; }56 } 57 public IFixedValueParameter<PercentValue> ConstantOptimizationRowsPercentageParameter {58 get { return (IFixedValueParameter<PercentValue>)Parameters[ ConstantOptimizationRowsPercentageParameterName]; }59 } 60 public IFixedValueParameter<BoolValue> Update ConstantsInTreeParameter {61 get { return (IFixedValueParameter<BoolValue>)Parameters[Update ConstantsInTreeParameterName]; }48 public IFixedValueParameter<IntValue> ParameterOptimizationIterationsParameter { 49 get { return (IFixedValueParameter<IntValue>)Parameters[ParameterOptimizationIterationsParameterName]; } 50 } 51 public IFixedValueParameter<DoubleValue> ParameterOptimizationImprovementParameter { 52 get { return (IFixedValueParameter<DoubleValue>)Parameters[ParameterOptimizationImprovementParameterName]; } 53 } 54 public IFixedValueParameter<PercentValue> ParameterOptimizationProbabilityParameter { 55 get { return (IFixedValueParameter<PercentValue>)Parameters[ParameterOptimizationProbabilityParameterName]; } 56 } 57 public IFixedValueParameter<PercentValue> ParameterOptimizationRowsPercentageParameter { 58 get { return (IFixedValueParameter<PercentValue>)Parameters[ParameterOptimizationRowsPercentageParameterName]; } 59 } 60 public IFixedValueParameter<BoolValue> UpdateParametersInTreeParameter { 61 get { return (IFixedValueParameter<BoolValue>)Parameters[UpdateParametersInTreeParameterName]; } 62 62 } 63 63 public IFixedValueParameter<BoolValue> UpdateVariableWeightsParameter { … … 76 76 77 77 78 public IntValue ConstantOptimizationIterations {79 get { return ConstantOptimizationIterationsParameter.Value; }80 } 81 public DoubleValue ConstantOptimizationImprovement {82 get { return ConstantOptimizationImprovementParameter.Value; }83 } 84 public PercentValue ConstantOptimizationProbability {85 get { return ConstantOptimizationProbabilityParameter.Value; }86 } 87 public PercentValue ConstantOptimizationRowsPercentage {88 get { return ConstantOptimizationRowsPercentageParameter.Value; }89 } 90 public bool Update ConstantsInTree {91 get { return Update ConstantsInTreeParameter.Value.Value; }92 set { Update ConstantsInTreeParameter.Value.Value = value; }78 public IntValue ParameterOptimizationIterations { 79 get { return ParameterOptimizationIterationsParameter.Value; } 80 } 81 public DoubleValue ParameterOptimizationImprovement { 82 get { return ParameterOptimizationImprovementParameter.Value; } 83 } 84 public PercentValue ParameterOptimizationProbability { 85 get { return ParameterOptimizationProbabilityParameter.Value; } 86 } 87 public PercentValue ParameterOptimizationRowsPercentage { 88 get { return ParameterOptimizationRowsPercentageParameter.Value; } 89 } 90 public bool UpdateParametersInTree { 91 get { return UpdateParametersInTreeParameter.Value.Value; } 92 set { UpdateParametersInTreeParameter.Value.Value = value; } 93 93 } 94 94 … … 108 108 109 109 [StorableConstructor] 110 protected SymbolicRegression ConstantOptimizationEvaluator(StorableConstructorFlag _) : base(_) { }111 protected SymbolicRegression ConstantOptimizationEvaluator(SymbolicRegressionConstantOptimizationEvaluator original, Cloner cloner)110 protected SymbolicRegressionParameterOptimizationEvaluator(StorableConstructorFlag _) : base(_) { } 111 protected SymbolicRegressionParameterOptimizationEvaluator(SymbolicRegressionParameterOptimizationEvaluator original, Cloner cloner) 112 112 : base(original, cloner) { 113 113 } 114 public SymbolicRegression ConstantOptimizationEvaluator()114 public SymbolicRegressionParameterOptimizationEvaluator() 115 115 : base() { 116 Parameters.Add(new FixedValueParameter<IntValue>( ConstantOptimizationIterationsParameterName, "Determines how many iterations should be calculated while optimizing the constantof a symbolic expression tree (0 indicates other or default stopping criterion).", new IntValue(10)));117 Parameters.Add(new FixedValueParameter<DoubleValue>( ConstantOptimizationImprovementParameterName, "Determines the relative improvement which must be achieved in the constantoptimization to continue with it (0 indicates other or default stopping criterion).", new DoubleValue(0)) { Hidden = true });118 Parameters.Add(new FixedValueParameter<PercentValue>( ConstantOptimizationProbabilityParameterName, "Determines the probability that the constants are optimized", new PercentValue(1)));119 Parameters.Add(new FixedValueParameter<PercentValue>( ConstantOptimizationRowsPercentageParameterName, "Determines the percentage of the rows which should be used for constantoptimization", new PercentValue(1)));120 Parameters.Add(new FixedValueParameter<BoolValue>(Update ConstantsInTreeParameterName, "Determines if the constants in the tree should be overwritten by the optimized constants.", new BoolValue(true)) { Hidden = true });116 Parameters.Add(new FixedValueParameter<IntValue>(ParameterOptimizationIterationsParameterName, "Determines how many iterations should be calculated while optimizing the parameter of a symbolic expression tree (0 indicates other or default stopping criterion).", new IntValue(10))); 117 Parameters.Add(new FixedValueParameter<DoubleValue>(ParameterOptimizationImprovementParameterName, "Determines the relative improvement which must be achieved in the parameter optimization to continue with it (0 indicates other or default stopping criterion).", new DoubleValue(0)) { Hidden = true }); 118 Parameters.Add(new FixedValueParameter<PercentValue>(ParameterOptimizationProbabilityParameterName, "Determines the probability that the parameters are optimized", new PercentValue(1))); 119 Parameters.Add(new FixedValueParameter<PercentValue>(ParameterOptimizationRowsPercentageParameterName, "Determines the percentage of the rows which should be used for parameter optimization", new PercentValue(1))); 120 Parameters.Add(new FixedValueParameter<BoolValue>(UpdateParametersInTreeParameterName, "Determines if the parameters in the tree should be overwritten by the optimized parameters.", new BoolValue(true)) { Hidden = true }); 121 121 Parameters.Add(new FixedValueParameter<BoolValue>(UpdateVariableWeightsParameterName, "Determines if the variable weights in the tree should be optimized.", new BoolValue(true)) { Hidden = true }); 122 122 123 123 Parameters.Add(new FixedValueParameter<BoolValue>(CountEvaluationsParameterName, "Determines if function and gradient evaluation should be counted.", new BoolValue(false))); 124 Parameters.Add(new ResultParameter<IntValue>(FunctionEvaluationsResultParameterName, "The number of function evaluations performed by the constants optimization evaluator", "Results", new IntValue()));125 Parameters.Add(new ResultParameter<IntValue>(GradientEvaluationsResultParameterName, "The number of gradient evaluations performed by the constants optimization evaluator", "Results", new IntValue()));124 Parameters.Add(new ResultParameter<IntValue>(FunctionEvaluationsResultParameterName, "The number of function evaluations performed by the parameters optimization evaluator", "Results", new IntValue())); 125 Parameters.Add(new ResultParameter<IntValue>(GradientEvaluationsResultParameterName, "The number of gradient evaluations performed by the parameters optimization evaluator", "Results", new IntValue())); 126 126 } 127 127 128 128 public override IDeepCloneable Clone(Cloner cloner) { 129 return new SymbolicRegression ConstantOptimizationEvaluator(this, cloner);129 return new SymbolicRegressionParameterOptimizationEvaluator(this, cloner); 130 130 } 131 131 132 132 [StorableHook(HookType.AfterDeserialization)] 133 133 private void AfterDeserialization() { 134 if (!Parameters.ContainsKey(UpdateConstantsInTreeParameterName)) 135 Parameters.Add(new FixedValueParameter<BoolValue>(UpdateConstantsInTreeParameterName, "Determines if the constants in the tree should be overwritten by the optimized constants.", new BoolValue(true))); 134 if (!Parameters.ContainsKey(UpdateParametersInTreeParameterName)) { 135 if (Parameters.ContainsKey("UpdateConstantsInSymbolicExpressionTree")) { 136 Parameters.Add(new FixedValueParameter<BoolValue>(UpdateParametersInTreeParameterName, "Determines if the parameters in the tree should be overwritten by the optimized parameters.", (BoolValue)Parameters["UpdateConstantsInSymbolicExpressionTree"].ActualValue)); 137 Parameters.Remove("UpdateConstantsInSymbolicExpressionTree"); 138 } else { 139 Parameters.Add(new FixedValueParameter<BoolValue>(UpdateParametersInTreeParameterName, "Determines if the parameters in the tree should be overwritten by the optimized parameters.", new BoolValue(true))); 140 } 141 } 142 136 143 if (!Parameters.ContainsKey(UpdateVariableWeightsParameterName)) 137 144 Parameters.Add(new FixedValueParameter<BoolValue>(UpdateVariableWeightsParameterName, "Determines if the variable weights in the tree should be optimized.", new BoolValue(true))); … … 140 147 Parameters.Add(new FixedValueParameter<BoolValue>(CountEvaluationsParameterName, "Determines if function and gradient evaluation should be counted.", new BoolValue(false))); 141 148 142 if (!Parameters.ContainsKey(FunctionEvaluationsResultParameterName)) 143 Parameters.Add(new ResultParameter<IntValue>(FunctionEvaluationsResultParameterName, "The number of function evaluations performed by the constants optimization evaluator", "Results", new IntValue())); 144 if (!Parameters.ContainsKey(GradientEvaluationsResultParameterName)) 145 Parameters.Add(new ResultParameter<IntValue>(GradientEvaluationsResultParameterName, "The number of gradient evaluations performed by the constants optimization evaluator", "Results", new IntValue())); 149 if (!Parameters.ContainsKey(FunctionEvaluationsResultParameterName)) { 150 if (Parameters.ContainsKey("Constants Optimization Function Evaluations")) { 151 Parameters.Remove("Constants Optimization Function Evaluations"); 152 } 153 Parameters.Add(new ResultParameter<IntValue>(FunctionEvaluationsResultParameterName, "The number of function evaluations performed by the parameters optimization evaluator", "Results", new IntValue())); 154 } 155 156 if (!Parameters.ContainsKey(GradientEvaluationsResultParameterName)) { 157 if (Parameters.ContainsKey("Constants Optimization Gradient Evaluations")) { 158 Parameters.Remove("Constants Optimization Gradient Evaluations"); 159 } 160 Parameters.Add(new ResultParameter<IntValue>(GradientEvaluationsResultParameterName, "The number of gradient evaluations performed by the parameters optimization evaluator", "Results", new IntValue())); 161 } 162 163 if (!Parameters.ContainsKey(ParameterOptimizationIterationsParameterName)) { 164 if (Parameters.ContainsKey("ConstantOptimizationIterations")) { 165 Parameters.Add(new FixedValueParameter<IntValue>(ParameterOptimizationIterationsParameterName, "Determines how many iterations should be calculated while optimizing the parameter of a symbolic expression tree (0 indicates other or default stopping criterion).", (IntValue)Parameters["ConstantOptimizationIterations"].ActualValue)); 166 Parameters.Remove("ConstantOptimizationIterations"); 167 } else { 168 Parameters.Add(new FixedValueParameter<IntValue>(ParameterOptimizationIterationsParameterName, "Determines how many iterations should be calculated while optimizing the parameter of a symbolic expression tree (0 indicates other or default stopping criterion).", new IntValue(10))); 169 } 170 } 171 172 if (!Parameters.ContainsKey(ParameterOptimizationImprovementParameterName)) { 173 if (Parameters.ContainsKey("CosntantOptimizationImprovement")) { 174 Parameters.Add(new FixedValueParameter<DoubleValue>(ParameterOptimizationImprovementParameterName, "Determines the relative improvement which must be achieved in the parameter optimization to continue with it (0 indicates other or default stopping criterion).", 175 (DoubleValue)Parameters["CosntantOptimizationImprovement"].ActualValue) { Hidden = true }); 176 Parameters.Remove("CosntantOptimizationImprovement"); 177 } else { 178 Parameters.Add(new FixedValueParameter<DoubleValue>(ParameterOptimizationImprovementParameterName, "Determines the relative improvement which must be achieved in the parameter optimization to continue with it (0 indicates other or default stopping criterion).", new DoubleValue(0)) { Hidden = true }); 179 } 180 } 181 182 if (!Parameters.ContainsKey(ParameterOptimizationProbabilityParameterName)) { 183 if (Parameters.ContainsKey("ConstantOptimizationProbability")) { 184 Parameters.Add(new FixedValueParameter<PercentValue>(ParameterOptimizationProbabilityParameterName, "Determines the probability that the parameters are optimized", 185 (PercentValue)Parameters["ConstantOptimizationProbability"].ActualValue)); 186 Parameters.Remove("ConstantOptimizationProbability"); 187 } else { 188 Parameters.Add(new FixedValueParameter<PercentValue>(ParameterOptimizationProbabilityParameterName, "Determines the probability that the parameters are optimized", new PercentValue(1))); 189 } 190 } 191 192 if (!Parameters.ContainsKey(ParameterOptimizationRowsPercentageParameterName)) { 193 if (Parameters.ContainsKey("ConstantOptimizationRowsPercentage")) { 194 Parameters.Add(new FixedValueParameter<PercentValue>(ParameterOptimizationRowsPercentageParameterName, "Determines the percentage of the rows which should be used for parameter optimization", (PercentValue)Parameters["ConstantOptimizationRowsPercentage"].ActualValue)); 195 Parameters.Remove("ConstantOptimizationRowsPercentage"); 196 } else { 197 Parameters.Add(new FixedValueParameter<PercentValue>(ParameterOptimizationRowsPercentageParameterName, "Determines the percentage of the rows which should be used for parameter optimization", new PercentValue(1))); 198 } 199 200 } 146 201 } 147 202 … … 150 205 var solution = SymbolicExpressionTreeParameter.ActualValue; 151 206 double quality; 152 if (RandomParameter.ActualValue.NextDouble() < ConstantOptimizationProbability.Value) {153 IEnumerable<int> constantOptimizationRows = GenerateRowsToEvaluate(ConstantOptimizationRowsPercentage.Value);207 if (RandomParameter.ActualValue.NextDouble() < ParameterOptimizationProbability.Value) { 208 IEnumerable<int> parameterOptimizationRows = GenerateRowsToEvaluate(ParameterOptimizationRowsPercentage.Value); 154 209 var counter = new EvaluationsCounter(); 155 quality = Optimize Constants(SymbolicDataAnalysisTreeInterpreterParameter.ActualValue, solution, ProblemDataParameter.ActualValue,156 constantOptimizationRows, ApplyLinearScalingParameter.ActualValue.Value, ConstantOptimizationIterations.Value, updateVariableWeights: UpdateVariableWeights, lowerEstimationLimit: EstimationLimitsParameter.ActualValue.Lower, upperEstimationLimit: EstimationLimitsParameter.ActualValue.Upper, updateConstantsInTree: UpdateConstantsInTree, counter: counter);157 158 if ( ConstantOptimizationRowsPercentage.Value != RelativeNumberOfEvaluatedSamplesParameter.ActualValue.Value) {210 quality = OptimizeParameters(SymbolicDataAnalysisTreeInterpreterParameter.ActualValue, solution, ProblemDataParameter.ActualValue, 211 parameterOptimizationRows, ApplyLinearScalingParameter.ActualValue.Value, ParameterOptimizationIterations.Value, updateVariableWeights: UpdateVariableWeights, lowerEstimationLimit: EstimationLimitsParameter.ActualValue.Lower, upperEstimationLimit: EstimationLimitsParameter.ActualValue.Upper, updateParametersInTree: UpdateParametersInTree, counter: counter); 212 213 if (ParameterOptimizationRowsPercentage.Value != RelativeNumberOfEvaluatedSamplesParameter.ActualValue.Value) { 159 214 var evaluationRows = GenerateRowsToEvaluate(); 160 215 quality = SymbolicRegressionSingleObjectivePearsonRSquaredEvaluator.Calculate(SymbolicDataAnalysisTreeInterpreterParameter.ActualValue, solution, EstimationLimitsParameter.ActualValue.Lower, EstimationLimitsParameter.ActualValue.Upper, ProblemDataParameter.ActualValue, evaluationRows, ApplyLinearScalingParameter.ActualValue.Value); … … 203 258 } 204 259 205 public static double Optimize Constants(ISymbolicDataAnalysisExpressionTreeInterpreter interpreter,260 public static double OptimizeParameters(ISymbolicDataAnalysisExpressionTreeInterpreter interpreter, 206 261 ISymbolicExpressionTree tree, IRegressionProblemData problemData, IEnumerable<int> rows, bool applyLinearScaling, 207 262 int maxIterations, bool updateVariableWeights = true, 208 263 double lowerEstimationLimit = double.MinValue, double upperEstimationLimit = double.MaxValue, 209 bool update ConstantsInTree = true, Action<double[], double, object> iterationCallback = null, EvaluationsCounter counter = null) {210 211 // Numeric constants in the tree become variables for parameter optimization.264 bool updateParametersInTree = true, Action<double[], double, object> iterationCallback = null, EvaluationsCounter counter = null) { 265 266 // Numeric parameters in the tree become variables for parameter optimization. 212 267 // Variables in the tree become parameters (fixed values) for parameter optimization. 213 268 // For each parameter (variable in the original tree) we store the 214 269 // variable name, variable value (for factor vars) and lag as a DataForVariable object. 215 270 // A dictionary is used to find parameters 216 double[] initial Constants;271 double[] initialParameters; 217 272 var parameters = new List<TreeToAutoDiffTermConverter.DataForVariable>(); 218 273 219 274 TreeToAutoDiffTermConverter.ParametricFunction func; 220 275 TreeToAutoDiffTermConverter.ParametricFunctionGradient func_grad; 221 if (!TreeToAutoDiffTermConverter.TryConvertToAutoDiff(tree, updateVariableWeights, applyLinearScaling, out parameters, out initial Constants, out func, out func_grad))222 throw new NotSupportedException("Could not optimize constants of symbolic expression tree due to not supported symbols used in the tree.");276 if (!TreeToAutoDiffTermConverter.TryConvertToAutoDiff(tree, updateVariableWeights, applyLinearScaling, out parameters, out initialParameters, out func, out func_grad)) 277 throw new NotSupportedException("Could not optimize parameters of symbolic expression tree due to not supported symbols used in the tree."); 223 278 if (parameters.Count == 0) return 0.0; // constant expressions always have a R² of 0.0 224 279 var parameterEntries = parameters.ToArray(); // order of entries must be the same for x 225 280 226 // extract inital constants281 // extract inital parameters 227 282 double[] c; 228 283 if (applyLinearScaling) { 229 c = new double[initial Constants.Length + 2];284 c = new double[initialParameters.Length + 2]; 230 285 c[0] = 0.0; 231 286 c[1] = 1.0; 232 Array.Copy(initial Constants, 0, c, 2, initialConstants.Length);287 Array.Copy(initialParameters, 0, c, 2, initialParameters.Length); 233 288 } else { 234 c = (double[])initial Constants.Clone();289 c = (double[])initialParameters.Clone(); 235 290 } 236 291 … … 283 338 counter.GradientEvaluations += rowEvaluationsCounter.GradientEvaluations / n; 284 339 285 //retVal == -7 => constantoptimization failed due to wrong gradient340 //retVal == -7 => parameter optimization failed due to wrong gradient 286 341 // -8 => optimizer detected NAN / INF in the target 287 342 // function and/ or gradient … … 290 345 var tmp = new double[c.Length - 2]; 291 346 Array.Copy(c, 2, tmp, 0, tmp.Length); 292 Update Constants(tree, tmp, updateVariableWeights);293 } else Update Constants(tree, c, updateVariableWeights);347 UpdateParameters(tree, tmp, updateVariableWeights); 348 } else UpdateParameters(tree, c, updateVariableWeights); 294 349 } 295 350 var quality = SymbolicRegressionSingleObjectivePearsonRSquaredEvaluator.Calculate(interpreter, tree, lowerEstimationLimit, upperEstimationLimit, problemData, rows, applyLinearScaling); 296 351 297 if (!update ConstantsInTree) UpdateConstants(tree, initialConstants, updateVariableWeights);352 if (!updateParametersInTree) UpdateParameters(tree, initialParameters, updateVariableWeights); 298 353 299 354 if (originalQuality - quality > 0.001 || double.IsNaN(quality)) { 300 Update Constants(tree, initialConstants, updateVariableWeights);355 UpdateParameters(tree, initialParameters, updateVariableWeights); 301 356 return originalQuality; 302 357 } … … 304 359 } 305 360 306 private static void Update Constants(ISymbolicExpressionTree tree, double[] constants, bool updateVariableWeights) {361 private static void UpdateParameters(ISymbolicExpressionTree tree, double[] parameters, bool updateVariableWeights) { 307 362 int i = 0; 308 363 foreach (var node in tree.Root.IterateNodesPrefix().OfType<SymbolicExpressionTreeTerminalNode>()) { … … 313 368 if (numberTreeNode.Parent.Symbol is Power 314 369 && numberTreeNode.Parent.GetSubtree(1) == numberTreeNode) continue; // exponents in powers are not optimizated (see TreeToAutoDiffTermConverter) 315 numberTreeNode.Value = constants[i++];370 numberTreeNode.Value = parameters[i++]; 316 371 } else if (updateVariableWeights && variableTreeNodeBase != null) 317 variableTreeNodeBase.Weight = constants[i++];372 variableTreeNodeBase.Weight = parameters[i++]; 318 373 else if (factorVarTreeNode != null) { 319 374 for (int j = 0; j < factorVarTreeNode.Weights.Length; j++) 320 factorVarTreeNode.Weights[j] = constants[i++];375 factorVarTreeNode.Weights[j] = parameters[i++]; 321 376 } 322 377 } … … 340 395 }; 341 396 } 342 public static bool CanOptimize Constants(ISymbolicExpressionTree tree) {397 public static bool CanOptimizeParameters(ISymbolicExpressionTree tree) { 343 398 return TreeToAutoDiffTermConverter.IsCompatible(tree); 344 399 } -
branches/3140_NumberSymbol/HeuristicLab.Problems.DataAnalysis.Symbolic.Regression/3.4/SingleObjective/ParameterOptimizationAnalyzer.cs
r18112 r18113 32 32 namespace HeuristicLab.Problems.DataAnalysis.Symbolic.Regression { 33 33 /// <summary> 34 /// An operator that optimizes the constants for the best symbolic expression tress in the current generation.34 /// An operator that optimizes the parameters for the best symbolic expression tress in the current generation. 35 35 /// </summary> 36 [Item(" ConstantOptimizationAnalyzer", "An operator that performs a constantoptimization on the best symbolic expression trees.")]36 [Item("ParameterOptimizationAnalyzer", "An operator that performs a parameter optimization on the best symbolic expression trees.")] 37 37 [StorableType("9FB87E7B-A9E2-49DD-A92A-78BD9FC17916")] 38 public sealed class ConstantOptimizationAnalyzer : SymbolicDataAnalysisSingleObjectiveAnalyzer, IStatefulItem {38 public sealed class ParameterOptimizationAnalyzer : SymbolicDataAnalysisSingleObjectiveAnalyzer, IStatefulItem { 39 39 private const string PercentageOfBestSolutionsParameterName = "PercentageOfBestSolutions"; 40 private const string ConstantOptimizationEvaluatorParameterName = "ConstantOptimizationOperator";40 private const string ParameterOptimizationEvaluatorParameterName = "ParameterOptimizationOperator"; 41 41 42 private const string DataTableName ConstantOptimizationImprovement = "ConstantOptimization Improvement";42 private const string DataTableNameParameterOptimizationImprovement = "Parameter Optimization Improvement"; 43 43 private const string DataRowNameMinimumImprovement = "Minimum improvement"; 44 44 private const string DataRowNameMedianImprovement = "Median improvement"; … … 51 51 } 52 52 53 public IFixedValueParameter<SymbolicRegression ConstantOptimizationEvaluator> ConstantOptimizationEvaluatorParameter {54 get { return (IFixedValueParameter<SymbolicRegression ConstantOptimizationEvaluator>)Parameters[ConstantOptimizationEvaluatorParameterName]; }53 public IFixedValueParameter<SymbolicRegressionParameterOptimizationEvaluator> ParameterOptimizationEvaluatorParameter { 54 get { return (IFixedValueParameter<SymbolicRegressionParameterOptimizationEvaluator>)Parameters[ParameterOptimizationEvaluatorParameterName]; } 55 55 } 56 56 #endregion 57 57 58 58 #region properties 59 public SymbolicRegression ConstantOptimizationEvaluator ConstantOptimizationEvaluator {60 get { return ConstantOptimizationEvaluatorParameter.Value; }59 public SymbolicRegressionParameterOptimizationEvaluator ParameterOptimizationEvaluator { 60 get { return ParameterOptimizationEvaluatorParameter.Value; } 61 61 } 62 62 public double PercentageOfBestSolutions { … … 64 64 } 65 65 66 private DataTable ConstantOptimizationImprovementDataTable {66 private DataTable ParameterOptimizationImprovementDataTable { 67 67 get { 68 68 IResult result; 69 ResultCollection.TryGetValue(DataTableName ConstantOptimizationImprovement, out result);69 ResultCollection.TryGetValue(DataTableNameParameterOptimizationImprovement, out result); 70 70 if (result == null) return null; 71 71 return (DataTable)result.Value; … … 73 73 } 74 74 private DataRow MinimumImprovement { 75 get { return ConstantOptimizationImprovementDataTable.Rows[DataRowNameMinimumImprovement]; }75 get { return ParameterOptimizationImprovementDataTable.Rows[DataRowNameMinimumImprovement]; } 76 76 } 77 77 private DataRow MedianImprovement { 78 get { return ConstantOptimizationImprovementDataTable.Rows[DataRowNameMedianImprovement]; }78 get { return ParameterOptimizationImprovementDataTable.Rows[DataRowNameMedianImprovement]; } 79 79 } 80 80 private DataRow AverageImprovement { 81 get { return ConstantOptimizationImprovementDataTable.Rows[DataRowNameAverageImprovement]; }81 get { return ParameterOptimizationImprovementDataTable.Rows[DataRowNameAverageImprovement]; } 82 82 } 83 83 private DataRow MaximumImprovement { 84 get { return ConstantOptimizationImprovementDataTable.Rows[DataRowNameMaximumImprovement]; }84 get { return ParameterOptimizationImprovementDataTable.Rows[DataRowNameMaximumImprovement]; } 85 85 } 86 86 #endregion 87 87 88 88 [StorableConstructor] 89 private ConstantOptimizationAnalyzer(StorableConstructorFlag _) : base(_) { }90 private ConstantOptimizationAnalyzer(ConstantOptimizationAnalyzer original, Cloner cloner) : base(original, cloner) { }91 public override IDeepCloneable Clone(Cloner cloner) { return new ConstantOptimizationAnalyzer(this, cloner); }92 public ConstantOptimizationAnalyzer()89 private ParameterOptimizationAnalyzer(StorableConstructorFlag _) : base(_) { } 90 private ParameterOptimizationAnalyzer(ParameterOptimizationAnalyzer original, Cloner cloner) : base(original, cloner) { } 91 public override IDeepCloneable Clone(Cloner cloner) { return new ParameterOptimizationAnalyzer(this, cloner); } 92 public ParameterOptimizationAnalyzer() 93 93 : base() { 94 94 Parameters.Add(new FixedValueParameter<PercentValue>(PercentageOfBestSolutionsParameterName, "The percentage of the top solutions which should be analyzed.", new PercentValue(0.1))); 95 Parameters.Add(new FixedValueParameter<SymbolicRegression ConstantOptimizationEvaluator>(ConstantOptimizationEvaluatorParameterName, "The operator used to perform the constantoptimization"));95 Parameters.Add(new FixedValueParameter<SymbolicRegressionParameterOptimizationEvaluator>(ParameterOptimizationEvaluatorParameterName, "The operator used to perform the parameter optimization")); 96 96 97 97 //Changed the ActualName of the EvaluationPartitionParameter so that it matches the parameter name of symbolic regression problems. 98 ConstantOptimizationEvaluator.EvaluationPartitionParameter.ActualName = "FitnessCalculationPartition"; 98 ParameterOptimizationEvaluator.EvaluationPartitionParameter.ActualName = "FitnessCalculationPartition"; 99 } 100 101 [StorableHook(HookType.AfterDeserialization)] 102 private void AfterDeserialization() { 103 if (!Parameters.ContainsKey(ParameterOptimizationEvaluatorParameterName)) { 104 if (Parameters.ContainsKey("ConstantOptimizationOperator")) { 105 Parameters.Add(new FixedValueParameter<SymbolicRegressionParameterOptimizationEvaluator>(ParameterOptimizationEvaluatorParameterName, "The operator used to perform the parameter optimization")); 106 Parameters.Remove("ConstantOptimizationOperator"); 107 } else { 108 Parameters.Add(new FixedValueParameter<SymbolicRegressionParameterOptimizationEvaluator>(ParameterOptimizationEvaluatorParameterName, "The operator used to perform the parameter optimization")); 109 } 110 } 99 111 } 100 112 … … 134 146 operationCollection.Parallel = true; 135 147 foreach (var scopeIndex in scopeIndexes) { 136 var childOperation = ExecutionContext.CreateChildOperation( ConstantOptimizationEvaluator, ExecutionContext.Scope.SubScopes[scopeIndex]);148 var childOperation = ExecutionContext.CreateChildOperation(ParameterOptimizationEvaluator, ExecutionContext.Scope.SubScopes[scopeIndex]); 137 149 operationCollection.Add(childOperation); 138 150 } … … 141 153 } 142 154 143 //code executed to analyze results of constantoptimization155 //code executed to analyze results of parameter optimization 144 156 double[] qualitiesAfterCoOp = scopeIndexes.Select(x => Quality[x].Value).ToArray(); 145 157 var qualityImprovement = qualitiesBeforeCoOp.Zip(qualitiesAfterCoOp, (b, a) => a - b).ToArray(); 146 158 147 if (!ResultCollection.ContainsKey(DataTableName ConstantOptimizationImprovement)) {148 var dataTable = new DataTable(DataTableName ConstantOptimizationImprovement);149 ResultCollection.Add(new Result(DataTableName ConstantOptimizationImprovement, dataTable));159 if (!ResultCollection.ContainsKey(DataTableNameParameterOptimizationImprovement)) { 160 var dataTable = new DataTable(DataTableNameParameterOptimizationImprovement); 161 ResultCollection.Add(new Result(DataTableNameParameterOptimizationImprovement, dataTable)); 150 162 dataTable.VisualProperties.YAxisTitle = "R²"; 151 163 -
branches/3140_NumberSymbol/HeuristicLab.Problems.DataAnalysis.Symbolic/3.4/Converters/DerivativeCalculator.cs
r17902 r18113 41 41 } 42 42 43 private static readonly Constant constantSy = new Constant(); 43 private static readonly Number numberSy = new Number(); 44 private static readonly Constant constSy = new Constant(); 44 45 private static readonly Addition addSy = new Addition(); 45 46 private static readonly Subtraction subSy = new Subtraction(); … … 52 53 53 54 public static ISymbolicExpressionTreeNode Derive(ISymbolicExpressionTreeNode branch, string variableName) { 54 if (branch.Symbol is Constant) {55 return Create Constant(0.0);55 if (branch.Symbol is INumericSymbol) { 56 return CreateNumber(0.0); 56 57 } 57 58 if (branch.Symbol is Variable) { 58 59 var varNode = branch as VariableTreeNode; 59 60 if (varNode.VariableName == variableName) { 60 return Create Constant(varNode.Weight);61 return CreateNumber(varNode.Weight); 61 62 } else { 62 return Create Constant(0.0);63 return CreateNumber(0.0); 63 64 } 64 65 } … … 102 103 if (branch.SubtreeCount == 1) { 103 104 var g = (ISymbolicExpressionTreeNode)branch.GetSubtree(0).Clone(); 104 var gPrime = Product(Create Constant(-1.0), Derive(g, variableName));105 var gPrime = Product(CreateNumber(-1.0), Derive(g, variableName)); 105 106 var sqrNode = new Square().CreateTreeNode(); 106 107 sqrNode.AddSubtree(g); … … 125 126 if (branch.Symbol is Logarithm) { 126 127 var f = (ISymbolicExpressionTreeNode)branch.GetSubtree(0).Clone(); 127 return Product(Div(Create Constant(1.0), f), Derive(f, variableName));128 return Product(Div(CreateNumber(1.0), f), Derive(f, variableName)); 128 129 } 129 130 if (branch.Symbol is Exponential) { … … 133 134 if (branch.Symbol is Square) { 134 135 var f = (ISymbolicExpressionTreeNode)branch.GetSubtree(0).Clone(); 135 return Product(Product(Create Constant(2.0), f), Derive(f, variableName));136 return Product(Product(CreateNumber(2.0), f), Derive(f, variableName)); 136 137 } 137 138 if (branch.Symbol is SquareRoot) { 138 139 var f = (ISymbolicExpressionTreeNode)branch.Clone(); 139 140 var u = (ISymbolicExpressionTreeNode)branch.GetSubtree(0).Clone(); 140 return Product(Div(Create Constant(1.0), Product(CreateConstant(2.0), f)), Derive(u, variableName));141 return Product(Div(CreateNumber(1.0), Product(CreateNumber(2.0), f)), Derive(u, variableName)); 141 142 } 142 143 if (branch.Symbol is CubeRoot) { 143 144 var f = (ISymbolicExpressionTreeNode)branch.Clone(); 144 145 var u = (ISymbolicExpressionTreeNode)branch.GetSubtree(0).Clone(); 145 return Product(Div(Create Constant(1.0), Product(CreateConstant(3.0), Square(f))), Derive(u, variableName)); // 1/3 1/cbrt(f(x))^2 d/dx f(x)146 return Product(Div(CreateNumber(1.0), Product(CreateNumber(3.0), Square(f))), Derive(u, variableName)); // 1/3 1/cbrt(f(x))^2 d/dx f(x) 146 147 } 147 148 if (branch.Symbol is Cube) { 148 149 var f = (ISymbolicExpressionTreeNode)branch.GetSubtree(0).Clone(); 149 return Product(Product(Create Constant(3.0), Square(f)), Derive(f, variableName));150 return Product(Product(CreateNumber(3.0), Square(f)), Derive(f, variableName)); 150 151 } 151 152 if (branch.Symbol is Power) { 152 153 // HL evaluators handle power strangely (exponent is rounded to an integer) 153 154 // here we only support the case when the exponent is a constant integer 154 var exponent = branch.GetSubtree(1) as ConstantTreeNode;155 var exponent = branch.GetSubtree(1) as INumericTreeNode; 155 156 if (exponent != null && Math.Truncate(exponent.Value) == exponent.Value) { 156 157 var newPower = (ISymbolicExpressionTreeNode)branch.Clone(); 157 158 var f = (ISymbolicExpressionTreeNode)newPower.GetSubtree(0).Clone(); 158 var newExponent = ( ConstantTreeNode)newPower.GetSubtree(1);159 var newExponent = (INumericTreeNode)newPower.GetSubtree(1); 159 160 newExponent.Value -= 1; 160 return Product(Product(Create Constant(exponent.Value), newPower), Derive(f, variableName));161 return Product(Product(CreateNumber(exponent.Value), newPower), Derive(f, variableName)); 161 162 } else throw new NotSupportedException("Cannot derive non-integer powers"); 162 163 } … … 171 172 var b = (ISymbolicExpressionTreeNode)branch.GetSubtree(1).Clone(); 172 173 173 var definition = Div(a, SquareRoot(Sum(Square(b), Create Constant(1.0))));174 var definition = Div(a, SquareRoot(Sum(Square(b), CreateNumber(1.0)))); 174 175 return Derive(definition, variableName); 175 176 } … … 184 185 var sin = (new Sine()).CreateTreeNode(); 185 186 sin.AddSubtree(u); 186 return Product(Create Constant(-1.0), Product(sin, Derive(u, variableName)));187 return Product(CreateNumber(-1.0), Product(sin, Derive(u, variableName))); 187 188 } 188 189 if (branch.Symbol is Tangent) { … … 196 197 var fxp = Derive(branch.GetSubtree(0), variableName); 197 198 var tanh = (ISymbolicExpressionTreeNode)branch.Clone(); 198 return Product(fxp, Subtract(Create Constant(1.0), Square(tanh)));199 return Product(fxp, Subtract(CreateNumber(1.0), Square(tanh))); 199 200 } 200 201 throw new NotSupportedException(string.Format("Symbol {0} is not supported.", branch.Symbol)); … … 253 254 } 254 255 255 private static ISymbolicExpressionTreeNode Create Constant(double v) {256 var constNode = (ConstantTreeNode)constantSy.CreateTreeNode();257 constNode.Value = v;258 return constNode;256 private static ISymbolicExpressionTreeNode CreateNumber(double v) { 257 var numberNode = (NumberTreeNode)numberSy.CreateTreeNode(); 258 numberNode.Value = v; 259 return numberNode; 259 260 } 260 261 … … 264 265 where 265 266 !(n.Symbol is Variable) && 267 !(n.Symbol is Number) && 266 268 !(n.Symbol is Constant) && 267 269 !(n.Symbol is Addition) && -
branches/3140_NumberSymbol/HeuristicLab.Problems.DataAnalysis.Symbolic/3.4/Converters/TreeSimplifier.cs
r17963 r18113 36 36 private static readonly Multiplication mulSymbol = new Multiplication(); 37 37 private static readonly Division divSymbol = new Division(); 38 private static readonly Number numberSymbol = new Number(); 38 39 private static readonly Constant constSymbol = new Constant(); 39 40 private static readonly Absolute absSymbol = new Absolute(); … … 240 241 } 241 242 243 private static bool IsNumber(ISymbolicExpressionTreeNode node) { 244 return node.Symbol is Number; 245 } 246 242 247 private static bool IsConstant(ISymbolicExpressionTreeNode node) { 243 248 return node.Symbol is Constant; 244 249 } 245 246 250 // dynamic 247 251 private static bool IsTimeLag(ISymbolicExpressionTreeNode node) { … … 261 265 /// <returns></returns> 262 266 public static ISymbolicExpressionTreeNode GetSimplifiedTree(ISymbolicExpressionTreeNode original) { 263 if (Is Constant(original) || IsVariableBase(original)) {267 if (IsNumber(original) || IsConstant(original) || IsVariableBase(original)) { 264 268 return (ISymbolicExpressionTreeNode)original.Clone(); 265 269 } else if (IsAbsolute(original)) { … … 335 339 clone.AddSubtree(simplifiedSubtree); 336 340 } 337 if (simplifiedSubtrees.TrueForAll( t => IsConstant(t))) {341 if (simplifiedSubtrees.TrueForAll(IsNumber)) { 338 342 SimplifyConstantExpression(clone); 339 343 } … … 501 505 var laggedTreeNode = original as ILaggedTreeNode; 502 506 var simplifiedSubtree = GetSimplifiedTree(original.GetSubtree(0)); 503 if (Is Constant(simplifiedSubtree)) {507 if (IsNumber(simplifiedSubtree)) { 504 508 return GetSimplifiedTree(MakeProduct(simplifiedSubtree, MakeConstant(-laggedTreeNode.Lag))); 505 509 } else { … … 514 518 private static ISymbolicExpressionTreeNode MakeTimeLag(ISymbolicExpressionTreeNode subtree, int lag) { 515 519 if (lag == 0) return subtree; 516 if (Is Constant(subtree)) return subtree;520 if (IsNumber(subtree)) return subtree; 517 521 var lagNode = (LaggedTreeNode)timeLagSymbol.CreateTreeNode(); 518 522 lagNode.Lag = lag; … … 534 538 535 539 private static ISymbolicExpressionTreeNode MakeNot(ISymbolicExpressionTreeNode t) { 536 if (Is Constant(t)) {537 var constNode = t as ConstantTreeNode;540 if (IsNumber(t)) { 541 var constNode = t as NumberTreeNode; 538 542 if (constNode.Value > 0) return MakeConstant(-1.0); 539 543 else return MakeConstant(1.0); … … 555 559 556 560 private static ISymbolicExpressionTreeNode MakeOr(ISymbolicExpressionTreeNode a, ISymbolicExpressionTreeNode b) { 557 if (Is Constant(a) && IsConstant(b)) {558 var constA = a as ConstantTreeNode;559 var constB = b as ConstantTreeNode;561 if (IsNumber(a) && IsNumber(b)) { 562 var constA = a as NumberTreeNode; 563 var constB = b as NumberTreeNode; 560 564 if (constA.Value > 0.0 || constB.Value > 0.0) { 561 565 return MakeConstant(1.0); … … 563 567 return MakeConstant(-1.0); 564 568 } 565 } else if (Is Constant(a)) {569 } else if (IsNumber(a)) { 566 570 return MakeOr(b, a); 567 } else if (Is Constant(b)) {568 var constT = b as ConstantTreeNode;571 } else if (IsNumber(b)) { 572 var constT = b as NumberTreeNode; 569 573 if (constT.Value > 0.0) { 570 574 // boolean expression is necessarily true … … 585 589 586 590 private static ISymbolicExpressionTreeNode MakeAnd(ISymbolicExpressionTreeNode a, ISymbolicExpressionTreeNode b) { 587 if (Is Constant(a) && IsConstant(b)) {588 var constA = a as ConstantTreeNode;589 var constB = b as ConstantTreeNode;591 if (IsNumber(a) && IsNumber(b)) { 592 var constA = a as NumberTreeNode; 593 var constB = b as NumberTreeNode; 590 594 if (constA.Value > 0.0 && constB.Value > 0.0) { 591 595 return MakeConstant(1.0); … … 593 597 return MakeConstant(-1.0); 594 598 } 595 } else if (Is Constant(a)) {599 } else if (IsNumber(a)) { 596 600 return MakeAnd(b, a); 597 } else if (Is Constant(b)) {598 var constB = b as ConstantTreeNode;601 } else if (IsNumber(b)) { 602 var constB = b as NumberTreeNode; 599 603 if (constB.Value > 0.0) { 600 604 // the constant value has no effect on the result of the boolean condition so we can drop the constant term … … 616 620 private static ISymbolicExpressionTreeNode MakeLessThan(ISymbolicExpressionTreeNode leftSide, 617 621 ISymbolicExpressionTreeNode rightSide) { 618 if (Is Constant(leftSide) && IsConstant(rightSide)) {619 var lsConst = leftSide as ConstantTreeNode;620 var rsConst = rightSide as ConstantTreeNode;622 if (IsNumber(leftSide) && IsNumber(rightSide)) { 623 var lsConst = leftSide as NumberTreeNode; 624 var rsConst = rightSide as NumberTreeNode; 621 625 if (lsConst.Value < rsConst.Value) return MakeConstant(1.0); 622 626 else return MakeConstant(-1.0); … … 631 635 private static ISymbolicExpressionTreeNode MakeGreaterThan(ISymbolicExpressionTreeNode leftSide, 632 636 ISymbolicExpressionTreeNode rightSide) { 633 if (Is Constant(leftSide) && IsConstant(rightSide)) {634 var lsConst = leftSide as ConstantTreeNode;635 var rsConst = rightSide as ConstantTreeNode;637 if (IsNumber(leftSide) && IsNumber(rightSide)) { 638 var lsConst = leftSide as NumberTreeNode; 639 var rsConst = rightSide as NumberTreeNode; 636 640 if (lsConst.Value > rsConst.Value) return MakeConstant(1.0); 637 641 else return MakeConstant(-1.0); … … 646 650 private static ISymbolicExpressionTreeNode MakeIfThenElse(ISymbolicExpressionTreeNode condition, 647 651 ISymbolicExpressionTreeNode trueBranch, ISymbolicExpressionTreeNode falseBranch) { 648 if (Is Constant(condition)) {649 var constT = condition as ConstantTreeNode;652 if (IsNumber(condition)) { 653 var constT = condition as NumberTreeNode; 650 654 if (constT.Value > 0.0) return trueBranch; 651 655 else return falseBranch; … … 667 671 668 672 private static ISymbolicExpressionTreeNode MakeSine(ISymbolicExpressionTreeNode node) { 669 if (Is Constant(node)) {670 var constT = node as ConstantTreeNode;673 if (IsNumber(node)) { 674 var constT = node as NumberTreeNode; 671 675 return MakeConstant(Math.Sin(constT.Value)); 672 676 } else if (IsFactor(node)) { … … 684 688 685 689 private static ISymbolicExpressionTreeNode MakeTangent(ISymbolicExpressionTreeNode node) { 686 if (Is Constant(node)) {687 var constT = node as ConstantTreeNode;690 if (IsNumber(node)) { 691 var constT = node as NumberTreeNode; 688 692 return MakeConstant(Math.Tan(constT.Value)); 689 693 } else if (IsFactor(node)) { … … 701 705 702 706 private static ISymbolicExpressionTreeNode MakeCosine(ISymbolicExpressionTreeNode node) { 703 if (Is Constant(node)) {704 var constT = node as ConstantTreeNode;707 if (IsNumber(node)) { 708 var constT = node as NumberTreeNode; 705 709 return MakeConstant(Math.Cos(constT.Value)); 706 710 } else if (IsFactor(node)) { … … 720 724 721 725 private static ISymbolicExpressionTreeNode MakeExp(ISymbolicExpressionTreeNode node) { 722 if (Is Constant(node)) {723 var constT = node as ConstantTreeNode;726 if (IsNumber(node)) { 727 var constT = node as NumberTreeNode; 724 728 return MakeConstant(Math.Exp(constT.Value)); 725 729 } else if (IsFactor(node)) { … … 744 748 } 745 749 private static ISymbolicExpressionTreeNode MakeLog(ISymbolicExpressionTreeNode node) { 746 if (Is Constant(node)) {747 var constT = node as ConstantTreeNode;750 if (IsNumber(node)) { 751 var constT = node as NumberTreeNode; 748 752 return MakeConstant(Math.Log(constT.Value)); 749 753 } else if (IsFactor(node)) { … … 762 766 763 767 private static ISymbolicExpressionTreeNode MakeSquare(ISymbolicExpressionTreeNode node) { 764 if (Is Constant(node)) {765 var constT = node as ConstantTreeNode;768 if (IsNumber(node)) { 769 var constT = node as NumberTreeNode; 766 770 return MakeConstant(constT.Value * constT.Value); 767 771 } else if (IsFactor(node)) { … … 796 800 797 801 private static ISymbolicExpressionTreeNode MakeCube(ISymbolicExpressionTreeNode node) { 798 if (Is Constant(node)) {799 var constT = node as ConstantTreeNode;802 if (IsNumber(node)) { 803 var constT = node as NumberTreeNode; 800 804 return MakeConstant(constT.Value * constT.Value * constT.Value); 801 805 } else if (IsFactor(node)) { … … 821 825 822 826 private static ISymbolicExpressionTreeNode MakeAbs(ISymbolicExpressionTreeNode node) { 823 if (Is Constant(node)) {824 var constT = node as ConstantTreeNode;827 if (IsNumber(node)) { 828 var constT = node as NumberTreeNode; 825 829 return MakeConstant(Math.Abs(constT.Value)); 826 830 } else if (IsFactor(node)) { … … 853 857 // constant folding only 854 858 private static ISymbolicExpressionTreeNode MakeAnalyticalQuotient(ISymbolicExpressionTreeNode a, ISymbolicExpressionTreeNode b) { 855 if (Is Constant(b)) {856 var c = b as ConstantTreeNode;859 if (IsNumber(b)) { 860 var c = b as NumberTreeNode; 857 861 return MakeFraction(a, MakeConstant(Math.Sqrt(1.0 + c.Value * c.Value))); 858 862 } else if (IsFactor(b)) { … … 871 875 872 876 private static ISymbolicExpressionTreeNode MakeSquareRoot(ISymbolicExpressionTreeNode node) { 873 if (Is Constant(node)) {874 var constT = node as ConstantTreeNode;877 if (IsNumber(node)) { 878 var constT = node as NumberTreeNode; 875 879 return MakeConstant(Math.Sqrt(constT.Value)); 876 880 } else if (IsFactor(node)) { … … 890 894 891 895 private static ISymbolicExpressionTreeNode MakeCubeRoot(ISymbolicExpressionTreeNode node) { 892 if (Is Constant(node)) {893 var constT = node as ConstantTreeNode;896 if (IsNumber(node)) { 897 var constT = node as NumberTreeNode; 894 898 return MakeConstant(Math.Pow(constT.Value, 1.0 / 3.0)); 895 899 } else if (IsFactor(node)) { … … 909 913 910 914 private static ISymbolicExpressionTreeNode MakeRoot(ISymbolicExpressionTreeNode a, ISymbolicExpressionTreeNode b) { 911 if (Is Constant(a) && IsConstant(b)) {912 var constA = a as ConstantTreeNode;913 var constB = b as ConstantTreeNode;915 if (IsNumber(a) && IsNumber(b)) { 916 var constA = a as NumberTreeNode; 917 var constB = b as NumberTreeNode; 914 918 return MakeConstant(Math.Pow(constA.Value, 1.0 / Math.Round(constB.Value))); 915 } else if (IsFactor(a) && Is Constant(b)) {919 } else if (IsFactor(a) && IsNumber(b)) { 916 920 var factNode = a as FactorVariableTreeNode; 917 var constNode = b as ConstantTreeNode;921 var constNode = b as NumberTreeNode; 918 922 return MakeFactor(factNode.Symbol, factNode.VariableName, 919 923 factNode.Weights.Select(w => Math.Pow(w, 1.0 / Math.Round(constNode.Value)))); 920 } else if (IsBinFactor(a) && Is Constant(b)) {924 } else if (IsBinFactor(a) && IsNumber(b)) { 921 925 var binFactor = a as BinaryFactorVariableTreeNode; 922 var constNode = b as ConstantTreeNode;926 var constNode = b as NumberTreeNode; 923 927 return MakeBinFactor(binFactor.Symbol, binFactor.VariableName, binFactor.VariableValue, Math.Pow(binFactor.Weight, 1.0 / Math.Round(constNode.Value))); 924 } else if (Is Constant(a) && IsFactor(b)) {925 var constNode = a as ConstantTreeNode;928 } else if (IsNumber(a) && IsFactor(b)) { 929 var constNode = a as NumberTreeNode; 926 930 var factNode = b as FactorVariableTreeNode; 927 931 return MakeFactor(factNode.Symbol, factNode.VariableName, factNode.Weights.Select(w => Math.Pow(constNode.Value, 1.0 / Math.Round(w)))); 928 } else if (Is Constant(a) && IsBinFactor(b)) {929 var constNode = a as ConstantTreeNode;932 } else if (IsNumber(a) && IsBinFactor(b)) { 933 var constNode = a as NumberTreeNode; 930 934 var factNode = b as BinaryFactorVariableTreeNode; 931 935 return MakeBinFactor(factNode.Symbol, factNode.VariableName, factNode.VariableValue, Math.Pow(constNode.Value, 1.0 / Math.Round(factNode.Weight))); … … 934 938 var node1 = b as FactorVariableTreeNode; 935 939 return MakeFactor(node0.Symbol, node0.VariableName, node0.Weights.Zip(node1.Weights, (u, v) => Math.Pow(u, 1.0 / Math.Round(v)))); 936 } else if (Is Constant(b)) {937 var constB = b as ConstantTreeNode;940 } else if (IsNumber(b)) { 941 var constB = b as NumberTreeNode; 938 942 var constBValue = Math.Round(constB.Value); 939 943 if (constBValue == 1.0) { … … 969 973 970 974 private static ISymbolicExpressionTreeNode MakePower(ISymbolicExpressionTreeNode a, ISymbolicExpressionTreeNode b) { 971 if (Is Constant(a) && IsConstant(b)) {972 var constA = a as ConstantTreeNode;973 var constB = b as ConstantTreeNode;975 if (IsNumber(a) && IsNumber(b)) { 976 var constA = a as NumberTreeNode; 977 var constB = b as NumberTreeNode; 974 978 return MakeConstant(Math.Pow(constA.Value, Math.Round(constB.Value))); 975 } else if (IsFactor(a) && Is Constant(b)) {979 } else if (IsFactor(a) && IsNumber(b)) { 976 980 var factNode = a as FactorVariableTreeNode; 977 var constNode = b as ConstantTreeNode;981 var constNode = b as NumberTreeNode; 978 982 return MakeFactor(factNode.Symbol, factNode.VariableName, factNode.Weights.Select(w => Math.Pow(w, Math.Round(constNode.Value)))); 979 } else if (IsBinFactor(a) && Is Constant(b)) {983 } else if (IsBinFactor(a) && IsNumber(b)) { 980 984 var binFactor = a as BinaryFactorVariableTreeNode; 981 var constNode = b as ConstantTreeNode;985 var constNode = b as NumberTreeNode; 982 986 return MakeBinFactor(binFactor.Symbol, binFactor.VariableName, binFactor.VariableValue, Math.Pow(binFactor.Weight, Math.Round(constNode.Value))); 983 } else if (Is Constant(a) && IsFactor(b)) {984 var constNode = a as ConstantTreeNode;987 } else if (IsNumber(a) && IsFactor(b)) { 988 var constNode = a as NumberTreeNode; 985 989 var factNode = b as FactorVariableTreeNode; 986 990 return MakeFactor(factNode.Symbol, factNode.VariableName, factNode.Weights.Select(w => Math.Pow(constNode.Value, Math.Round(w)))); 987 } else if (Is Constant(a) && IsBinFactor(b)) {988 var constNode = a as ConstantTreeNode;991 } else if (IsNumber(a) && IsBinFactor(b)) { 992 var constNode = a as NumberTreeNode; 989 993 var factNode = b as BinaryFactorVariableTreeNode; 990 994 return MakeBinFactor(factNode.Symbol, factNode.VariableName, factNode.VariableValue, Math.Pow(constNode.Value, Math.Round(factNode.Weight))); … … 993 997 var node1 = b as FactorVariableTreeNode; 994 998 return MakeFactor(node0.Symbol, node0.VariableName, node0.Weights.Zip(node1.Weights, (u, v) => Math.Pow(u, Math.Round(v)))); 995 } else if (Is Constant(b)) {996 var constB = b as ConstantTreeNode;999 } else if (IsNumber(b)) { 1000 var constB = b as NumberTreeNode; 997 1001 double exponent = Math.Round(constB.Value); 998 1002 if (exponent == 0.0) { … … 1028 1032 // MakeFraction, MakeProduct and MakeSum take two already simplified trees and create a new simplified tree 1029 1033 private static ISymbolicExpressionTreeNode MakeFraction(ISymbolicExpressionTreeNode a, ISymbolicExpressionTreeNode b) { 1030 if (Is Constant(a) && IsConstant(b)) {1034 if (IsNumber(a) && IsNumber(b)) { 1031 1035 // fold constants 1032 return MakeConstant((( ConstantTreeNode)a).Value / ((ConstantTreeNode)b).Value);1033 } else if ((Is Constant(a) && ((ConstantTreeNode)a).Value != 1.0)) {1036 return MakeConstant(((NumberTreeNode)a).Value / ((NumberTreeNode)b).Value); 1037 } else if ((IsNumber(a) && ((NumberTreeNode)a).Value != 1.0)) { 1034 1038 // a / x => (a * 1/a) / (x * 1/a) => 1 / (x * 1/a) 1035 1039 return MakeFraction(MakeConstant(1.0), MakeProduct(b, Invert(a))); 1036 } else if (IsVariableBase(a) && Is Constant(b)) {1040 } else if (IsVariableBase(a) && IsNumber(b)) { 1037 1041 // merge constant values into variable weights 1038 var constB = (( ConstantTreeNode)b).Value;1042 var constB = ((NumberTreeNode)b).Value; 1039 1043 ((VariableTreeNodeBase)a).Weight /= constB; 1040 1044 return a; 1041 } else if (IsFactor(a) && Is Constant(b)) {1045 } else if (IsFactor(a) && IsNumber(b)) { 1042 1046 var factNode = a as FactorVariableTreeNode; 1043 var constNode = b as ConstantTreeNode;1047 var constNode = b as NumberTreeNode; 1044 1048 return MakeFactor(factNode.Symbol, factNode.VariableName, factNode.Weights.Select(w => w / constNode.Value)); 1045 } else if (IsBinFactor(a) && Is Constant(b)) {1049 } else if (IsBinFactor(a) && IsNumber(b)) { 1046 1050 var factNode = a as BinaryFactorVariableTreeNode; 1047 var constNode = b as ConstantTreeNode;1051 var constNode = b as NumberTreeNode; 1048 1052 return MakeBinFactor(factNode.Symbol, factNode.VariableName, factNode.VariableValue, factNode.Weight / constNode.Value); 1049 1053 } else if (IsFactor(a) && IsFactor(b) && AreSameTypeAndVariable(a, b)) { … … 1070 1074 var bVar = b as VariableTreeNode; 1071 1075 return MakeConstant(aVar.Weight / bVar.Weight); 1072 } else if (IsAddition(a) && Is Constant(b)) {1076 } else if (IsAddition(a) && IsNumber(b)) { 1073 1077 return a.Subtrees 1074 1078 .Select(x => GetSimplifiedTree(x)) 1075 1079 .Select(x => MakeFraction(x, GetSimplifiedTree(b))) 1076 1080 .Aggregate((c, d) => MakeSum(c, d)); 1077 } else if (IsMultiplication(a) && Is Constant(b)) {1081 } else if (IsMultiplication(a) && IsNumber(b)) { 1078 1082 return MakeProduct(a, Invert(b)); 1079 } else if (IsDivision(a) && Is Constant(b)) {1083 } else if (IsDivision(a) && IsNumber(b)) { 1080 1084 // (a1 / a2) / c => (a1 / (a2 * c)) 1081 1085 return MakeFraction(a.GetSubtree(0), MakeProduct(a.GetSubtree(1), b)); … … 1100 1104 1101 1105 private static ISymbolicExpressionTreeNode MakeSum(ISymbolicExpressionTreeNode a, ISymbolicExpressionTreeNode b) { 1102 if (Is Constant(a) && IsConstant(b)) {1106 if (IsNumber(a) && IsNumber(b)) { 1103 1107 // fold constants 1104 (( ConstantTreeNode)a).Value += ((ConstantTreeNode)b).Value;1108 ((NumberTreeNode)a).Value += ((NumberTreeNode)b).Value; 1105 1109 return a; 1106 } else if (Is Constant(a)) {1110 } else if (IsNumber(a)) { 1107 1111 // c + x => x + c 1108 1112 // b is not constant => make sure constant is on the right 1109 1113 return MakeSum(b, a); 1110 } else if (Is Constant(b) && ((ConstantTreeNode)b).Value == 0.0) {1114 } else if (IsNumber(b) && ((NumberTreeNode)b).Value == 0.0) { 1111 1115 // x + 0 => x 1112 1116 return a; 1113 } else if (IsFactor(a) && Is Constant(b)) {1117 } else if (IsFactor(a) && IsNumber(b)) { 1114 1118 var factNode = a as FactorVariableTreeNode; 1115 var constNode = b as ConstantTreeNode;1119 var constNode = b as NumberTreeNode; 1116 1120 return MakeFactor(factNode.Symbol, factNode.VariableName, factNode.Weights.Select((w) => w + constNode.Value)); 1117 1121 } else if (IsFactor(a) && IsFactor(b) && AreSameTypeAndVariable(a, b)) { … … 1138 1142 for (int i = 0; i < a.Subtrees.Count() - 1; i++) add.AddSubtree(a.GetSubtree(i)); 1139 1143 for (int i = 0; i < b.Subtrees.Count() - 1; i++) add.AddSubtree(b.GetSubtree(i)); 1140 if (Is Constant(a.Subtrees.Last()) && IsConstant(b.Subtrees.Last())) {1144 if (IsNumber(a.Subtrees.Last()) && IsNumber(b.Subtrees.Last())) { 1141 1145 add.AddSubtree(MakeSum(a.Subtrees.Last(), b.Subtrees.Last())); 1142 } else if (Is Constant(a.Subtrees.Last())) {1146 } else if (IsNumber(a.Subtrees.Last())) { 1143 1147 add.AddSubtree(b.Subtrees.Last()); 1144 1148 add.AddSubtree(a.Subtrees.Last()); … … 1155 1159 } else if (IsAddition(b)) { 1156 1160 return MakeSum(b, a); 1157 } else if (IsAddition(a) && Is Constant(b)) {1161 } else if (IsAddition(a) && IsNumber(b)) { 1158 1162 // a is an addition and b is a constant => append b to a and make sure the constants are merged 1159 1163 var add = addSymbol.CreateTreeNode(); 1160 1164 // add all sub trees except for the last 1161 1165 for (int i = 0; i < a.Subtrees.Count() - 1; i++) add.AddSubtree(a.GetSubtree(i)); 1162 if (Is Constant(a.Subtrees.Last()))1166 if (IsNumber(a.Subtrees.Last())) 1163 1167 add.AddSubtree(MakeSum(a.Subtrees.Last(), b)); 1164 1168 else { … … 1201 1205 group node by GroupId(node) into g 1202 1206 select g; 1203 var constant = (from node in subtrees.OfType< ConstantTreeNode>()1207 var constant = (from node in subtrees.OfType<NumberTreeNode>() 1204 1208 select node.Value).DefaultIfEmpty(0.0).Sum(); 1205 var unchangedSubtrees = subtrees.Where(t => t.SubtreeCount > 0 || !(t is IVariableTreeNode) && !(t is ConstantTreeNode));1209 var unchangedSubtrees = subtrees.Where(t => t.SubtreeCount > 0 || !(t is IVariableTreeNode) && !(t is NumberTreeNode)); 1206 1210 1207 1211 foreach (var variableNodeGroup in groupedVarNodes) { … … 1250 1254 1251 1255 private static ISymbolicExpressionTreeNode MakeProduct(ISymbolicExpressionTreeNode a, ISymbolicExpressionTreeNode b) { 1252 if (Is Constant(a) && IsConstant(b)) {1256 if (IsNumber(a) && IsNumber(b)) { 1253 1257 // fold constants 1254 return MakeConstant((( ConstantTreeNode)a).Value * ((ConstantTreeNode)b).Value);1255 } else if (Is Constant(a)) {1258 return MakeConstant(((NumberTreeNode)a).Value * ((NumberTreeNode)b).Value); 1259 } else if (IsNumber(a)) { 1256 1260 // a * $ => $ * a 1257 1261 return MakeProduct(b, a); … … 1264 1268 var node1 = b as BinaryFactorVariableTreeNode; 1265 1269 return MakeBinFactor(node0.Symbol, node0.VariableName, node0.VariableValue, node0.Weight * node1.Weight); 1266 } else if (IsFactor(a) && Is Constant(b)) {1270 } else if (IsFactor(a) && IsNumber(b)) { 1267 1271 var node0 = a as FactorVariableTreeNode; 1268 var node1 = b as ConstantTreeNode;1272 var node1 = b as NumberTreeNode; 1269 1273 return MakeFactor(node0.Symbol, node0.VariableName, node0.Weights.Select(w => w * node1.Value)); 1270 } else if (IsBinFactor(a) && Is Constant(b)) {1274 } else if (IsBinFactor(a) && IsNumber(b)) { 1271 1275 var node0 = a as BinaryFactorVariableTreeNode; 1272 var node1 = b as ConstantTreeNode;1276 var node1 = b as NumberTreeNode; 1273 1277 return MakeBinFactor(node0.Symbol, node0.VariableName, node0.VariableValue, node0.Weight * node1.Value); 1274 1278 } else if (IsBinFactor(a) && IsFactor(b)) { … … 1282 1286 if (wi < 0) throw new ArgumentException(); 1283 1287 return MakeBinFactor(node1.Symbol, node1.VariableName, node1.VariableValue, node1.Weight * node0.Weights[wi]); 1284 } else if (Is Constant(b) && ((ConstantTreeNode)b).Value == 1.0) {1288 } else if (IsNumber(b) && ((NumberTreeNode)b).Value == 1.0) { 1285 1289 // $ * 1.0 => $ 1286 1290 return a; 1287 } else if (Is Constant(b) && ((ConstantTreeNode)b).Value == 0.0) {1291 } else if (IsNumber(b) && ((NumberTreeNode)b).Value == 0.0) { 1288 1292 return MakeConstant(0); 1289 } else if (Is Constant(b) && IsVariableBase(a)) {1293 } else if (IsNumber(b) && IsVariableBase(a)) { 1290 1294 // multiply constants into variables weights 1291 ((VariableTreeNodeBase)a).Weight *= (( ConstantTreeNode)b).Value;1295 ((VariableTreeNodeBase)a).Weight *= ((NumberTreeNode)b).Value; 1292 1296 return a; 1293 } else if (Is Constant(b) && IsAddition(a) ||1297 } else if (IsNumber(b) && IsAddition(a) || 1294 1298 IsFactor(b) && IsAddition(a) || 1295 1299 IsBinFactor(b) && IsAddition(a)) { … … 1321 1325 } else if (IsAbsolute(a) && IsAbsolute(b)) { 1322 1326 return MakeAbs(MakeProduct(a.GetSubtree(0), b.GetSubtree(0))); 1323 } else if (IsAbsolute(a) && Is Constant(b)) {1324 var constNode = b as ConstantTreeNode;1327 } else if (IsAbsolute(a) && IsNumber(b)) { 1328 var constNode = b as NumberTreeNode; 1325 1329 var posF = Math.Abs(constNode.Value); 1326 1330 if (constNode.Value > 0) { … … 1391 1395 var constantProduct = (from node in subtrees.OfType<VariableTreeNodeBase>() 1392 1396 select node.Weight) 1393 .Concat(from node in subtrees.OfType< ConstantTreeNode>()1397 .Concat(from node in subtrees.OfType<NumberTreeNode>() 1394 1398 select node.Value) 1395 1399 .DefaultIfEmpty(1.0) … … 1397 1401 1398 1402 var unchangedSubtrees = from tree in subtrees 1399 where tree.SubtreeCount > 0 || !(tree is IVariableTreeNode) && !(tree is ConstantTreeNode)1403 where tree.SubtreeCount > 0 || !(tree is IVariableTreeNode) && !(tree is NumberTreeNode) 1400 1404 select tree; 1401 1405 … … 1446 1450 /// <returns>-x</returns> 1447 1451 private static ISymbolicExpressionTreeNode Negate(ISymbolicExpressionTreeNode x) { 1448 if (Is Constant(x)) {1449 (( ConstantTreeNode)x).Value *= -1;1452 if (IsNumber(x)) { 1453 ((NumberTreeNode)x).Value *= -1; 1450 1454 } else if (IsVariableBase(x)) { 1451 1455 var variableTree = (VariableTreeNodeBase)x; … … 1483 1487 /// <returns></returns> 1484 1488 private static ISymbolicExpressionTreeNode Invert(ISymbolicExpressionTreeNode x) { 1485 if (Is Constant(x)) {1486 return MakeConstant(1.0 / (( ConstantTreeNode)x).Value);1489 if (IsNumber(x)) { 1490 return MakeConstant(1.0 / ((NumberTreeNode)x).Value); 1487 1491 } else if (IsFactor(x)) { 1488 1492 var factorNode = (FactorVariableTreeNode)x; … … 1497 1501 1498 1502 private static ISymbolicExpressionTreeNode MakeConstant(double value) { 1499 ConstantTreeNode constantTreeNode = (ConstantTreeNode)(constSymbol.CreateTreeNode());1500 constantTreeNode.Value = value;1501 return constantTreeNode;1503 NumberTreeNode numberTreeNode = (NumberTreeNode)(numberSymbol.CreateTreeNode()); 1504 numberTreeNode.Value = value; 1505 return numberTreeNode; 1502 1506 } 1503 1507 -
branches/3140_NumberSymbol/HeuristicLab.Problems.DataAnalysis.Symbolic/3.4/Hashing/SymbolicExpressionTreeHash.cs
r18093 r18113 36 36 private static readonly Sine sin = new Sine(); 37 37 private static readonly Cosine cos = new Cosine(); 38 private static readonly Num Num = new Num();38 private static readonly Number number = new Number(); 39 39 40 40 private static ISymbolicExpressionTreeNode ActualRoot(this ISymbolicExpressionTree tree) => tree.Root.GetSubtree(0).GetSubtree(0); … … 66 66 var symbol = node.Symbol; 67 67 var name = symbol.Name; 68 if (node is Num TreeNode constantNode) {68 if (node is NumberTreeNode constantNode) { 69 69 name = strict ? constantNode.Value.ToString() : symbol.Name; 70 70 } else if (node is VariableTreeNode variableNode) { … … 222 222 variableTreeNode.VariableName = variable.VariableName; 223 223 variableTreeNode.Weight = variable.Weight; 224 } else if (node.Data is Num TreeNode @const) {225 var constantTreeNode = (Num TreeNode)treeNodes[i];224 } else if (node.Data is NumberTreeNode @const) { 225 var constantTreeNode = (NumberTreeNode)treeNodes[i]; 226 226 constantTreeNode.Value = @const.Value; 227 227 } … … 285 285 286 286 var symbol = child.Data.Symbol; 287 if (child.Data is Num TreeNode firstConst) {287 if (child.Data is NumberTreeNode firstConst) { 288 288 // fold sibling constant nodes into the first constant 289 289 for (int k = j + 1; k < children.Length; ++k) { 290 290 var sibling = nodes[children[k]]; 291 if (sibling.Data is Num TreeNode otherConst) {291 if (sibling.Data is NumberTreeNode otherConst) { 292 292 sibling.Enabled = false; 293 293 node.Arity--; … … 301 301 for (int k = j + 1; k < children.Length; ++k) { 302 302 var sibling = nodes[children[k]]; 303 if (sibling.Data is Num TreeNode constantNode) {303 if (sibling.Data is NumberTreeNode constantNode) { 304 304 sibling.Enabled = false; 305 305 node.Arity--; … … 329 329 330 330 if (node.Arity == 0) { // if everything is simplified this node becomes constant 331 var constantTreeNode = Num.CreateTreeNode<NumTreeNode>();331 var constantTreeNode = number.CreateTreeNode<NumberTreeNode>(); 332 332 constantTreeNode.Value = 1; 333 333 nodes[i] = constantTreeNode.ToHashNode(); … … 344 344 var tmp = nodes; 345 345 346 if (children.All(x => tmp[x].Data.Symbol is Num )) {347 var v = ((Num TreeNode)nodes[children.First()].Data).Value;346 if (children.All(x => tmp[x].Data.Symbol is Number)) { 347 var v = ((NumberTreeNode)nodes[children.First()].Data).Value; 348 348 if (node.Arity == 1) { 349 349 v = 1 / v; 350 350 } else if (node.Arity > 1) { 351 351 foreach (var j in children.Skip(1)) { 352 v /= ((Num TreeNode)nodes[j].Data).Value;352 v /= ((NumberTreeNode)nodes[j].Data).Value; 353 353 } 354 354 } 355 var constantTreeNode = Num.CreateTreeNode<NumTreeNode>();355 var constantTreeNode = number.CreateTreeNode<NumberTreeNode>(); 356 356 constantTreeNode.Value = v; 357 357 nodes[i] = constantTreeNode.ToHashNode(); … … 368 368 } 369 369 if (node.Arity == 0) { 370 var constantTreeNode = Num.CreateTreeNode<NumTreeNode>();370 var constantTreeNode = number.CreateTreeNode<NumberTreeNode>(); 371 371 constantTreeNode.Value = 1; // x / x = 1 372 372 nodes[i] = constantTreeNode.ToHashNode(); … … 383 383 var childSymbol = child.Data.Symbol; 384 384 385 if (childSymbol is Num ) {385 if (childSymbol is Number) { 386 386 nodes[i].Enabled = false; 387 387 } else if ((parentSymbol is Exponential && childSymbol is Logarithm) || (parentSymbol is Logarithm && childSymbol is Exponential)) { … … 393 393 var children = nodes.IterateChildren(i); 394 394 var tmp = nodes; 395 if (children.All(x => tmp[x].Data.Symbol is Num )) {395 if (children.All(x => tmp[x].Data.Symbol is Number)) { 396 396 foreach (var j in children) { 397 397 nodes[j].Enabled = false; 398 398 } 399 nodes[i] = Num.CreateTreeNode().ToHashNode();399 nodes[i] = number.CreateTreeNode().ToHashNode(); 400 400 } 401 401 } -
branches/3140_NumberSymbol/HeuristicLab.Problems.DataAnalysis.Symbolic/3.4/SymbolicDataAnalysisModel.cs
r18093 r18113 115 115 if (linearScalingCalculator.ErrorState != OnlineCalculatorError.None) return; 116 116 117 Num TreeNode alphaTreeNode = null;118 Num TreeNode betaTreeNode = null;117 NumberTreeNode alphaTreeNode = null; 118 NumberTreeNode betaTreeNode = null; 119 119 // check if model has a structure that can be re-used for scaling 120 120 var startNode = SymbolicExpressionTree.Root.GetSubtree(0); 121 121 var addNode = startNode.GetSubtree(0); 122 122 if (addNode.Symbol is Addition && addNode.SubtreeCount == 2) { 123 alphaTreeNode = (Num TreeNode)addNode.Subtrees.LastOrDefault(n => n is NumTreeNode);123 alphaTreeNode = (NumberTreeNode)addNode.Subtrees.LastOrDefault(n => n is NumberTreeNode); 124 124 var mulNode = addNode.Subtrees.FirstOrDefault(n => n.Symbol is Multiplication); 125 125 if (mulNode != null) { 126 betaTreeNode = (Num TreeNode)mulNode.Subtrees.LastOrDefault(n => n is NumTreeNode);126 betaTreeNode = (NumberTreeNode)mulNode.Subtrees.LastOrDefault(n => n is NumberTreeNode); 127 127 } 128 128 } … … 146 146 var addition = new Addition(); 147 147 var node = addition.CreateTreeNode(); 148 var alphaConst = Make Constant(alpha);148 var alphaConst = MakeNumber(alpha); 149 149 node.AddSubtree(treeNode); 150 150 node.AddSubtree(alphaConst); … … 157 157 return treeNode; 158 158 } else { 159 var multiplic iation = new Multiplication();160 var node = multiplic iation.CreateTreeNode();161 var betaConst = Make Constant(beta);159 var multiplication = new Multiplication(); 160 var node = multiplication.CreateTreeNode(); 161 var betaConst = MakeNumber(beta); 162 162 node.AddSubtree(treeNode); 163 163 node.AddSubtree(betaConst); … … 166 166 } 167 167 168 private static ISymbolicExpressionTreeNode Make Constant(double c) {169 var node = (Num TreeNode)(new Num()).CreateTreeNode();168 private static ISymbolicExpressionTreeNode MakeNumber(double c) { 169 var node = (NumberTreeNode)(new Number()).CreateTreeNode(); 170 170 node.Value = c; 171 171 return node;
Note: See TracChangeset
for help on using the changeset viewer.