[17737] | 1 | using HeuristicLab.Common;
|
---|
| 2 | using System;
|
---|
| 3 | using System.Collections.Generic;
|
---|
| 4 | using System.Linq;
|
---|
| 5 |
|
---|
| 6 | namespace 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)
|
---|
[17779] | 36 | => Transform(vals, mean: 0, stdDev: 1);
|
---|
[17737] | 37 |
|
---|
[17779] | 38 | public static double[] Transform(double[] vals, double mean, double stdDev) {
|
---|
[17737] | 39 | var result = new double[vals.Length];
|
---|
| 40 |
|
---|
[17779] | 41 | var scale = vals.StandardDeviationPop() / stdDev;
|
---|
[17737] | 42 | for (int i = 0; i < vals.Length; i++) {
|
---|
[17779] | 43 | result[i] = vals[i] / scale;
|
---|
[17737] | 44 | }
|
---|
| 45 |
|
---|
[17779] | 46 | var offset = result.Average() - mean;
|
---|
[17737] | 47 | for (int i = 0; i < vals.Length; i++) {
|
---|
[17779] | 48 | result[i] = result[i] - offset;
|
---|
[17737] | 49 | }
|
---|
| 50 |
|
---|
| 51 | return result;
|
---|
| 52 | }
|
---|
| 53 | }
|
---|
| 54 | }
|
---|