Changeset 17918


Ignore:
Timestamp:
03/29/21 09:54:58 (2 weeks ago)
Author:
mkommend
Message:

#3105: Merge trunk changes into branch.

Location:
branches/3105_PythonFormatter
Files:
2 deleted
39 edited
20 copied

Legend:

Unmodified
Added
Removed
  • branches/3105_PythonFormatter

  • branches/3105_PythonFormatter/HeuristicLab.Algorithms.DataAnalysis

  • branches/3105_PythonFormatter/HeuristicLab.Algorithms.DataAnalysis.Views

  • branches/3105_PythonFormatter/HeuristicLab.Algorithms.DataAnalysis.Views/3.4/RandomForestModelEvaluationView.cs

    r17180 r17918  
    7979    private IContent CreateModel(int idx) {
    8080      idx -= 1;
    81       var rfModel = Content.Model as RandomForestModel;
     81      var rfModel = Content.Model as IRandomForestModel;
    8282      if (rfModel == null) return null;
    8383      var regProblemData = Content.ProblemData as IRegressionProblemData;
  • branches/3105_PythonFormatter/HeuristicLab.Algorithms.DataAnalysis/3.4

  • branches/3105_PythonFormatter/HeuristicLab.Algorithms.DataAnalysis/3.4/GAM/GeneralizedAdditiveModelAlgorithm.cs

    r17815 r17918  
    3939  [Creatable(CreatableAttribute.Categories.DataAnalysisRegression, Priority = 600)]
    4040  public sealed class GeneralizedAdditiveModelAlgorithm : FixedDataAnalysisAlgorithm<IRegressionProblem> {
     41
    4142    #region ParameterNames
    4243
     
    4647    private const string SetSeedRandomlyParameterName = "SetSeedRandomly";
    4748    private const string CreateSolutionParameterName = "CreateSolution";
     49
    4850    #endregion
    4951
     
    141143      var problemData = Problem.ProblemData;
    142144      var ds = problemData.Dataset;
    143       var trainRows = problemData.TrainingIndices;
    144       var testRows = problemData.TestIndices;
     145      var trainRows = problemData.TrainingIndices.ToArray();
     146      var testRows = problemData.TestIndices.ToArray();
    145147      var avgY = problemData.TargetVariableTrainingValues.Average();
    146148      var inputVars = problemData.AllowedInputVariables.ToArray();
     
    178180      double[] resTest = problemData.TargetVariableTestValues.Select(yi => yi - avgY).ToArray();
    179181
    180       curRMSE.Value = res.StandardDeviation();
    181       curRMSETest.Value = resTest.StandardDeviation();
    182       rmseRow.Values.Add(res.StandardDeviation());
    183       rmseRowTest.Values.Add(resTest.StandardDeviation());
     182      curRMSE.Value = RMSE(res);
     183      curRMSETest.Value = RMSE(resTest);
     184      rmseRow.Values.Add(curRMSE.Value);
     185      rmseRowTest.Values.Add(curRMSETest.Value);
    184186
    185187
     
    197199          AddInPlace(resTest, f[inputIdx].GetEstimatedValues(ds, testRows));
    198200
    199           rssTable[inputIdx, 0] = res.Variance();
     201          rssTable[inputIdx, 0] = MSE(res);
    200202          f[inputIdx] = RegressSpline(problemData, inputVar, res, lambda);
    201203
     
    204206        }
    205207
    206         curRMSE.Value = res.StandardDeviation();
    207         curRMSETest.Value = resTest.StandardDeviation();
     208        curRMSE.Value = RMSE(res);
     209        curRMSETest.Value = RMSE(resTest);
    208210        rmseRow.Values.Add(curRMSE.Value);
    209211        rmseRowTest.Values.Add(curRMSETest.Value);
     
    215217        var model = new RegressionEnsembleModel(f.Concat(new[] { new ConstantModel(avgY, problemData.TargetVariable) }));
    216218        model.AverageModelEstimates = false;
    217         var solution = model.CreateRegressionSolution((IRegressionProblemData)problemData.Clone());
     219        var solution = model.CreateRegressionSolution((IRegressionProblemData)problemData.Clone());       
    218220        Results.Add(new Result("Ensemble solution", solution));
    219221      }
     222    }
     223
     224    public static double MSE(IEnumerable<double> residuals) {
     225      var mse  = residuals.Select(r => r * r).Average();
     226      return mse;
     227    }
     228
     229    public static double RMSE(IEnumerable<double> residuals) {
     230      var mse = MSE(residuals);
     231      var rmse = Math.Sqrt(mse);
     232      return rmse;
    220233    }
    221234
  • branches/3105_PythonFormatter/HeuristicLab.Algorithms.DataAnalysis/3.4/GAM/Spline1dModel.cs

    r17839 r17918  
    2626using HeuristicLab.Core;
    2727using HeuristicLab.Problems.DataAnalysis;
     28using System;
    2829
    2930namespace HeuristicLab.Algorithms.DataAnalysis {
     
    3536    private alglib.spline1d.spline1dinterpolant interpolant;
    3637
    37     [Storable]
    38     private readonly string[] variablesUsedForPrediction;
    39     public override IEnumerable<string> VariablesUsedForPrediction {
    40       get {
    41         return variablesUsedForPrediction;
     38    [Storable(OldName = "variablesUsedForPrediction")]
     39    private string[] StorableVariablesUsedForPrediction {
     40      set {
     41        if (value.Length > 1) throw new ArgumentException("A one-dimensional spline model supports only one input variable.");
     42        inputVariable = value[0];
    4243      }
    4344    }
     45
     46    [Storable]
     47    private string inputVariable;
     48    public override IEnumerable<string> VariablesUsedForPrediction => new[] { inputVariable };
    4449
    4550    [StorableConstructor]
     
    4954
    5055    private Spline1dModel(Spline1dModel orig, Cloner cloner) : base(orig, cloner) {
    51       this.variablesUsedForPrediction = orig.VariablesUsedForPrediction.ToArray();
     56      this.inputVariable = orig.inputVariable;
    5257      this.interpolant = (alglib.spline1d.spline1dinterpolant)orig.interpolant.make_copy();
    5358    }
    5459    public Spline1dModel(alglib.spline1d.spline1dinterpolant interpolant, string targetVar, string inputVar)
    55       : base(targetVar, "Spline model (1d)") {
    56       this.interpolant = (alglib.spline1d.spline1dinterpolant)interpolant.make_copy();     
    57       this.variablesUsedForPrediction = new string[] { inputVar };
     60      : base(targetVar, $"Spline model ({inputVar})") {
     61      this.interpolant = (alglib.spline1d.spline1dinterpolant)interpolant.make_copy();
     62      this.inputVariable = inputVar;     
    5863    }
    5964
    6065
    61     public override IDeepCloneable Clone(Cloner cloner) {
    62       return new Spline1dModel(this, cloner);
     66    public override IDeepCloneable Clone(Cloner cloner) => new Spline1dModel(this, cloner);
     67
     68    public override IRegressionSolution CreateRegressionSolution(IRegressionProblemData problemData) {
     69      var solution =  new RegressionSolution(this, (IRegressionProblemData)problemData.Clone());
     70      solution.Name = $"Regression Spline ({inputVariable})";
     71
     72      return solution;
    6373    }
    6474
    65     public override IRegressionSolution CreateRegressionSolution(IRegressionProblemData problemData) {
    66       return new RegressionSolution(this, (IRegressionProblemData)problemData.Clone());
    67     }
    68 
    69     public double GetEstimatedValue(double x) {
    70       return alglib.spline1d.spline1dcalc(interpolant, x);
    71     }
     75    public double GetEstimatedValue(double x) => alglib.spline1d.spline1dcalc(interpolant, x);
    7276
    7377    public override IEnumerable<double> GetEstimatedValues(IDataset dataset, IEnumerable<int> rows) {
    74       var x = dataset.GetDoubleValues(VariablesUsedForPrediction.First(), rows).ToArray();
    75       foreach (var xi in x) {
    76         yield return GetEstimatedValue(xi);
    77       }
     78      return dataset.GetDoubleValues(inputVariable, rows).Select(GetEstimatedValue);
    7879    }
    7980
  • branches/3105_PythonFormatter/HeuristicLab.Algorithms.DataAnalysis/3.4/GradientBoostedTrees/GradientBoostedTreesAlgorithm.cs

    r17180 r17918  
    281281            new AccuracyMaximizationThresholdCalculator());
    282282          var classificationProblemData = new ClassificationProblemData(problemData.Dataset,
    283             problemData.AllowedInputVariables, problemData.TargetVariable, problemData.Transformations);
     283            problemData.AllowedInputVariables, problemData.TargetVariable, transformations: problemData.Transformations);
    284284          classificationProblemData.TrainingPartition.Start = Problem.ProblemData.TrainingPartition.Start;
    285285          classificationProblemData.TrainingPartition.End = Problem.ProblemData.TrainingPartition.End;
  • branches/3105_PythonFormatter/HeuristicLab.Algorithms.DataAnalysis/3.4/RandomForest/RandomForestModelSurrogate.cs

    r17278 r17918  
    135135    }
    136136
     137    public override bool IsProblemDataCompatible(IDataAnalysisProblemData problemData, out string errorMessage) {
     138      return ActualModel.IsProblemDataCompatible(problemData, out errorMessage);
     139    }
     140
    137141    //RegressionModel methods
    138142    public bool IsProblemDataCompatible(IRegressionProblemData problemData, out string errorMessage) {
  • branches/3105_PythonFormatter/HeuristicLab.DataPreprocessing

  • branches/3105_PythonFormatter/HeuristicLab.DataPreprocessing/3.4

  • branches/3105_PythonFormatter/HeuristicLab.DataPreprocessing/3.4/ProblemDataCreator.cs

    r17180 r17918  
    9696        targetVariable = context.Data.VariableNames.First();
    9797      var inputVariables = GetDoubleInputVariables(targetVariable);
    98       var newProblemData = new ClassificationProblemData(ExportedDataset, inputVariables, targetVariable, Transformations) {
     98      var newProblemData = new ClassificationProblemData(ExportedDataset, inputVariables, targetVariable, transformations: Transformations) {
    9999        PositiveClass = oldProblemData.PositiveClass
    100100      };
  • branches/3105_PythonFormatter/HeuristicLab.Encodings.SymbolicExpressionTreeEncoding

  • branches/3105_PythonFormatter/HeuristicLab.Encodings.SymbolicExpressionTreeEncoding/3.4/Crossovers/SubtreeCrossover.cs

    r17491 r17918  
    5555      get { return (IValueLookupParameter<IntValue>)Parameters[MaximumSymbolicExpressionTreeDepthParameterName]; }
    5656    }
    57     public IFixedValueParameter<DoubleValue> CrossoverProbabilityParameter {
    58       get { return (IFixedValueParameter<DoubleValue>)Parameters[CrossoverProbabilityParameterName]; }
     57    public IFixedValueParameter<PercentValue> CrossoverProbabilityParameter {
     58      get { return (IFixedValueParameter<PercentValue>)Parameters[CrossoverProbabilityParameterName]; }
    5959    }
    6060    #endregion
     
    8181      Parameters.Add(new ValueLookupParameter<IntValue>(MaximumSymbolicExpressionTreeLengthParameterName, "The maximal length (number of nodes) of the symbolic expression tree."));
    8282      Parameters.Add(new ValueLookupParameter<IntValue>(MaximumSymbolicExpressionTreeDepthParameterName, "The maximal depth of the symbolic expression tree (a tree with one node has depth = 0)."));
    83       Parameters.Add(new ValueLookupParameter<PercentValue>(InternalCrossoverPointProbabilityParameterName, "The probability to select an internal crossover point (instead of a leaf node).", new PercentValue(0.9)));
    84       Parameters.Add(new FixedValueParameter<DoubleValue>(CrossoverProbabilityParameterName, "", new DoubleValue(1)));
     83      Parameters.Add(new ValueLookupParameter<PercentValue>(InternalCrossoverPointProbabilityParameterName, "The probability to select an internal crossover point (instead of a leaf node).", new PercentValue(0.9, true)));
     84      Parameters.Add(new FixedValueParameter<PercentValue>(CrossoverProbabilityParameterName, "The probability that a crossover is performed. Otherwise a copy of the first parent is returned.", new PercentValue(1, true)));
    8585    }
    8686
    8787    [StorableHook(HookType.AfterDeserialization)]
    8888    private void AfterDeserialization() {
     89      // replace with PercentValue for files which had CrossoverProbability as DoubleValue
     90      if (Parameters.ContainsKey(CrossoverProbabilityParameterName) && (Parameters[CrossoverProbabilityParameterName] is IFixedValueParameter<DoubleValue> oldParam)) {
     91        var oldValue = oldParam.Value.Value;
     92        Parameters.Remove(oldParam);
     93        Parameters.Add(new FixedValueParameter<PercentValue>(CrossoverProbabilityParameterName, "The probability that a crossover is performed. Otherwise a copy of the first parent is returned.", new PercentValue(oldValue)));
     94      }
    8995      if (!Parameters.ContainsKey(CrossoverProbabilityParameterName)) {
    90         Parameters.Add(new FixedValueParameter<DoubleValue>(CrossoverProbabilityParameterName, "", new DoubleValue(1)));
     96        Parameters.Add(new FixedValueParameter<PercentValue>(CrossoverProbabilityParameterName, "The probability that a crossover is performed. Otherwise a copy of the first parent is returned.", new PercentValue(1, true)));
    9197      }
    9298    }
     
    106112      double probability,
    107113      double internalCrossoverPointProbability, int maxTreeLength, int maxTreeDepth) {
    108       if ((probability < 1) && (random.NextDouble() >= probability)) return random.NextDouble() < 0.5 ? parent0 : parent1;
     114      if ((probability < 1) && (random.NextDouble() >= probability)) return parent0;
    109115      // select a random crossover point in the first parent
    110116      CutPoint crossoverPoint0;
  • branches/3105_PythonFormatter/HeuristicLab.Problems.DataAnalysis

  • branches/3105_PythonFormatter/HeuristicLab.Problems.DataAnalysis.Symbolic

  • branches/3105_PythonFormatter/HeuristicLab.Problems.DataAnalysis.Symbolic.Regression

  • branches/3105_PythonFormatter/HeuristicLab.Problems.DataAnalysis.Symbolic.Regression/3.4

  • branches/3105_PythonFormatter/HeuristicLab.Problems.DataAnalysis.Symbolic.Regression/3.4/HeuristicLab.Problems.DataAnalysis.Symbolic.Regression-3.4.csproj

    r16658 r17918  
    119119  </ItemGroup>
    120120  <ItemGroup>
     121    <Compile Include="MultiObjective\NMSEConstraintsEvaluator.cs" />
    121122    <Compile Include="MultiObjective\PearsonRSquaredNestedTreeSizeEvaluator.cs" />
    122123    <Compile Include="MultiObjective\PearsonRSquaredNumberOfVariablesEvaluator.cs" />
     
    125126    <Compile Include="MultiObjective\SymbolicRegressionMultiObjectiveValidationBestSolutionAnalyzer.cs" />
    126127    <Compile Include="Plugin.cs" />
     128    <Compile Include="ShapeConstraintsAnalyzer.cs" />
    127129    <Compile Include="SingleObjective\ConstantOptimizationAnalyzer.cs" />
     130    <Compile Include="SingleObjective\Evaluators\NMSEConstraintsEvaluator.cs" />
    128131    <Compile Include="SingleObjective\Evaluators\SymbolicRegressionMeanRelativeErrorEvaluator.cs" />
    129132    <Compile Include="SingleObjective\SymbolicRegressionSolutionsAnalyzer.cs" />
  • branches/3105_PythonFormatter/HeuristicLab.Problems.DataAnalysis.Symbolic.Regression/3.4/SingleObjective/SymbolicRegressionSingleObjectiveProblem.cs

    r17180 r17918  
    9191        changed = true;
    9292      }
     93
     94      if (!Operators.OfType<ShapeConstraintsAnalyzer>().Any()) {
     95        Operators.Add(new ShapeConstraintsAnalyzer());
     96        changed = true;
     97      }
    9398      if (changed) {
    9499        ParameterizeOperators();
     
    113118      Operators.Add(new SymbolicRegressionSolutionsAnalyzer());
    114119      Operators.Add(new SymbolicExpressionTreePhenotypicSimilarityCalculator());
     120      Operators.Add(new ShapeConstraintsAnalyzer());
    115121      Operators.Add(new SymbolicRegressionPhenotypicDiversityAnalyzer(Operators.OfType<SymbolicExpressionTreePhenotypicSimilarityCalculator>()) { DiversityResultName = "Phenotypic Diversity" });
    116122      ParameterizeOperators();
  • branches/3105_PythonFormatter/HeuristicLab.Problems.DataAnalysis.Symbolic.Regression/3.4/SymbolicRegressionSolution.cs

    r17579 r17918  
    109109          Add(new Result(ModelBoundsResultName, "Results concerning the derivation of symbolic regression solution", value));
    110110        }
    111 
    112111      }
    113112    }
  • branches/3105_PythonFormatter/HeuristicLab.Problems.DataAnalysis.Symbolic/3.4/Converters/DerivativeCalculator.cs

    r17180 r17918  
    149149        return Product(Product(CreateConstant(3.0), Square(f)), Derive(f, variableName));
    150150      }
     151      if (branch.Symbol is Power) {
     152        // HL evaluators handle power strangely (exponent is rounded to an integer)
     153        // here we only support the case when the exponent is a constant integer
     154        var exponent = branch.GetSubtree(1) as ConstantTreeNode;
     155        if (exponent != null && Math.Truncate(exponent.Value) == exponent.Value) {
     156          var newPower = (ISymbolicExpressionTreeNode)branch.Clone();
     157          var f = (ISymbolicExpressionTreeNode)newPower.GetSubtree(0).Clone();
     158          var newExponent = (ConstantTreeNode)newPower.GetSubtree(1);
     159          newExponent.Value -= 1;
     160          return Product(Product(CreateConstant(exponent.Value), newPower), Derive(f, variableName));
     161        } else throw new NotSupportedException("Cannot derive non-integer powers");
     162      }
    151163      if (branch.Symbol is Absolute) {
    152164        var f = (ISymbolicExpressionTreeNode)branch.GetSubtree(0).Clone();
     
    263275          !(n.Symbol is Cube) &&
    264276          !(n.Symbol is CubeRoot) &&
     277          !(n.Symbol is Power) &&
    265278          !(n.Symbol is Absolute) &&
    266279          !(n.Symbol is AnalyticQuotient) &&
     280          !(n.Symbol is HyperbolicTangent) &&
    267281          !(n.Symbol is Sine) &&
    268282          !(n.Symbol is Cosine) &&
  • branches/3105_PythonFormatter/HeuristicLab.Problems.DataAnalysis.Symbolic/3.4/HeuristicLab.Problems.DataAnalysis.Symbolic-3.4.csproj

    r17855 r17918  
    107107      <Private>False</Private>
    108108    </Reference>
    109     <Reference Include="HEAL.Attic, Version=1.0.0.0, Culture=neutral, PublicKeyToken=ba48961d6f65dcec, processorArchitecture=MSIL">
     109    <Reference Include="HEAL.Attic, Version=1.4.0.0, Culture=neutral, PublicKeyToken=ba48961d6f65dcec, processorArchitecture=MSIL">
    110110      <SpecificVersion>False</SpecificVersion>
    111111      <HintPath>..\..\bin\HEAL.Attic.dll</HintPath>
     
    158158    <Compile Include="Formatters\SymbolicDataAnalysisExpressionCSharpFormatter.cs" />
    159159    <Compile Include="Grammars\DataAnalysisGrammar.cs" />
     160    <Compile Include="Grammars\IntervalArithmeticGrammar.cs" />
    160161    <Compile Include="Hashing\HashExtensions.cs" />
    161162    <Compile Include="Hashing\HashUtil.cs" />
     
    164165    <Compile Include="Importer\SymbolicExpressionImporter.cs" />
    165166    <Compile Include="Importer\Token.cs" />
     167    <Compile Include="Interfaces\IBoundsEstimator.cs" />
    166168    <Compile Include="Interfaces\IModelBacktransformator.cs" />
    167169    <Compile Include="Interfaces\IVariableTreeNode.cs" />
     
    169171    <Compile Include="Interpreter\BatchInstruction.cs" />
    170172    <Compile Include="Interpreter\BatchOperations.cs" />
     173    <Compile Include="Interpreter\IntervalArithBoundsEstimator.cs" />
     174    <Compile Include="Interpreter\IntervalArithCompiledExpressionBoundsEstimator.cs" />
    171175    <Compile Include="Interpreter\IntervalInterpreter.cs" />
    172176    <Compile Include="Interpreter\SymbolicDataAnalysisExpressionCompiledTreeInterpreter.cs" />
    173177    <Compile Include="Interpreter\SymbolicDataAnalysisExpressionTreeBatchInterpreter.cs" />
    174178    <Compile Include="Interpreter\SymbolicDataAnalysisExpressionTreeNativeInterpreter.cs" />
     179    <Compile Include="IntervalUtil.cs" />
    175180    <Compile Include="Selectors\DiversitySelector.cs" />
    176181    <Compile Include="SymbolicDataAnalysisExpressionTreeAverageSimilarityCalculator.cs" />
  • branches/3105_PythonFormatter/HeuristicLab.Problems.DataAnalysis.Symbolic/3.4/Importer/InfixExpressionParser.cs

    r17180 r17918  
    6464    }
    6565
    66     private class SymbolNameComparer : IEqualityComparer<ISymbol>, IComparer<ISymbol> {
     66    private class SymbolComparer : IEqualityComparer<ISymbol>, IComparer<ISymbol> {
    6767      public int Compare(ISymbol x, ISymbol y) {
    6868        return x.Name.CompareTo(y.Name);
     
    7070
    7171      public bool Equals(ISymbol x, ISymbol y) {
    72         return Compare(x, y) == 0;
     72        return x.GetType() == y.GetType();
    7373      }
    7474
    7575      public int GetHashCode(ISymbol obj) {
    76         return obj.Name.GetHashCode();
     76        return obj.GetType().GetHashCode();
    7777      }
    7878    }
     
    8080    // the lookup table is also used in the corresponding formatter
    8181    internal static readonly BidirectionalLookup<string, ISymbol>
    82       knownSymbols = new BidirectionalLookup<string, ISymbol>(StringComparer.InvariantCulture, new SymbolNameComparer());
     82      knownSymbols = new BidirectionalLookup<string, ISymbol>(StringComparer.InvariantCulture, new SymbolComparer());
    8383
    8484    private Constant constant = new Constant();
  • branches/3105_PythonFormatter/HeuristicLab.Problems.DataAnalysis.Symbolic/3.4/Interpreter/IntervalInterpreter.cs

    r17579 r17918  
    11#region License Information
     2
    23/* HeuristicLab
    34 * Copyright (C) Heuristic and Evolutionary Algorithms Laboratory (HEAL)
     
    1819 * along with HeuristicLab. If not, see <http://www.gnu.org/licenses/>.
    1920 */
     21
    2022#endregion
    2123
     
    3234namespace HeuristicLab.Problems.DataAnalysis.Symbolic {
    3335  [StorableType("DE6C1E1E-D7C1-4070-847E-63B68562B10C")]
    34   [Item("IntervalInterpreter", "Intperter for calculation of intervals of symbolic models.")]
     36  [Item("IntervalInterpreter", "Interpreter for calculation of intervals of symbolic models.")]
    3537  public sealed class IntervalInterpreter : ParameterizedNamedItem, IStatefulItem {
    36 
    3738    private const string EvaluatedSolutionsParameterName = "EvaluatedSolutions";
    38 
    39     public IFixedValueParameter<IntValue> EvaluatedSolutionsParameter {
    40       get { return (IFixedValueParameter<IntValue>)Parameters[EvaluatedSolutionsParameterName]; }
    41     }
     39    public IFixedValueParameter<IntValue> EvaluatedSolutionsParameter =>
     40      (IFixedValueParameter<IntValue>)Parameters[EvaluatedSolutionsParameterName];
    4241
    4342    public int EvaluatedSolutions {
    44       get { return EvaluatedSolutionsParameter.Value.Value; }
    45       set { EvaluatedSolutionsParameter.Value.Value = value; }
     43      get => EvaluatedSolutionsParameter.Value.Value;
     44      set => EvaluatedSolutionsParameter.Value.Value = value;
    4645    }
    4746
    4847    [StorableConstructor]
    4948    private IntervalInterpreter(StorableConstructorFlag _) : base(_) { }
     49
    5050    private IntervalInterpreter(IntervalInterpreter original, Cloner cloner)
    51         : base(original, cloner) { }
     51      : base(original, cloner) { }
    5252
    5353    public IntervalInterpreter()
    54         : base("IntervalInterpreter", "Intperter for calculation of intervals of symbolic models.") {
    55       Parameters.Add(new FixedValueParameter<IntValue>(EvaluatedSolutionsParameterName, "A counter for the total number of solutions the interpreter has evaluated", new IntValue(0)));
     54      : base("IntervalInterpreter", "Interpreter for calculation of intervals of symbolic models.") {
     55      Parameters.Add(new FixedValueParameter<IntValue>(EvaluatedSolutionsParameterName,
     56        "A counter for the total number of solutions the interpreter has evaluated", new IntValue(0)));
    5657    }
    5758
     
    6364
    6465    #region IStatefulItem Members
     66
    6567    public void InitializeState() {
    6668      EvaluatedSolutions = 0;
    6769    }
     70
    6871    public void ClearState() { }
     72
    6973    #endregion
    7074
    71     public Interval GetSymbolicExpressionTreeInterval(ISymbolicExpressionTree tree, IDataset dataset, IEnumerable<int> rows = null) {
     75    public Interval GetSymbolicExpressionTreeInterval(
     76      ISymbolicExpressionTree tree, IDataset dataset,
     77      IEnumerable<int> rows = null) {
    7278      var variableRanges = DatasetUtil.GetVariableRanges(dataset, rows);
    7379      return GetSymbolicExpressionTreeInterval(tree, variableRanges);
    7480    }
    7581
    76     public Interval GetSymbolicExpressionTreeIntervals(ISymbolicExpressionTree tree, IDataset dataset,
    77       out IDictionary<ISymbolicExpressionTreeNode, Interval> nodeIntervals, IEnumerable<int> rows = null) {
     82    public Interval GetSymbolicExpressionTreeIntervals(
     83      ISymbolicExpressionTree tree, IDataset dataset,
     84      out IDictionary<ISymbolicExpressionTreeNode, Interval>
     85        nodeIntervals, IEnumerable<int> rows = null) {
    7886      var variableRanges = DatasetUtil.GetVariableRanges(dataset, rows);
    7987      return GetSymbolicExpressionTreeIntervals(tree, variableRanges, out nodeIntervals);
    8088    }
    8189
    82     public Interval GetSymbolicExpressionTreeInterval(ISymbolicExpressionTree tree, IReadOnlyDictionary<string, Interval> variableRanges) {
     90    public Interval GetSymbolicExpressionTreeInterval(
     91      ISymbolicExpressionTree tree,
     92      IReadOnlyDictionary<string, Interval> variableRanges) {
    8393      lock (syncRoot) {
    8494        EvaluatedSolutions++;
    8595      }
    86       int instructionCount = 0;
     96
     97      Interval outputInterval;
     98
     99      var instructionCount = 0;
    87100      var instructions = PrepareInterpreterState(tree, variableRanges);
    88       var outputInterval = Evaluate(instructions, ref instructionCount);
    89 
    90       // because of numerical errors the bounds might be incorrect
    91       if (outputInterval.LowerBound <= outputInterval.UpperBound)
    92         return outputInterval;
    93       else
    94         return new Interval(outputInterval.UpperBound, outputInterval.LowerBound);
    95     }
    96 
    97 
    98     public Interval GetSymbolicExpressionTreeIntervals(ISymbolicExpressionTree tree,
    99       IReadOnlyDictionary<string, Interval> variableRanges, out IDictionary<ISymbolicExpressionTreeNode, Interval> nodeIntervals) {
     101      outputInterval = Evaluate(instructions, ref instructionCount);
     102
     103      return outputInterval.LowerBound <= outputInterval.UpperBound
     104        ? outputInterval
     105        : new Interval(outputInterval.UpperBound, outputInterval.LowerBound);
     106    }
     107
     108
     109    public Interval GetSymbolicExpressionTreeIntervals(
     110      ISymbolicExpressionTree tree,
     111      IReadOnlyDictionary<string, Interval> variableRanges,
     112      out IDictionary<ISymbolicExpressionTreeNode, Interval>
     113        nodeIntervals) {
    100114      lock (syncRoot) {
    101115        EvaluatedSolutions++;
    102116      }
    103       int instructionCount = 0;
     117
    104118      var intervals = new Dictionary<ISymbolicExpressionTreeNode, Interval>();
    105119      var instructions = PrepareInterpreterState(tree, variableRanges);
    106       var outputInterval = Evaluate(instructions, ref instructionCount, intervals);
    107 
    108       // fix incorrect intervals if necessary (could occur because of numerical errors)
     120
     121      Interval outputInterval;
     122      var instructionCount = 0;
     123      outputInterval = Evaluate(instructions, ref instructionCount, intervals);
     124
    109125      nodeIntervals = new Dictionary<ISymbolicExpressionTreeNode, Interval>();
    110126      foreach (var kvp in intervals) {
     
    119135      if (outputInterval.IsInfiniteOrUndefined || outputInterval.LowerBound <= outputInterval.UpperBound)
    120136        return outputInterval;
    121       else
    122         return new Interval(outputInterval.UpperBound, outputInterval.LowerBound);
    123     }
    124 
    125 
    126     private static Instruction[] PrepareInterpreterState(ISymbolicExpressionTree tree, IReadOnlyDictionary<string, Interval> variableRanges) {
     137
     138      return new Interval(outputInterval.UpperBound, outputInterval.LowerBound);
     139    }
     140
     141
     142    private static Instruction[] PrepareInterpreterState(
     143      ISymbolicExpressionTree tree,
     144      IReadOnlyDictionary<string, Interval> variableRanges) {
    127145      if (variableRanges == null)
    128146        throw new ArgumentNullException("No variablew ranges are present!", nameof(variableRanges));
    129147
    130       //Check if all variables used in the tree are present in the dataset
    131       foreach (var variable in tree.IterateNodesPrefix().OfType<VariableTreeNode>().Select(n => n.VariableName).Distinct()) {
    132         if (!variableRanges.ContainsKey(variable)) throw new InvalidOperationException($"No ranges for variable {variable} is present");
    133       }
    134 
    135       Instruction[] code = SymbolicExpressionTreeCompiler.Compile(tree, OpCodes.MapSymbolToOpCode);
    136       foreach (Instruction instr in code.Where(i => i.opCode == OpCodes.Variable)) {
     148      // Check if all variables used in the tree are present in the dataset
     149      foreach (var variable in tree.IterateNodesPrefix().OfType<VariableTreeNode>().Select(n => n.VariableName)
     150                                   .Distinct())
     151        if (!variableRanges.ContainsKey(variable))
     152          throw new InvalidOperationException($"No ranges for variable {variable} is present");
     153
     154      var code = SymbolicExpressionTreeCompiler.Compile(tree, OpCodes.MapSymbolToOpCode);
     155      foreach (var instr in code.Where(i => i.opCode == OpCodes.Variable)) {
    137156        var variableTreeNode = (VariableTreeNode)instr.dynamicNode;
    138157        instr.data = variableRanges[variableTreeNode.VariableName];
    139158      }
     159
    140160      return code;
    141161    }
    142162
    143     private Interval Evaluate(Instruction[] instructions, ref int instructionCounter, IDictionary<ISymbolicExpressionTreeNode, Interval> nodeIntervals = null) {
    144       Instruction currentInstr = instructions[instructionCounter];
    145       //Use ref parameter, because the tree will be iterated through recursively from the left-side branch to the right side
    146       //Update instructionCounter, whenever Evaluate is called
     163    // Use ref parameter, because the tree will be iterated through recursively from the left-side branch to the right side
     164    // Update instructionCounter, whenever Evaluate is called
     165    public static Interval Evaluate(
     166    Instruction[] instructions, ref int instructionCounter,
     167      IDictionary<ISymbolicExpressionTreeNode, Interval> nodeIntervals = null,
     168      IReadOnlyDictionary<string, Interval> variableIntervals = null) {
     169      var currentInstr = instructions[instructionCounter];
     170
    147171      instructionCounter++;
    148       Interval result = null;
     172      Interval result;
    149173
    150174      switch (currentInstr.opCode) {
    151         //Variables, Constants, ...
    152175        case OpCodes.Variable: {
    153176            var variableTreeNode = (VariableTreeNode)currentInstr.dynamicNode;
    154177            var weightInterval = new Interval(variableTreeNode.Weight, variableTreeNode.Weight);
    155             var variableInterval = (Interval)currentInstr.data;
     178
     179            Interval variableInterval;
     180            if (variableIntervals != null && variableIntervals.ContainsKey(variableTreeNode.VariableName))
     181              variableInterval = variableIntervals[variableTreeNode.VariableName];
     182            else
     183              variableInterval = (Interval)currentInstr.data;
    156184
    157185            result = Interval.Multiply(variableInterval, weightInterval);
     
    163191            break;
    164192          }
    165         //Elementary arithmetic rules
    166193        case OpCodes.Add: {
    167             result = Evaluate(instructions, ref instructionCounter, nodeIntervals);
    168             for (int i = 1; i < currentInstr.nArguments; i++) {
    169               var argumentInterval = Evaluate(instructions, ref instructionCounter, nodeIntervals);
     194            result = Evaluate(instructions, ref instructionCounter, nodeIntervals, variableIntervals);
     195            for (var i = 1; i < currentInstr.nArguments; i++) {
     196              var argumentInterval = Evaluate(instructions, ref instructionCounter, nodeIntervals, variableIntervals);
    170197              result = Interval.Add(result, argumentInterval);
    171198            }
     199
    172200            break;
    173201          }
    174202        case OpCodes.Sub: {
    175             result = Evaluate(instructions, ref instructionCounter, nodeIntervals);
     203            result = Evaluate(instructions, ref instructionCounter, nodeIntervals, variableIntervals);
    176204            if (currentInstr.nArguments == 1)
    177205              result = Interval.Multiply(new Interval(-1, -1), result);
    178206
    179             for (int i = 1; i < currentInstr.nArguments; i++) {
    180               var argumentInterval = Evaluate(instructions, ref instructionCounter, nodeIntervals);
     207            for (var i = 1; i < currentInstr.nArguments; i++) {
     208              var argumentInterval = Evaluate(instructions, ref instructionCounter, nodeIntervals, variableIntervals);
    181209              result = Interval.Subtract(result, argumentInterval);
    182210            }
     211
    183212            break;
    184213          }
    185214        case OpCodes.Mul: {
    186             result = Evaluate(instructions, ref instructionCounter, nodeIntervals);
    187             for (int i = 1; i < currentInstr.nArguments; i++) {
    188               var argumentInterval = Evaluate(instructions, ref instructionCounter, nodeIntervals);
     215            result = Evaluate(instructions, ref instructionCounter, nodeIntervals, variableIntervals);
     216            for (var i = 1; i < currentInstr.nArguments; i++) {
     217              var argumentInterval = Evaluate(instructions, ref instructionCounter, nodeIntervals, variableIntervals);
    189218              result = Interval.Multiply(result, argumentInterval);
    190219            }
     220
    191221            break;
    192222          }
    193223        case OpCodes.Div: {
    194             result = Evaluate(instructions, ref instructionCounter, nodeIntervals);
     224            result = Evaluate(instructions, ref instructionCounter, nodeIntervals, variableIntervals);
    195225            if (currentInstr.nArguments == 1)
    196226              result = Interval.Divide(new Interval(1, 1), result);
    197227
    198             for (int i = 1; i < currentInstr.nArguments; i++) {
    199               var argumentInterval = Evaluate(instructions, ref instructionCounter, nodeIntervals);
     228            for (var i = 1; i < currentInstr.nArguments; i++) {
     229              var argumentInterval = Evaluate(instructions, ref instructionCounter, nodeIntervals, variableIntervals);
    200230              result = Interval.Divide(result, argumentInterval);
    201231            }
    202             break;
    203           }
    204         //Trigonometric functions
     232
     233            break;
     234          }
    205235        case OpCodes.Sin: {
    206             var argumentInterval = Evaluate(instructions, ref instructionCounter, nodeIntervals);
     236            var argumentInterval = Evaluate(instructions, ref instructionCounter, nodeIntervals, variableIntervals);
    207237            result = Interval.Sine(argumentInterval);
    208238            break;
    209239          }
    210240        case OpCodes.Cos: {
    211             var argumentInterval = Evaluate(instructions, ref instructionCounter, nodeIntervals);
     241            var argumentInterval = Evaluate(instructions, ref instructionCounter, nodeIntervals, variableIntervals);
    212242            result = Interval.Cosine(argumentInterval);
    213243            break;
    214244          }
    215245        case OpCodes.Tan: {
    216             var argumentInterval = Evaluate(instructions, ref instructionCounter, nodeIntervals);
     246            var argumentInterval = Evaluate(instructions, ref instructionCounter, nodeIntervals, variableIntervals);
    217247            result = Interval.Tangens(argumentInterval);
    218248            break;
    219249          }
    220250        case OpCodes.Tanh: {
    221             var argumentInterval = Evaluate(instructions, ref instructionCounter, nodeIntervals);
     251            var argumentInterval = Evaluate(instructions, ref instructionCounter, nodeIntervals, variableIntervals);
    222252            result = Interval.HyperbolicTangent(argumentInterval);
    223253            break;
    224254          }
    225         //Exponential functions
    226255        case OpCodes.Log: {
    227             var argumentInterval = Evaluate(instructions, ref instructionCounter, nodeIntervals);
     256            var argumentInterval = Evaluate(instructions, ref instructionCounter, nodeIntervals, variableIntervals);
    228257            result = Interval.Logarithm(argumentInterval);
    229258            break;
    230259          }
    231260        case OpCodes.Exp: {
    232             var argumentInterval = Evaluate(instructions, ref instructionCounter, nodeIntervals);
     261            var argumentInterval = Evaluate(instructions, ref instructionCounter, nodeIntervals, variableIntervals);
    233262            result = Interval.Exponential(argumentInterval);
    234263            break;
    235264          }
    236265        case OpCodes.Square: {
    237             var argumentInterval = Evaluate(instructions, ref instructionCounter, nodeIntervals);
     266            var argumentInterval = Evaluate(instructions, ref instructionCounter, nodeIntervals, variableIntervals);
    238267            result = Interval.Square(argumentInterval);
    239268            break;
    240269          }
    241270        case OpCodes.SquareRoot: {
    242             var argumentInterval = Evaluate(instructions, ref instructionCounter, nodeIntervals);
     271            var argumentInterval = Evaluate(instructions, ref instructionCounter, nodeIntervals, variableIntervals);
    243272            result = Interval.SquareRoot(argumentInterval);
    244273            break;
    245274          }
    246275        case OpCodes.Cube: {
    247             var argumentInterval = Evaluate(instructions, ref instructionCounter, nodeIntervals);
     276            var argumentInterval = Evaluate(instructions, ref instructionCounter, nodeIntervals, variableIntervals);
    248277            result = Interval.Cube(argumentInterval);
    249278            break;
    250279          }
    251280        case OpCodes.CubeRoot: {
    252             var argumentInterval = Evaluate(instructions, ref instructionCounter, nodeIntervals);
     281            var argumentInterval = Evaluate(instructions, ref instructionCounter, nodeIntervals, variableIntervals);
    253282            result = Interval.CubicRoot(argumentInterval);
    254283            break;
    255284          }
    256285        case OpCodes.Absolute: {
    257             var argumentInterval = Evaluate(instructions, ref instructionCounter, nodeIntervals);
     286            var argumentInterval = Evaluate(instructions, ref instructionCounter, nodeIntervals, variableIntervals);
    258287            result = Interval.Absolute(argumentInterval);
    259288            break;
    260289          }
    261290        case OpCodes.AnalyticQuotient: {
    262             result = Evaluate(instructions, ref instructionCounter, nodeIntervals);
    263             for (var i = 1; i < currentInstr.nArguments; i++) {
    264               var argumentInterval = Evaluate(instructions, ref instructionCounter, nodeIntervals);
    265               result = Interval.AnalyticalQuotient(result, argumentInterval);
     291            result = Evaluate(instructions, ref instructionCounter, nodeIntervals, variableIntervals);
     292            for (var i = 1; i < currentInstr.nArguments; i++) {
     293              var argumentInterval = Evaluate(instructions, ref instructionCounter, nodeIntervals, variableIntervals);
     294              result = Interval.AnalyticQuotient(result, argumentInterval);
    266295            }
    267296
     
    272301      }
    273302
    274       if (nodeIntervals != null)
     303      if (!(nodeIntervals == null || nodeIntervals.ContainsKey(currentInstr.dynamicNode)))
    275304        nodeIntervals.Add(currentInstr.dynamicNode, result);
    276305
     
    278307    }
    279308
     309
    280310    public static bool IsCompatible(ISymbolicExpressionTree tree) {
    281       var containsUnknownSyumbol = (
     311      var containsUnknownSymbols = (
    282312        from n in tree.Root.GetSubtree(0).IterateNodesPrefix()
    283313        where
    284           !(n.Symbol is Problems.DataAnalysis.Symbolic.Variable) &&
     314          !(n.Symbol is Variable) &&
    285315          !(n.Symbol is Constant) &&
    286316          !(n.Symbol is StartSymbol) &&
     
    292322          !(n.Symbol is Cosine) &&
    293323          !(n.Symbol is Tangent) &&
     324          !(n.Symbol is HyperbolicTangent) &&
    294325          !(n.Symbol is Logarithm) &&
    295326          !(n.Symbol is Exponential) &&
     
    301332          !(n.Symbol is AnalyticQuotient)
    302333        select n).Any();
    303       return !containsUnknownSyumbol;
     334      return !containsUnknownSymbols;
    304335    }
    305336  }
  • branches/3105_PythonFormatter/HeuristicLab.Problems.DataAnalysis.Views

  • branches/3105_PythonFormatter/HeuristicLab.Problems.DataAnalysis.Views/3.4/HeuristicLab.Problems.DataAnalysis.Views-3.4.csproj

    r17579 r17918  
    103103      <Private>False</Private>
    104104    </Reference>
     105    <Reference Include="HEAL.Attic, Version=1.5.0.0, Culture=neutral, PublicKeyToken=ba48961d6f65dcec, processorArchitecture=MSIL">
     106      <SpecificVersion>False</SpecificVersion>
     107      <HintPath>..\..\bin\HEAL.Attic.dll</HintPath>
     108    </Reference>
    105109    <Reference Include="System" />
    106110    <Reference Include="System.Core">
     
    221225    <Compile Include="Interfaces\IDataPreprocessorStarter.cs" />
    222226    <Compile Include="Interfaces\IPartialDependencePlot.cs" />
    223     <Compile Include="IntervalCollectionView.cs">
    224       <SubType>UserControl</SubType>
    225     </Compile>
    226     <Compile Include="IntervalCollectionView.Designer.cs">
    227       <DependentUpon>IntervalCollectionView.cs</DependentUpon>
    228     </Compile>
    229227    <Compile Include="MenuItems\ChangeDataOfOptimizersMenuItem.cs" />
    230228    <Compile Include="MenuItems\ShrinkDataAnalysisRunsMenuItem.cs" />
     
    242240      <DependentUpon>ProblemDataView.cs</DependentUpon>
    243241    </Compile>
     242    <Compile Include="Properties\Resources.Designer.cs">
     243      <AutoGen>True</AutoGen>
     244      <DesignTime>True</DesignTime>
     245      <DependentUpon>Resources.resx</DependentUpon>
     246    </Compile>
    244247    <Compile Include="Regression\ConfidenceRegressionSolutionEstimatedValuesView.cs">
    245248      <SubType>UserControl</SubType>
     
    254257      <DependentUpon>ConfidenceRegressionSolutionLineChartView.cs</DependentUpon>
    255258    </Compile>
     259    <Compile Include="Regression\IntervalCollectionView.cs">
     260      <SubType>UserControl</SubType>
     261    </Compile>
     262    <Compile Include="Regression\IntervalCollectionView.Designer.cs">
     263      <DependentUpon>IntervalCollectionView.cs</DependentUpon>
     264    </Compile>
    256265    <Compile Include="Regression\RegressionEnsembleSolutionModelWeightsView.cs">
    257266      <SubType>UserControl</SubType>
     
    343352    <Compile Include="Regression\RegressionSolutionScatterPlotView.Designer.cs">
    344353      <DependentUpon>RegressionSolutionScatterPlotView.cs</DependentUpon>
     354    </Compile>
     355    <Compile Include="Regression\ShapeConstraintsView.cs">
     356      <SubType>UserControl</SubType>
     357    </Compile>
     358    <Compile Include="Regression\ShapeConstraintsView.Designer.cs">
     359      <DependentUpon>ShapeConstraintsView.cs</DependentUpon>
     360    </Compile>
     361    <Compile Include="Regression\ShapeConstraintView.cs">
     362      <SubType>UserControl</SubType>
     363    </Compile>
     364    <Compile Include="Regression\ShapeConstraintView.Designer.cs">
     365      <DependentUpon>ShapeConstraintView.cs</DependentUpon>
    345366    </Compile>
    346367    <Compile Include="Solution Views\ClassificationSolutionView.cs">
     
    605626      <DependentUpon>AbstractFeatureCorrelationView.cs</DependentUpon>
    606627    </EmbeddedResource>
     628    <EmbeddedResource Include="Properties\Resources.resx">
     629      <Generator>ResXFileCodeGenerator</Generator>
     630      <LastGenOutput>Resources.Designer.cs</LastGenOutput>
     631    </EmbeddedResource>
    607632  </ItemGroup>
    608633  <ItemGroup>
    609     <Reference Include="HEAL.Attic, Version=1.0.0.0, Culture=neutral, PublicKeyToken=ba48961d6f65dcec, processorArchitecture=MSIL">
    610       <SpecificVersion>False</SpecificVersion>
    611       <HintPath>..\..\bin\HEAL.Attic.dll</HintPath>
    612       <Private>False</Private>
    613     </Reference>
     634    <EmbeddedResource Include="Resources\shapeConstraintsHelp.rtf" />
     635    <None Include="Resources\VS2008ImageLibrary_Annotations_Information.png" />
    614636  </ItemGroup>
    615637  <Import Project="$(MSBuildToolsPath)\Microsoft.CSharp.targets" />
  • branches/3105_PythonFormatter/HeuristicLab.Problems.DataAnalysis.Views/3.4/Regression/RegressionSolutionLineChartViewBase.cs

    r17180 r17918  
    8181        this.chart.Series[ESTIMATEDVALUES_TRAINING_SERIES_NAME].LegendText = ESTIMATEDVALUES_TRAINING_SERIES_NAME;
    8282        this.chart.Series[ESTIMATEDVALUES_TRAINING_SERIES_NAME].ChartType = SeriesChartType.FastLine;
    83         this.chart.Series[ESTIMATEDVALUES_TRAINING_SERIES_NAME].EmptyPointStyle.Color = this.chart.Series[ESTIMATEDVALUES_TRAINING_SERIES_NAME].Color;
    8483        int[] trainingIdx;
    8584        double[] trainingY;
     
    120119        double min = double.MaxValue, max = double.MinValue;
    121120        foreach (var point in chart.Series.SelectMany(x => x.Points)) {
    122           if (!point.YValues.Any() || double.IsInfinity(point.YValues[0]) || double.IsNaN(point.YValues[0]))
     121          if (point.IsEmpty || !point.YValues.Any() || double.IsInfinity(point.YValues[0]) || double.IsNaN(point.YValues[0]))
    123122            continue;
    124123          var y = point.YValues[0];
  • branches/3105_PythonFormatter/HeuristicLab.Problems.DataAnalysis/3.4

  • branches/3105_PythonFormatter/HeuristicLab.Problems.DataAnalysis/3.4/DatasetExtensions.cs

    r17180 r17918  
    9696    }
    9797
     98    public static IntervalCollection GetIntervals(this IDataset dataset) {
     99      IntervalCollection intervalCollection = new IntervalCollection();
     100      foreach (var variable in dataset.DoubleVariables) { // intervals are only possible for double variables
     101        var variableInterval = Interval.GetInterval(dataset.GetDoubleValues(variable));
     102        intervalCollection.AddInterval(variable, variableInterval);
     103      }
     104
     105      return intervalCollection;
     106    }
     107
    98108    public static IEnumerable<KeyValuePair<string, IEnumerable<string>>> GetFactorVariableValues(
    99109      this IDataset ds, IEnumerable<string> factorVariables, IEnumerable<int> rows) {
  • branches/3105_PythonFormatter/HeuristicLab.Problems.DataAnalysis/3.4/HeuristicLab.Problems.DataAnalysis-3.4.csproj

    r17579 r17918  
    142142    <Compile Include="Implementation\Interval\Interval.cs" />
    143143    <Compile Include="Implementation\Interval\IntervalCollection.cs" />
     144    <Compile Include="Implementation\Interval\ShapeConstraint.cs" />
     145    <Compile Include="Implementation\Interval\ShapeConstraintsParser.cs" />
    144146    <Compile Include="Implementation\Regression\ConfidenceBoundRegressionSolution.cs" />
    145147    <Compile Include="Implementation\Regression\ConstantRegressionModel.cs" />
    146148    <Compile Include="Implementation\Regression\ConstantRegressionSolution.cs" />
     149    <Compile Include="Implementation\Regression\ShapeConstraints.cs" />
    147150    <Compile Include="Implementation\Regression\RegressionEnsembleProblemData.cs" />
    148151    <Compile Include="Implementation\Regression\RegressionEnsembleModel.cs">
  • branches/3105_PythonFormatter/HeuristicLab.Problems.DataAnalysis/3.4/Implementation/Classification/ClassificationProblemData.cs

    r17835 r17918  
    306306        classNamesCache.Add(ClassNamesParameter.Value[i, 0]);
    307307    }
     308
    308309    public override IDeepCloneable Clone(Cloner cloner) {
    309310      if (this == emptyProblemData) return emptyProblemData;
     
    314315
    315316    public ClassificationProblemData(IClassificationProblemData classificationProblemData)
    316       : this(classificationProblemData.Dataset, classificationProblemData.AllowedInputVariables, classificationProblemData.TargetVariable, classificationProblemData.ClassNames, classificationProblemData.PositiveClass) {
    317      
     317      : this(classificationProblemData, classificationProblemData.Dataset) {
     318    }
     319
     320    /// <summary>
     321    /// This method satisfies a common use case: making a copy of the problem but providing a different dataset.
     322    /// One must be careful here that the dataset passed is not modified, as that would invalidate the problem data internals.
     323    /// Passing a ModifiableDataset to this constructor is therefore discouraged.
     324    /// </summary>
     325    /// <param name="classificationProblemData">The original instance of classification problem data.</param>
     326    /// <param name="dataset">The new dataset.</param>
     327    public ClassificationProblemData(IClassificationProblemData classificationProblemData, IDataset dataset)
     328    : this(classificationProblemData.Dataset, classificationProblemData.AllowedInputVariables, classificationProblemData.TargetVariable, classificationProblemData.ClassNames, classificationProblemData.PositiveClass) {
     329
    318330      TrainingPartition.Start = classificationProblemData.TrainingPartition.Start;
    319331      TrainingPartition.End = classificationProblemData.TrainingPartition.End;
    320332      TestPartition.Start = classificationProblemData.TestPartition.Start;
    321333      TestPartition.End = classificationProblemData.TestPartition.End;
    322      
     334
    323335      for (int i = 0; i < Classes; i++) {
    324336        for (int j = 0; j < Classes; j++) {
     
    328340    }
    329341
    330     public ClassificationProblemData(IDataset dataset, IEnumerable<string> allowedInputVariables, string targetVariable, IEnumerable<ITransformation> transformations = null)
    331       : this(dataset, allowedInputVariables, targetVariable, Enumerable.Empty<string>(), null, transformations) { }
    332 
    333342    public ClassificationProblemData(IDataset dataset, IEnumerable<string> allowedInputVariables, string targetVariable,
    334       IEnumerable<string> classNames,
     343      IEnumerable<string> classNames = null,
    335344      string positiveClass = null, // can be null in which case it's set as the first class name
    336345      IEnumerable<ITransformation> transformations = null)
     
    348357
    349358      // set the class names
    350       if (classNames.Any()) {
     359      if (classNames != null && classNames.Any()) {
    351360        // better to allocate lists because we use these multiple times below
    352361        var names = classNames.ToList();
    353         var values = ClassValues.ToList();
     362        var values = ClassValuesCache;
    354363
    355364        if (names.Count != values.Count) {
  • branches/3105_PythonFormatter/HeuristicLab.Problems.DataAnalysis/3.4/Implementation/Interval/Interval.cs

    r17583 r17918  
    3333    [Storable]
    3434    public double UpperBound { get; private set; }
     35
     36    public double Width => UpperBound - LowerBound;
    3537
    3638    [StorableConstructor]
     
    6769    }
    6870
     71    private Interval(double v) : this(v, v) { }
     72
    6973    public bool Contains(double value) {
    7074      return LowerBound <= value && value <= UpperBound;
     
    126130        return false;
    127131
    128       return (UpperBound.IsAlmost(other.UpperBound) || (double.IsNaN(UpperBound) && double.IsNaN(other.UpperBound)))
    129         && (LowerBound.IsAlmost(other.LowerBound) || (double.IsNaN(LowerBound) && double.IsNaN(other.LowerBound)));
     132      return (UpperBound==other.UpperBound || (double.IsNaN(UpperBound) && double.IsNaN(other.UpperBound)))
     133        && (LowerBound==other.LowerBound || (double.IsNaN(LowerBound) && double.IsNaN(other.LowerBound)));
    130134    }
    131135
     
    267271    }
    268272
    269     public static Interval AnalyticalQuotient(Interval a, Interval b) {
     273    public static Interval AnalyticQuotient(Interval a, Interval b) {
    270274      var dividend = a;
    271275      var divisor = Add(Square(b), new Interval(1.0, 1.0));
     
    276280    }
    277281    #endregion
     282
     283    #region arithmetic overloads
     284    public static Interval operator +(Interval a, Interval b) => Add(a, b);
     285    public static Interval operator +(Interval a, double b) => Add(a, new Interval(b));
     286    public static Interval operator +(double a, Interval b) => Add(new Interval(a), b);
     287    public static Interval operator -(Interval a, Interval b) => Subtract(a, b);
     288    public static Interval operator -(Interval a, double b) => Subtract(a, new Interval(b));
     289    public static Interval operator -(double a, Interval b) => Subtract(new Interval(a), b);
     290    public static Interval operator -(Interval a) => Subtract(new Interval(0), a);
     291    public static Interval operator *(Interval a, Interval b) => Multiply(a, b);
     292    public static Interval operator *(Interval a, double b) => Multiply(a, new Interval(b));
     293    public static Interval operator *(double a, Interval b) => Multiply(new Interval(a), b);
     294    public static Interval operator /(Interval a, Interval b) => Divide(a, b);
     295    public static Interval operator /(Interval a, double b) => Divide(a, new Interval(b));
     296    public static Interval operator /(double a, Interval b) => Divide(new Interval(a), b);
     297    public static Interval Exponential(double a) { return Exponential(new Interval(a)); }
     298    public static Interval Logarithm(double a) { return Logarithm(new Interval(a)); }
     299    public static Interval Sine(double a) { return Sine(new Interval(a)); }
     300    public static Interval Cosine(double a) { return Cosine(new Interval(a)); }
     301    public static Interval Tangens(double a) { return Tangens(new Interval(a)); }
     302    public static Interval HyperbolicTangent(double a) { return HyperbolicTangent(new Interval(a)); }
     303    public static Interval Square(double a) { return Square(new Interval(a)); }
     304    public static Interval Cube(double a) { return Cube(new Interval(a)); }
     305    public static Interval SquareRoot(double a) { return SquareRoot(new Interval(a)); }
     306    public static Interval CubicRoot(double a) { return CubicRoot(new Interval(a)); }
     307    public static Interval Absolute(double a) { return Absolute(new Interval(a)); }
     308    public static Interval AnalyticQuotient(Interval a, double b) { return AnalyticQuotient(a, new Interval(b)); }
     309    public static Interval AnalyticQuotient(double a, Interval b) { return AnalyticQuotient(new Interval(a), b); }
     310    public static Interval AnalyticQuotient(double a, double b) { return AnalyticQuotient(new Interval(a), new Interval(b)); }
     311    #endregion
    278312  }
    279313}
  • branches/3105_PythonFormatter/HeuristicLab.Problems.DataAnalysis/3.4/Implementation/Interval/IntervalCollection.cs

    r17564 r17918  
    11#region License Information
    22/* HeuristicLab
    3  * Copyright (C) 2002-2019 Heuristic and Evolutionary Algorithms Laboratory (HEAL)
     3 * Copyright (C) Heuristic and Evolutionary Algorithms Laboratory (HEAL)
    44 *
    55 * This file is part of HeuristicLab.
     
    3434      get => HeuristicLab.Common.Resources.VSImageLibrary.Object;
    3535    }
    36     private IDictionary<string, Interval> intervals { get; } = new Dictionary<string, Interval>();
    3736
    38     [Storable(Name = "StorableIntervalInformation")]
     37    private IDictionary<string, Interval> intervals { get; set; } = new Dictionary<string, Interval>();
     38
     39    [Storable(OldName = "StorableIntervalInformation")]
    3940    private KeyValuePair<string, double[]>[] StorableIntervalInformation {
     41      set {
     42        foreach (var varInt in value)
     43          intervals.Add(varInt.Key, new Interval(varInt.Value[0], varInt.Value[1]));
     44      }
     45    }
     46
     47    [Storable]
     48    private object[] StorableIntervals {
    4049      get {
    41         var l = new List<KeyValuePair<string, double[]>>();
    42         foreach (var varInt in intervals)
     50        var names = intervals.Keys.ToArray();
     51        var lowerBounds = intervals.Values.Select(i => i.LowerBound).ToArray();
     52        var upperBounds = intervals.Values.Select(i => i.UpperBound).ToArray();
    4353
    44           l.Add(new KeyValuePair<string, double[]>(varInt.Key,
    45             new double[] { varInt.Value.LowerBound, varInt.Value.UpperBound }));
    46         return l.ToArray();
     54        return new object[] { names, lowerBounds, upperBounds };
    4755      }
    4856
    4957      set {
    50         foreach (var varInt in value)
    51           intervals.Add(varInt.Key, new Interval(varInt.Value[0], varInt.Value[1]));
     58        var names = (string[])value[0];
     59        var lowerBounds = (double[])value[1];
     60        var upperBounds = (double[])value[2];
     61
     62        for (int i = 0; i < names.Length; i++) {
     63          intervals.Add(names[i], new Interval(lowerBounds[i], upperBounds[i]));
     64        }
    5265      }
    5366    }
     
    8093    public void SetInterval(string identifier, Interval interval) {
    8194      intervals[identifier] = interval;
     95      RaiseChanged();
    8296    }
    8397
    8498    public void AddInterval(string identifier, Interval interval) {
    8599      intervals.Add(identifier, interval);
     100      RaiseChanged();
    86101    }
    87102
    88103    public void DeleteInterval(string identifier) {
    89104      intervals.Remove(identifier);
     105      RaiseChanged();
    90106    }
    91107
    92108    public IReadOnlyDictionary<string, Interval> GetReadonlyDictionary() {
     109      return intervals.ToDictionary(pair => pair.Key, pair => pair.Value);
     110    }
     111
     112    public IDictionary<string, Interval> GetDictionary() {
    93113      return intervals.ToDictionary(pair => pair.Key, pair => pair.Value);
    94114    }
     
    98118        yield return Tuple.Create(variableInterval.Key, variableInterval.Value);
    99119    }
     120
     121    public event EventHandler Changed;
     122    private void RaiseChanged() {
     123      var handler = Changed;
     124      if (handler != null)
     125        handler(this, EventArgs.Empty);
     126    }
     127
    100128  }
    101129}
  • branches/3105_PythonFormatter/HeuristicLab.Problems.DataAnalysis/3.4/Implementation/Regression/RegressionProblemData.cs

    r17579 r17918  
    3535    protected const string TargetVariableParameterName = "TargetVariable";
    3636    protected const string VariableRangesParameterName = "VariableRanges";
    37     protected const string IntervalConstraintsParameterName = "IntervalConstraints";
     37    protected const string ShapeConstraintsParameterName = "ShapeConstraints";
    3838    public string Filename { get; set; }
    3939
     
    9494      problemData.Parameters.Add(new ConstrainedValueParameter<StringValue>(TargetVariableParameterName, new ItemSet<StringValue>()));
    9595      problemData.Parameters.Add(new FixedValueParameter<IntervalCollection>(VariableRangesParameterName, "", new IntervalCollection()));
     96      problemData.Parameters.Add(new FixedValueParameter<ShapeConstraints>(ShapeConstraintsParameterName, "", new ShapeConstraints()));
    9697      emptyProblemData = problemData;
    9798    }
    9899    #endregion
    99100
    100     public IConstrainedValueParameter<StringValue> TargetVariableParameter {
    101       get { return (IConstrainedValueParameter<StringValue>)Parameters[TargetVariableParameterName]; }
    102     }
    103 
     101    #region parameter properties
     102    public IConstrainedValueParameter<StringValue> TargetVariableParameter => (IConstrainedValueParameter<StringValue>)Parameters[TargetVariableParameterName];
     103    public IFixedValueParameter<ShapeConstraints> ShapeConstraintsParameter => (IFixedValueParameter<ShapeConstraints>)Parameters[ShapeConstraintsParameterName];
    104104    public IFixedValueParameter<IntervalCollection> VariableRangesParameter => (IFixedValueParameter<IntervalCollection>)Parameters[VariableRangesParameterName];
    105 
     105    #endregion
     106
     107    #region properties
    106108    public IntervalCollection VariableRanges {
    107109      get => VariableRangesParameter.Value;
    108110    }
     111
     112
     113    public ShapeConstraints ShapeConstraints => ShapeConstraintsParameter.Value;
    109114
    110115
     
    120125      }
    121126    }
    122 
    123     public IEnumerable<double> TargetVariableValues {
    124       get { return Dataset.GetDoubleValues(TargetVariable); }
    125     }
    126     public IEnumerable<double> TargetVariableTrainingValues {
    127       get { return Dataset.GetDoubleValues(TargetVariable, TrainingIndices); }
    128     }
    129     public IEnumerable<double> TargetVariableTestValues {
    130       get { return Dataset.GetDoubleValues(TargetVariable, TestIndices); }
    131     }
     127    public IEnumerable<double> TargetVariableValues => Dataset.GetDoubleValues(TargetVariable);
     128    public IEnumerable<double> TargetVariableTrainingValues => Dataset.GetDoubleValues(TargetVariable, TrainingIndices);
     129    public IEnumerable<double> TargetVariableTestValues => Dataset.GetDoubleValues(TargetVariable, TestIndices);
     130    #endregion
     131
    132132
    133133
     
    137137    private void AfterDeserialization() {
    138138      if (!Parameters.ContainsKey(VariableRangesParameterName)) {
    139         var intervalCollection = CalculateDatasetIntervals(this.Dataset);
     139        var intervalCollection = Dataset.GetIntervals();
    140140        Parameters.Add(new FixedValueParameter<IntervalCollection>(VariableRangesParameterName, intervalCollection));
    141141      }
     142      if (Parameters.ContainsKey("IntervalConstraints")) {
     143        var param = (IFixedValueParameter<ShapeConstraints>)Parameters["IntervalConstraints"];
     144        Parameters.Remove(param);
     145        Parameters.Add(new FixedValueParameter<ShapeConstraints>(ShapeConstraintsParameterName, param.Value));
     146      }
     147      if (!Parameters.ContainsKey(ShapeConstraintsParameterName)) {
     148        Parameters.Add(new FixedValueParameter<ShapeConstraints>(ShapeConstraintsParameterName, new ShapeConstraints()));
     149      }
     150
    142151      RegisterParameterEvents();
    143152    }
     
    163172    }
    164173
    165     public RegressionProblemData(IDataset dataset, IEnumerable<string> allowedInputVariables, string targetVariable, IEnumerable<ITransformation> transformations = null)
     174    public RegressionProblemData(IDataset dataset, IEnumerable<string> allowedInputVariables, string targetVariable,
     175      IEnumerable<ITransformation> transformations = null,
     176      IntervalCollection variableRanges = null,
     177      ShapeConstraints shapeConstraints = null)
    166178      : base(dataset, allowedInputVariables, transformations ?? Enumerable.Empty<ITransformation>()) {
    167179      var variables = InputVariables.Select(x => x.AsReadOnly()).ToList();
    168180      Parameters.Add(new ConstrainedValueParameter<StringValue>(TargetVariableParameterName, new ItemSet<StringValue>(variables), variables.Where(x => x.Value == targetVariable).First()));
    169       var intervalCollection = CalculateDatasetIntervals(this.Dataset);
    170       Parameters.Add(new FixedValueParameter<IntervalCollection>(VariableRangesParameterName, intervalCollection));
     181      if (variableRanges == null) {
     182        variableRanges = Dataset.GetIntervals();
     183      }
     184      Parameters.Add(new FixedValueParameter<IntervalCollection>(VariableRangesParameterName, variableRanges));
     185
     186      if (shapeConstraints == null) {
     187        shapeConstraints = new ShapeConstraints();
     188      }
     189      Parameters.Add(new FixedValueParameter<ShapeConstraints>(ShapeConstraintsParameterName, shapeConstraints));
    171190      RegisterParameterEvents();
    172191    }
    173 
    174     private static IntervalCollection CalculateDatasetIntervals(IDataset dataset) {
    175       IntervalCollection intervalCollection = new IntervalCollection();
    176       foreach (var variable in dataset.DoubleVariables) {// intervals are only possible for double variables
    177         var variableInterval = Interval.GetInterval(dataset.GetDoubleValues(variable));
    178         intervalCollection.AddInterval(variable, variableInterval);
    179       }
    180 
    181       return intervalCollection;
    182     }
    183 
    184192    private void RegisterParameterEvents() {
    185       TargetVariableParameter.ValueChanged += new EventHandler(TargetVariableParameter_ValueChanged);
    186     }
    187     private void TargetVariableParameter_ValueChanged(object sender, EventArgs e) {
     193      TargetVariableParameter.ValueChanged += new EventHandler(Parameter_ValueChanged);
     194      // VariableRanges and ShapeConstraints are fixed parameters
     195    }
     196    private void Parameter_ValueChanged(object sender, EventArgs e) {
    188197      OnChanged();
    189198    }
  • branches/3105_PythonFormatter/HeuristicLab.Problems.DataAnalysis/3.4/Interfaces/Regression/IRegressionProblemData.cs

    r17579 r17918  
    11#region License Information
     2
    23/* HeuristicLab
    34 * Copyright (C) Heuristic and Evolutionary Algorithms Laboratory (HEAL)
     
    1819 * along with HeuristicLab. If not, see <http://www.gnu.org/licenses/>.
    1920 */
     21
    2022#endregion
    2123
     
    2830    string TargetVariable { get; set; }
    2931
    30     IntervalCollection VariableRanges { get;}
     32    IntervalCollection VariableRanges { get; }
     33    ShapeConstraints ShapeConstraints { get; }
    3134
    3235    IEnumerable<double> TargetVariableValues { get; }
  • branches/3105_PythonFormatter/HeuristicLab.Tests

  • branches/3105_PythonFormatter/HeuristicLab.Tests/HeuristicLab.Problems.DataAnalysis-3.4/IntervalTest.cs

    r17754 r17918  
    1212    private readonly Interval e = new Interval(4, 6);
    1313
     14    private void CheckLowerAndUpperBoundOfInterval(Interval expected, Interval calculated) {
     15      var lowerBoundExpected = expected.LowerBound;
     16      var upperBoundExpected = expected.UpperBound;
     17      var lowerBoundCalculated = calculated.LowerBound;
     18      var upperBoundCalculated = calculated.UpperBound;
     19
     20      if(double.IsNaN(lowerBoundExpected) && double.IsNaN(lowerBoundCalculated)) {
     21        Assert.IsTrue(double.IsNaN(lowerBoundExpected) && double.IsNaN(lowerBoundCalculated));
     22      } else if (double.IsNaN(upperBoundExpected) && double.IsNaN(upperBoundCalculated)) {
     23        Assert.IsTrue(double.IsNaN(upperBoundExpected) && double.IsNaN(upperBoundCalculated));
     24      } else {
     25        Assert.AreEqual(lowerBoundExpected, lowerBoundCalculated, 1e-9);
     26        Assert.AreEqual(upperBoundExpected, upperBoundCalculated, 1e-9);
     27      }
     28    }
     29
    1430    [TestMethod]
    1531    [TestCategory("Problems.DataAnalysis")]
     
    3349
    3450      //[-1, 1] - [-2, 2] = [-3, 3]
    35       Assert.AreEqual<Interval>(Interval.Subtract(a, b), new Interval(-3, 3));
     51      CheckLowerAndUpperBoundOfInterval(Interval.Subtract(a, b), new Interval(-3, 3));
    3652      //([-1, 1] - [-2, 2]) - [0, 3] = [-6, 3]
    37       Assert.AreEqual<Interval>(Interval.Subtract(Interval.Subtract(a, b), c), new Interval(-6, 3));
     53      CheckLowerAndUpperBoundOfInterval(Interval.Subtract(Interval.Subtract(a, b), c), new Interval(-6, 3));
    3854      //([-1, 1] - [0, 3]) - [-2, 2] = [-6, 3]
    39       Assert.AreEqual<Interval>(Interval.Subtract(Interval.Subtract(a, c), b), new Interval(-6, 3));
     55      CheckLowerAndUpperBoundOfInterval(Interval.Subtract(Interval.Subtract(a, c), b), new Interval(-6, 3));
    4056    }
    4157
     
    4763
    4864      //[-1, 1] * [-2, 2] = [-2, 2]
    49       Assert.AreEqual<Interval>(Interval.Multiply(a, b), new Interval(-2, 2));
     65      CheckLowerAndUpperBoundOfInterval(Interval.Multiply(a, b), new Interval(-2, 2));
    5066      //([-1, 1] * [-2, 2]) * [0, 3] = [-6, 6]
    51       Assert.AreEqual<Interval>(Interval.Multiply(Interval.Multiply(a, b), c), new Interval(-6, 6));
     67      CheckLowerAndUpperBoundOfInterval(Interval.Multiply(Interval.Multiply(a, b), c), new Interval(-6, 6));
    5268      //([-1, 1] * [0, 3]) * [-2, 2] = [-6, 6]
    53       Assert.AreEqual<Interval>(Interval.Multiply(Interval.Multiply(a, c), b), new Interval(-6, 6));
     69      CheckLowerAndUpperBoundOfInterval(Interval.Multiply(Interval.Multiply(a, c), b), new Interval(-6, 6));
    5470
    5571      // [-2, 0] * [-2, 0]  = [0, 4]
    56       Assert.AreEqual<Interval>(new Interval(0, 4), Interval.Multiply(new Interval(-2, 0), new Interval(-2, 0)));
     72      CheckLowerAndUpperBoundOfInterval(new Interval(0, 4), Interval.Multiply(new Interval(-2, 0), new Interval(-2, 0)));
    5773    }
    5874
     
    6480
    6581      //[4, 6] / [1, 3] = [4/3, 6]
    66       Assert.AreEqual<Interval>(Interval.Divide(e, d), new Interval(4.0 / 3.0, 6));
     82      CheckLowerAndUpperBoundOfInterval(Interval.Divide(e, d), new Interval(4.0 / 3.0, 6));
    6783      //([4, 6] / [1, 3]) / [1, 3] = [4/9, 6]
    68       Assert.AreEqual<Interval>(Interval.Divide(Interval.Divide(e, d), d), new Interval(4.0 / 9.0, 6));
     84      CheckLowerAndUpperBoundOfInterval(Interval.Divide(Interval.Divide(e, d), d), new Interval(4.0 / 9.0, 6));
    6985      //[4, 6] / [0, 3] = [4/3, +Inf]
    70       Assert.AreEqual<Interval>(Interval.Divide(e, c), new Interval(4.0 / 3.0, double.PositiveInfinity));
     86      CheckLowerAndUpperBoundOfInterval(Interval.Divide(e, c), new Interval(4.0 / 3.0, double.PositiveInfinity));
    7187      //[-1, 1] / [0, 3] = [+Inf, -Inf]
    72       Assert.AreEqual<Interval>(Interval.Divide(a, c), new Interval(double.NegativeInfinity, double.PositiveInfinity));
     88      CheckLowerAndUpperBoundOfInterval(Interval.Divide(a, c), new Interval(double.NegativeInfinity, double.PositiveInfinity));
    7389      //Devision by 0 ==> IsInfiniteOrUndefined == true
    7490      Assert.IsTrue(Interval.Divide(e, c).IsInfiniteOrUndefined);
    7591      //Devision by 0 ==> IsInfiniteOrUndefined == true
    7692      Assert.IsTrue(Interval.Divide(a, c).IsInfiniteOrUndefined);
    77       Assert.AreEqual<Interval>(Interval.Divide(d, b), new Interval(double.NegativeInfinity, double.PositiveInfinity));
     93      CheckLowerAndUpperBoundOfInterval(Interval.Divide(d, b), new Interval(double.NegativeInfinity, double.PositiveInfinity));
    7894    }
    7995
     
    84100      //sine depends on interval
    85101      //sin([0, 2*pi]) = [-1, 1]
    86       Assert.AreEqual<Interval>(Interval.Sine(new Interval(0, 2 * Math.PI)), new Interval(-1, 1));
     102      CheckLowerAndUpperBoundOfInterval(Interval.Sine(new Interval(0, 2 * Math.PI)), new Interval(-1, 1));
    87103      //sin([-pi/2, pi/2]) = [sin(-pi/2), sin(pi/2)]
    88       Assert.AreEqual<Interval>(Interval.Sine(new Interval(-1 * Math.PI / 2, Math.PI / 2)), new Interval(-1, 1));
     104      CheckLowerAndUpperBoundOfInterval(Interval.Sine(new Interval(-1 * Math.PI / 2, Math.PI / 2)), new Interval(-1, 1));
    89105      //sin([0, pi/2]) = [sin(0), sin(pi/2)]
    90       Assert.AreEqual<Interval>(Interval.Sine(new Interval(0, Math.PI / 2)), new Interval(0, 1));
     106      CheckLowerAndUpperBoundOfInterval(Interval.Sine(new Interval(0, Math.PI / 2)), new Interval(0, 1));
    91107      //sin([pi, 3*pi/2]) = [sin(pi), sin(3*pi/2)]
    92       Assert.AreEqual<Interval>(Interval.Sine(new Interval(Math.PI, 3 * Math.PI / 2)), new Interval(-1, 0));
    93       Assert.AreEqual<Interval>(Interval.Sine(new Interval(1, 2)), new Interval(Math.Min(Math.Sin(1), Math.Sin(2)), 1));
    94       Assert.AreEqual<Interval>(Interval.Sine(new Interval(1, 3)), new Interval(Math.Min(Math.Sin(1), Math.Sin(3)), 1));
    95       Assert.AreEqual<Interval>(Interval.Sine(new Interval(Math.PI, 5 * Math.PI / 2)), new Interval(-1, 1));
     108      CheckLowerAndUpperBoundOfInterval(Interval.Sine(new Interval(Math.PI, 3 * Math.PI / 2)), new Interval(-1, 0));
     109      CheckLowerAndUpperBoundOfInterval(Interval.Sine(new Interval(1, 2)), new Interval(Math.Min(Math.Sin(1), Math.Sin(2)), 1));
     110      CheckLowerAndUpperBoundOfInterval(Interval.Sine(new Interval(1, 3)), new Interval(Math.Min(Math.Sin(1), Math.Sin(3)), 1));
     111      CheckLowerAndUpperBoundOfInterval(Interval.Sine(new Interval(Math.PI, 5 * Math.PI / 2)), new Interval(-1, 1));
    96112    }
    97113
     
    101117    public void CosineIntervalTest() {
    102118      //Cosine uses sine Interval.Sine(Interval.Subtract(a, new Interval(Math.PI / 2, Math.PI / 2)));
    103       Assert.AreEqual<Interval>(Interval.Cosine(new Interval(0, 2 * Math.PI)), new Interval(-1, 1));
    104       Assert.AreEqual<Interval>(new Interval(-1, 1), Interval.Cosine(new Interval(Math.PI, 4 * Math.PI / 2)));
     119      CheckLowerAndUpperBoundOfInterval(Interval.Cosine(new Interval(0, 2 * Math.PI)), new Interval(-1, 1));
     120      CheckLowerAndUpperBoundOfInterval(new Interval(-1, 1), Interval.Cosine(new Interval(Math.PI, 4 * Math.PI / 2)));
    105121    }
    106122
     
    110126    public void LogIntervalTest() {
    111127      //Log([3, 5]) = [log(3), log(5)]
    112       Assert.AreEqual<Interval>(new Interval(Math.Log(3), Math.Log(5)), Interval.Logarithm(new Interval(3, 5)));
     128      CheckLowerAndUpperBoundOfInterval(new Interval(Math.Log(3), Math.Log(5)), Interval.Logarithm(new Interval(3, 5)));
    113129      //Log([0.5, 1]) = [log(0.5), log(1)]
    114       Assert.AreEqual<Interval>(new Interval(Math.Log(0.5), 0), Interval.Logarithm(new Interval(0.5, 1)));
     130      CheckLowerAndUpperBoundOfInterval(new Interval(Math.Log(0.5), 0), Interval.Logarithm(new Interval(0.5, 1)));
    115131      //Log([-1, 5]) = [NaN, log(5)]
    116132      var result = Interval.Logarithm(new Interval(-1, 5));
    117       Assert.AreEqual<Interval>(new Interval(double.NaN, Math.Log(5)),result);
     133      CheckLowerAndUpperBoundOfInterval(new Interval(double.NaN, Math.Log(5)),result);
    118134      Assert.IsTrue(result.IsInfiniteOrUndefined);
    119135    }
     
    125141    public void ExponentialIntervalTest() {
    126142      //Exp([0, 1]) = [exp(0), exp(1)]
    127       Assert.AreEqual<Interval>(new Interval(1, Math.Exp(1)), Interval.Exponential(new Interval(0, 1)));
     143      CheckLowerAndUpperBoundOfInterval(new Interval(1, Math.Exp(1)), Interval.Exponential(new Interval(0, 1)));
    128144    }
    129145
     
    133149    [TestProperty("Time", "short")]
    134150    public void SquareIntervalTest() {
    135       Assert.AreEqual<Interval>(new Interval(1, 4), Interval.Square(new Interval(1, 2)));
    136       Assert.AreEqual<Interval>(new Interval(1, 4), Interval.Square(new Interval(-2, -1)));
    137       Assert.AreEqual<Interval>(new Interval(0, 4), Interval.Square(new Interval(-2, 2)));
     151      CheckLowerAndUpperBoundOfInterval(new Interval(1, 4), Interval.Square(new Interval(1, 2)));
     152      CheckLowerAndUpperBoundOfInterval(new Interval(1, 4), Interval.Square(new Interval(-2, -1)));
     153      CheckLowerAndUpperBoundOfInterval(new Interval(0, 4), Interval.Square(new Interval(-2, 2)));
    138154    }
    139155
     
    142158    [TestProperty("Time", "short")]
    143159    public void SquarerootIntervalTest() {
    144       Assert.AreEqual<Interval>(new Interval(-2, 2), Interval.SquareRoot(new Interval(1, 4)));
    145       Assert.AreEqual<Interval>(new Interval(double.NaN, double.NaN), Interval.SquareRoot(new Interval(-4, -1)));
     160      CheckLowerAndUpperBoundOfInterval(new Interval(-2, 2), Interval.SquareRoot(new Interval(1, 4)));
     161      CheckLowerAndUpperBoundOfInterval(new Interval(double.NaN, double.NaN), Interval.SquareRoot(new Interval(-4, -1)));
    146162    }
    147163
     
    150166    [TestProperty("Time", "short")]
    151167    public void CubeIntervalTest() {
    152       Assert.AreEqual<Interval>(new Interval(1, 8), Interval.Cube(new Interval(1, 2)));
    153       Assert.AreEqual<Interval>(new Interval(-8, -1), Interval.Cube(new Interval(-2, -1)));
    154       Assert.AreEqual<Interval>(new Interval(-8, 8), Interval.Cube(new Interval(-2, 2)));
     168      CheckLowerAndUpperBoundOfInterval(new Interval(1, 8), Interval.Cube(new Interval(1, 2)));
     169      CheckLowerAndUpperBoundOfInterval(new Interval(-8, -1), Interval.Cube(new Interval(-2, -1)));
     170      CheckLowerAndUpperBoundOfInterval(new Interval(-8, 8), Interval.Cube(new Interval(-2, 2)));
    155171    }
    156172
     
    159175    [TestProperty("Time", "short")]
    160176    public void CubeRootIntervalTest() {
    161       Assert.AreEqual<Interval>(new Interval(1, 2), Interval.CubicRoot(new Interval(1, 8)));
    162       Assert.AreEqual<Interval>(new Interval(-2, -2), Interval.CubicRoot(new Interval(-8, -8)));
    163       Assert.AreEqual<Interval>(new Interval(-2, 2), Interval.CubicRoot(new Interval(-8, 8)));
     177      CheckLowerAndUpperBoundOfInterval(new Interval(1, 2), Interval.CubicRoot(new Interval(1, 8)));
     178      CheckLowerAndUpperBoundOfInterval(new Interval(-2, -2), Interval.CubicRoot(new Interval(-8, -8)));
     179      CheckLowerAndUpperBoundOfInterval(new Interval(-2, 2), Interval.CubicRoot(new Interval(-8, 8)));
    164180      Assert.AreEqual(new Interval(2, 2), Interval.CubicRoot(new Interval(8, 8)));
    165181      Assert.AreEqual(new Interval(-Math.Pow(6, 1.0 / 3), 2), Interval.CubicRoot(new Interval(-6, 8)));
     
    204220      //Assert.AreEqual(new Interval(aZero.LowerBound/Math.Sqrt(5), aZero.UpperBound/Math.Sqrt(5)), Interval.AnalyticalQuotient(aZero, bNeg));
    205221      //Assert.AreEqual(new Interval(aNeg.LowerBound/Math.Sqrt(5), aNeg.UpperBound/Math.Sqrt(17)), Interval.AnalyticalQuotient(aNeg, bNeg));
    206       Assert.AreEqual(new Interval(double.NegativeInfinity, double.PositiveInfinity), Interval.AnalyticalQuotient(aPos, bZero));
    207       Assert.AreEqual(new Interval(double.NegativeInfinity, double.PositiveInfinity), Interval.AnalyticalQuotient(aPos, bPos));
    208       Assert.AreEqual(new Interval(double.NegativeInfinity, double.PositiveInfinity), Interval.AnalyticalQuotient(aZero, bNeg));
     222      Assert.AreEqual(new Interval(double.NegativeInfinity, double.PositiveInfinity), Interval.AnalyticQuotient(aPos, bZero));
     223      Assert.AreEqual(new Interval(double.NegativeInfinity, double.PositiveInfinity), Interval.AnalyticQuotient(aPos, bPos));
     224      Assert.AreEqual(new Interval(double.NegativeInfinity, double.PositiveInfinity), Interval.AnalyticQuotient(aZero, bNeg));
    209225    }
    210226
     
    313329    [TestProperty("Time", "short")]
    314330    public void GeometricTest() {
    315       Assert.AreEqual(new Interval(-1, -0.936456687290796), Interval.Cosine(new Interval(3, 3.5)));
    316       Assert.AreEqual(new Interval(-1, -0.936456687290796), Interval.Cosine(new Interval(-3.5, -3)));
    317       Assert.AreEqual(new Interval(-1, 1), Interval.Cosine(new Interval(-3.5, 3)));
    318       Assert.AreEqual(new Interval(-0.839071529076452, 0.843853958732493), Interval.Cosine(new Interval(10, 12)));
    319       Assert.AreEqual(new Interval(0.136737218207833, 0.907446781450197), Interval.Cosine(new Interval(13, 14)));
    320       Assert.AreEqual(new Interval(-0.839071529076452, 1), Interval.Cosine(new Interval(10, 14)));
    321       Assert.AreEqual(new Interval(-1, 0.136737218207833), Interval.Cosine(new Interval(14, 16)));
    322       Assert.AreEqual(new Interval(-0.839071529076452, 0.004425697988051), Interval.Cosine(new Interval(-11, -10)));
    323       Assert.AreEqual(new Interval(0.136737218207833, 0.907446781450197), Interval.Cosine(new Interval(-14, -13)));
    324       Assert.AreEqual(new Interval(-1, 0.136737218207833), Interval.Cosine(new Interval(-16, -14)));
    325       Assert.AreEqual(new Interval(0.101585703696621, 1), Interval.Cosine(new Interval(-102, -100)));
    326       Assert.AreEqual(new Interval(-1, 1), Interval.Cosine(new Interval(4.6e15, 4.7e15)));
    327       Assert.AreEqual(new Interval(0.87758256189037265, 0.87758256189037276), Interval.Cosine(new Interval(0.5, 0.5)));
    328       Assert.AreEqual(new Interval(-0.09904103659872825, 0.8775825618903728), Interval.Cosine(new Interval(0.5, 1.67)));
    329       Assert.AreEqual(new Interval(-1.0, 0.77556587851025016), Interval.Cosine(new Interval(2.1, 5.6)));
    330       Assert.AreEqual(new Interval(-1.0, 1.0), Interval.Cosine(new Interval(0.5, 8.5)));
    331       Assert.AreEqual(new Interval(-1.0, -0.09904103659872801), Interval.Cosine(new Interval(1.67, 3.2)));
    332 
    333 
    334       Assert.AreEqual(new Interval(double.NegativeInfinity, double.PositiveInfinity), Interval.Tangens(new Interval(double.NegativeInfinity, double.PositiveInfinity)));
    335       Assert.AreEqual(new Interval(0, 1.55740772465490223051), Interval.Tangens(new Interval(0, 1)));
    336       Assert.AreEqual(new Interval(-1.55740772465490223051, 0), Interval.Tangens(new Interval(-1, 0)));
    337       Assert.AreEqual(new Interval(double.NegativeInfinity, double.PositiveInfinity), Interval.Tangens(new Interval(-2, -1)));
    338       Assert.AreEqual(new Interval(double.NegativeInfinity, double.PositiveInfinity), Interval.Tangens(new Interval(202, 203)));
    339       Assert.AreEqual(new Interval(0.54630248984379048, 0.5463024898437906), Interval.Tangens(new Interval(0.5, 0.5)));
    340       Assert.AreEqual(new Interval(double.NegativeInfinity, double.PositiveInfinity), Interval.Tangens(new Interval(0.5,
     331      CheckLowerAndUpperBoundOfInterval(new Interval(-1, -0.936456687290796), Interval.Cosine(new Interval(3, 3.5)));
     332      CheckLowerAndUpperBoundOfInterval(new Interval(-1, -0.936456687290796), Interval.Cosine(new Interval(-3.5, -3)));
     333      CheckLowerAndUpperBoundOfInterval(new Interval(-1, 1), Interval.Cosine(new Interval(-3.5, 3)));
     334      CheckLowerAndUpperBoundOfInterval(new Interval(-0.839071529076452, 0.843853958732493), Interval.Cosine(new Interval(10, 12)));
     335      CheckLowerAndUpperBoundOfInterval(new Interval(0.136737218207833, 0.907446781450197), Interval.Cosine(new Interval(13, 14)));
     336      CheckLowerAndUpperBoundOfInterval(new Interval(-0.839071529076452, 1), Interval.Cosine(new Interval(10, 14)));
     337      CheckLowerAndUpperBoundOfInterval(new Interval(-1, 0.136737218207833), Interval.Cosine(new Interval(14, 16)));
     338      CheckLowerAndUpperBoundOfInterval(new Interval(-0.839071529076452, 0.004425697988051), Interval.Cosine(new Interval(-11, -10)));
     339      CheckLowerAndUpperBoundOfInterval(new Interval(0.136737218207833, 0.907446781450197), Interval.Cosine(new Interval(-14, -13)));
     340      CheckLowerAndUpperBoundOfInterval(new Interval(-1, 0.136737218207833), Interval.Cosine(new Interval(-16, -14)));
     341      CheckLowerAndUpperBoundOfInterval(new Interval(0.101585703696621, 1), Interval.Cosine(new Interval(-102, -100)));
     342      CheckLowerAndUpperBoundOfInterval(new Interval(-1, 1), Interval.Cosine(new Interval(4.6e15, 4.7e15)));
     343      CheckLowerAndUpperBoundOfInterval(new Interval(0.87758256189037265, 0.87758256189037276), Interval.Cosine(new Interval(0.5, 0.5)));
     344      CheckLowerAndUpperBoundOfInterval(new Interval(-0.09904103659872825, 0.8775825618903728), Interval.Cosine(new Interval(0.5, 1.67)));
     345      CheckLowerAndUpperBoundOfInterval(new Interval(-1.0, 0.77556587851025016), Interval.Cosine(new Interval(2.1, 5.6)));
     346      CheckLowerAndUpperBoundOfInterval(new Interval(-1.0, 1.0), Interval.Cosine(new Interval(0.5, 8.5)));
     347      CheckLowerAndUpperBoundOfInterval(new Interval(-1.0, -0.09904103659872801), Interval.Cosine(new Interval(1.67, 3.2)));
     348
     349      CheckLowerAndUpperBoundOfInterval(new Interval(double.NegativeInfinity, double.PositiveInfinity), Interval.Tangens(new Interval(double.NegativeInfinity, double.PositiveInfinity)));
     350      CheckLowerAndUpperBoundOfInterval(new Interval(0, 1.55740772465490223051), Interval.Tangens(new Interval(0, 1)));
     351      CheckLowerAndUpperBoundOfInterval(new Interval(-1.55740772465490223051, 0), Interval.Tangens(new Interval(-1, 0)));
     352      CheckLowerAndUpperBoundOfInterval(new Interval(double.NegativeInfinity, double.PositiveInfinity), Interval.Tangens(new Interval(-2, -1)));
     353      CheckLowerAndUpperBoundOfInterval(new Interval(double.NegativeInfinity, double.PositiveInfinity), Interval.Tangens(new Interval(202, 203)));
     354      CheckLowerAndUpperBoundOfInterval(new Interval(0.54630248984379048, 0.5463024898437906), Interval.Tangens(new Interval(0.5, 0.5)));
     355      CheckLowerAndUpperBoundOfInterval(new Interval(double.NegativeInfinity, double.PositiveInfinity), Interval.Tangens(new Interval(0.5,
    341356        1.67)));
    342       //Assert.AreEqual(new Interval(-10.047182299210307, 0.5847385445957865), Interval.Tangens(new Interval(1.67, 3.2)));
    343       Assert.AreEqual(new Interval(double.NegativeInfinity, double.PositiveInfinity), Interval.Tangens(new Interval(
     357
     358      CheckLowerAndUpperBoundOfInterval(new Interval(double.NegativeInfinity, double.PositiveInfinity), Interval.Tangens(new Interval(
    344359        6.638314112824137, 8.38263151220128)));
    345360
    346 
    347 
    348       Assert.AreEqual(new Interval(0.47942553860420295, 0.47942553860420301), Interval.Sine(new Interval(0.5, 0.5)));
    349       Assert.AreEqual(new Interval(4.7942553860420295e-01, 1.0), Interval.Sine(new Interval(0.5, 1.67)));
    350       Assert.AreEqual(new Interval(-5.8374143427580093e-02, 9.9508334981018021e-01), Interval.Sine(new Interval(1.67,
     361      CheckLowerAndUpperBoundOfInterval(new Interval(0.47942553860420295, 0.47942553860420301), Interval.Sine(new Interval(0.5, 0.5)));
     362      CheckLowerAndUpperBoundOfInterval(new Interval(4.7942553860420295e-01, 1.0), Interval.Sine(new Interval(0.5, 1.67)));
     363      CheckLowerAndUpperBoundOfInterval(new Interval(-5.8374143427580093e-02, 9.9508334981018021e-01), Interval.Sine(new Interval(1.67,
    351364        3.2)));
    352       Assert.AreEqual(new Interval(-1.0, 0.863209366648874), Interval.Sine(new Interval(2.1, 5.6)));
    353       Assert.AreEqual(new Interval(-1.0, 1.0), Interval.Sine(new Interval(0.5, 8.5)));
    354       Assert.AreEqual(new Interval(-1.0, 0.9775301176650971), Interval.Sine(new Interval(-4.5, 0.1)));
    355       Assert.AreEqual(new Interval(-1.0, 1.0), Interval.Sine(new Interval(1.3, 6.3)));
     365      CheckLowerAndUpperBoundOfInterval(new Interval(-1.0, 0.863209366648874), Interval.Sine(new Interval(2.1, 5.6)));
     366      CheckLowerAndUpperBoundOfInterval(new Interval(-1.0, 1.0), Interval.Sine(new Interval(0.5, 8.5)));
     367      CheckLowerAndUpperBoundOfInterval(new Interval(-1.0, 0.9775301176650971), Interval.Sine(new Interval(-4.5, 0.1)));
     368      CheckLowerAndUpperBoundOfInterval(new Interval(-1.0, 1.0), Interval.Sine(new Interval(1.3, 6.3)));
    356369    }
    357370
  • branches/3105_PythonFormatter/HeuristicLab.Visualization.ChartControlsExtensions/3.3/ChartUtil.cs

    r17180 r17918  
    8888    private static double RoundDown(this double value, int decimalRank) {
    8989      if (decimalRank > 0) {
    90         var floor = (int)Math.Floor(value);
    91         var pow = (int)Math.Pow(10, decimalRank);
     90        var floor = Math.Floor(value);
     91        var pow = Math.Pow(10, decimalRank);
    9292        var mod = Mod(floor, pow);
    9393        return floor - mod;
     
    9898    private static double RoundUp(this double value, int decimalRank) {
    9999      if (decimalRank > 0) {
    100         var ceil = (int)Math.Ceiling(value);
    101         var pow = (int)Math.Pow(10, decimalRank);
     100        var ceil = Math.Ceiling(value);
     101        var pow = Math.Pow(10, decimalRank);
    102102        var mod = Mod(ceil, pow);
    103103        return ceil - mod + pow;
Note: See TracChangeset for help on using the changeset viewer.