Free cookie consent management tool by TermsFeed Policy Generator

Changeset 17769 for branches


Ignore:
Timestamp:
10/02/20 11:38:13 (4 years ago)
Author:
chaider
Message:

#3076

  • Added parameter for estimator
  • Used IntervalUtil methods for the constraint checking
Location:
branches/3076_IA_evaluators_analyzers/HeuristicLab.Problems.DataAnalysis.Symbolic.Regression/3.4
Files:
3 edited

Legend:

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

    r17761 r17769  
    3939    SymbolicRegressionMultiObjectiveMultiSoftConstraintEvaluator : SymbolicRegressionMultiObjectiveSplittingEvaluator {
    4040    public const string DimensionsParameterName = "Dimensions";
    41 
    42     public IFixedValueParameter<IntValue> DimensionsParameter => (IFixedValueParameter<IntValue>)Parameters[DimensionsParameterName];
    43 
     41    private const string BoundsEstimatorParameterName = "Bounds estimator";
     42
     43    public IFixedValueParameter<IntValue> DimensionsParameter =>
     44      (IFixedValueParameter<IntValue>) Parameters[DimensionsParameterName];
     45
     46    public IValueParameter<IBoundsEstimator> BoundsEstimatorParameter =>
     47      (IValueParameter<IBoundsEstimator>) Parameters[BoundsEstimatorParameterName];
     48
     49    public IBoundsEstimator BoundsEstimator {
     50      get => BoundsEstimatorParameter.Value;
     51      set => BoundsEstimatorParameter.Value = value;
     52    }
    4453
    4554    #region Constructors
     55
    4656    public SymbolicRegressionMultiObjectiveMultiSoftConstraintEvaluator() {
    4757      Parameters.Add(new FixedValueParameter<IntValue>(DimensionsParameterName, new IntValue(2)));
     58      Parameters.Add(new ValueParameter<IBoundsEstimator>(BoundsEstimatorParameterName, new IABoundsEstimator()));
    4859    }
    4960
     
    5869    [StorableHook(HookType.AfterDeserialization)]
    5970    private void AfterDeserialization() {
    60       if(!Parameters.ContainsKey(DimensionsParameterName))
     71      if (!Parameters.ContainsKey(DimensionsParameterName))
    6172        Parameters.Add(new FixedValueParameter<IntValue>(DimensionsParameterName, new IntValue(2)));
     73
     74      if (!Parameters.ContainsKey(BoundsEstimatorParameterName))
     75        Parameters.Add(new ValueParameter<IBoundsEstimator>(BoundsEstimatorParameterName, new IABoundsEstimator()));
    6276    }
    6377
     
    6882
    6983    public override IOperation InstrumentedApply() {
    70       var rows                  = GenerateRowsToEvaluate();
    71       var solution              = SymbolicExpressionTreeParameter.ActualValue;
    72       var problemData           = ProblemDataParameter.ActualValue;
    73       var interpreter           = SymbolicDataAnalysisTreeInterpreterParameter.ActualValue;
    74       var estimationLimits      = EstimationLimitsParameter.ActualValue;
    75       var minIntervalWidth      = MinSplittingWidth;
    76       var maxIntervalSplitDepth = MaxSplittingDepth;
    77       var applyLinearScaling  = ApplyLinearScalingParameter.ActualValue.Value;
    78 
    79       if (applyLinearScaling) {
    80         //Check for interval arithmetic grammar
    81         //remove scaling nodes for linear scaling evaluation
    82         var                    rootNode  = new ProgramRootSymbol().CreateTreeNode();
    83         var                    startNode = new StartSymbol().CreateTreeNode();
    84         SymbolicExpressionTree newTree   = null;
    85         foreach (var node in solution.IterateNodesPrefix())
    86           if (node.Symbol.Name == "Scaling") {
    87             for (var i = 0; i < node.SubtreeCount; ++i) startNode.AddSubtree(node.GetSubtree(i));
    88             rootNode.AddSubtree(startNode);
    89             newTree = new SymbolicExpressionTree(rootNode);
    90             break;
    91           }
    92 
    93         //calculate alpha and beta for scaling
    94         var estimatedValues = interpreter.GetSymbolicExpressionTreeValues(newTree, problemData.Dataset, rows);
    95         var targetValues    = problemData.Dataset.GetDoubleValues(problemData.TargetVariable, rows);
    96         OnlineLinearScalingParameterCalculator.Calculate(estimatedValues, targetValues, out var alpha, out var beta,
    97           out var errorState);
    98         //Set alpha and beta to the scaling nodes from ia grammar
    99         foreach (var node in solution.IterateNodesPrefix())
    100           if (node.Symbol.Name == "Offset") {
    101             node.RemoveSubtree(1);
    102             var alphaNode = new ConstantTreeNode(new Constant()) {Value = alpha};
    103             node.AddSubtree(alphaNode);
    104           } else if (node.Symbol.Name == "Scaling") {
    105             node.RemoveSubtree(1);
    106             var betaNode = new ConstantTreeNode(new Constant()) {Value = beta};
    107             node.AddSubtree(betaNode);
    108           }
    109       }
    110 
    111       if (UseConstantOptimization)
     84      var rows = GenerateRowsToEvaluate();
     85      var solution = SymbolicExpressionTreeParameter.ActualValue;
     86      var problemData = ProblemDataParameter.ActualValue;
     87      var interpreter = SymbolicDataAnalysisTreeInterpreterParameter.ActualValue;
     88      var estimationLimits = EstimationLimitsParameter.ActualValue;
     89      var applyLinearScaling = ApplyLinearScalingParameter.ActualValue.Value;
     90
     91      if (UseConstantOptimization) {
    11292        SymbolicRegressionConstantOptimizationEvaluator.OptimizeConstants(interpreter, solution, problemData, rows,
    11393          false,
     
    11696          estimationLimits.Lower,
    11797          estimationLimits.Upper);
     98      } else {
     99        if (applyLinearScaling) {
     100          //Check for interval arithmetic grammar
     101          //remove scaling nodes for linear scaling evaluation
     102          var rootNode = new ProgramRootSymbol().CreateTreeNode();
     103          var startNode = new StartSymbol().CreateTreeNode();
     104          SymbolicExpressionTree newTree = null;
     105          foreach (var node in solution.IterateNodesPrefix())
     106            if (node.Symbol.Name == "Scaling") {
     107              for (var i = 0; i < node.SubtreeCount; ++i) startNode.AddSubtree(node.GetSubtree(i));
     108              rootNode.AddSubtree(startNode);
     109              newTree = new SymbolicExpressionTree(rootNode);
     110              break;
     111            }
     112
     113          //calculate alpha and beta for scaling
     114          var estimatedValues = interpreter.GetSymbolicExpressionTreeValues(newTree, problemData.Dataset, rows);
     115          var targetValues = problemData.Dataset.GetDoubleValues(problemData.TargetVariable, rows);
     116          OnlineLinearScalingParameterCalculator.Calculate(estimatedValues, targetValues, out var alpha, out var beta,
     117            out var errorState);
     118          //Set alpha and beta to the scaling nodes from ia grammar
     119          foreach (var node in solution.IterateNodesPrefix())
     120            if (node.Symbol.Name == "Offset") {
     121              node.RemoveSubtree(1);
     122              var alphaNode = new ConstantTreeNode(new Constant()) {Value = alpha};
     123              node.AddSubtree(alphaNode);
     124            } else if (node.Symbol.Name == "Scaling") {
     125              node.RemoveSubtree(1);
     126              var betaNode = new ConstantTreeNode(new Constant()) {Value = beta};
     127              node.AddSubtree(betaNode);
     128            }
     129        }
     130      }
    118131
    119132      var qualities = Calculate(interpreter, solution, estimationLimits.Lower, estimationLimits.Upper, problemData,
    120         rows, UseIntervalSplitting);
     133        rows, BoundsEstimator);
    121134      QualitiesParameter.ActualValue = new DoubleArray(qualities);
    122135      return base.InstrumentedApply();
    123136    }
    124137
    125     public override double[] Evaluate(IExecutionContext context, ISymbolicExpressionTree tree,
    126                                       IRegressionProblemData problemData,
    127                                       IEnumerable<int> rows) {
     138    public override double[] Evaluate(
     139      IExecutionContext context, ISymbolicExpressionTree tree,
     140      IRegressionProblemData problemData,
     141      IEnumerable<int> rows) {
    128142      SymbolicDataAnalysisTreeInterpreterParameter.ExecutionContext = context;
    129       EstimationLimitsParameter.ExecutionContext                    = context;
    130       ApplyLinearScalingParameter.ExecutionContext                  = context;
     143      EstimationLimitsParameter.ExecutionContext = context;
     144      ApplyLinearScalingParameter.ExecutionContext = context;
    131145
    132146      var quality = Calculate(SymbolicDataAnalysisTreeInterpreterParameter.ActualValue, tree,
    133147        EstimationLimitsParameter.ActualValue.Lower, EstimationLimitsParameter.ActualValue.Upper,
    134         problemData, rows, UseIntervalSplitting);
     148        problemData, rows, BoundsEstimator);
    135149
    136150      SymbolicDataAnalysisTreeInterpreterParameter.ExecutionContext = null;
    137       EstimationLimitsParameter.ExecutionContext                    = null;
    138       ApplyLinearScalingParameter.ExecutionContext                  = null;
     151      EstimationLimitsParameter.ExecutionContext = null;
     152      ApplyLinearScalingParameter.ExecutionContext = null;
    139153
    140154      return quality;
     
    142156
    143157
    144     public static double[] Calculate(ISymbolicDataAnalysisExpressionTreeInterpreter interpreter,
    145                                      ISymbolicExpressionTree solution, double lowerEstimationLimit,
    146                                      double upperEstimationLimit,
    147                                      IRegressionProblemData problemData, IEnumerable<int> rows, bool splitting) {
     158    public static double[] Calculate(
     159      ISymbolicDataAnalysisExpressionTreeInterpreter interpreter,
     160      ISymbolicExpressionTree solution, double lowerEstimationLimit,
     161      double upperEstimationLimit,
     162      IRegressionProblemData problemData, IEnumerable<int> rows, IBoundsEstimator estimator) {
    148163      OnlineCalculatorError errorState;
    149       var estimatedValues =
    150         interpreter.GetSymbolicExpressionTreeValues(solution, problemData.Dataset, rows);
     164      var estimatedValues = interpreter.GetSymbolicExpressionTreeValues(solution, problemData.Dataset, rows);
    151165      var targetValues = problemData.Dataset.GetDoubleValues(problemData.TargetVariable, rows);
     166      var constraints = problemData.IntervalConstraints.Constraints.Where(c => c.Enabled);
     167      var intervalCollection = problemData.VariableRanges;
    152168
    153169      double nmse;
     
    160176        nmse = 1.0;
    161177
    162       var constraints    = problemData.IntervalConstraints.Constraints.Where(c => c.Enabled);
    163       var variableRanges = problemData.VariableRanges.GetReadonlyDictionary();
    164 
    165       var objectives          = new List<double> {nmse};
    166       var intervalInterpreter = new IntervalInterpreter(){UseIntervalSplitting = splitting};
    167 
    168       var constraintObjectives = new List<double>();
    169       foreach (var c in constraints) {
    170         var penalty = ConstraintExceeded(c, intervalInterpreter, variableRanges,
    171           solution);
    172         var maxP = 0.1;
    173 
    174         if (double.IsNaN(penalty) || double.IsInfinity(penalty) || penalty > maxP)
    175           penalty = maxP;
    176 
    177         constraintObjectives.Add(penalty);
    178       }
    179 
    180       objectives.AddRange(constraintObjectives);
    181 
     178
     179      var objectives = new List<double> {nmse};
     180      ////var intervalInterpreter = new IntervalInterpreter() {UseIntervalSplitting = splitting};
     181
     182      //var constraintObjectives = new List<double>();
     183      //foreach (var c in constraints) {
     184      //  var penalty = ConstraintExceeded(c, intervalInterpreter, variableRanges,
     185      //    solution);
     186      //  var maxP = 0.1;
     187
     188      //  if (double.IsNaN(penalty) || double.IsInfinity(penalty) || penalty > maxP)
     189      //    penalty = maxP;
     190
     191      //  constraintObjectives.Add(penalty);
     192      //}
     193
     194      //objectives.AddRange(constraintObjectives);
     195
     196      //return objectives.ToArray();
     197
     198      var results = IntervalUtil.IntervalConstraintsViolation(constraints, estimator, intervalCollection, solution);
     199      objectives.AddRange(results);
    182200      return objectives.ToArray();
    183     }
    184 
    185     public static double ConstraintExceeded(IntervalConstraint constraint, IntervalInterpreter intervalInterpreter,
    186                                             IReadOnlyDictionary<string, Interval> variableRanges,
    187                                             ISymbolicExpressionTree solution) {
    188       if (constraint.Variable != null && !variableRanges.ContainsKey(constraint.Variable))
    189         throw new ArgumentException(
    190           $"The given variable {constraint.Variable} in the constraint does not exists in the model.",
    191           nameof(IntervalConstraintsParser));
    192       Interval resultInterval;
    193       if (!constraint.IsDerivative) {
    194         resultInterval =
    195           intervalInterpreter.GetSymbolicExpressionTreeInterval(solution, variableRanges);
    196       }
    197       else {
    198         var tree = solution;
    199         for (var i = 0; i < constraint.NumberOfDerivations; ++i)
    200           tree = DerivativeCalculator.Derive(tree, constraint.Variable);
    201 
    202         resultInterval =
    203           intervalInterpreter.GetSymbolicExpressionTreeInterval(tree, variableRanges);
    204       }
    205      
    206       //Calculate soft-constraints for intervals
    207       if (constraint.Interval.Contains(resultInterval)) return 0;
    208       var pLower = 0.0;
    209       var pUpper = 0.0;
    210       if (constraint.Interval.Contains(resultInterval.LowerBound))
    211         pLower = 0;
    212       else
    213         pLower = constraint.Interval.LowerBound - resultInterval.LowerBound;
    214 
    215       if (constraint.Interval.Contains(resultInterval.UpperBound))
    216         pUpper = 0;
    217       else
    218         pUpper = resultInterval.UpperBound - constraint.Interval.UpperBound;
    219       var penalty = Math.Abs(pLower) + Math.Abs(pUpper);
    220 
    221       return penalty;
    222201    }
    223202
     
    226205     * All following objectives have to be minimized ==> Constraints
    227206     */
     207
    228208    public override IEnumerable<bool> Maximization {
    229209      get {
    230         var objectives = new List<bool> {false};          //First NMSE ==> min
     210        var objectives = new List<bool> {false}; //First NMSE ==> min
    231211        objectives.AddRange(Enumerable.Repeat(false, DimensionsParameter.Value.Value)); //Constraints ==> min
    232        
     212
    233213        return objectives;
    234214      }
  • branches/3076_IA_evaluators_analyzers/HeuristicLab.Problems.DataAnalysis.Symbolic.Regression/3.4/SingleObjective/Evaluators/SymbolicRegressionSingleObjectiveConstraintEvaluator.cs

    r17764 r17769  
    4343
    4444    public IValueParameter<IBoundsEstimator> BoundsEstimatorParameter =>
    45       (IValueParameter<IBoundsEstimator>)Parameters[BoundsEstimatorParameterName];
     45      (IValueParameter<IBoundsEstimator>) Parameters[BoundsEstimatorParameterName];
    4646
    4747    public bool UseConstantOptimization {
     
    122122        Parameters.Add(new ValueParameter<IBoundsEstimator>(BoundsEstimatorParameterName,
    123123          "Select the Boundsestimator.", new IABoundsEstimator()));
    124 
    125124    }
    126125
     
    178177
    179178      var quality = Calculate(interpreter, solution, estimationLimits.Lower, estimationLimits.Upper, problemData, rows,
    180         UseSoftConstraints, PenaltyMultiplier);
     179        PenaltyMultiplier, BoundsEstimator);
    181180      QualityParameter.ActualValue = new DoubleValue(quality);
    182181
     
    188187      ISymbolicExpressionTree solution, double lowerEstimationLimit,
    189188      double upperEstimationLimit,
    190       IRegressionProblemData problemData, IEnumerable<int> rows, bool useSoftConstraints,
    191       double penaltyMultiplier) {
     189      IRegressionProblemData problemData, IEnumerable<int> rows,
     190      double penaltyMultiplier, IBoundsEstimator estimator) {
    192191      var estimatedValues = interpreter.GetSymbolicExpressionTreeValues(solution, problemData.Dataset, rows);
    193192      var targetValues = problemData.Dataset.GetDoubleValues(problemData.TargetVariable, rows);
    194193      var constraints = problemData.IntervalConstraints.EnabledConstraints;
    195       var variableRanges = problemData.VariableRanges.GetReadonlyDictionary();
     194      var intervalCollection = problemData.VariableRanges;
    196195
    197196      var boundedEstimatedValues = estimatedValues.LimitToRange(lowerEstimationLimit, upperEstimationLimit);
     
    199198        out var errorState);
    200199
    201       if (!SymbolicRegressionConstraintAnalyzer.ConstraintsSatisfied(constraints, variableRanges, solution,
    202         out var error)) {
    203         if (useSoftConstraints) {
    204           if (double.IsNaN(error) || double.IsInfinity(error)) {
    205             nmse += penaltyMultiplier * 1.0;
    206           } else {
    207             nmse += penaltyMultiplier * error;
    208           }
    209 
    210           nmse = Math.Min(1.0, nmse);
    211         } else {
    212           nmse = 1.0;
    213         }
    214       }
    215 
    216200      if (errorState != OnlineCalculatorError.None) {
     201        return 1.0;
     202      }
     203
     204      //if (!SymbolicRegressionConstraintAnalyzer.ConstraintsSatisfied(constraints, variableRanges, solution,
     205      //  out var error)) {
     206      //  if (useSoftConstraints) {
     207      //    if (double.IsNaN(error) || double.IsInfinity(error)) {
     208      //      nmse += penaltyMultiplier * 1.0;
     209      //    } else {
     210      //      nmse += penaltyMultiplier * error;
     211      //    }
     212
     213      //    nmse = Math.Min(1.0, nmse);
     214      //  } else {
     215      //    nmse = 1.0;
     216      //  }
     217      //}
     218
     219
     220      if (IntervalUtil.IntervalConstraintsViolation(constraints, estimator, intervalCollection, solution)
     221                      .Any(x => x != 0.0)) {
    217222        nmse = 1.0;
    218223      }
     
    230235      var nmse = Calculate(SymbolicDataAnalysisTreeInterpreterParameter.ActualValue, tree,
    231236        EstimationLimitsParameter.ActualValue.Lower, EstimationLimitsParameter.ActualValue.Upper,
    232         problemData, rows, UseSoftConstraints, PenaltyMultiplier);
     237        problemData, rows, PenaltyMultiplier, BoundsEstimator);
    233238
    234239      SymbolicDataAnalysisTreeInterpreterParameter.ExecutionContext = null;
  • branches/3076_IA_evaluators_analyzers/HeuristicLab.Problems.DataAnalysis.Symbolic.Regression/3.4/SymbolicRegressionConstraintAnalyzer.cs

    r17766 r17769  
    2929
    3030    public ILookupParameter<IRegressionProblemData> RegressionProblemDataParameter =>
    31       (ILookupParameter<IRegressionProblemData>)Parameters[ProblemDataParameterName];
     31      (ILookupParameter<IRegressionProblemData>) Parameters[ProblemDataParameterName];
    3232
    3333    public IResultParameter<DataTable> ConstraintViolationParameter =>
    34       (IResultParameter<DataTable>)Parameters[ConstraintViolationParameterName];
     34      (IResultParameter<DataTable>) Parameters[ConstraintViolationParameterName];
    3535
    3636    public ILookupParameter<DoubleValue> PenalityMultiplierParameter =>
    37       (ILookupParameter<DoubleValue>)Parameters[PenalityMultiplierParameterName];
     37      (ILookupParameter<DoubleValue>) Parameters[PenalityMultiplierParameterName];
    3838
    3939    public IValueParameter<IntValue> StepSizeParameter =>
    40       (IValueParameter<IntValue>)Parameters[StepSizeParameterName];
     40      (IValueParameter<IntValue>) Parameters[StepSizeParameterName];
    4141
    4242    public IValueParameter<IntValue> MaximumStepsParameter =>
    43       (IValueParameter<IntValue>)Parameters[MaximumStepsParameterName];
     43      (IValueParameter<IntValue>) Parameters[MaximumStepsParameterName];
    4444
    4545    public IResultParameter<DataTable> PenalityMultiplierResultParameter =>
    46       (IResultParameter<DataTable>)Parameters[PenalityMultiplierResultParameterName];
     46      (IResultParameter<DataTable>) Parameters[PenalityMultiplierResultParameterName];
     47
    4748    public IValueParameter<DoubleValue> StartPenalityParameter =>
    48       (IValueParameter<DoubleValue>)Parameters[StartPenalityParameterName];
     49      (IValueParameter<DoubleValue>) Parameters[StartPenalityParameterName];
    4950
    5051    #endregion
     
    8081
    8182
    82 
    83 
    8483      ConstraintViolationParameter.DefaultValue = new DataTable(ConstraintViolationParameterName) {
    85         VisualProperties =
    86           {
    87             XAxisTitle = "Generations",
    88             YAxisTitle = "Constraint Violations"
    89           }
     84        VisualProperties = {
     85          XAxisTitle = "Generations",
     86          YAxisTitle = "Constraint Violations"
     87        }
    9088      };
    9189
    9290      PenalityMultiplierResultParameter.DefaultValue = new DataTable(PenalityMultiplierResultParameterName) {
    93         VisualProperties =
    94           {
    95             XAxisTitle = "Generations",
    96             YAxisTitle = "Penality Multiplier"
    97           }
     91        VisualProperties = {
     92          XAxisTitle = "Generations",
     93          YAxisTitle = "Penality Multiplier"
     94        }
    9895      };
    9996    }
     
    114111      if (!Parameters.ContainsKey(PenalityMultiplierParameterName))
    115112        Parameters.Add(new LookupParameter<DoubleValue>(PenalityMultiplierParameterName,
    116         "Lookup parameter for the penality multiplier.", "PenalityMultiplier"));
     113          "Lookup parameter for the penality multiplier.", "PenalityMultiplier"));
    117114
    118115      if (!Parameters.ContainsKey(PenalityMultiplierResultParameterName)) {
    119116        Parameters.Add(new ResultParameter<DataTable>(PenalityMultiplierResultParameterName,
    120         "Shows the behavior of the penality multiplier."));
     117          "Shows the behavior of the penality multiplier."));
    121118
    122119        PenalityMultiplierResultParameter.DefaultValue = new DataTable(PenalityMultiplierResultParameterName) {
    123           VisualProperties =
    124           {
     120          VisualProperties = {
    125121            XAxisTitle = "Generations",
    126122            YAxisTitle = "Penality Multiplier"
     
    131127      if (!Parameters.ContainsKey(StepSizeParameterName))
    132128        Parameters.Add(new ValueParameter<IntValue>(StepSizeParameterName,
    133         "Defines the step size for the increasing penality multiplier.", new IntValue(1)));
     129          "Defines the step size for the increasing penality multiplier.", new IntValue(1)));
    134130
    135131      if (!Parameters.ContainsKey(MaximumStepsParameterName))
    136132        Parameters.Add(new ValueParameter<IntValue>(MaximumStepsParameterName,
    137         "Defines maximum steps for the increasing penality multiplier.", new IntValue(1000)));
    138 
     133          "Defines maximum steps for the increasing penality multiplier.", new IntValue(1000)));
    139134
    140135
    141136      if (!Parameters.ContainsKey(StartPenalityParameterName))
    142137        Parameters.Add(new ValueParameter<DoubleValue>(StartPenalityParameterName,
    143         "The start value for the penality multiplier.", new DoubleValue(0.5)));
     138          "The start value for the penality multiplier.", new DoubleValue(0.5)));
    144139    }
    145140
     
    150145      var startValue = StartPenalityParameter?.Value?.Value ?? 0.5;
    151146      var maximumSteps = MaximumStepsParameter?.Value?.Value ?? 1000;
    152       var penalityMultiplier = new DoubleValue(LinearDiscreteDoubleValueModifier.Apply(0, startValue, 1.0, (int)(Iterations / stepSize) * stepSize, 0, maximumSteps));
     147      var penalityMultiplier = new DoubleValue(LinearDiscreteDoubleValueModifier.Apply(0, startValue, 1.0,
     148        (int) (Iterations / stepSize) * stepSize, 0, maximumSteps));
    153149      PenalityMultiplierParameter.ActualValue = penalityMultiplier;
    154150      //GeneralizedExponentialDiscreteDoubleValueModifier
     
    170166      var interpreter = new IntervalInterpreter();
    171167      foreach (var constraint in constraints) {
    172         var violations = trees.Select(tree => ConstraintSatisfied(constraint, interpreter, variableRanges, tree, out double error))
     168        var violations = trees.Select(tree =>
     169                                 ConstraintSatisfied(constraint, interpreter, variableRanges, tree, out double error))
    173170                              .Count(satisfied => !satisfied);
    174171        newDataTable.Rows[constraint.Expression].Values.Add(violations);
     
    191188        throw new
    192189          ArgumentException($"The given variable {constraint.Variable} in the constraint does not exists in the model.",
    193                             nameof(IntervalConstraintsParser));
     190            nameof(IntervalConstraintsParser));
    194191
    195192      Interval resultInterval;
    196193
    197       // create new variable ranges for defined regions
    198       IDictionary<string, Interval> regionRanges = new Dictionary<string, Interval>();
     194      //Create new variable ranges for defined regions
     195      var regionRanges = new IntervalCollection();
    199196      foreach (var kvp in variableRanges) {
    200         var value = constraint.Regions.Where(r => r.VariableName == kvp.Key).FirstOrDefault();
    201         if (kvp.Key != constraint.Target && value != null) {
    202           regionRanges.Add(kvp.Key, value.Interval);
     197        if (kvp.Key != constraint.Target &&
     198            constraint.Regions.GetReadonlyDictionary().TryGetValue(kvp.Key, out Interval val)) {
     199          regionRanges.AddInterval(kvp.Key, val);
    203200        } else {
    204           regionRanges.Add(kvp);
     201          regionRanges.AddInterval(kvp.Key, kvp.Value);
    205202        }
    206203      }
     
    208205      // calculate result interval
    209206      if (!constraint.IsDerivative) {
    210         resultInterval = intervalInterpreter.GetSymbolicExpressionTreeInterval(solution, new ReadOnlyDictionary<string, Interval>(regionRanges));
     207        resultInterval =
     208          intervalInterpreter.GetSymbolicExpressionTreeInterval(solution,
     209            regionRanges.GetReadonlyDictionary());
    211210      } else {
    212211        var tree = solution;
     
    217216        }
    218217
    219         resultInterval = intervalInterpreter.GetSymbolicExpressionTreeInterval(tree, new ReadOnlyDictionary<string, Interval>(regionRanges));
     218        resultInterval =
     219          intervalInterpreter.GetSymbolicExpressionTreeInterval(tree,
     220            regionRanges.GetReadonlyDictionary());
    220221      }
    221222
     
    248249        if (constraint.Variable != null && !variableRanges.ContainsKey(constraint.Variable))
    249250          throw new
    250             ArgumentException($"The given variable {constraint.Variable} in the constraint does not exists in the model.",
    251                               nameof(IntervalConstraintsParser));
    252 
    253         satisfied = ConstraintSatisfied(constraint, intervalInterpreter, variableRanges, solution, out double e) && satisfied;
     251            ArgumentException(
     252              $"The given variable {constraint.Variable} in the constraint does not exists in the model.",
     253              nameof(IntervalConstraintsParser));
     254
     255        satisfied = ConstraintSatisfied(constraint, intervalInterpreter, variableRanges, solution, out double e) &&
     256                    satisfied;
    254257        error += e;
    255258        //if (!satisfied) return false;
Note: See TracChangeset for help on using the changeset viewer.