Free cookie consent management tool by TermsFeed Policy Generator

source: branches/3073_IA_constraint_splitting/HeuristicLab.Problems.DataAnalysis/3.4/Implementation/Interval/Interval.cs @ 18006

Last change on this file since 18006 was 17770, checked in by bburlacu, 4 years ago

#3073: Add arithmetic operator overloads for the Interval class

  • Property svn:mergeinfo set to (toggle deleted branches)
    /branches/2971_named_intervals/HeuristicLab.Problems.DataAnalysis/3.4/Implementation/Interval/Interval.csmergedeligible
    /stable/HeuristicLab.Problems.DataAnalysis/3.4/Implementation/Interval/Interval.csmergedeligible
    /trunk/HeuristicLab.Problems.DataAnalysis/3.4/Implementation/Interval/Interval.csmergedeligible
    /branches/2435-alglib_3_15/HeuristicLab.Problems.DataAnalysis/3.4/Implementation/Interval/Interval.cs16683-17036
    /branches/2520_PersistenceReintegration/HeuristicLab.Problems.DataAnalysis/3.4/Implementation/Interval/Interval.cs16451-16564
    /branches/2839_HiveProjectManagement/HeuristicLab.Problems.DataAnalysis/3.4/Implementation/Interval/Interval.cs15761-16116
    /branches/2892_LR-prediction-intervals/HeuristicLab.Problems.DataAnalysis/3.4/Implementation/Interval/Interval.cs15743-16388
    /branches/2904_CalculateImpacts/3.4/Implementation/Interval/Interval.cs15808-16421
    /branches/2915-AbsoluteSymbol/HeuristicLab.Problems.DataAnalysis/3.4/Implementation/Interval/Interval.cs15943-16355
    /branches/2947_ConfigurableIndexedDataTable/HeuristicLab.Problems.DataAnalysis/3.4/Implementation/Interval/Interval.cs16148-16526
    /branches/2965_CancelablePersistence/HeuristicLab.Problems.DataAnalysis/3.4/Implementation/Interval/Interval.cs16321-16439
    /branches/2966_interval_calculation/HeuristicLab.Problems.DataAnalysis/3.4/Implementation/Interval/Interval.cs16320-16406
    /branches/Async/HeuristicLab.Problems.DataAnalysis/3.4/Implementation/Interval/Interval.cs13329-15286
    /branches/Classification-Extensions/HeuristicLab.Problems.DataAnalysis/3.4/Implementation/Interval/Interval.cs11606-11761
    /branches/ClassificationModelComparison/HeuristicLab.Problems.DataAnalysis/3.4/Implementation/Interval/Interval.cs9073-13099
    /branches/CloningRefactoring/HeuristicLab.Problems.DataAnalysis/3.4/Implementation/Interval/Interval.cs4656-4721
    /branches/DataAnalysis Refactoring/HeuristicLab.Problems.DataAnalysis/3.4/Implementation/Interval/Interval.cs5471-5808
    /branches/DataAnalysis SolutionEnsembles/HeuristicLab.Problems.DataAnalysis/3.4/Implementation/Interval/Interval.cs5815-6180
    /branches/DataAnalysis/HeuristicLab.Problems.DataAnalysis/3.4/Implementation/Interval/Interval.cs4220,​4226,​4236-4238,​4389,​4458-4459,​4462,​4464
    /branches/DataAnalysisCSVImport/HeuristicLab.Problems.DataAnalysis/3.4/Implementation/Interval/Interval.cs8713-8875
    /branches/DataPreprocessing/HeuristicLab.Problems.DataAnalysis/3.4/Implementation/Interval/Interval.cs10085-11101
    /branches/DatasetFeatureCorrelation/HeuristicLab.Problems.DataAnalysis/3.4/Implementation/Interval/Interval.cs8035-8538
    /branches/GP.Grammar.Editor/HeuristicLab.Problems.DataAnalysis/3.4/Implementation/Interval/Interval.cs6284-6795
    /branches/GP.Symbols (TimeLag, Diff, Integral)/HeuristicLab.Problems.DataAnalysis/3.4/Implementation/Interval/Interval.cs5060
    /branches/HeuristicLab.DatasetRefactor/sources/HeuristicLab.Problems.DataAnalysis/3.4/Implementation/Interval/Interval.cs11570-12508
    /branches/HeuristicLab.Problems.Orienteering/HeuristicLab.Problems.DataAnalysis/3.4/Implementation/Interval/Interval.cs11130-12721
    /branches/HeuristicLab.RegressionSolutionGradientView/HeuristicLab.Problems.DataAnalysis/3.4/Implementation/Interval/Interval.cs13819-14091
    /branches/HeuristicLab.TimeSeries/HeuristicLab.Problems.DataAnalysis/3.4/Implementation/Interval/Interval.cs7098-8789
    /branches/LogResidualEvaluator/HeuristicLab.Problems.DataAnalysis/3.4/Implementation/Interval/Interval.cs10202-10483
    /branches/NET40/sources/HeuristicLab.Problems.DataAnalysis/3.4/Implementation/Interval/Interval.cs5138-5162
    /branches/ParallelEngine/HeuristicLab.Problems.DataAnalysis/3.4/Implementation/Interval/Interval.cs5175-5192
    /branches/ProblemInstancesRegressionAndClassification/HeuristicLab.Problems.DataAnalysis/3.4/Implementation/Interval/Interval.cs7570-7810
    /branches/QAPAlgorithms/HeuristicLab.Problems.DataAnalysis/3.4/Implementation/Interval/Interval.cs6350-6627
    /branches/Restructure trunk solution/HeuristicLab.Problems.DataAnalysis/3.4/Implementation/Interval/Interval.cs6828
    /branches/SensitivityEvaluator/HeuristicLab.Problems.DataAnalysis/3.4/Implementation/Interval/Interval.cs12212-16784
    /branches/SimplifierViewsProgress/HeuristicLab.Problems.DataAnalysis/3.4/Implementation/Interval/Interval.cs15318-15370
    /branches/SpectralKernelForGaussianProcesses/HeuristicLab.Problems.DataAnalysis/3.4/Implementation/Interval/Interval.cs10204-10479
    /branches/Trunk/HeuristicLab.Problems.DataAnalysis/3.4/Implementation/Interval/Interval.cs6829-6865
    /branches/histogram/HeuristicLab.Problems.DataAnalysis/3.4/Implementation/Interval/Interval.cs5959-6341
    /branches/symbreg-factors-2650/HeuristicLab.Problems.DataAnalysis/3.4/Implementation/Interval/Interval.cs14232-14825
    /trunk/HeuristicLab.Problems.DataAnalysis/3.4/Implementation/Interval.cs17301-17367
