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

Last change on this file since 11732 was 11732, checked in by gkronber, 7 years ago

#2283: refactoring and bug fixes

File size: 1.6 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    public static bool IsAlmost(this double x, double y) {
10      return Math.Abs(x - y) < 1.0e-6;
11    }
12
13    public static T SelectRandom<T>(this IEnumerable<T> xs, Random rand) {
14      var xsArr = xs.ToArray();
15      return xsArr[rand.Next(xsArr.Length)];
16    }
17
18    public static IEnumerable<T> SampleProportional<T>(this IEnumerable<T> source, Random random, IEnumerable<double> weights) {
19      var sourceArray = source.ToArray();
20      var valueArray = weights.ToArray();
21      double total = valueArray.Sum();
22
23      while (true) {
24        int index = 0;
25        double ball = valueArray[index], sum = random.NextDouble() * total;
26        while (ball < sum)
27          ball += valueArray[++index];
28        yield return sourceArray[index];
29      }
30    }
31
32    public static double RSq(IEnumerable<double> xs, IEnumerable<double> ys) {
33      // two pass implementation, but we don't care
34      var meanX = xs.Average();
35      var meanY = ys.Average();
36
37      var s = 0.0;
38      var ssX = 0.0;
39      var ssY = 0.0;
40      foreach (var p in xs.Zip(ys, (x, y) => new { x, y })) {
41        s += (p.x - meanX) * (p.y - meanY);
42        ssX += Math.Pow(p.x - meanX, 2);
43        ssY += Math.Pow(p.y - meanY, 2);
44      }
45
46      if (s.IsAlmost(0)) return 0;
47      if (ssX.IsAlmost(0) || ssY.IsAlmost(0)) return 0;
48      return s * s / (ssX * ssY);
49    }
50
51
52  }
53}
Note: See TracBrowser for help on using the repository browser.