Free cookie consent management tool by TermsFeed Policy Generator

source: branches/HeuristicLab.Problems.GrammaticalOptimization-gkr/HeuristicLab.Common/Extensions.cs @ 13402

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

#2283: eurocast experiments

File size: 2.1 KB
Line 
1using System;
2using System.Collections.Generic;
3using System.Linq;
4using System.Text;
5using System.Threading.Tasks;
6
7namespace HeuristicLab.Common {
8  public static class Extensions {
9
10    public static bool IsAlmost(this double x, double y) {
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;
14      return Math.Abs(x - y) < 1.0e-12;
15    }
16
17    public static T SelectRandom<T>(this IEnumerable<T> xs, Random rand) {
18      var n = xs.Count();
19      return xs.ElementAt(rand.Next(n));
20    }
21
22    public static T SampleProportional<T>(this IEnumerable<T> elements, Random random, IEnumerable<double> weights) {
23      double total = weights.Sum();
24
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;
37      }
38      return elemEnumerator.Current;
39    }
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;
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);
55        ssX += (x - meanX) * (x - meanX);
56        ssY += (y - meanY) * (y - meanY);
57      }
58      if (xEnum.MoveNext() | yEnum.MoveNext()) throw new ArgumentException("lengths are not equal");
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
66  }
67}
Note: See TracBrowser for help on using the repository browser.