File size: 13.8 KB
Line 
1#region License Information
2/* HeuristicLab
3 * Copyright (C) Heuristic and Evolutionary Algorithms Laboratory (HEAL)
4 *
5 * This file is part of HeuristicLab.
6 *
7 * HeuristicLab is free software: you can redistribute it and/or modify
8 * it under the terms of the GNU General Public License as published by
9 * the Free Software Foundation, either version 3 of the License, or
10 * (at your option) any later version.
11 *
12 * HeuristicLab is distributed in the hope that it will be useful,
13 * but WITHOUT ANY WARRANTY; without even the implied warranty of
14 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
15 * GNU General Public License for more details.
16 *
17 * You should have received a copy of the GNU General Public License
18 * along with HeuristicLab. If not, see <http://www.gnu.org/licenses/>.
19 */
20#endregion
21
22using System;
23using System.Collections.Generic;
24using System.Linq;
25using HEAL.Attic;
26using HeuristicLab.Common;
27
28namespace HeuristicLab.Problems.DataAnalysis {
29  [StorableType("849e42d3-8934-419d-9aff-64ad81c06b67")]
30  public class Interval : IEquatable<Interval> {
31    [Storable]
32    public double LowerBound { get; private set; }
33    [Storable]
34    public double UpperBound { get; private set; }
35
36    public double Width => UpperBound - LowerBound;
37
38    [StorableConstructor]
39    protected Interval(StorableConstructorFlag _) { }
40
41    /// <summary>
42    /// Creates an interval with given bounds, where lower bound must be smaller than
43    /// the upper bound. Floating point precision errors trough calculations are fixed by,
44    /// checking if the intervals are almost the same (E-12). If this is the case, the bounds
45    /// will be set to the bound closer to zero.
46    /// </summary>
47    /// <param name="lowerBound">Lower bound of the interval</param>
48    /// <param name="upperBound">Upper bound of the interval</param>
49    public Interval(double lowerBound, double upperBound) {
50      if (lowerBound.IsAlmost(upperBound)) {
51        //If the bounds go over zero
52        if (lowerBound <= 0 && upperBound >= 0) {
53          lowerBound = 0.0;
54          upperBound = 0.0;
55          //Interval is negative
56        } else if (upperBound < 0) {
57          lowerBound = upperBound;
58          //Interval is positive
59        } else {
60          upperBound = lowerBound;
61        }
62      }
63
64      if (lowerBound > upperBound)
65        throw new ArgumentException("lowerBound must be smaller than or equal to upperBound.");
66
67      this.LowerBound = lowerBound;
68      this.UpperBound = upperBound;
69    }
70
71    private Interval(double v) : this(v, v) { }
72
73    public bool Contains(double value) {
74      return LowerBound <= value && value <= UpperBound;
75    }
76
77    public bool Contains(Interval other) {
78      if (double.IsNegativeInfinity(LowerBound) && double.IsPositiveInfinity(UpperBound)) return true;
79      if (other.LowerBound >= LowerBound && other.UpperBound <= UpperBound) return true;
80 
81      return false;
82    }
83
84    public Tuple<Interval, Interval> Split() {
85      var midpoint = Width / 2;
86      var left     = new Interval(LowerBound, LowerBound + midpoint - double.Epsilon);
87      var right    = new Interval(LowerBound + midpoint, UpperBound);
88      return Tuple.Create(left, right);
89    }
90
91    //Interval Intersection
92    public static Interval operator &(Interval lhs, Interval rhs) {
93      return new Interval(Math.Max(lhs.LowerBound, rhs.LowerBound), Math.Min(lhs.UpperBound, rhs.UpperBound));
94    }
95
96    //Interval Union
97    public static Interval operator |(Interval lhs, Interval rhs) {
98      return new Interval(Math.Min(lhs.LowerBound, rhs.LowerBound), Math.Max(lhs.UpperBound, rhs.UpperBound));
99    }
100
101    public override string ToString() {
102      return "Interval: [" + LowerBound + ", " + UpperBound + "]";
103    }
104
105    public bool IsInfiniteOrUndefined {
106      get {
107        return double.IsInfinity(LowerBound) || double.IsInfinity(UpperBound) ||
108                double.IsNaN(LowerBound) || double.IsNaN(UpperBound);
109      }
110    }
111
112    /// <summary>
113    /// True if the interval is positive without zero
114    /// </summary>
115    public bool IsPositive {
116      get => LowerBound > 0.0;
117    }
118
119    /// <summary>
120    /// True if the interval is negative without zero
121    /// </summary>
122    public bool IsNegative {
123      get => UpperBound < 0.0;
124    }
125
126    public static Interval GetInterval(IEnumerable<double> values) {
127      if (values == null) throw new ArgumentNullException("values");
128      if (!values.Any()) throw new ArgumentException($"No values are present.");
129
130      var min = double.MaxValue;
131      var max = double.MinValue;
132
133      foreach (var value in values) {
134        //If an value is NaN return an interval [NaN, NaN]
135        if (double.IsNaN(value)) return new Interval(double.NaN, double.NaN);
136
137        if (value < min) min = value;
138        if (value > max) max = value;
139      }
140
141      return new Interval(min, max);
142    }
143
144    #region Equals, GetHashCode, == , !=
145    public bool Equals(Interval other) {
146      if (other == null)
147        return false;
148
149      return (UpperBound.IsAlmost(other.UpperBound) || (double.IsNaN(UpperBound) && double.IsNaN(other.UpperBound)))
150        && (LowerBound.IsAlmost(other.LowerBound) || (double.IsNaN(LowerBound) && double.IsNaN(other.LowerBound)));
151    }
152
153    public override bool Equals(object obj) {
154      return Equals(obj as Interval);
155    }
156
157    public override int GetHashCode() {
158      return LowerBound.GetHashCode() ^ UpperBound.GetHashCode();
159    }
160
161    public static bool operator ==(Interval interval1, Interval interval2) {
162      if (ReferenceEquals(interval1, null)) return ReferenceEquals(interval2, null);
163      return interval1.Equals(interval2);
164    }
165    public static bool operator !=(Interval interval1, Interval interval2) {
166      return !(interval1 == interval2);
167    }
168    #endregion
169
170    #region operations
171
172    // [x1,x2] + [y1,y2] = [x1 + y1,x2 + y2]
173    public static Interval Add(Interval a, Interval b) {
174      return new Interval(a.LowerBound + b.LowerBound, a.UpperBound + b.UpperBound);
175    }
176
177    // [x1,x2] − [y1,y2] = [x1 − y2,x2 − y1]
178    public static Interval Subtract(Interval a, Interval b) {
179      return new Interval(a.LowerBound - b.UpperBound, a.UpperBound - b.LowerBound);
180    }
181
182    // [x1,x2] * [y1,y2] = [min(x1*y1,x1*y2,x2*y1,x2*y2),max(x1*y1,x1*y2,x2*y1,x2*y2)]
183    public static Interval Multiply(Interval a, Interval b) {
184      double v1 = a.LowerBound * b.LowerBound;
185      double v2 = a.LowerBound * b.UpperBound;
186      double v3 = a.UpperBound * b.LowerBound;
187      double v4 = a.UpperBound * b.UpperBound;
188
189      double min = Math.Min(Math.Min(v1, v2), Math.Min(v3, v4));
190      double max = Math.Max(Math.Max(v1, v2), Math.Max(v3, v4));
191      return new Interval(min, max);
192    }
193
194    //Division by intervals containing 0 is implemented as defined in
195    //http://en.wikipedia.org/wiki/Interval_arithmetic
196    public static Interval Divide(Interval a, Interval b) {
197      if (b.Contains(0.0)) {
198        if (b.LowerBound.IsAlmost(0.0)) return Interval.Multiply(a, new Interval(1.0 / b.UpperBound, double.PositiveInfinity));
199        else if (b.UpperBound.IsAlmost(0.0)) return Interval.Multiply(a, new Interval(double.NegativeInfinity, 1.0 / b.LowerBound));
200        else return new Interval(double.NegativeInfinity, double.PositiveInfinity);
201      }
202      return Interval.Multiply(a, new Interval(1.0 / b.UpperBound, 1.0 / b.LowerBound));
203    }
204
205    public static Interval Sine(Interval a) {
206      if (Math.Abs(a.UpperBound - a.LowerBound) >= Math.PI * 2) return new Interval(-1, 1);
207
208      //divide the interval by PI/2 so that the optima lie at x element of N (0,1,2,3,4,...)
209      double Pihalf = Math.PI / 2;
210      Interval scaled = Interval.Divide(a, new Interval(Pihalf, Pihalf));
211      //move to positive scale
212      if (scaled.LowerBound < 0) {
213        int periodsToMove = Math.Abs((int)scaled.LowerBound / 4) + 1;
214        scaled = Interval.Add(scaled, new Interval(periodsToMove * 4, periodsToMove * 4));
215      }
216
217      double scaledLowerBound = scaled.LowerBound % 4.0;
218      double scaledUpperBound = scaled.UpperBound % 4.0;
219      if (scaledUpperBound < scaledLowerBound) scaledUpperBound += 4.0;
220      List<double> sinValues = new List<double>();
221      sinValues.Add(Math.Sin(scaledLowerBound * Pihalf));
222      sinValues.Add(Math.Sin(scaledUpperBound * Pihalf));
223
224      int startValue = (int)Math.Ceiling(scaledLowerBound);
225      while (startValue < scaledUpperBound) {
226        sinValues.Add(Math.Sin(startValue * Pihalf));
227        startValue += 1;
228      }
229
230      return new Interval(sinValues.Min(), sinValues.Max());
231    }
232    public static Interval Cosine(Interval a) {
233      return Interval.Sine(Interval.Add(a, new Interval(Math.PI / 2, Math.PI / 2)));
234    }
235    public static Interval Tangens(Interval a) {
236      return Interval.Divide(Interval.Sine(a), Interval.Cosine(a));
237    }
238    public static Interval HyperbolicTangent(Interval a) {
239      return new Interval(Math.Tanh(a.LowerBound), Math.Tanh(a.UpperBound));
240    }
241
242    public static Interval Logarithm(Interval a) {
243      return new Interval(Math.Log(a.LowerBound), Math.Log(a.UpperBound));
244    }
245    public static Interval Exponential(Interval a) {
246      return new Interval(Math.Exp(a.LowerBound), Math.Exp(a.UpperBound));
247    }
248
249    public static Interval Square(Interval a) {
250      if (a.UpperBound <= 0) return new Interval(a.UpperBound * a.UpperBound, a.LowerBound * a.LowerBound);     // interval is negative
251      else if (a.LowerBound >= 0) return new Interval(a.LowerBound * a.LowerBound, a.UpperBound * a.UpperBound); // interval is positive
252      else return new Interval(0, Math.Max(a.LowerBound * a.LowerBound, a.UpperBound * a.UpperBound)); // interval goes over zero
253    }
254
255    public static Interval Cube(Interval a) {
256      return new Interval(Math.Pow(a.LowerBound, 3), Math.Pow(a.UpperBound, 3));
257    }
258
259    /// <summary>
260    /// The interval contains both possible results of the calculated square root +-sqrt(x). That results in a wider
261    /// interval, but it contains all possible solutions.
262    /// </summary>
263    /// <param name="a">Interval to build square root from.</param>
264    /// <returns></returns>
265    public static Interval SquareRoot(Interval a) {
266      if (a.LowerBound < 0) return new Interval(double.NaN, double.NaN);
267      return new Interval(-Math.Sqrt(a.UpperBound), Math.Sqrt(a.UpperBound));
268    }
269
270    public static Interval CubicRoot(Interval a) {
271      var lower = (a.LowerBound < 0) ? -Math.Pow(-a.LowerBound, 1d / 3d) : Math.Pow(a.LowerBound, 1d / 3d);
272      var upper = (a.UpperBound < 0) ? -Math.Pow(-a.UpperBound, 1d / 3d) : Math.Pow(a.UpperBound, 1d / 3d);
273
274      return new Interval(lower, upper);
275    }
276
277    public static Interval Absolute(Interval a) {
278      var absLower = Math.Abs(a.LowerBound);
279      var absUpper = Math.Abs(a.UpperBound);
280      var min = Math.Min(absLower, absUpper);
281      var max = Math.Max(absLower, absUpper);
282
283      if (a.Contains(0.0)) {
284        min = 0.0;
285      }
286
287      return new Interval(min, max);
288    }
289
290    public static Interval AnalyticalQuotient(Interval a, Interval b) {
291      var dividend = a;
292      var divisor = Add(Square(b), new Interval(1.0, 1.0));
293      divisor = SquareRoot(divisor);
294
295      var quotient = Divide(dividend, divisor);
296      return quotient;
297    }
298    #endregion
299
300    #region arithmetic overloads
301    public static Interval operator +(Interval a, Interval b) => Add(a, b);
302    public static Interval operator +(Interval a, double b) => Add(a, new Interval(b));
303    public static Interval operator +(double a, Interval b) => Add(new Interval(a), b);
304    public static Interval operator -(Interval a, Interval b) => Subtract(a, b);
305    public static Interval operator -(Interval a, double b) => Subtract(a, new Interval(b));
306    public static Interval operator -(double a, Interval b) => Subtract(new Interval(a), b);
307    public static Interval operator -(Interval a) => Subtract(new Interval(0), a);
308    public static Interval operator *(Interval a, Interval b) => Multiply(a, b);
309    public static Interval operator *(Interval a, double b) => Multiply(a, new Interval(b));
310    public static Interval operator *(double a, Interval b) => Multiply(new Interval(a), b);
311    public static Interval operator /(Interval a, Interval b) => Divide(a, b);
312    public static Interval operator /(Interval a, double b) => Divide(a, new Interval(b));
313    public static Interval operator /(double a, Interval b) => Divide(new Interval(a), b);
314    public static Interval Exponential(double a) { return Exponential(new Interval(a)); }
315    public static Interval Logarithm(double a) { return Logarithm(new Interval(a)); }
316    public static Interval Sine(double a) { return Sine(new Interval(a)); }
317    public static Interval Cosine(double a) { return Cosine(new Interval(a)); }
318    public static Interval Tangens(double a) { return Tangens(new Interval(a)); }
319    public static Interval HyperbolicTangent(double a) { return HyperbolicTangent(new Interval(a)); }
320    public static Interval Square(double a) { return Square(new Interval(a)); }
321    public static Interval Cube(double a) { return Cube(new Interval(a)); }
322    public static Interval SquareRoot(double a) { return SquareRoot(new Interval(a)); }
323    public static Interval CubicRoot(double a) { return CubicRoot(new Interval(a)); }
324    public static Interval Absolute(double a) { return Absolute(new Interval(a)); }
325    public static Interval AnalyticQuotient(Interval a, double b) { return AnalyticalQuotient(a, new Interval(b)); }
326    public static Interval AnalyticQuotient(double a, Interval b) { return AnalyticalQuotient(new Interval(a), b); }
327    public static Interval AnalyticQuotient(double a, double b) { return AnalyticalQuotient(new Interval(a), new Interval(b)); }
328    #endregion
329  }
330}
Note: See TracBrowser for help on using the repository browser.