Free cookie consent management tool by TermsFeed Policy Generator

source: branches/2886_SymRegGrammarEnumeration/ExpressionClustering/Flann.cs @ 15840

Last change on this file since 15840 was 15840, checked in by gkronber, 6 years ago

#2886 added utility console program for clustering of expressions

File size: 7.5 KB
Line 
1using System;
2using System.Collections.Generic;
3using System.Linq;
4using System.Runtime.InteropServices;
5using System.Text;
6using System.Threading.Tasks;
7
8namespace ExpressionClustering {
9  // /* file flann_example.c */
10  // # include "flann.h"
11  // # include <stdio.h>
12  // # include <assert.h>
13  //   /* Function that reads a dataset */
14  //   float* read_points(char* filename, int* rows, int* cols);
15  //   int main(int argc, char** argv) {
16  //     int rows, cols;
17  //     int t_rows, t_cols;
18  //     float speedup;
19  //     /* read dataset points from file dataset.dat */
20  //     float* dataset = read_points("dataset.dat", &rows, &cols);
21  //     float* testset = read_points("testset.dat", &t_rows, &t_cols);
22  //     /* points in dataset and testset should have the same dimensionality */
23  //     assert(cols == t_cols);
24  //     /* number of nearest neighbors to search */
25  //     int nn = 3;
26  //     /* allocate memory for the nearest-neighbors indices */
27  //     int* result = (int*)malloc(t_rows * nn * sizeof(int));
28  //     /* allocate memory for the distances */
29  //     float* dists = (float*)malloc(t_rows * nn * sizeof(float));
30  // /* index parameters are stored here */
31  // struct FLANNParameters p = DEFAULT_FLANN_PARAMETERS;
32  // p.algorithm = FLANN_INDEX_AUTOTUNED; /* or FLANN_INDEX_KDTREE, FLANN_INDEX_KMEANS, ... /*
33  // p.target_precision = 0.9; /* want 90% target precision */
34  // /* compute the 3 nearest-neighbors of each point in the testset */
35  // flann_find_nearest_neighbors(dataset, rows, cols, testset, t_rows,
36  // result, dists, nn, &p);
37  // ...
38  // free(dataset);
39  // free(testset);
40  // free(result);
41  // free(dists);
42  // return 0;
43  // }
44
45  public static class Flann {
46
47    public enum flann_algorithm_t {
48      FLANN_INDEX_LINEAR = 0,
49      FLANN_INDEX_KDTREE = 1,
50      FLANN_INDEX_KMEANS = 2,
51      FLANN_INDEX_COMPOSITE = 3,
52      FLANN_INDEX_KDTREE_SINGLE = 3,
53      FLANN_INDEX_SAVED = 254,
54      FLANN_INDEX_AUTOTUNED = 255
55    };
56
57
58    public enum flann_centers_init_t {
59      FLANN_CENTERS_RANDOM = 0,
60      FLANN_CENTERS_GONZALES = 1,
61      FLANN_CENTERS_KMEANSPP = 2
62    };
63
64    public enum flann_log_level_t {
65      FLANN_LOG_NONE = 0,
66      FLANN_LOG_FATAL = 1,
67      FLANN_LOG_ERROR = 2,
68      FLANN_LOG_WARN = 3,
69      FLANN_LOG_INFO = 4
70    };
71
72    public enum flann_distance_t {
73      FLANN_DIST_EUCLIDEAN = 1, // squared euclidean distance
74      FLANN_DIST_MANHATTAN = 2,
75      FLANN_DIST_MINKOWSKI = 3,
76      FLANN_DIST_HIST_INTERSECT = 5,
77      FlANN_DIST_HELLINGER = 6,
78      FLANN_DIST_CHI_SQUARE = 7, // chi-square
79      FLANN_DIST_KULLBACK_LEIBLER = 8, // kullback-leibler divergence
80    };
81
82    public struct FLANNParameters {
83      public flann_algorithm_t algorithm; /* the algorithm to use */
84
85      /* search time parameters */
86      public int checks;                /* how many leafs (features) to check in one search */
87      public float cb_index;            /* cluster boundary index. Used when searching the kmeans tree */
88
89      /*  kdtree index parameters */
90      public int trees;                 /* number of randomized trees to use (for kdtree) */
91
92      /* kmeans index parameters */
93      public int branching;             /* branching factor (for kmeans tree) */
94      public int iterations;            /* max iterations to perform in one kmeans cluetering (kmeans tree) */
95      public flann_centers_init_t centers_init;  /* algorithm used for picking the initial cluster centers for kmeans tree */
96
97      /* autotuned index parameters */
98      public float target_precision;    /* precision desired (used for autotuning, -1 otherwise) */
99      public float build_weight;        /* build tree time weighting factor */
100      public float memory_weight;       /* index memory weigthing factor */
101      public float sample_fraction;     /* what fraction of the dataset to use for autotuning */
102
103      /* other parameters */
104      public flann_log_level_t log_level;    /* determines the verbosity of each flann function */
105      public long random_seed;            /* random seed to use */
106    };
107
108    // struct FLANNParameters DEFAULT_FLANN_PARAMETERS = {
109    // FLANN_INDEX_KDTREE,
110    // 32, 0.2f, 0.0f,
111    // 4, 4,
112    // 32, 11, FLANN_CENTERS_RANDOM,
113    // 0.9f, 0.01f, 0, 0.1f,
114    // FLANN_LOG_NONE, 0
115    // };
116
117
118    public static FLANNParameters DEFAULT_FLANN_PARAMETERS = new FLANNParameters() {
119      algorithm = flann_algorithm_t.FLANN_INDEX_KDTREE,
120      checks = 32,
121      cb_index = 0.2f,
122      trees = 4,
123      branching = 32,
124      iterations = 11,
125      centers_init = flann_centers_init_t.FLANN_CENTERS_RANDOM,
126      target_precision = 0.9f,
127      build_weight = 0.01f,
128      memory_weight = 0,
129      sample_fraction = 0.1f,
130      log_level = flann_log_level_t.FLANN_LOG_NONE,
131      random_seed = 0,
132    };
133
134
135    [DllImport("flann-1.7.1.dll")]
136    public static extern int flann_find_nearest_neighbors(float[] dataset, int rows, int cols, float[] testset, int t_rows, int[] result, float[] dist, int nn, ref FLANNParameters flann_params);
137
138    [DllImport("flann-1.7.1.dll")]
139    public static extern int flann_build_index(float[] dataset, int rows, int cols, ref float speedup, ref FLANNParameters flann_params);
140
141    [DllImport("flann-1.7.1.dll")]
142    public static extern void flann_set_distance_type(flann_distance_t distance_type, int order);
143
144    [DllImport("flann-1.7.1.dll")]
145    public static extern int flann_compute_cluster_centers(float[] dataset, int rows, int cols, int clusters, float[] result, ref FLANNParameters flann_params);
146
147    public static int FindNearestNeighbours(List<double[]> dataset, List<double[]> queryset, out List<int> results, out List<double> distances, int nearestNeighbours = 3) {
148      var _nn = nearestNeighbours;
149      var _tRows = queryset.Count;
150      var _dists = new float[_nn * _tRows];
151      var _result = new int[_nn * _tRows];
152      var _dim = dataset.First().Length;
153      FLANNParameters p = DEFAULT_FLANN_PARAMETERS;
154      p.algorithm = flann_algorithm_t.FLANN_INDEX_AUTOTUNED;
155      p.centers_init = flann_centers_init_t.FLANN_CENTERS_RANDOM;
156      p.target_precision = 0.9f;
157      p.log_level = flann_log_level_t.FLANN_LOG_INFO;
158      // copy training set
159      var _ds = new float[dataset.Count * _dim];
160      var i = 0;
161      for (int d = 0; d < _dim; d++) {
162        foreach (var e in dataset) {
163          _ds[i++] = (float)e[d];
164        }
165      }
166
167      flann_set_distance_type(flann_distance_t.FLANN_DIST_EUCLIDEAN, 0);
168
169      int nClusters = 100;
170      float[] centers = new float[nClusters * _dim];
171      flann_compute_cluster_centers(_ds, rows: dataset.Count, cols: _dim, clusters: nClusters, result: centers, flann_params: ref p);
172
173      float speedup = -1.0f;
174      // _ds must be a rows × cols matrix stored in row-major order (one feature on each row)
175      var index = flann_build_index(_ds, rows: dataset.Count, cols: _dim, speedup: ref speedup, flann_params: ref p);
176
177      // copy testset
178      var _testset = new float[_tRows * _dim];
179      i = 0;
180      foreach (var e in queryset) {
181        foreach (var ei in e) {
182          _testset[i++] = (float)ei;
183        }
184      }
185      var res =
186        flann_find_nearest_neighbors(
187          _ds, dataset.Count, _dim,
188        _testset, _tRows,
189        _result, _dists, _nn, ref p);
190
191
192      distances = _dists.Select(fi => (double)fi).ToList();
193      results = _result.ToList();
194      return res;
195    }
196
197
198  }
199}
Note: See TracBrowser for help on using the repository browser.