Free cookie consent management tool by TermsFeed Policy Generator

source: branches/HeuristicLab.Problems.GrammaticalOptimization/HeuristicLab.Common/Extensions.cs @ 12207

Last change on this file since 12207 was 11974, checked in by gkronber, 10 years ago

#2283: eurocast experiments

File size: 2.1 KB
RevLine 
[11659]1using System;
2using System.Collections.Generic;
3using System.Linq;
4using System.Text;
5using System.Threading.Tasks;
6
[11727]7namespace HeuristicLab.Common {
[11659]8  public static class Extensions {
[11974]9
[11659]10    public static bool IsAlmost(this double x, double y) {
[11974]11      if (double.IsNaN(x) || double.IsNaN(y)) return false;
12      if (double.IsPositiveInfinity(x) && double.IsPositiveInfinity(y)) return true;
13      if (double.IsNegativeInfinity(x) && double.IsNegativeInfinity(y)) return true;
[11742]14      return Math.Abs(x - y) < 1.0e-12;
[11659]15    }
16
17    public static T SelectRandom<T>(this IEnumerable<T> xs, Random rand) {
[11799]18      var n = xs.Count();
19      return xs.ElementAt(rand.Next(n));
[11659]20    }
[11730]21
[11799]22    public static T SampleProportional<T>(this IEnumerable<T> elements, Random random, IEnumerable<double> weights) {
23      double total = weights.Sum();
[11730]24
[11799]25      var elemEnumerator = elements.GetEnumerator();
26      elemEnumerator.MoveNext();
27      var weightEnumerator = weights.GetEnumerator();
28      weightEnumerator.MoveNext();
29
30      var r = random.NextDouble() * total;
31      var agg = weightEnumerator.Current;
32
33      while (agg < r) {
34        weightEnumerator.MoveNext();
35        elemEnumerator.MoveNext();
36        agg += weightEnumerator.Current;
[11730]37      }
[11799]38      return elemEnumerator.Current;
[11730]39    }
[11732]40
41    public static double RSq(IEnumerable<double> xs, IEnumerable<double> ys) {
42      // two pass implementation, but we don't care
43      var meanX = xs.Average();
44      var meanY = ys.Average();
45
46      var s = 0.0;
47      var ssX = 0.0;
48      var ssY = 0.0;
[11742]49      var xEnum = xs.GetEnumerator();
50      var yEnum = ys.GetEnumerator();
51      while (xEnum.MoveNext() & yEnum.MoveNext()) {
52        var x = xEnum.Current;
53        var y = yEnum.Current;
54        s += (x - meanX) * (y - meanY);
[11799]55        ssX += (x - meanX) * (x - meanX);
56        ssY += (y - meanY) * (y - meanY);
[11732]57      }
[11742]58      if (xEnum.MoveNext() | yEnum.MoveNext()) throw new ArgumentException("lengths are not equal");
[11732]59
60      if (s.IsAlmost(0)) return 0;
61      if (ssX.IsAlmost(0) || ssY.IsAlmost(0)) return 0;
62      return s * s / (ssX * ssY);
63    }
64
65
[11659]66  }
67}
Note: See TracBrowser for help on using the repository browser.