Free cookie consent management tool by TermsFeed Policy Generator

source: branches/3022-FastFunctionExtraction/FFX/Utils.cs @ 18153

Last change on this file since 18153 was 17779, checked in by gkronber, 4 years ago

#3022: made a few changes while reviewing the code.

File size: 2.1 KB
Line 
1using HeuristicLab.Common;
2using System;
3using System.Collections.Generic;
4using System.Linq;
5
6namespace HeuristicLab.Algorithms.DataAnalysis.FastFunctionExtraction {
7    internal static class Utils {
8        // return the nth row of a matrix
9        public static T[] GetRow<T>(this T[,] matrix, int n) {
10            var columns = matrix.GetLength(1);
11            var array = new T[columns];
12            for (int i = 0; i < columns; ++i)
13                array[i] = matrix[n, i];
14            return array;
15        }
16
17        public static IEnumerable<int> FindAllIndices<T>(this IEnumerable<T> values, Predicate<T> match) {
18            return values.Select((b, i) => match(b) ? i : -1).Where(i => i != -1).ToArray();
19        }
20
21        public static int[] Argsort<T>(T[] vals) where T : IComparable {
22            var indices = Enumerable.Range(0, vals.Length).ToArray();
23            Array.Sort(indices, (idx1, idx2) => vals[idx1].CompareTo(vals[idx2]));
24            return indices;
25        }
26
27        public static IEnumerable<double> Linspace(double start, double end, int n) {
28            if (end < start) throw new ArgumentException("end must be higher that start");
29            if (n <= 0) return Enumerable.Empty<double>();
30            if (n == 1) return new double[1] { start };
31            var range = end - start;
32            return Enumerable.Range(0, n).Select(idx => start + range * idx / (n - 1));
33        }
34
35        public static double[] Normalize(double[] vals)
36            => Transform(vals, mean: 0, stdDev: 1);
37
38        public static double[] Transform(double[] vals, double mean, double stdDev) {
39            var result = new double[vals.Length];
40
41            var scale = vals.StandardDeviationPop() / stdDev;
42            for (int i = 0; i < vals.Length; i++) {
43                result[i] = vals[i] / scale;
44            }
45
46            var offset = result.Average() - mean;
47            for (int i = 0; i < vals.Length; i++) {
48                result[i] = result[i] - offset;
49            }
50
51            return result;
52        }
53    }
54}
Note: See TracBrowser for help on using the repository browser.