Free cookie consent management tool by TermsFeed Policy Generator

Changeset 17898


Ignore:
Timestamp:
03/16/21 13:34:18 (4 years ago)
Author:
gkronber
Message:

#3076 refactoring to prepare for branch reintegration

Location:
branches/3076_IA_evaluators_analyzers_reintegration/HeuristicLab.Problems.DataAnalysis.Symbolic.Regression/3.4
Files:
1 deleted
3 edited

Legend:

Unmodified
Added
Removed
  • branches/3076_IA_evaluators_analyzers_reintegration/HeuristicLab.Problems.DataAnalysis.Symbolic.Regression/3.4/MultiObjective/SymbolicRegressionMultiObjectiveMultiSoftConstraintEvaluator.cs

    r17897 r17898  
    2222#endregion
    2323
     24using System;
    2425using System.Collections.Generic;
    2526using System.Linq;
     
    8788    public override IOperation InstrumentedApply() {
    8889      var rows = GenerateRowsToEvaluate();
    89       var solution = SymbolicExpressionTreeParameter.ActualValue;
     90      var tree = SymbolicExpressionTreeParameter.ActualValue;
    9091      var problemData = ProblemDataParameter.ActualValue;
    9192      var interpreter = SymbolicDataAnalysisTreeInterpreterParameter.ActualValue;
     
    9495
    9596      if (UseConstantOptimization) {
    96         SymbolicRegressionConstantOptimizationEvaluator.OptimizeConstants(interpreter, solution, problemData, rows,
     97        SymbolicRegressionConstantOptimizationEvaluator.OptimizeConstants(interpreter, tree, problemData, rows,
    9798          false,
    9899          ConstantOptimizationIterations,
     
    103104        if (applyLinearScaling) {
    104105          //Check for interval arithmetic grammar
    105           //remove scaling nodes for linear scaling evaluation
     106          if (!(tree.Root.Grammar is IntervalArithmeticGrammar))
     107            throw new ArgumentException($"{ItemName} can only be used with IntervalArithmeticGrammar.");
     108
    106109          var rootNode = new ProgramRootSymbol().CreateTreeNode();
    107110          var startNode = new StartSymbol().CreateTreeNode();
    108           SymbolicExpressionTree newTree = null;
    109           foreach (var node in solution.IterateNodesPrefix())
    110             if (node.Symbol.Name == "Scaling") {
    111               for (var i = 0; i < node.SubtreeCount; ++i) startNode.AddSubtree(node.GetSubtree(i));
    112               rootNode.AddSubtree(startNode);
    113               newTree = new SymbolicExpressionTree(rootNode);
    114               break;
    115             }
     111          var offset = tree.Root.GetSubtree(0) //Start
     112                                .GetSubtree(0); //Offset
     113          var scaling = offset.GetSubtree(0);
     114          var t = (ISymbolicExpressionTreeNode)scaling.GetSubtree(0).Clone();
     115          rootNode.AddSubtree(startNode);
     116          startNode.AddSubtree(t);
     117          var newTree = new SymbolicExpressionTree(rootNode);
    116118
    117119          //calculate alpha and beta for scaling
    118120          var estimatedValues = interpreter.GetSymbolicExpressionTreeValues(newTree, problemData.Dataset, rows);
     121
    119122          var targetValues = problemData.Dataset.GetDoubleValues(problemData.TargetVariable, rows);
    120123          OnlineLinearScalingParameterCalculator.Calculate(estimatedValues, targetValues, out var alpha, out var beta,
    121124            out var errorState);
    122125          //Set alpha and beta to the scaling nodes from ia grammar
    123           foreach (var node in solution.IterateNodesPrefix())
    124             if (node.Symbol.Name == "Offset") {
    125               node.RemoveSubtree(1);
    126               var alphaNode = new ConstantTreeNode(new Constant()) { Value = alpha };
    127               node.AddSubtree(alphaNode);
    128             } else if (node.Symbol.Name == "Scaling") {
    129               node.RemoveSubtree(1);
    130               var betaNode = new ConstantTreeNode(new Constant()) { Value = beta };
    131               node.AddSubtree(betaNode);
    132             }
     126          var offsetParameter = offset.GetSubtree(1) as ConstantTreeNode;
     127          offsetParameter.Value = alpha;
     128          var scalingParameter = scaling.GetSubtree(1) as ConstantTreeNode;
     129          scalingParameter.Value = beta;
    133130        }
    134131      }
    135132
    136       var qualities = Calculate(interpreter, solution, estimationLimits.Lower, estimationLimits.Upper, problemData,
     133      var qualities = Calculate(interpreter, tree, estimationLimits.Lower, estimationLimits.Upper, problemData,
    137134        rows, BoundsEstimator);
    138135      QualitiesParameter.ActualValue = new DoubleArray(qualities);
  • branches/3076_IA_evaluators_analyzers_reintegration/HeuristicLab.Problems.DataAnalysis.Symbolic.Regression/3.4/SingleObjective/Evaluators/SymbolicRegressionSingleObjectiveConstraintEvaluator.cs

    r17892 r17898  
    1 using System;
     1#region License Information
     2/* HeuristicLab
     3 * Copyright (C) Heuristic and Evolutionary Algorithms Laboratory (HEAL)
     4 *
     5 * This file is part of HeuristicLab.
     6 *
     7 * HeuristicLab is free software: you can redistribute it and/or modify
     8 * it under the terms of the GNU General Public License as published by
     9 * the Free Software Foundation, either version 3 of the License, or
     10 * (at your option) any later version.
     11 *
     12 * HeuristicLab is distributed in the hope that it will be useful,
     13 * but WITHOUT ANY WARRANTY; without even the implied warranty of
     14 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
     15 * GNU General Public License for more details.
     16 *
     17 * You should have received a copy of the GNU General Public License
     18 * along with HeuristicLab. If not, see <http://www.gnu.org/licenses/>.
     19 */
     20#endregion
     21
     22using System;
    223using System.Collections.Generic;
    324using System.Linq;
     
    1132
    1233namespace HeuristicLab.Problems.DataAnalysis.Symbolic {
    13   [Item("Constraints Evaluator", "Calculates NMSE of a symbolic regression solution with respect to constraints.")]
     34  [Item("NMSE Evaluator (with shape-constraints)", "Calculates NMSE of a symbolic regression solution and checks constraints the fitness is a combination of NMSE and constraint violations.")]
    1435  [StorableType("27473973-DD8D-4375-997D-942E2280AE8E")]
    1536  public class SymbolicRegressionSingleObjectiveConstraintEvaluator : SymbolicRegressionSingleObjectiveEvaluator {
    1637    #region Parameter/Properties
    1738
    18     private const string UseConstantOptimizationParameterName = "Use Constant Optimization";
    19 
    20     private const string ConstantOptimizationIterationsParameterName = "Constant Optimization Iterations";
    21 
    22     private const string UseSoftConstraintsParameterName = "Use Soft Constraints Evaluation";
    23 
    24     private const string BoundsEstimatorParameterName = "Bounds estimator";
    25 
    26     private const string MaximumPenaltyFactorParamterName = "Maximum Penalty Factor";
    27 
    28 
    29     public IFixedValueParameter<BoolValue> UseConstantOptimizationParameter =>
    30       (IFixedValueParameter<BoolValue>)Parameters[UseConstantOptimizationParameterName];
     39    private const string OptimizeParametersParameterName = "OptimizeParameters";
     40    private const string ParameterOptimizationIterationsParameterName = "ParameterOptimizationIterations";
     41    private const string UseSoftConstraintsParameterName = "UseSoftConstraintsEvaluation";
     42    private const string BoundsEstimatorParameterName = "BoundsEstimator";
     43    private const string PenaltyFactorParameterName = "PenaltyFactor";
     44
     45
     46    public IFixedValueParameter<BoolValue> OptimizerParametersParameter =>
     47      (IFixedValueParameter<BoolValue>)Parameters[OptimizeParametersParameterName];
    3148
    3249    public IFixedValueParameter<IntValue> ConstantOptimizationIterationsParameter =>
    33       (IFixedValueParameter<IntValue>)Parameters[ConstantOptimizationIterationsParameterName];
     50      (IFixedValueParameter<IntValue>)Parameters[ParameterOptimizationIterationsParameterName];
    3451
    3552    public IFixedValueParameter<BoolValue> UseSoftConstraintsParameter =>
     
    3855    public IValueParameter<IBoundsEstimator> BoundsEstimatorParameter =>
    3956      (IValueParameter<IBoundsEstimator>)Parameters[BoundsEstimatorParameterName];
    40     public IFixedValueParameter<DoubleValue> MaximumPenaltyFactorParamter =>
    41       (IFixedValueParameter<DoubleValue>)Parameters[MaximumPenaltyFactorParamterName];
    42 
    43     public bool UseConstantOptimization {
    44       get => UseConstantOptimizationParameter.Value.Value;
    45       set => UseConstantOptimizationParameter.Value.Value = value;
     57    public IFixedValueParameter<DoubleValue> PenaltyFactorParameter =>
     58      (IFixedValueParameter<DoubleValue>)Parameters[PenaltyFactorParameterName];
     59
     60    public bool OptimizeParameters {
     61      get => OptimizerParametersParameter.Value.Value;
     62      set => OptimizerParametersParameter.Value.Value = value;
    4663    }
    4764
     
    5673    }
    5774
    58     public double PenaltyMultiplier {
    59       get => 1.0;//PenaltyMultiplierParameter.Value.Value;
    60       //set => PenaltyMultiplierParameter.Value.Value = value;
    61     }
    62 
    6375    public IBoundsEstimator BoundsEstimator {
    6476      get => BoundsEstimatorParameter.Value;
     
    6678    }
    6779
    68     public double MaximumPenaltyFactor {
    69       get => MaximumPenaltyFactorParamter.Value.Value;
    70       set => MaximumPenaltyFactorParamter.Value.Value = value;
    71     }
    72 
    73 
    74     //Use false for maximization, because we try to minimize the NMSE
    75     public override bool Maximization => false;
     80    public double PenalityFactor {
     81      get => PenaltyFactorParameter.Value.Value;
     82      set => PenaltyFactorParameter.Value.Value = value;
     83    }
     84
     85
     86    public override bool Maximization => false; // NMSE is minimized
    7687
    7788    #endregion
     
    8697
    8798    public SymbolicRegressionSingleObjectiveConstraintEvaluator() {
    88       Parameters.Add(new FixedValueParameter<BoolValue>(UseConstantOptimizationParameterName,
    89         "Define whether constant optimization is active or not.", new BoolValue(false)));
    90       Parameters.Add(new FixedValueParameter<IntValue>(ConstantOptimizationIterationsParameterName,
    91         "Define how many constant optimization steps should be performed.", new IntValue(10)));
     99      Parameters.Add(new FixedValueParameter<BoolValue>(OptimizeParametersParameterName,
     100        "Define whether optimization of numeric parameters is active or not (default: false).", new BoolValue(false)));
     101      Parameters.Add(new FixedValueParameter<IntValue>(ParameterOptimizationIterationsParameterName,
     102        "Define how many parameter optimization steps should be performed (default: 10).", new IntValue(10)));
    92103      Parameters.Add(new FixedValueParameter<BoolValue>(UseSoftConstraintsParameterName,
    93         "Define whether the constraints are penalized by soft or hard constraints.", new BoolValue(false)));
     104        "Define whether the constraints are penalized by soft or hard constraints (default: false).", new BoolValue(false)));
    94105      Parameters.Add(new ValueParameter<IBoundsEstimator>(BoundsEstimatorParameterName,
    95         "Select the Boundsestimator.", new IntervalArithBoundsEstimator()));
    96       Parameters.Add(new FixedValueParameter<DoubleValue>(MaximumPenaltyFactorParamterName,
    97         "Specify how hard constraints violations should be punished", new DoubleValue(1.5)));
     106        "The estimator which is used to estimate output ranges of models (default: interval arithmetic).", new IntervalArithBoundsEstimator()));
     107      Parameters.Add(new FixedValueParameter<DoubleValue>(PenaltyFactorParameterName,
     108        "Punishment factor for constraint violations for soft constraint handling (fitness = NMSE + penaltyFactor * avg(violations)) (default: 1.0)", new DoubleValue(1.0)));
    98109    }
    99110
    100111    [StorableHook(HookType.AfterDeserialization)]
    101112    private void AfterDeserialization() {
    102       if (!Parameters.ContainsKey(UseConstantOptimizationParameterName)) {
    103         Parameters.Add(new FixedValueParameter<BoolValue>(UseConstantOptimizationParameterName,
    104           "Define whether constant optimization is active or not.", new BoolValue(false)));
    105       }
    106 
    107       if (!Parameters.ContainsKey(ConstantOptimizationIterationsParameterName)) {
    108         Parameters.Add(new FixedValueParameter<IntValue>(ConstantOptimizationIterationsParameterName,
    109           "Define how many constant optimization steps should be performed.", new IntValue(10)));
     113      if (!Parameters.ContainsKey(OptimizeParametersParameterName)) {
     114        Parameters.Add(new FixedValueParameter<BoolValue>(OptimizeParametersParameterName,
     115          "Define whether optimization of numeric parameters is active or not (default: false).", new BoolValue(false)));
     116      }
     117
     118      if (!Parameters.ContainsKey(ParameterOptimizationIterationsParameterName)) {
     119        Parameters.Add(new FixedValueParameter<IntValue>(ParameterOptimizationIterationsParameterName,
     120          "Define how many parameter optimization steps should be performed (default: 10).", new IntValue(10)));
    110121      }
    111122
    112123      if (!Parameters.ContainsKey(UseSoftConstraintsParameterName)) {
    113124        Parameters.Add(new FixedValueParameter<BoolValue>(UseSoftConstraintsParameterName,
    114           "Define whether the constraints are penalized by soft or hard constraints.", new BoolValue(false)));
     125          "Define whether the constraints are penalized by soft or hard constraints (default: false).", new BoolValue(false)));
    115126      }
    116127
    117128      if (!Parameters.ContainsKey(BoundsEstimatorParameterName))
    118129        Parameters.Add(new ValueParameter<IBoundsEstimator>(BoundsEstimatorParameterName,
    119           "Select the Boundsestimator.", new IntervalArithBoundsEstimator()));
    120 
    121       if (!Parameters.ContainsKey(MaximumPenaltyFactorParamterName)) {
    122         Parameters.Add(new FixedValueParameter<DoubleValue>(MaximumPenaltyFactorParamterName,
    123           "Specify how hard constraints violations should be punished", new DoubleValue(1.5)));
     130          "The estimator which is used to estimate output ranges of models (default: interval arithmetic).", new IntervalArithBoundsEstimator()));
     131
     132      if (!Parameters.ContainsKey(PenaltyFactorParameterName)) {
     133        Parameters.Add(new FixedValueParameter<DoubleValue>(PenaltyFactorParameterName,
     134          "Punishment factor for constraint violations for soft constraint handling (fitness = NMSE + penaltyFactor * avg(violations)) (default: 1.0)", new DoubleValue(1.0)));
    124135      }
    125136    }
     
    133144    public override IOperation InstrumentedApply() {
    134145      var rows = GenerateRowsToEvaluate();
    135       var solution = SymbolicExpressionTreeParameter.ActualValue;
     146      var tree = SymbolicExpressionTreeParameter.ActualValue;
    136147      var problemData = ProblemDataParameter.ActualValue;
    137148      var interpreter = SymbolicDataAnalysisTreeInterpreterParameter.ActualValue;
     
    139150      var applyLinearScaling = ApplyLinearScalingParameter.ActualValue.Value;
    140151
    141       if (UseConstantOptimization) {
    142         SymbolicRegressionConstantOptimizationEvaluator.OptimizeConstants(interpreter, solution, problemData, rows,
     152      if (OptimizeParameters) {
     153        SymbolicRegressionConstantOptimizationEvaluator.OptimizeConstants(interpreter, tree, problemData, rows,
    143154          false, ConstantOptimizationIterations, true,
    144155          estimationLimits.Lower, estimationLimits.Upper);
     
    146157        if (applyLinearScaling) {
    147158          //Check for interval arithmetic grammar
    148           //remove scaling nodes for linear scaling evaluation
     159          if (!(tree.Root.Grammar is IntervalArithmeticGrammar))
     160            throw new ArgumentException($"{ItemName} can only be used with IntervalArithmeticGrammar.");
     161
    149162          var rootNode = new ProgramRootSymbol().CreateTreeNode();
    150163          var startNode = new StartSymbol().CreateTreeNode();
    151           SymbolicExpressionTree newTree = null;
    152           foreach (var node in solution.IterateNodesPrefix())
    153             if (node.Symbol.Name == "Scaling") {
    154               for (var i = 0; i < node.SubtreeCount; ++i) startNode.AddSubtree(node.GetSubtree(i));
    155               rootNode.AddSubtree(startNode);
    156               newTree = new SymbolicExpressionTree(rootNode);
    157               break;
    158             }
     164          var offset = tree.Root.GetSubtree(0) //Start
     165                                .GetSubtree(0); //Offset
     166          var scaling = offset.GetSubtree(0);
     167          var t = (ISymbolicExpressionTreeNode)scaling.GetSubtree(0).Clone();
     168          rootNode.AddSubtree(startNode);
     169          startNode.AddSubtree(t);
     170          var newTree = new SymbolicExpressionTree(rootNode);
    159171
    160172          //calculate alpha and beta for scaling
    161173          var estimatedValues = interpreter.GetSymbolicExpressionTreeValues(newTree, problemData.Dataset, rows);
     174
    162175          var targetValues = problemData.Dataset.GetDoubleValues(problemData.TargetVariable, rows);
    163176          OnlineLinearScalingParameterCalculator.Calculate(estimatedValues, targetValues, out var alpha, out var beta,
    164177            out var errorState);
    165           //Set alpha and beta to the scaling nodes from ia grammar
    166           foreach (var node in solution.IterateNodesPrefix())
    167             if (node.Symbol.Name == "Offset") {
    168               node.RemoveSubtree(1);
    169               var alphaNode = new ConstantTreeNode(new Constant()) { Value = alpha };
    170               node.AddSubtree(alphaNode);
    171             } else if (node.Symbol.Name == "Scaling") {
    172               node.RemoveSubtree(1);
    173               var betaNode = new ConstantTreeNode(new Constant()) { Value = beta };
    174               node.AddSubtree(betaNode);
    175             }
    176         }
    177       }
    178 
    179       var quality = Calculate(interpreter, solution, estimationLimits.Lower, estimationLimits.Upper, problemData, rows,
    180         PenaltyMultiplier, BoundsEstimator, UseSoftConstraints, MaximumPenaltyFactor);
     178
     179          if (errorState == OnlineCalculatorError.None) {
     180            //Set alpha and beta to the scaling nodes from ia grammar
     181            var offsetParameter = offset.GetSubtree(1) as ConstantTreeNode;
     182            offsetParameter.Value = alpha;
     183            var scalingParameter = scaling.GetSubtree(1) as ConstantTreeNode;
     184            scalingParameter.Value = beta;
     185          }
     186        } // else: alpha and beta are evolved
     187      }
     188
     189      var quality = Calculate(interpreter, tree, estimationLimits.Lower, estimationLimits.Upper, problemData, rows,
     190        BoundsEstimator, UseSoftConstraints, PenalityFactor);
    181191      QualityParameter.ActualValue = new DoubleValue(quality);
    182192
     
    186196    public static double Calculate(
    187197      ISymbolicDataAnalysisExpressionTreeInterpreter interpreter,
    188       ISymbolicExpressionTree solution, double lowerEstimationLimit,
    189       double upperEstimationLimit,
     198      ISymbolicExpressionTree tree,
     199      double lowerEstimationLimit, double upperEstimationLimit,
    190200      IRegressionProblemData problemData, IEnumerable<int> rows,
    191       double penaltyMultiplier, IBoundsEstimator estimator,
    192       bool useSoftConstraints, double maximumPenaltyFactor) {
    193 
    194       var estimatedValues = interpreter.GetSymbolicExpressionTreeValues(solution, problemData.Dataset, rows);
     201      IBoundsEstimator estimator,
     202      bool useSoftConstraints = false, double penaltyFactor = 1.0) {
     203
     204      var estimatedValues = interpreter.GetSymbolicExpressionTreeValues(tree, problemData.Dataset, rows);
    195205      var targetValues = problemData.Dataset.GetDoubleValues(problemData.TargetVariable, rows);
    196206      var constraints = problemData.ShapeConstraints.EnabledConstraints;
     
    205215      }
    206216
    207       var constraintResults = IntervalUtil.GetConstraintViolations(constraints, estimator, intervalCollection, solution);
    208 
    209       if (constraintResults.Any(x => double.IsNaN(x) || double.IsInfinity(x))) {
     217      var constraintViolations = IntervalUtil.GetConstraintViolations(constraints, estimator, intervalCollection, tree);
     218
     219      if (constraintViolations.Any(x => double.IsNaN(x) || double.IsInfinity(x))) {
    210220        return 1.0;
    211221      }
    212222
    213 
    214223      if (useSoftConstraints) {
    215         if (maximumPenaltyFactor < 0.0)
    216           throw new ArgumentException("The parameter has to be greater or equal 0.0!", nameof(maximumPenaltyFactor));
    217 
    218         var zip = constraints.Zip(constraintResults, (c, e) => new { Constraint = c, Error = e });
    219         double sum = 0.0;
    220 
    221         foreach (var x in zip) {
    222           if (x.Constraint.Weight <= 0)
    223             throw new ArgumentException("Constraint weights <= 0 are not allowed!");
    224 
    225           double e = x.Error / x.Constraint.Weight;
    226 
    227           e = double.IsNaN(e) ? 0.0 : e;
    228           e = e > 1.0 ? 1.0 : e;
    229 
    230           sum += Math.Sqrt(e) * maximumPenaltyFactor;
    231         }
    232 
    233         double avgError = sum / zip.Count();
    234         nmse = nmse * avgError + nmse;
    235         nmse = Math.Min(1.0, nmse);
    236       } else if (constraintResults.Any(x => x != 0.0)) {
    237         nmse = 1.0;
     224        if (penaltyFactor < 0.0)
     225          throw new ArgumentException("The parameter has to be greater or equal 0.0!", nameof(penaltyFactor));
     226
     227        var weightedViolationSum = constraints
     228          .Zip(constraintViolations, (c, v) => c.Weight * v)
     229          .Average();
     230
     231        return Math.Min(nmse, 1.0) + penaltyFactor * weightedViolationSum;
     232      } else if (constraintViolations.Any(x => x > 0.0)) {
     233        return 1.0;
    238234      }
    239235
     
    250246      var nmse = Calculate(SymbolicDataAnalysisTreeInterpreterParameter.ActualValue, tree,
    251247        EstimationLimitsParameter.ActualValue.Lower, EstimationLimitsParameter.ActualValue.Upper,
    252         problemData, rows, PenaltyMultiplier, BoundsEstimator, UseSoftConstraints, MaximumPenaltyFactor);
     248        problemData, rows, BoundsEstimator, UseSoftConstraints, PenalityFactor);
    253249
    254250      SymbolicDataAnalysisTreeInterpreterParameter.ExecutionContext = null;
  • branches/3076_IA_evaluators_analyzers_reintegration/HeuristicLab.Problems.DataAnalysis.Symbolic.Regression/3.4/SymbolicRegressionConstraintAnalyzer.cs

    r17892 r17898  
    1 using System.Linq;
     1#region License Information
     2/* HeuristicLab
     3 * Copyright (C) Heuristic and Evolutionary Algorithms Laboratory (HEAL)
     4 *
     5 * This file is part of HeuristicLab.
     6 *
     7 * HeuristicLab is free software: you can redistribute it and/or modify
     8 * it under the terms of the GNU General Public License as published by
     9 * the Free Software Foundation, either version 3 of the License, or
     10 * (at your option) any later version.
     11 *
     12 * HeuristicLab is distributed in the hope that it will be useful,
     13 * but WITHOUT ANY WARRANTY; without even the implied warranty of
     14 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
     15 * GNU General Public License for more details.
     16 *
     17 * You should have received a copy of the GNU General Public License
     18 * along with HeuristicLab. If not, see <http://www.gnu.org/licenses/>.
     19 */
     20#endregion
     21
     22using System.Linq;
    223using HEAL.Attic;
    324using HeuristicLab.Analysis;
     
    1031namespace HeuristicLab.Problems.DataAnalysis.Symbolic.Regression {
    1132  [StorableType("4318C6BD-E0A1-45FE-AC30-96E7F73B51FB")]
     33  [Item("Symbolic regression constraint analyser", "Analyzes the number of shape-constraint violations of symbolic regression models.")]
    1234  public class SymbolicRegressionConstraintAnalyzer : SymbolicDataAnalysisAnalyzer, ISymbolicExpressionTreeAnalyzer {
    1335    private const string ProblemDataParameterName = "ProblemData";
    14     private const string ConstraintViolationParameterName = "ConstraintViolations";
    15     private const string ConstraintUnsatisfiedSolutionsParameterName = "Constraint Unsatisfied Solutions";
     36    private const string ConstraintViolationsParameterName = "ConstraintViolations";
     37    private const string InfeasibleSolutionsParameterName = "InfeasibleSolutions";
    1638
    1739    #region parameter properties
     
    2042      (ILookupParameter<IRegressionProblemData>) Parameters[ProblemDataParameterName];
    2143
    22     public IResultParameter<DataTable> ConstraintViolationParameter =>
    23       (IResultParameter<DataTable>) Parameters[ConstraintViolationParameterName];
     44    public IResultParameter<DataTable> ConstraintViolationsParameter =>
     45      (IResultParameter<DataTable>) Parameters[ConstraintViolationsParameterName];
    2446
    25     public IResultParameter<DataTable> ConstraintUnsatisfiedSolutionsParameter =>
    26       (IResultParameter<DataTable>)Parameters[ConstraintUnsatisfiedSolutionsParameterName];
     47    public IResultParameter<DataTable> InfeasibleSolutionsParameter =>
     48      (IResultParameter<DataTable>)Parameters[InfeasibleSolutionsParameterName];
    2749
    2850    #endregion
    2951
     52    #region properties
     53    public IRegressionProblemData RegressionProblemData => RegressionProblemDataParameter.ActualValue;
     54    public DataTable ConstraintViolations => ConstraintViolationsParameter.ActualValue;
     55    public DataTable InfeasibleSolutions => InfeasibleSolutionsParameter.ActualValue;
     56    #endregion
     57
    3058    public override bool EnabledByDefault => false;
    31     public static int Iterations { get; set; } = 0;
    32 
    33     public IBoundsEstimator BoundsEstimator { get; set; } = new IntervalArithBoundsEstimator();
    3459
    3560    [StorableConstructor]
     
    4671      Parameters.Add(new LookupParameter<IRegressionProblemData>(ProblemDataParameterName,
    4772        "The problem data of the symbolic data analysis problem."));
    48       Parameters.Add(new ResultParameter<DataTable>(ConstraintViolationParameterName,
    49         "Shows the number of constraint violations!"));
    50       Parameters.Add(new ResultParameter<DataTable>(ConstraintUnsatisfiedSolutionsParameterName,
    51         "Shows the number of solutions with unsatisfied constraints."));
     73      Parameters.Add(new ResultParameter<DataTable>(ConstraintViolationsParameterName,
     74        "The number of constraint violations."));
     75      Parameters.Add(new ResultParameter<DataTable>(InfeasibleSolutionsParameterName,
     76        "The number of infeasible solutions."));
    5277
    5378
    54       ConstraintViolationParameter.DefaultValue = new DataTable(ConstraintViolationParameterName) {
     79      ConstraintViolationsParameter.DefaultValue = new DataTable(ConstraintViolationsParameterName) {
    5580        VisualProperties = {
    5681          XAxisTitle = "Generations",
    57           YAxisTitle = "Constraint Violations"
     82          YAxisTitle = "Constraint violations"
    5883        }
    5984      };
    6085
    61       ConstraintUnsatisfiedSolutionsParameter.DefaultValue = new DataTable(ConstraintUnsatisfiedSolutionsParameterName) {
     86      InfeasibleSolutionsParameter.DefaultValue = new DataTable(InfeasibleSolutionsParameterName) {
    6287        VisualProperties = {
    6388          XAxisTitle = "Generations",
    64           YAxisTitle = "Constraint Unsatisfied Solutions"
     89          YAxisTitle = "Infeasible solutions"
    6590        }
    6691      };
    67     }
    68 
    69     public override void InitializeState() {
    70       Iterations = 0;
    71       base.InitializeState();
    72     }
    73 
    74     public override void ClearState() {
    75       Iterations = 0;
    76       base.ClearState();
    7792    }
    7893
     
    8095    [StorableHook(HookType.AfterDeserialization)]
    8196    private void AfterDeserialization() {
    82       if (Parameters.ContainsKey(ConstraintUnsatisfiedSolutionsParameterName)) return;
    83       Parameters.Add(new ResultParameter<DataTable>(ConstraintUnsatisfiedSolutionsParameterName,
    84         "Shows the number of solutions with unsatisfied constraints."));
     97      if (Parameters.ContainsKey(InfeasibleSolutionsParameterName)) return;
     98      Parameters.Add(new ResultParameter<DataTable>(InfeasibleSolutionsParameterName,
     99        "The number of infeasible solutions."));
    85100
    86       ConstraintUnsatisfiedSolutionsParameter.DefaultValue = new DataTable(ConstraintUnsatisfiedSolutionsParameterName) {
     101      InfeasibleSolutionsParameter.DefaultValue = new DataTable(InfeasibleSolutionsParameterName) {
    87102        VisualProperties = {
    88103          XAxisTitle = "Generations",
    89           YAxisTitle = "Constraint Unsatisfied Solutions"
     104          YAxisTitle = "Infeasible solutions"
    90105        }
    91106      };
     
    93108
    94109    public override IOperation Apply() {
    95       Iterations++;
     110      var problemData = RegressionProblemData;
     111      var trees = SymbolicExpressionTree.ToArray();
    96112
    97       var problemData = RegressionProblemDataParameter.ActualValue;
    98       var trees = SymbolicExpressionTreeParameter.ActualValue;
     113      var results = ResultCollection;
     114      var constraints = problemData.ShapeConstraints.EnabledConstraints;
     115      var variableRanges = problemData.VariableRanges;
     116      var constraintViolationsTable = ConstraintViolations;
     117      var estimator = new IntervalArithBoundsEstimator();
    99118
    100       var results = ResultCollectionParameter.ActualValue;
    101       var constraints = problemData.ShapeConstraints.EnabledConstraints;
    102       var variableRanges = problemData.VariableRanges.GetReadonlyDictionary();
    103       var intervalCollection = problemData.VariableRanges;
    104       var newDataTable = ConstraintViolationParameter.ActualValue;
    105       var solutions = SymbolicExpressionTree.ToArray();
    106 
    107       if (newDataTable.Rows.Count == 0)
     119      if (constraintViolationsTable.Rows.Any())
    108120        foreach (var constraint in constraints)
    109           newDataTable.Rows.Add(new DataRow(constraint.ToString()));
     121          constraintViolationsTable.Rows.Add(new DataRow(constraint.ToString()));
    110122
    111123      foreach (var constraint in constraints) {
    112         var violations = trees.Count(tree => IntervalUtil.GetConstraintViolation(constraint, BoundsEstimator, intervalCollection, tree) > 0.0);
    113 
    114         newDataTable.Rows[constraint.ToString()].Values.Add(violations);
     124        var numViolations = trees.Count(tree => IntervalUtil.GetConstraintViolation(constraint, estimator, variableRanges, tree) > 0.0);
     125        constraintViolationsTable.Rows[constraint.ToString()].Values.Add(numViolations);
    115126      }
    116127
    117       var constraintUnsatisfiedSolutionsDataTable = ConstraintUnsatisfiedSolutionsParameter.ActualValue;
     128      var constraintUnsatisfiedSolutionsDataTable = InfeasibleSolutions;
    118129      if (constraintUnsatisfiedSolutionsDataTable.Rows.Count == 0)
    119         constraintUnsatisfiedSolutionsDataTable.Rows.Add(new DataRow(ConstraintUnsatisfiedSolutionsParameterName));
     130        constraintUnsatisfiedSolutionsDataTable.Rows.Add(new DataRow(InfeasibleSolutionsParameterName));
    120131
    121       constraintUnsatisfiedSolutionsDataTable.Rows[ConstraintUnsatisfiedSolutionsParameterName]
     132      constraintUnsatisfiedSolutionsDataTable.Rows[InfeasibleSolutionsParameterName]
    122133        .Values
    123         .Add(solutions.Count(s => IntervalUtil.GetConstraintViolations(constraints, BoundsEstimator, intervalCollection, s).Any(x => x != 0.0)));
     134        .Add(trees.Count(t => IntervalUtil.GetConstraintViolations(constraints, estimator, variableRanges, t).Any(x => x > 0.0)));
    124135
    125136      return base.Apply();
    126137    }
    127 
    128    
    129138  }
    130139}
Note: See TracChangeset for help on using the changeset viewer.