tesseract  4.00.00dev
cluster.cpp
Go to the documentation of this file.
1 /******************************************************************************
2  ** Filename: cluster.c
3  ** Purpose: Routines for clustering points in N-D space
4  ** Author: Dan Johnson
5  ** History: 5/29/89, DSJ, Created.
6  **
7  ** (c) Copyright Hewlett-Packard Company, 1988.
8  ** Licensed under the Apache License, Version 2.0 (the "License");
9  ** you may not use this file except in compliance with the License.
10  ** You may obtain a copy of the License at
11  ** http://www.apache.org/licenses/LICENSE-2.0
12  ** Unless required by applicable law or agreed to in writing, software
13  ** distributed under the License is distributed on an "AS IS" BASIS,
14  ** WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
15  ** See the License for the specific language governing permissions and
16  ** limitations under the License.
17  ******************************************************************************/
18 #include "const.h"
19 #include "cluster.h"
20 #include "emalloc.h"
21 #include "genericheap.h"
22 #include "helpers.h"
23 #include "kdpair.h"
24 #include "matrix.h"
25 #include "tprintf.h"
26 #include "danerror.h"
27 #include <math.h>
28 
29 #define HOTELLING 1 // If true use Hotelling's test to decide where to split.
30 #define FTABLE_X 10 // Size of FTable.
31 #define FTABLE_Y 100 // Size of FTable.
32 
33 // Table of values approximating the cumulative F-distribution for a confidence of 1%.
34 const double FTable[FTABLE_Y][FTABLE_X] = {
35  {4052.19, 4999.52, 5403.34, 5624.62, 5763.65, 5858.97, 5928.33, 5981.10, 6022.50, 6055.85,},
36  {98.502, 99.000, 99.166, 99.249, 99.300, 99.333, 99.356, 99.374, 99.388, 99.399,},
37  {34.116, 30.816, 29.457, 28.710, 28.237, 27.911, 27.672, 27.489, 27.345, 27.229,},
38  {21.198, 18.000, 16.694, 15.977, 15.522, 15.207, 14.976, 14.799, 14.659, 14.546,},
39  {16.258, 13.274, 12.060, 11.392, 10.967, 10.672, 10.456, 10.289, 10.158, 10.051,},
40  {13.745, 10.925, 9.780, 9.148, 8.746, 8.466, 8.260, 8.102, 7.976, 7.874,},
41  {12.246, 9.547, 8.451, 7.847, 7.460, 7.191, 6.993, 6.840, 6.719, 6.620,},
42  {11.259, 8.649, 7.591, 7.006, 6.632, 6.371, 6.178, 6.029, 5.911, 5.814,},
43  {10.561, 8.022, 6.992, 6.422, 6.057, 5.802, 5.613, 5.467, 5.351, 5.257,},
44  {10.044, 7.559, 6.552, 5.994, 5.636, 5.386, 5.200, 5.057, 4.942, 4.849,},
45  { 9.646, 7.206, 6.217, 5.668, 5.316, 5.069, 4.886, 4.744, 4.632, 4.539,},
46  { 9.330, 6.927, 5.953, 5.412, 5.064, 4.821, 4.640, 4.499, 4.388, 4.296,},
47  { 9.074, 6.701, 5.739, 5.205, 4.862, 4.620, 4.441, 4.302, 4.191, 4.100,},
48  { 8.862, 6.515, 5.564, 5.035, 4.695, 4.456, 4.278, 4.140, 4.030, 3.939,},
49  { 8.683, 6.359, 5.417, 4.893, 4.556, 4.318, 4.142, 4.004, 3.895, 3.805,},
50  { 8.531, 6.226, 5.292, 4.773, 4.437, 4.202, 4.026, 3.890, 3.780, 3.691,},
51  { 8.400, 6.112, 5.185, 4.669, 4.336, 4.102, 3.927, 3.791, 3.682, 3.593,},
52  { 8.285, 6.013, 5.092, 4.579, 4.248, 4.015, 3.841, 3.705, 3.597, 3.508,},
53  { 8.185, 5.926, 5.010, 4.500, 4.171, 3.939, 3.765, 3.631, 3.523, 3.434,},
54  { 8.096, 5.849, 4.938, 4.431, 4.103, 3.871, 3.699, 3.564, 3.457, 3.368,},
55  { 8.017, 5.780, 4.874, 4.369, 4.042, 3.812, 3.640, 3.506, 3.398, 3.310,},
56  { 7.945, 5.719, 4.817, 4.313, 3.988, 3.758, 3.587, 3.453, 3.346, 3.258,},
57  { 7.881, 5.664, 4.765, 4.264, 3.939, 3.710, 3.539, 3.406, 3.299, 3.211,},
58  { 7.823, 5.614, 4.718, 4.218, 3.895, 3.667, 3.496, 3.363, 3.256, 3.168,},
59  { 7.770, 5.568, 4.675, 4.177, 3.855, 3.627, 3.457, 3.324, 3.217, 3.129,},
60  { 7.721, 5.526, 4.637, 4.140, 3.818, 3.591, 3.421, 3.288, 3.182, 3.094,},
61  { 7.677, 5.488, 4.601, 4.106, 3.785, 3.558, 3.388, 3.256, 3.149, 3.062,},
62  { 7.636, 5.453, 4.568, 4.074, 3.754, 3.528, 3.358, 3.226, 3.120, 3.032,},
63  { 7.598, 5.420, 4.538, 4.045, 3.725, 3.499, 3.330, 3.198, 3.092, 3.005,},
64  { 7.562, 5.390, 4.510, 4.018, 3.699, 3.473, 3.305, 3.173, 3.067, 2.979,},
65  { 7.530, 5.362, 4.484, 3.993, 3.675, 3.449, 3.281, 3.149, 3.043, 2.955,},
66  { 7.499, 5.336, 4.459, 3.969, 3.652, 3.427, 3.258, 3.127, 3.021, 2.934,},
67  { 7.471, 5.312, 4.437, 3.948, 3.630, 3.406, 3.238, 3.106, 3.000, 2.913,},
68  { 7.444, 5.289, 4.416, 3.927, 3.611, 3.386, 3.218, 3.087, 2.981, 2.894,},
69  { 7.419, 5.268, 4.396, 3.908, 3.592, 3.368, 3.200, 3.069, 2.963, 2.876,},
70  { 7.396, 5.248, 4.377, 3.890, 3.574, 3.351, 3.183, 3.052, 2.946, 2.859,},
71  { 7.373, 5.229, 4.360, 3.873, 3.558, 3.334, 3.167, 3.036, 2.930, 2.843,},
72  { 7.353, 5.211, 4.343, 3.858, 3.542, 3.319, 3.152, 3.021, 2.915, 2.828,},
73  { 7.333, 5.194, 4.327, 3.843, 3.528, 3.305, 3.137, 3.006, 2.901, 2.814,},
74  { 7.314, 5.179, 4.313, 3.828, 3.514, 3.291, 3.124, 2.993, 2.888, 2.801,},
75  { 7.296, 5.163, 4.299, 3.815, 3.501, 3.278, 3.111, 2.980, 2.875, 2.788,},
76  { 7.280, 5.149, 4.285, 3.802, 3.488, 3.266, 3.099, 2.968, 2.863, 2.776,},
77  { 7.264, 5.136, 4.273, 3.790, 3.476, 3.254, 3.087, 2.957, 2.851, 2.764,},
78  { 7.248, 5.123, 4.261, 3.778, 3.465, 3.243, 3.076, 2.946, 2.840, 2.754,},
79  { 7.234, 5.110, 4.249, 3.767, 3.454, 3.232, 3.066, 2.935, 2.830, 2.743,},
80  { 7.220, 5.099, 4.238, 3.757, 3.444, 3.222, 3.056, 2.925, 2.820, 2.733,},
81  { 7.207, 5.087, 4.228, 3.747, 3.434, 3.213, 3.046, 2.916, 2.811, 2.724,},
82  { 7.194, 5.077, 4.218, 3.737, 3.425, 3.204, 3.037, 2.907, 2.802, 2.715,},
83  { 7.182, 5.066, 4.208, 3.728, 3.416, 3.195, 3.028, 2.898, 2.793, 2.706,},
84  { 7.171, 5.057, 4.199, 3.720, 3.408, 3.186, 3.020, 2.890, 2.785, 2.698,},
85  { 7.159, 5.047, 4.191, 3.711, 3.400, 3.178, 3.012, 2.882, 2.777, 2.690,},
86  { 7.149, 5.038, 4.182, 3.703, 3.392, 3.171, 3.005, 2.874, 2.769, 2.683,},
87  { 7.139, 5.030, 4.174, 3.695, 3.384, 3.163, 2.997, 2.867, 2.762, 2.675,},
88  { 7.129, 5.021, 4.167, 3.688, 3.377, 3.156, 2.990, 2.860, 2.755, 2.668,},
89  { 7.119, 5.013, 4.159, 3.681, 3.370, 3.149, 2.983, 2.853, 2.748, 2.662,},
90  { 7.110, 5.006, 4.152, 3.674, 3.363, 3.143, 2.977, 2.847, 2.742, 2.655,},
91  { 7.102, 4.998, 4.145, 3.667, 3.357, 3.136, 2.971, 2.841, 2.736, 2.649,},
92  { 7.093, 4.991, 4.138, 3.661, 3.351, 3.130, 2.965, 2.835, 2.730, 2.643,},
93  { 7.085, 4.984, 4.132, 3.655, 3.345, 3.124, 2.959, 2.829, 2.724, 2.637,},
94  { 7.077, 4.977, 4.126, 3.649, 3.339, 3.119, 2.953, 2.823, 2.718, 2.632,},
95  { 7.070, 4.971, 4.120, 3.643, 3.333, 3.113, 2.948, 2.818, 2.713, 2.626,},
96  { 7.062, 4.965, 4.114, 3.638, 3.328, 3.108, 2.942, 2.813, 2.708, 2.621,},
97  { 7.055, 4.959, 4.109, 3.632, 3.323, 3.103, 2.937, 2.808, 2.703, 2.616,},
98  { 7.048, 4.953, 4.103, 3.627, 3.318, 3.098, 2.932, 2.803, 2.698, 2.611,},
99  { 7.042, 4.947, 4.098, 3.622, 3.313, 3.093, 2.928, 2.798, 2.693, 2.607,},
100  { 7.035, 4.942, 4.093, 3.618, 3.308, 3.088, 2.923, 2.793, 2.689, 2.602,},
101  { 7.029, 4.937, 4.088, 3.613, 3.304, 3.084, 2.919, 2.789, 2.684, 2.598,},
102  { 7.023, 4.932, 4.083, 3.608, 3.299, 3.080, 2.914, 2.785, 2.680, 2.593,},
103  { 7.017, 4.927, 4.079, 3.604, 3.295, 3.075, 2.910, 2.781, 2.676, 2.589,},
104  { 7.011, 4.922, 4.074, 3.600, 3.291, 3.071, 2.906, 2.777, 2.672, 2.585,},
105  { 7.006, 4.917, 4.070, 3.596, 3.287, 3.067, 2.902, 2.773, 2.668, 2.581,},
106  { 7.001, 4.913, 4.066, 3.591, 3.283, 3.063, 2.898, 2.769, 2.664, 2.578,},
107  { 6.995, 4.908, 4.062, 3.588, 3.279, 3.060, 2.895, 2.765, 2.660, 2.574,},
108  { 6.990, 4.904, 4.058, 3.584, 3.275, 3.056, 2.891, 2.762, 2.657, 2.570,},
109  { 6.985, 4.900, 4.054, 3.580, 3.272, 3.052, 2.887, 2.758, 2.653, 2.567,},
110  { 6.981, 4.896, 4.050, 3.577, 3.268, 3.049, 2.884, 2.755, 2.650, 2.563,},
111  { 6.976, 4.892, 4.047, 3.573, 3.265, 3.046, 2.881, 2.751, 2.647, 2.560,},
112  { 6.971, 4.888, 4.043, 3.570, 3.261, 3.042, 2.877, 2.748, 2.644, 2.557,},
113  { 6.967, 4.884, 4.040, 3.566, 3.258, 3.039, 2.874, 2.745, 2.640, 2.554,},
114  { 6.963, 4.881, 4.036, 3.563, 3.255, 3.036, 2.871, 2.742, 2.637, 2.551,},
115  { 6.958, 4.877, 4.033, 3.560, 3.252, 3.033, 2.868, 2.739, 2.634, 2.548,},
116  { 6.954, 4.874, 4.030, 3.557, 3.249, 3.030, 2.865, 2.736, 2.632, 2.545,},
117  { 6.950, 4.870, 4.027, 3.554, 3.246, 3.027, 2.863, 2.733, 2.629, 2.542,},
118  { 6.947, 4.867, 4.024, 3.551, 3.243, 3.025, 2.860, 2.731, 2.626, 2.539,},
119  { 6.943, 4.864, 4.021, 3.548, 3.240, 3.022, 2.857, 2.728, 2.623, 2.537,},
120  { 6.939, 4.861, 4.018, 3.545, 3.238, 3.019, 2.854, 2.725, 2.621, 2.534,},
121  { 6.935, 4.858, 4.015, 3.543, 3.235, 3.017, 2.852, 2.723, 2.618, 2.532,},
122  { 6.932, 4.855, 4.012, 3.540, 3.233, 3.014, 2.849, 2.720, 2.616, 2.529,},
123  { 6.928, 4.852, 4.010, 3.538, 3.230, 3.012, 2.847, 2.718, 2.613, 2.527,},
124  { 6.925, 4.849, 4.007, 3.535, 3.228, 3.009, 2.845, 2.715, 2.611, 2.524,},
125  { 6.922, 4.846, 4.004, 3.533, 3.225, 3.007, 2.842, 2.713, 2.609, 2.522,},
126  { 6.919, 4.844, 4.002, 3.530, 3.223, 3.004, 2.840, 2.711, 2.606, 2.520,},
127  { 6.915, 4.841, 3.999, 3.528, 3.221, 3.002, 2.838, 2.709, 2.604, 2.518,},
128  { 6.912, 4.838, 3.997, 3.525, 3.218, 3.000, 2.835, 2.706, 2.602, 2.515,},
129  { 6.909, 4.836, 3.995, 3.523, 3.216, 2.998, 2.833, 2.704, 2.600, 2.513,},
130  { 6.906, 4.833, 3.992, 3.521, 3.214, 2.996, 2.831, 2.702, 2.598, 2.511,},
131  { 6.904, 4.831, 3.990, 3.519, 3.212, 2.994, 2.829, 2.700, 2.596, 2.509,},
132  { 6.901, 4.829, 3.988, 3.517, 3.210, 2.992, 2.827, 2.698, 2.594, 2.507,},
133  { 6.898, 4.826, 3.986, 3.515, 3.208, 2.990, 2.825, 2.696, 2.592, 2.505,},
134  { 6.895, 4.824, 3.984, 3.513, 3.206, 2.988, 2.823, 2.694, 2.590, 2.503}
135 };
136 
141 #define MINVARIANCE 0.0004
142 
149 #define MINSAMPLESPERBUCKET 5
150 #define MINSAMPLES (MINBUCKETS * MINSAMPLESPERBUCKET)
151 #define MINSAMPLESNEEDED 1
152 
159 #define BUCKETTABLESIZE 1024
160 #define NORMALEXTENT 3.0
161 
162 struct TEMPCLUSTER {
165 };
166 
169 
170 struct STATISTICS {
173  FLOAT32 *Min; // largest negative distance from the mean
174  FLOAT32 *Max; // largest positive distance from the mean
175 };
176 
177 struct BUCKETS {
178  DISTRIBUTION Distribution; // distribution being tested for
179  uinT32 SampleCount; // # of samples in histogram
180  FLOAT64 Confidence; // confidence level of test
181  FLOAT64 ChiSquared; // test threshold
182  uinT16 NumberOfBuckets; // number of cells in histogram
183  uinT16 Bucket[BUCKETTABLESIZE];// mapping to histogram buckets
184  uinT32 *Count; // frequency of occurrence histogram
185  FLOAT32 *ExpectedCount; // expected histogram
186 };
187 
188 struct CHISTRUCT{
192 };
193 
194 // For use with KDWalk / MakePotentialClusters
196  ClusterHeap *heap; // heap used to hold temp clusters, "best" on top
197  TEMPCLUSTER *candidates; // array of potential clusters
198  KDTREE *tree; // kd-tree to be searched for neighbors
199  inT32 next; // next candidate to be used
200 };
201 
202 typedef FLOAT64 (*DENSITYFUNC) (inT32);
203 typedef FLOAT64 (*SOLVEFUNC) (CHISTRUCT *, double);
204 
205 #define Odd(N) ((N)%2)
206 #define Mirror(N,R) ((R) - (N) - 1)
207 #define Abs(N) ( ( (N) < 0 ) ? ( -(N) ) : (N) )
208 
209 //--------------Global Data Definitions and Declarations----------------------
217 #define SqrtOf2Pi 2.506628275
218 static const FLOAT64 kNormalStdDev = BUCKETTABLESIZE / (2.0 * NORMALEXTENT);
219 static const FLOAT64 kNormalVariance =
221 static const FLOAT64 kNormalMagnitude =
222  (2.0 * NORMALEXTENT) / (SqrtOf2Pi * BUCKETTABLESIZE);
223 static const FLOAT64 kNormalMean = BUCKETTABLESIZE / 2;
224 
227 #define LOOKUPTABLESIZE 8
228 #define MAXDEGREESOFFREEDOM MAXBUCKETS
229 
230 static const uinT32 kCountTable[LOOKUPTABLESIZE] = {
231  MINSAMPLES, 200, 400, 600, 800, 1000, 1500, 2000
232 }; // number of samples
233 
234 static const uinT16 kBucketsTable[LOOKUPTABLESIZE] = {
235  MINBUCKETS, 16, 20, 24, 27, 30, 35, MAXBUCKETS
236 }; // number of buckets
237 
238 /*-------------------------------------------------------------------------
239  Private Function Prototypes
240 --------------------------------------------------------------------------*/
241 void CreateClusterTree(CLUSTERER *Clusterer);
242 
244  inT32 Level);
245 
247  CLUSTER *Cluster,
248  FLOAT32 *Distance);
249 
250 CLUSTER *MakeNewCluster(CLUSTERER *Clusterer, TEMPCLUSTER *TempCluster);
251 
253 register PARAM_DESC ParamDesc[],
254 register inT32 n1,
255 register inT32 n2,
256 register FLOAT32 m[],
257 register FLOAT32 m1[], register FLOAT32 m2[]);
258 
260 
261 PROTOTYPE *MakePrototype(CLUSTERER *Clusterer,
262  CLUSTERCONFIG *Config,
263  CLUSTER *Cluster);
264 
266  CLUSTER *Cluster,
267  STATISTICS *Statistics,
268  PROTOSTYLE Style,
269  inT32 MinSamples);
270 
272  CLUSTERCONFIG *Config,
273  CLUSTER *Cluster,
274  STATISTICS *Statistics);
275 
277  CLUSTER *Cluster,
278  STATISTICS *Statistics,
279  BUCKETS *Buckets);
280 
282  CLUSTER *Cluster,
283  STATISTICS *Statistics,
284  BUCKETS *Buckets);
285 
287  CLUSTER *Cluster,
288  STATISTICS *Statistics,
289  BUCKETS *NormalBuckets,
290  FLOAT64 Confidence);
291 
292 void MakeDimRandom(uinT16 i, PROTOTYPE *Proto, PARAM_DESC *ParamDesc);
293 
294 void MakeDimUniform(uinT16 i, PROTOTYPE *Proto, STATISTICS *Statistics);
295 
297 PARAM_DESC ParamDesc[], CLUSTER * Cluster);
298 
300  CLUSTER *Cluster,
301  STATISTICS *Statistics);
302 
304  CLUSTER *Cluster,
305  STATISTICS *Statistics);
306 
307 PROTOTYPE *NewMixedProto(inT16 N, CLUSTER *Cluster, STATISTICS *Statistics);
308 
309 PROTOTYPE *NewSimpleProto(inT16 N, CLUSTER *Cluster);
310 
311 BOOL8 Independent (PARAM_DESC ParamDesc[],
312 inT16 N, FLOAT32 * CoVariance, FLOAT32 Independence);
313 
314 BUCKETS *GetBuckets(CLUSTERER* clusterer,
315  DISTRIBUTION Distribution,
316  uinT32 SampleCount,
317  FLOAT64 Confidence);
318 
319 BUCKETS *MakeBuckets(DISTRIBUTION Distribution,
320  uinT32 SampleCount,
321  FLOAT64 Confidence);
322 
324 
326 
328 
330 
332 
333 void FillBuckets(BUCKETS *Buckets,
334  CLUSTER *Cluster,
335  uinT16 Dim,
336  PARAM_DESC *ParamDesc,
337  FLOAT32 Mean,
338  FLOAT32 StdDev);
339 
340 uinT16 NormalBucket(PARAM_DESC *ParamDesc,
341  FLOAT32 x,
342  FLOAT32 Mean,
343  FLOAT32 StdDev);
344 
345 uinT16 UniformBucket(PARAM_DESC *ParamDesc,
346  FLOAT32 x,
347  FLOAT32 Mean,
348  FLOAT32 StdDev);
349 
350 BOOL8 DistributionOK(BUCKETS *Buckets);
351 
352 void FreeStatistics(STATISTICS *Statistics);
353 
354 void FreeBuckets(BUCKETS *Buckets);
355 
356 void FreeCluster(CLUSTER *Cluster);
357 
358 uinT16 DegreesOfFreedom(DISTRIBUTION Distribution, uinT16 HistogramBuckets);
359 
360 int NumBucketsMatch(void *arg1, // BUCKETS *Histogram,
361  void *arg2); // uinT16 *DesiredNumberOfBuckets);
362 
363 int ListEntryMatch(void *arg1, void *arg2);
364 
365 void AdjustBuckets(BUCKETS *Buckets, uinT32 NewSampleCount);
366 
367 void InitBuckets(BUCKETS *Buckets);
368 
369 int AlphaMatch(void *arg1, // CHISTRUCT *ChiStruct,
370  void *arg2); // CHISTRUCT *SearchKey);
371 
372 CHISTRUCT *NewChiStruct(uinT16 DegreesOfFreedom, FLOAT64 Alpha);
373 
374 FLOAT64 Solve(SOLVEFUNC Function,
375  void *FunctionParams,
376  FLOAT64 InitialGuess,
377  FLOAT64 Accuracy);
378 
379 FLOAT64 ChiArea(CHISTRUCT *ChiParams, FLOAT64 x);
380 
382  CLUSTER *Cluster,
383  FLOAT32 MaxIllegal);
384 
385 double InvertMatrix(const float* input, int size, float* inv);
386 
387 //--------------------------Public Code--------------------------------------
398 CLUSTERER *
399 MakeClusterer (inT16 SampleSize, const PARAM_DESC ParamDesc[]) {
400  CLUSTERER *Clusterer;
401  int i;
402 
403  // allocate main clusterer data structure and init simple fields
404  Clusterer = (CLUSTERER *) Emalloc (sizeof (CLUSTERER));
405  Clusterer->SampleSize = SampleSize;
406  Clusterer->NumberOfSamples = 0;
407  Clusterer->NumChar = 0;
408 
409  // init fields which will not be used initially
410  Clusterer->Root = NULL;
411  Clusterer->ProtoList = NIL_LIST;
412 
413  // maintain a copy of param descriptors in the clusterer data structure
414  Clusterer->ParamDesc =
415  (PARAM_DESC *) Emalloc (SampleSize * sizeof (PARAM_DESC));
416  for (i = 0; i < SampleSize; i++) {
417  Clusterer->ParamDesc[i].Circular = ParamDesc[i].Circular;
418  Clusterer->ParamDesc[i].NonEssential = ParamDesc[i].NonEssential;
419  Clusterer->ParamDesc[i].Min = ParamDesc[i].Min;
420  Clusterer->ParamDesc[i].Max = ParamDesc[i].Max;
421  Clusterer->ParamDesc[i].Range = ParamDesc[i].Max - ParamDesc[i].Min;
422  Clusterer->ParamDesc[i].HalfRange = Clusterer->ParamDesc[i].Range / 2;
423  Clusterer->ParamDesc[i].MidRange =
424  (ParamDesc[i].Max + ParamDesc[i].Min) / 2;
425  }
426 
427  // allocate a kd tree to hold the samples
428  Clusterer->KDTree = MakeKDTree (SampleSize, ParamDesc);
429 
430  // Initialize cache of histogram buckets to minimize recomputing them.
431  for (int d = 0; d < DISTRIBUTION_COUNT; ++d) {
432  for (int c = 0; c < MAXBUCKETS + 1 - MINBUCKETS; ++c)
433  Clusterer->bucket_cache[d][c] = NULL;
434  }
435 
436  return Clusterer;
437 } // MakeClusterer
438 
455 SAMPLE* MakeSample(CLUSTERER * Clusterer, const FLOAT32* Feature,
456  inT32 CharID) {
457  SAMPLE *Sample;
458  int i;
459 
460  // see if the samples have already been clustered - if so trap an error
461  if (Clusterer->Root != NULL)
463  "Can't add samples after they have been clustered");
464 
465  // allocate the new sample and initialize it
466  Sample = (SAMPLE *) Emalloc (sizeof (SAMPLE) +
467  (Clusterer->SampleSize -
468  1) * sizeof (FLOAT32));
469  Sample->Clustered = FALSE;
470  Sample->Prototype = FALSE;
471  Sample->SampleCount = 1;
472  Sample->Left = NULL;
473  Sample->Right = NULL;
474  Sample->CharID = CharID;
475 
476  for (i = 0; i < Clusterer->SampleSize; i++)
477  Sample->Mean[i] = Feature[i];
478 
479  // add the sample to the KD tree - keep track of the total # of samples
480  Clusterer->NumberOfSamples++;
481  KDStore (Clusterer->KDTree, Sample->Mean, (char *) Sample);
482  if (CharID >= Clusterer->NumChar)
483  Clusterer->NumChar = CharID + 1;
484 
485  // execute hook for monitoring clustering operation
486  // (*SampleCreationHook)( Sample );
487 
488  return (Sample);
489 } // MakeSample
490 
513  //only create cluster tree if samples have never been clustered before
514  if (Clusterer->Root == NULL)
515  CreateClusterTree(Clusterer);
516 
517  //deallocate the old prototype list if one exists
518  FreeProtoList (&Clusterer->ProtoList);
519  Clusterer->ProtoList = NIL_LIST;
520 
521  //compute prototypes starting at the root node in the tree
522  ComputePrototypes(Clusterer, Config);
523  // We don't need the cluster pointers in the protos any more, so null them
524  // out, which makes it safe to delete the clusterer.
525  LIST proto_list = Clusterer->ProtoList;
526  iterate(proto_list) {
527  PROTOTYPE *proto = reinterpret_cast<PROTOTYPE *>(first_node(proto_list));
528  proto->Cluster = NULL;
529  }
530  return Clusterer->ProtoList;
531 } // ClusterSamples
532 
546 void FreeClusterer(CLUSTERER *Clusterer) {
547  if (Clusterer != NULL) {
548  free(Clusterer->ParamDesc);
549  if (Clusterer->KDTree != NULL)
550  FreeKDTree (Clusterer->KDTree);
551  if (Clusterer->Root != NULL)
552  FreeCluster (Clusterer->Root);
553  // Free up all used buckets structures.
554  for (int d = 0; d < DISTRIBUTION_COUNT; ++d) {
555  for (int c = 0; c < MAXBUCKETS + 1 - MINBUCKETS; ++c)
556  if (Clusterer->bucket_cache[d][c] != NULL)
557  FreeBuckets(Clusterer->bucket_cache[d][c]);
558  }
559 
560  free(Clusterer);
561  }
562 } // FreeClusterer
563 
573 void FreeProtoList(LIST *ProtoList) {
574  destroy_nodes(*ProtoList, FreePrototype);
575 } // FreeProtoList
576 
587 void FreePrototype(void *arg) { //PROTOTYPE *Prototype)
588  PROTOTYPE *Prototype = (PROTOTYPE *) arg;
589 
590  // unmark the corresponding cluster (if there is one
591  if (Prototype->Cluster != NULL)
592  Prototype->Cluster->Prototype = FALSE;
593 
594  // deallocate the prototype statistics and then the prototype itself
595  free (Prototype->Distrib);
596  free (Prototype->Mean);
597  if (Prototype->Style != spherical) {
598  free (Prototype->Variance.Elliptical);
599  free (Prototype->Magnitude.Elliptical);
600  free (Prototype->Weight.Elliptical);
601  }
602  free(Prototype);
603 } // FreePrototype
604 
620 CLUSTER *NextSample(LIST *SearchState) {
621  CLUSTER *Cluster;
622 
623  if (*SearchState == NIL_LIST)
624  return (NULL);
625  Cluster = (CLUSTER *) first_node (*SearchState);
626  *SearchState = pop (*SearchState);
627  while (TRUE) {
628  if (Cluster->Left == NULL)
629  return (Cluster);
630  *SearchState = push (*SearchState, Cluster->Right);
631  Cluster = Cluster->Left;
632  }
633 } // NextSample
634 
644 FLOAT32 Mean(PROTOTYPE *Proto, uinT16 Dimension) {
645  return (Proto->Mean[Dimension]);
646 } // Mean
647 
658  switch (Proto->Style) {
659  case spherical:
660  return ((FLOAT32) sqrt ((double) Proto->Variance.Spherical));
661  case elliptical:
662  return ((FLOAT32)
663  sqrt ((double) Proto->Variance.Elliptical[Dimension]));
664  case mixed:
665  switch (Proto->Distrib[Dimension]) {
666  case normal:
667  return ((FLOAT32)
668  sqrt ((double) Proto->Variance.Elliptical[Dimension]));
669  case uniform:
670  case D_random:
671  return (Proto->Variance.Elliptical[Dimension]);
672  case DISTRIBUTION_COUNT:
673  ASSERT_HOST(!"Distribution count not allowed!");
674  }
675  }
676  return 0.0f;
677 } // StandardDeviation
678 
679 
680 /*---------------------------------------------------------------------------
681  Private Code
682 ----------------------------------------------------------------------------*/
698 void CreateClusterTree(CLUSTERER *Clusterer) {
699  ClusteringContext context;
700  ClusterPair HeapEntry;
701  TEMPCLUSTER *PotentialCluster;
702 
703  // each sample and its nearest neighbor form a "potential" cluster
704  // save these in a heap with the "best" potential clusters on top
705  context.tree = Clusterer->KDTree;
706  context.candidates = (TEMPCLUSTER *)
707  Emalloc(Clusterer->NumberOfSamples * sizeof(TEMPCLUSTER));
708  context.next = 0;
709  context.heap = new ClusterHeap(Clusterer->NumberOfSamples);
710  KDWalk(context.tree, (void_proc)MakePotentialClusters, &context);
711 
712  // form potential clusters into actual clusters - always do "best" first
713  while (context.heap->Pop(&HeapEntry)) {
714  PotentialCluster = HeapEntry.data;
715 
716  // if main cluster of potential cluster is already in another cluster
717  // then we don't need to worry about it
718  if (PotentialCluster->Cluster->Clustered) {
719  continue;
720  }
721 
722  // if main cluster is not yet clustered, but its nearest neighbor is
723  // then we must find a new nearest neighbor
724  else if (PotentialCluster->Neighbor->Clustered) {
725  PotentialCluster->Neighbor =
726  FindNearestNeighbor(context.tree, PotentialCluster->Cluster,
727  &HeapEntry.key);
728  if (PotentialCluster->Neighbor != NULL) {
729  context.heap->Push(&HeapEntry);
730  }
731  }
732 
733  // if neither cluster is already clustered, form permanent cluster
734  else {
735  PotentialCluster->Cluster =
736  MakeNewCluster(Clusterer, PotentialCluster);
737  PotentialCluster->Neighbor =
738  FindNearestNeighbor(context.tree, PotentialCluster->Cluster,
739  &HeapEntry.key);
740  if (PotentialCluster->Neighbor != NULL) {
741  context.heap->Push(&HeapEntry);
742  }
743  }
744  }
745 
746  // the root node in the cluster tree is now the only node in the kd-tree
747  Clusterer->Root = (CLUSTER *) RootOf(Clusterer->KDTree);
748 
749  // free up the memory used by the K-D tree, heap, and temp clusters
750  FreeKDTree(context.tree);
751  Clusterer->KDTree = NULL;
752  delete context.heap;
753  free(context.candidates);
754 } // CreateClusterTree
755 
766  CLUSTER *Cluster, inT32 Level) {
767  ClusterPair HeapEntry;
768  int next = context->next;
769  context->candidates[next].Cluster = Cluster;
770  HeapEntry.data = &(context->candidates[next]);
771  context->candidates[next].Neighbor =
772  FindNearestNeighbor(context->tree,
773  context->candidates[next].Cluster,
774  &HeapEntry.key);
775  if (context->candidates[next].Neighbor != NULL) {
776  context->heap->Push(&HeapEntry);
777  context->next++;
778  }
779 } // MakePotentialClusters
780 
797 CLUSTER *
798 FindNearestNeighbor(KDTREE * Tree, CLUSTER * Cluster, FLOAT32 * Distance)
799 #define MAXNEIGHBORS 2
800 #define MAXDISTANCE MAX_FLOAT32
801 {
803  FLOAT32 Dist[MAXNEIGHBORS];
804  int NumberOfNeighbors;
805  inT32 i;
806  CLUSTER *BestNeighbor;
807 
808  // find the 2 nearest neighbors of the cluster
810  &NumberOfNeighbors, (void **)Neighbor, Dist);
811 
812  // search for the nearest neighbor that is not the cluster itself
813  *Distance = MAXDISTANCE;
814  BestNeighbor = NULL;
815  for (i = 0; i < NumberOfNeighbors; i++) {
816  if ((Dist[i] < *Distance) && (Neighbor[i] != Cluster)) {
817  *Distance = Dist[i];
818  BestNeighbor = Neighbor[i];
819  }
820  }
821  return BestNeighbor;
822 } // FindNearestNeighbor
823 
836 CLUSTER *MakeNewCluster(CLUSTERER *Clusterer, TEMPCLUSTER *TempCluster) {
837  CLUSTER *Cluster;
838 
839  // allocate the new cluster and initialize it
840  Cluster = (CLUSTER *) Emalloc(
841  sizeof(CLUSTER) + (Clusterer->SampleSize - 1) * sizeof(FLOAT32));
842  Cluster->Clustered = FALSE;
843  Cluster->Prototype = FALSE;
844  Cluster->Left = TempCluster->Cluster;
845  Cluster->Right = TempCluster->Neighbor;
846  Cluster->CharID = -1;
847 
848  // mark the old clusters as "clustered" and delete them from the kd-tree
849  Cluster->Left->Clustered = TRUE;
850  Cluster->Right->Clustered = TRUE;
851  KDDelete(Clusterer->KDTree, Cluster->Left->Mean, Cluster->Left);
852  KDDelete(Clusterer->KDTree, Cluster->Right->Mean, Cluster->Right);
853 
854  // compute the mean and sample count for the new cluster
855  Cluster->SampleCount =
856  MergeClusters(Clusterer->SampleSize, Clusterer->ParamDesc,
857  Cluster->Left->SampleCount, Cluster->Right->SampleCount,
858  Cluster->Mean, Cluster->Left->Mean, Cluster->Right->Mean);
859 
860  // add the new cluster to the KD tree
861  KDStore(Clusterer->KDTree, Cluster->Mean, Cluster);
862  return Cluster;
863 } // MakeNewCluster
864 
881  PARAM_DESC ParamDesc[],
882  inT32 n1,
883  inT32 n2,
884  FLOAT32 m[],
885  FLOAT32 m1[], FLOAT32 m2[]) {
886  inT32 i, n;
887 
888  n = n1 + n2;
889  for (i = N; i > 0; i--, ParamDesc++, m++, m1++, m2++) {
890  if (ParamDesc->Circular) {
891  // if distance between means is greater than allowed
892  // reduce upper point by one "rotation" to compute mean
893  // then normalize the mean back into the accepted range
894  if ((*m2 - *m1) > ParamDesc->HalfRange) {
895  *m = (n1 * *m1 + n2 * (*m2 - ParamDesc->Range)) / n;
896  if (*m < ParamDesc->Min)
897  *m += ParamDesc->Range;
898  }
899  else if ((*m1 - *m2) > ParamDesc->HalfRange) {
900  *m = (n1 * (*m1 - ParamDesc->Range) + n2 * *m2) / n;
901  if (*m < ParamDesc->Min)
902  *m += ParamDesc->Range;
903  }
904  else
905  *m = (n1 * *m1 + n2 * *m2) / n;
906  }
907  else
908  *m = (n1 * *m1 + n2 * *m2) / n;
909  }
910  return n;
911 } // MergeClusters
912 
924 void ComputePrototypes(CLUSTERER *Clusterer, CLUSTERCONFIG *Config) {
925  LIST ClusterStack = NIL_LIST;
926  CLUSTER *Cluster;
927  PROTOTYPE *Prototype;
928 
929  // use a stack to keep track of clusters waiting to be processed
930  // initially the only cluster on the stack is the root cluster
931  if (Clusterer->Root != NULL)
932  ClusterStack = push (NIL_LIST, Clusterer->Root);
933 
934  // loop until we have analyzed all clusters which are potential prototypes
935  while (ClusterStack != NIL_LIST) {
936  // remove the next cluster to be analyzed from the stack
937  // try to make a prototype from the cluster
938  // if successful, put it on the proto list, else split the cluster
939  Cluster = (CLUSTER *) first_node (ClusterStack);
940  ClusterStack = pop (ClusterStack);
941  Prototype = MakePrototype(Clusterer, Config, Cluster);
942  if (Prototype != NULL) {
943  Clusterer->ProtoList = push (Clusterer->ProtoList, Prototype);
944  }
945  else {
946  ClusterStack = push (ClusterStack, Cluster->Right);
947  ClusterStack = push (ClusterStack, Cluster->Left);
948  }
949  }
950 } // ComputePrototypes
951 
970  CLUSTERCONFIG *Config,
971  CLUSTER *Cluster) {
972  STATISTICS *Statistics;
973  PROTOTYPE *Proto;
974  BUCKETS *Buckets;
975 
976  // filter out clusters which contain samples from the same character
977  if (MultipleCharSamples (Clusterer, Cluster, Config->MaxIllegal))
978  return NULL;
979 
980  // compute the covariance matrix and ranges for the cluster
981  Statistics =
982  ComputeStatistics(Clusterer->SampleSize, Clusterer->ParamDesc, Cluster);
983 
984  // check for degenerate clusters which need not be analyzed further
985  // note that the MinSamples test assumes that all clusters with multiple
986  // character samples have been removed (as above)
987  Proto = MakeDegenerateProto(
988  Clusterer->SampleSize, Cluster, Statistics, Config->ProtoStyle,
989  (inT32) (Config->MinSamples * Clusterer->NumChar));
990  if (Proto != NULL) {
991  FreeStatistics(Statistics);
992  return Proto;
993  }
994  // check to ensure that all dimensions are independent
995  if (!Independent(Clusterer->ParamDesc, Clusterer->SampleSize,
996  Statistics->CoVariance, Config->Independence)) {
997  FreeStatistics(Statistics);
998  return NULL;
999  }
1000 
1001  if (HOTELLING && Config->ProtoStyle == elliptical) {
1002  Proto = TestEllipticalProto(Clusterer, Config, Cluster, Statistics);
1003  if (Proto != NULL) {
1004  FreeStatistics(Statistics);
1005  return Proto;
1006  }
1007  }
1008 
1009  // create a histogram data structure used to evaluate distributions
1010  Buckets = GetBuckets(Clusterer, normal, Cluster->SampleCount,
1011  Config->Confidence);
1012 
1013  // create a prototype based on the statistics and test it
1014  switch (Config->ProtoStyle) {
1015  case spherical:
1016  Proto = MakeSphericalProto(Clusterer, Cluster, Statistics, Buckets);
1017  break;
1018  case elliptical:
1019  Proto = MakeEllipticalProto(Clusterer, Cluster, Statistics, Buckets);
1020  break;
1021  case mixed:
1022  Proto = MakeMixedProto(Clusterer, Cluster, Statistics, Buckets,
1023  Config->Confidence);
1024  break;
1025  case automatic:
1026  Proto = MakeSphericalProto(Clusterer, Cluster, Statistics, Buckets);
1027  if (Proto != NULL)
1028  break;
1029  Proto = MakeEllipticalProto(Clusterer, Cluster, Statistics, Buckets);
1030  if (Proto != NULL)
1031  break;
1032  Proto = MakeMixedProto(Clusterer, Cluster, Statistics, Buckets,
1033  Config->Confidence);
1034  break;
1035  }
1036  FreeStatistics(Statistics);
1037  return Proto;
1038 } // MakePrototype
1039 
1063 PROTOTYPE *MakeDegenerateProto( //this was MinSample
1064  uinT16 N,
1065  CLUSTER *Cluster,
1066  STATISTICS *Statistics,
1067  PROTOSTYLE Style,
1068  inT32 MinSamples) {
1069  PROTOTYPE *Proto = NULL;
1070 
1071  if (MinSamples < MINSAMPLESNEEDED)
1072  MinSamples = MINSAMPLESNEEDED;
1073 
1074  if (Cluster->SampleCount < MinSamples) {
1075  switch (Style) {
1076  case spherical:
1077  Proto = NewSphericalProto (N, Cluster, Statistics);
1078  break;
1079  case elliptical:
1080  case automatic:
1081  Proto = NewEllipticalProto (N, Cluster, Statistics);
1082  break;
1083  case mixed:
1084  Proto = NewMixedProto (N, Cluster, Statistics);
1085  break;
1086  }
1087  Proto->Significant = FALSE;
1088  }
1089  return (Proto);
1090 } // MakeDegenerateProto
1091 
1106  CLUSTERCONFIG *Config,
1107  CLUSTER *Cluster,
1108  STATISTICS *Statistics) {
1109  // Fraction of the number of samples used as a range around 1 within
1110  // which a cluster has the magic size that allows a boost to the
1111  // FTable by kFTableBoostMargin, thus allowing clusters near the
1112  // magic size (equal to the number of sample characters) to be more
1113  // likely to stay together.
1114  const double kMagicSampleMargin = 0.0625;
1115  const double kFTableBoostMargin = 2.0;
1116 
1117  int N = Clusterer->SampleSize;
1118  CLUSTER* Left = Cluster->Left;
1119  CLUSTER* Right = Cluster->Right;
1120  if (Left == NULL || Right == NULL)
1121  return NULL;
1122  int TotalDims = Left->SampleCount + Right->SampleCount;
1123  if (TotalDims < N + 1 || TotalDims < 2)
1124  return NULL;
1125  const int kMatrixSize = N * N * sizeof(FLOAT32);
1126  FLOAT32* Covariance = static_cast<FLOAT32 *>(Emalloc(kMatrixSize));
1127  FLOAT32* Inverse = static_cast<FLOAT32 *>(Emalloc(kMatrixSize));
1128  FLOAT32* Delta = static_cast<FLOAT32*>(Emalloc(N * sizeof(FLOAT32)));
1129  // Compute a new covariance matrix that only uses essential features.
1130  for (int i = 0; i < N; ++i) {
1131  int row_offset = i * N;
1132  if (!Clusterer->ParamDesc[i].NonEssential) {
1133  for (int j = 0; j < N; ++j) {
1134  if (!Clusterer->ParamDesc[j].NonEssential)
1135  Covariance[j + row_offset] = Statistics->CoVariance[j + row_offset];
1136  else
1137  Covariance[j + row_offset] = 0.0f;
1138  }
1139  } else {
1140  for (int j = 0; j < N; ++j) {
1141  if (i == j)
1142  Covariance[j + row_offset] = 1.0f;
1143  else
1144  Covariance[j + row_offset] = 0.0f;
1145  }
1146  }
1147  }
1148  double err = InvertMatrix(Covariance, N, Inverse);
1149  if (err > 1) {
1150  tprintf("Clustering error: Matrix inverse failed with error %g\n", err);
1151  }
1152  int EssentialN = 0;
1153  for (int dim = 0; dim < N; ++dim) {
1154  if (!Clusterer->ParamDesc[dim].NonEssential) {
1155  Delta[dim] = Left->Mean[dim] - Right->Mean[dim];
1156  ++EssentialN;
1157  } else {
1158  Delta[dim] = 0.0f;
1159  }
1160  }
1161  // Compute Hotelling's T-squared.
1162  double Tsq = 0.0;
1163  for (int x = 0; x < N; ++x) {
1164  double temp = 0.0;
1165  for (int y = 0; y < N; ++y) {
1166  temp += Inverse[y + N*x] * Delta[y];
1167  }
1168  Tsq += Delta[x] * temp;
1169  }
1170  free(Covariance);
1171  free(Inverse);
1172  free(Delta);
1173  // Changed this function to match the formula in
1174  // Statistical Methods in Medical Research p 473
1175  // By Peter Armitage, Geoffrey Berry, J. N. S. Matthews.
1176  // Tsq *= Left->SampleCount * Right->SampleCount / TotalDims;
1177  double F = Tsq * (TotalDims - EssentialN - 1) / ((TotalDims - 2)*EssentialN);
1178  int Fx = EssentialN;
1179  if (Fx > FTABLE_X)
1180  Fx = FTABLE_X;
1181  --Fx;
1182  int Fy = TotalDims - EssentialN - 1;
1183  if (Fy > FTABLE_Y)
1184  Fy = FTABLE_Y;
1185  --Fy;
1186  double FTarget = FTable[Fy][Fx];
1187  if (Config->MagicSamples > 0 &&
1188  TotalDims >= Config->MagicSamples * (1.0 - kMagicSampleMargin) &&
1189  TotalDims <= Config->MagicSamples * (1.0 + kMagicSampleMargin)) {
1190  // Give magic-sized clusters a magic FTable boost.
1191  FTarget += kFTableBoostMargin;
1192  }
1193  if (F < FTarget) {
1194  return NewEllipticalProto (Clusterer->SampleSize, Cluster, Statistics);
1195  }
1196  return NULL;
1197 }
1198 
1213  CLUSTER *Cluster,
1214  STATISTICS *Statistics,
1215  BUCKETS *Buckets) {
1216  PROTOTYPE *Proto = NULL;
1217  int i;
1218 
1219  // check that each dimension is a normal distribution
1220  for (i = 0; i < Clusterer->SampleSize; i++) {
1221  if (Clusterer->ParamDesc[i].NonEssential)
1222  continue;
1223 
1224  FillBuckets (Buckets, Cluster, i, &(Clusterer->ParamDesc[i]),
1225  Cluster->Mean[i],
1226  sqrt ((FLOAT64) (Statistics->AvgVariance)));
1227  if (!DistributionOK (Buckets))
1228  break;
1229  }
1230  // if all dimensions matched a normal distribution, make a proto
1231  if (i >= Clusterer->SampleSize)
1232  Proto = NewSphericalProto (Clusterer->SampleSize, Cluster, Statistics);
1233  return (Proto);
1234 } // MakeSphericalProto
1235 
1250  CLUSTER *Cluster,
1251  STATISTICS *Statistics,
1252  BUCKETS *Buckets) {
1253  PROTOTYPE *Proto = NULL;
1254  int i;
1255 
1256  // check that each dimension is a normal distribution
1257  for (i = 0; i < Clusterer->SampleSize; i++) {
1258  if (Clusterer->ParamDesc[i].NonEssential)
1259  continue;
1260 
1261  FillBuckets (Buckets, Cluster, i, &(Clusterer->ParamDesc[i]),
1262  Cluster->Mean[i],
1263  sqrt ((FLOAT64) Statistics->
1264  CoVariance[i * (Clusterer->SampleSize + 1)]));
1265  if (!DistributionOK (Buckets))
1266  break;
1267  }
1268  // if all dimensions matched a normal distribution, make a proto
1269  if (i >= Clusterer->SampleSize)
1270  Proto = NewEllipticalProto (Clusterer->SampleSize, Cluster, Statistics);
1271  return (Proto);
1272 } // MakeEllipticalProto
1273 
1292  CLUSTER *Cluster,
1293  STATISTICS *Statistics,
1294  BUCKETS *NormalBuckets,
1295  FLOAT64 Confidence) {
1296  PROTOTYPE *Proto;
1297  int i;
1298  BUCKETS *UniformBuckets = NULL;
1299  BUCKETS *RandomBuckets = NULL;
1300 
1301  // create a mixed proto to work on - initially assume all dimensions normal*/
1302  Proto = NewMixedProto (Clusterer->SampleSize, Cluster, Statistics);
1303 
1304  // find the proper distribution for each dimension
1305  for (i = 0; i < Clusterer->SampleSize; i++) {
1306  if (Clusterer->ParamDesc[i].NonEssential)
1307  continue;
1308 
1309  FillBuckets (NormalBuckets, Cluster, i, &(Clusterer->ParamDesc[i]),
1310  Proto->Mean[i],
1311  sqrt ((FLOAT64) Proto->Variance.Elliptical[i]));
1312  if (DistributionOK (NormalBuckets))
1313  continue;
1314 
1315  if (RandomBuckets == NULL)
1316  RandomBuckets =
1317  GetBuckets(Clusterer, D_random, Cluster->SampleCount, Confidence);
1318  MakeDimRandom (i, Proto, &(Clusterer->ParamDesc[i]));
1319  FillBuckets (RandomBuckets, Cluster, i, &(Clusterer->ParamDesc[i]),
1320  Proto->Mean[i], Proto->Variance.Elliptical[i]);
1321  if (DistributionOK (RandomBuckets))
1322  continue;
1323 
1324  if (UniformBuckets == NULL)
1325  UniformBuckets =
1326  GetBuckets(Clusterer, uniform, Cluster->SampleCount, Confidence);
1327  MakeDimUniform(i, Proto, Statistics);
1328  FillBuckets (UniformBuckets, Cluster, i, &(Clusterer->ParamDesc[i]),
1329  Proto->Mean[i], Proto->Variance.Elliptical[i]);
1330  if (DistributionOK (UniformBuckets))
1331  continue;
1332  break;
1333  }
1334  // if any dimension failed to match a distribution, discard the proto
1335  if (i < Clusterer->SampleSize) {
1336  FreePrototype(Proto);
1337  Proto = NULL;
1338  }
1339  return (Proto);
1340 } // MakeMixedProto
1341 
1352 void MakeDimRandom(uinT16 i, PROTOTYPE *Proto, PARAM_DESC *ParamDesc) {
1353  Proto->Distrib[i] = D_random;
1354  Proto->Mean[i] = ParamDesc->MidRange;
1355  Proto->Variance.Elliptical[i] = ParamDesc->HalfRange;
1356 
1357  // subtract out the previous magnitude of this dimension from the total
1358  Proto->TotalMagnitude /= Proto->Magnitude.Elliptical[i];
1359  Proto->Magnitude.Elliptical[i] = 1.0 / ParamDesc->Range;
1360  Proto->TotalMagnitude *= Proto->Magnitude.Elliptical[i];
1361  Proto->LogMagnitude = log ((double) Proto->TotalMagnitude);
1362 
1363  // note that the proto Weight is irrelevant for D_random protos
1364 } // MakeDimRandom
1365 
1376 void MakeDimUniform(uinT16 i, PROTOTYPE *Proto, STATISTICS *Statistics) {
1377  Proto->Distrib[i] = uniform;
1378  Proto->Mean[i] = Proto->Cluster->Mean[i] +
1379  (Statistics->Min[i] + Statistics->Max[i]) / 2;
1380  Proto->Variance.Elliptical[i] =
1381  (Statistics->Max[i] - Statistics->Min[i]) / 2;
1382  if (Proto->Variance.Elliptical[i] < MINVARIANCE)
1383  Proto->Variance.Elliptical[i] = MINVARIANCE;
1384 
1385  // subtract out the previous magnitude of this dimension from the total
1386  Proto->TotalMagnitude /= Proto->Magnitude.Elliptical[i];
1387  Proto->Magnitude.Elliptical[i] =
1388  1.0 / (2.0 * Proto->Variance.Elliptical[i]);
1389  Proto->TotalMagnitude *= Proto->Magnitude.Elliptical[i];
1390  Proto->LogMagnitude = log ((double) Proto->TotalMagnitude);
1391 
1392  // note that the proto Weight is irrelevant for uniform protos
1393 } // MakeDimUniform
1394 
1411 STATISTICS *
1412 ComputeStatistics (inT16 N, PARAM_DESC ParamDesc[], CLUSTER * Cluster) {
1413  STATISTICS *Statistics;
1414  int i, j;
1415  FLOAT32 *CoVariance;
1416  FLOAT32 *Distance;
1417  LIST SearchState;
1418  SAMPLE *Sample;
1419  uinT32 SampleCountAdjustedForBias;
1420 
1421  // allocate memory to hold the statistics results
1422  Statistics = (STATISTICS *) Emalloc (sizeof (STATISTICS));
1423  Statistics->CoVariance = (FLOAT32 *) Emalloc (N * N * sizeof (FLOAT32));
1424  Statistics->Min = (FLOAT32 *) Emalloc (N * sizeof (FLOAT32));
1425  Statistics->Max = (FLOAT32 *) Emalloc (N * sizeof (FLOAT32));
1426 
1427  // allocate temporary memory to hold the sample to mean distances
1428  Distance = (FLOAT32 *) Emalloc (N * sizeof (FLOAT32));
1429 
1430  // initialize the statistics
1431  Statistics->AvgVariance = 1.0;
1432  CoVariance = Statistics->CoVariance;
1433  for (i = 0; i < N; i++) {
1434  Statistics->Min[i] = 0.0;
1435  Statistics->Max[i] = 0.0;
1436  for (j = 0; j < N; j++, CoVariance++)
1437  *CoVariance = 0;
1438  }
1439  // find each sample in the cluster and merge it into the statistics
1440  InitSampleSearch(SearchState, Cluster);
1441  while ((Sample = NextSample (&SearchState)) != NULL) {
1442  for (i = 0; i < N; i++) {
1443  Distance[i] = Sample->Mean[i] - Cluster->Mean[i];
1444  if (ParamDesc[i].Circular) {
1445  if (Distance[i] > ParamDesc[i].HalfRange)
1446  Distance[i] -= ParamDesc[i].Range;
1447  if (Distance[i] < -ParamDesc[i].HalfRange)
1448  Distance[i] += ParamDesc[i].Range;
1449  }
1450  if (Distance[i] < Statistics->Min[i])
1451  Statistics->Min[i] = Distance[i];
1452  if (Distance[i] > Statistics->Max[i])
1453  Statistics->Max[i] = Distance[i];
1454  }
1455  CoVariance = Statistics->CoVariance;
1456  for (i = 0; i < N; i++)
1457  for (j = 0; j < N; j++, CoVariance++)
1458  *CoVariance += Distance[i] * Distance[j];
1459  }
1460  // normalize the variances by the total number of samples
1461  // use SampleCount-1 instead of SampleCount to get an unbiased estimate
1462  // also compute the geometic mean of the diagonal variances
1463  // ensure that clusters with only 1 sample are handled correctly
1464  if (Cluster->SampleCount > 1)
1465  SampleCountAdjustedForBias = Cluster->SampleCount - 1;
1466  else
1467  SampleCountAdjustedForBias = 1;
1468  CoVariance = Statistics->CoVariance;
1469  for (i = 0; i < N; i++)
1470  for (j = 0; j < N; j++, CoVariance++) {
1471  *CoVariance /= SampleCountAdjustedForBias;
1472  if (j == i) {
1473  if (*CoVariance < MINVARIANCE)
1474  *CoVariance = MINVARIANCE;
1475  Statistics->AvgVariance *= *CoVariance;
1476  }
1477  }
1478  Statistics->AvgVariance = (float)pow((double)Statistics->AvgVariance,
1479  1.0 / N);
1480 
1481  // release temporary memory and return
1482  free(Distance);
1483  return (Statistics);
1484 } // ComputeStatistics
1485 
1500  CLUSTER *Cluster,
1501  STATISTICS *Statistics) {
1502  PROTOTYPE *Proto;
1503 
1504  Proto = NewSimpleProto (N, Cluster);
1505 
1506  Proto->Variance.Spherical = Statistics->AvgVariance;
1507  if (Proto->Variance.Spherical < MINVARIANCE)
1508  Proto->Variance.Spherical = MINVARIANCE;
1509 
1510  Proto->Magnitude.Spherical =
1511  1.0 / sqrt ((double) (2.0 * PI * Proto->Variance.Spherical));
1512  Proto->TotalMagnitude = (float)pow((double)Proto->Magnitude.Spherical,
1513  (double) N);
1514  Proto->Weight.Spherical = 1.0 / Proto->Variance.Spherical;
1515  Proto->LogMagnitude = log ((double) Proto->TotalMagnitude);
1516 
1517  return (Proto);
1518 } // NewSphericalProto
1519 
1533  CLUSTER *Cluster,
1534  STATISTICS *Statistics) {
1535  PROTOTYPE *Proto;
1536  FLOAT32 *CoVariance;
1537  int i;
1538 
1539  Proto = NewSimpleProto (N, Cluster);
1540  Proto->Variance.Elliptical = (FLOAT32 *) Emalloc (N * sizeof (FLOAT32));
1541  Proto->Magnitude.Elliptical = (FLOAT32 *) Emalloc (N * sizeof (FLOAT32));
1542  Proto->Weight.Elliptical = (FLOAT32 *) Emalloc (N * sizeof (FLOAT32));
1543 
1544  CoVariance = Statistics->CoVariance;
1545  Proto->TotalMagnitude = 1.0;
1546  for (i = 0; i < N; i++, CoVariance += N + 1) {
1547  Proto->Variance.Elliptical[i] = *CoVariance;
1548  if (Proto->Variance.Elliptical[i] < MINVARIANCE)
1549  Proto->Variance.Elliptical[i] = MINVARIANCE;
1550 
1551  Proto->Magnitude.Elliptical[i] =
1552  1.0 / sqrt ((double) (2.0 * PI * Proto->Variance.Elliptical[i]));
1553  Proto->Weight.Elliptical[i] = 1.0 / Proto->Variance.Elliptical[i];
1554  Proto->TotalMagnitude *= Proto->Magnitude.Elliptical[i];
1555  }
1556  Proto->LogMagnitude = log ((double) Proto->TotalMagnitude);
1557  Proto->Style = elliptical;
1558  return (Proto);
1559 } // NewEllipticalProto
1560 
1576 PROTOTYPE *NewMixedProto(inT16 N, CLUSTER *Cluster, STATISTICS *Statistics) {
1577  PROTOTYPE *Proto;
1578  int i;
1579 
1580  Proto = NewEllipticalProto (N, Cluster, Statistics);
1581  Proto->Distrib = (DISTRIBUTION *) Emalloc (N * sizeof (DISTRIBUTION));
1582 
1583  for (i = 0; i < N; i++) {
1584  Proto->Distrib[i] = normal;
1585  }
1586  Proto->Style = mixed;
1587  return (Proto);
1588 } // NewMixedProto
1589 
1601  PROTOTYPE *Proto;
1602  int i;
1603 
1604  Proto = (PROTOTYPE *) Emalloc (sizeof (PROTOTYPE));
1605  Proto->Mean = (FLOAT32 *) Emalloc (N * sizeof (FLOAT32));
1606 
1607  for (i = 0; i < N; i++)
1608  Proto->Mean[i] = Cluster->Mean[i];
1609  Proto->Distrib = NULL;
1610 
1611  Proto->Significant = TRUE;
1612  Proto->Merged = FALSE;
1613  Proto->Style = spherical;
1614  Proto->NumSamples = Cluster->SampleCount;
1615  Proto->Cluster = Cluster;
1616  Proto->Cluster->Prototype = TRUE;
1617  return (Proto);
1618 } // NewSimpleProto
1619 
1640 BOOL8
1642 inT16 N, FLOAT32 * CoVariance, FLOAT32 Independence) {
1643  int i, j;
1644  FLOAT32 *VARii; // points to ith on-diagonal element
1645  FLOAT32 *VARjj; // points to jth on-diagonal element
1646  FLOAT32 CorrelationCoeff;
1647 
1648  VARii = CoVariance;
1649  for (i = 0; i < N; i++, VARii += N + 1) {
1650  if (ParamDesc[i].NonEssential)
1651  continue;
1652 
1653  VARjj = VARii + N + 1;
1654  CoVariance = VARii + 1;
1655  for (j = i + 1; j < N; j++, CoVariance++, VARjj += N + 1) {
1656  if (ParamDesc[j].NonEssential)
1657  continue;
1658 
1659  if ((*VARii == 0.0) || (*VARjj == 0.0))
1660  CorrelationCoeff = 0.0;
1661  else
1662  CorrelationCoeff =
1663  sqrt (sqrt (*CoVariance * *CoVariance / (*VARii * *VARjj)));
1664  if (CorrelationCoeff > Independence)
1665  return (FALSE);
1666  }
1667  }
1668  return (TRUE);
1669 } // Independent
1670 
1689  DISTRIBUTION Distribution,
1690  uinT32 SampleCount,
1691  FLOAT64 Confidence) {
1692  // Get an old bucket structure with the same number of buckets.
1693  uinT16 NumberOfBuckets = OptimumNumberOfBuckets(SampleCount);
1694  BUCKETS *Buckets =
1695  clusterer->bucket_cache[Distribution][NumberOfBuckets - MINBUCKETS];
1696 
1697  // If a matching bucket structure is not found, make one and save it.
1698  if (Buckets == NULL) {
1699  Buckets = MakeBuckets(Distribution, SampleCount, Confidence);
1700  clusterer->bucket_cache[Distribution][NumberOfBuckets - MINBUCKETS] =
1701  Buckets;
1702  } else {
1703  // Just adjust the existing buckets.
1704  if (SampleCount != Buckets->SampleCount)
1705  AdjustBuckets(Buckets, SampleCount);
1706  if (Confidence != Buckets->Confidence) {
1707  Buckets->Confidence = Confidence;
1708  Buckets->ChiSquared = ComputeChiSquared(
1709  DegreesOfFreedom(Distribution, Buckets->NumberOfBuckets),
1710  Confidence);
1711  }
1712  InitBuckets(Buckets);
1713  }
1714  return Buckets;
1715 } // GetBuckets
1716 
1736  uinT32 SampleCount,
1737  FLOAT64 Confidence) {
1738  const DENSITYFUNC DensityFunction[] =
1739  { NormalDensity, UniformDensity, UniformDensity };
1740  int i, j;
1741  BUCKETS *Buckets;
1742  FLOAT64 BucketProbability;
1743  FLOAT64 NextBucketBoundary;
1744  FLOAT64 Probability;
1745  FLOAT64 ProbabilityDelta;
1746  FLOAT64 LastProbDensity;
1747  FLOAT64 ProbDensity;
1748  uinT16 CurrentBucket;
1749  BOOL8 Symmetrical;
1750 
1751  // allocate memory needed for data structure
1752  Buckets = static_cast<BUCKETS*>(Emalloc(sizeof(BUCKETS)));
1753  Buckets->NumberOfBuckets = OptimumNumberOfBuckets(SampleCount);
1754  Buckets->SampleCount = SampleCount;
1755  Buckets->Confidence = Confidence;
1756  Buckets->Count = static_cast<uinT32*>(
1757  Emalloc(Buckets->NumberOfBuckets * sizeof(uinT32)));
1758  Buckets->ExpectedCount = static_cast<FLOAT32*>(
1759  Emalloc(Buckets->NumberOfBuckets * sizeof(FLOAT32)));
1760 
1761  // initialize simple fields
1762  Buckets->Distribution = Distribution;
1763  for (i = 0; i < Buckets->NumberOfBuckets; i++) {
1764  Buckets->Count[i] = 0;
1765  Buckets->ExpectedCount[i] = 0.0;
1766  }
1767 
1768  // all currently defined distributions are symmetrical
1769  Symmetrical = TRUE;
1770  Buckets->ChiSquared = ComputeChiSquared(
1771  DegreesOfFreedom(Distribution, Buckets->NumberOfBuckets), Confidence);
1772 
1773  if (Symmetrical) {
1774  // allocate buckets so that all have approx. equal probability
1775  BucketProbability = 1.0 / (FLOAT64) (Buckets->NumberOfBuckets);
1776 
1777  // distribution is symmetric so fill in upper half then copy
1778  CurrentBucket = Buckets->NumberOfBuckets / 2;
1779  if (Odd (Buckets->NumberOfBuckets))
1780  NextBucketBoundary = BucketProbability / 2;
1781  else
1782  NextBucketBoundary = BucketProbability;
1783 
1784  Probability = 0.0;
1785  LastProbDensity =
1786  (*DensityFunction[(int) Distribution]) (BUCKETTABLESIZE / 2);
1787  for (i = BUCKETTABLESIZE / 2; i < BUCKETTABLESIZE; i++) {
1788  ProbDensity = (*DensityFunction[(int) Distribution]) (i + 1);
1789  ProbabilityDelta = Integral (LastProbDensity, ProbDensity, 1.0);
1790  Probability += ProbabilityDelta;
1791  if (Probability > NextBucketBoundary) {
1792  if (CurrentBucket < Buckets->NumberOfBuckets - 1)
1793  CurrentBucket++;
1794  NextBucketBoundary += BucketProbability;
1795  }
1796  Buckets->Bucket[i] = CurrentBucket;
1797  Buckets->ExpectedCount[CurrentBucket] +=
1798  (FLOAT32) (ProbabilityDelta * SampleCount);
1799  LastProbDensity = ProbDensity;
1800  }
1801  // place any leftover probability into the last bucket
1802  Buckets->ExpectedCount[CurrentBucket] +=
1803  (FLOAT32) ((0.5 - Probability) * SampleCount);
1804 
1805  // copy upper half of distribution to lower half
1806  for (i = 0, j = BUCKETTABLESIZE - 1; i < j; i++, j--)
1807  Buckets->Bucket[i] =
1808  Mirror(Buckets->Bucket[j], Buckets->NumberOfBuckets);
1809 
1810  // copy upper half of expected counts to lower half
1811  for (i = 0, j = Buckets->NumberOfBuckets - 1; i <= j; i++, j--)
1812  Buckets->ExpectedCount[i] += Buckets->ExpectedCount[j];
1813  }
1814  return Buckets;
1815 } // MakeBuckets
1816 
1833  uinT8 Last, Next;
1834  FLOAT32 Slope;
1835 
1836  if (SampleCount < kCountTable[0])
1837  return kBucketsTable[0];
1838 
1839  for (Last = 0, Next = 1; Next < LOOKUPTABLESIZE; Last++, Next++) {
1840  if (SampleCount <= kCountTable[Next]) {
1841  Slope = (FLOAT32) (kBucketsTable[Next] - kBucketsTable[Last]) /
1842  (FLOAT32) (kCountTable[Next] - kCountTable[Last]);
1843  return ((uinT16) (kBucketsTable[Last] +
1844  Slope * (SampleCount - kCountTable[Last])));
1845  }
1846  }
1847  return kBucketsTable[Last];
1848 } // OptimumNumberOfBuckets
1849 
1868 FLOAT64
1869 ComputeChiSquared (uinT16 DegreesOfFreedom, FLOAT64 Alpha)
1870 #define CHIACCURACY 0.01
1871 #define MINALPHA (1e-200)
1872 {
1873  static LIST ChiWith[MAXDEGREESOFFREEDOM + 1];
1874 
1875  CHISTRUCT *OldChiSquared;
1876  CHISTRUCT SearchKey;
1877 
1878  // limit the minimum alpha that can be used - if alpha is too small
1879  // it may not be possible to compute chi-squared.
1880  Alpha = ClipToRange(Alpha, MINALPHA, 1.0);
1881  if (Odd (DegreesOfFreedom))
1882  DegreesOfFreedom++;
1883 
1884  /* find the list of chi-squared values which have already been computed
1885  for the specified number of degrees of freedom. Search the list for
1886  the desired chi-squared. */
1887  SearchKey.Alpha = Alpha;
1888  OldChiSquared = (CHISTRUCT *) first_node (search (ChiWith[DegreesOfFreedom],
1889  &SearchKey, AlphaMatch));
1890 
1891  if (OldChiSquared == NULL) {
1892  OldChiSquared = NewChiStruct (DegreesOfFreedom, Alpha);
1893  OldChiSquared->ChiSquared = Solve (ChiArea, OldChiSquared,
1894  (FLOAT64) DegreesOfFreedom,
1895  (FLOAT64) CHIACCURACY);
1896  ChiWith[DegreesOfFreedom] = push (ChiWith[DegreesOfFreedom],
1897  OldChiSquared);
1898  }
1899  else {
1900  // further optimization might move OldChiSquared to front of list
1901  }
1902 
1903  return (OldChiSquared->ChiSquared);
1904 
1905 } // ComputeChiSquared
1906 
1924  FLOAT64 Distance;
1925 
1926  Distance = x - kNormalMean;
1927  return kNormalMagnitude * exp(-0.5 * Distance * Distance / kNormalVariance);
1928 } // NormalDensity
1929 
1940  static FLOAT64 UniformDistributionDensity = (FLOAT64) 1.0 / BUCKETTABLESIZE;
1941 
1942  if ((x >= 0.0) && (x <= BUCKETTABLESIZE))
1943  return UniformDistributionDensity;
1944  else
1945  return (FLOAT64) 0.0;
1946 } // UniformDensity
1947 
1959  return (f1 + f2) * Dx / 2.0;
1960 } // Integral
1961 
1984 void FillBuckets(BUCKETS *Buckets,
1985  CLUSTER *Cluster,
1986  uinT16 Dim,
1987  PARAM_DESC *ParamDesc,
1988  FLOAT32 Mean,
1989  FLOAT32 StdDev) {
1990  uinT16 BucketID;
1991  int i;
1992  LIST SearchState;
1993  SAMPLE *Sample;
1994 
1995  // initialize the histogram bucket counts to 0
1996  for (i = 0; i < Buckets->NumberOfBuckets; i++)
1997  Buckets->Count[i] = 0;
1998 
1999  if (StdDev == 0.0) {
2000  /* if the standard deviation is zero, then we can't statistically
2001  analyze the cluster. Use a pseudo-analysis: samples exactly on
2002  the mean are distributed evenly across all buckets. Samples greater
2003  than the mean are placed in the last bucket; samples less than the
2004  mean are placed in the first bucket. */
2005 
2006  InitSampleSearch(SearchState, Cluster);
2007  i = 0;
2008  while ((Sample = NextSample (&SearchState)) != NULL) {
2009  if (Sample->Mean[Dim] > Mean)
2010  BucketID = Buckets->NumberOfBuckets - 1;
2011  else if (Sample->Mean[Dim] < Mean)
2012  BucketID = 0;
2013  else
2014  BucketID = i;
2015  Buckets->Count[BucketID] += 1;
2016  i++;
2017  if (i >= Buckets->NumberOfBuckets)
2018  i = 0;
2019  }
2020  }
2021  else {
2022  // search for all samples in the cluster and add to histogram buckets
2023  InitSampleSearch(SearchState, Cluster);
2024  while ((Sample = NextSample (&SearchState)) != NULL) {
2025  switch (Buckets->Distribution) {
2026  case normal:
2027  BucketID = NormalBucket (ParamDesc, Sample->Mean[Dim],
2028  Mean, StdDev);
2029  break;
2030  case D_random:
2031  case uniform:
2032  BucketID = UniformBucket (ParamDesc, Sample->Mean[Dim],
2033  Mean, StdDev);
2034  break;
2035  default:
2036  BucketID = 0;
2037  }
2038  Buckets->Count[Buckets->Bucket[BucketID]] += 1;
2039  }
2040  }
2041 } // FillBuckets
2042 
2057  FLOAT32 x,
2058  FLOAT32 Mean,
2059  FLOAT32 StdDev) {
2060  FLOAT32 X;
2061 
2062  // wraparound circular parameters if necessary
2063  if (ParamDesc->Circular) {
2064  if (x - Mean > ParamDesc->HalfRange)
2065  x -= ParamDesc->Range;
2066  else if (x - Mean < -ParamDesc->HalfRange)
2067  x += ParamDesc->Range;
2068  }
2069 
2070  X = ((x - Mean) / StdDev) * kNormalStdDev + kNormalMean;
2071  if (X < 0)
2072  return 0;
2073  if (X > BUCKETTABLESIZE - 1)
2074  return ((uinT16) (BUCKETTABLESIZE - 1));
2075  return (uinT16) floor((FLOAT64) X);
2076 } // NormalBucket
2077 
2092  FLOAT32 x,
2093  FLOAT32 Mean,
2094  FLOAT32 StdDev) {
2095  FLOAT32 X;
2096 
2097  // wraparound circular parameters if necessary
2098  if (ParamDesc->Circular) {
2099  if (x - Mean > ParamDesc->HalfRange)
2100  x -= ParamDesc->Range;
2101  else if (x - Mean < -ParamDesc->HalfRange)
2102  x += ParamDesc->Range;
2103  }
2104 
2105  X = ((x - Mean) / (2 * StdDev) * BUCKETTABLESIZE + BUCKETTABLESIZE / 2.0);
2106  if (X < 0)
2107  return 0;
2108  if (X > BUCKETTABLESIZE - 1)
2109  return (uinT16) (BUCKETTABLESIZE - 1);
2110  return (uinT16) floor((FLOAT64) X);
2111 } // UniformBucket
2112 
2126  FLOAT32 FrequencyDifference;
2127  FLOAT32 TotalDifference;
2128  int i;
2129 
2130  // compute how well the histogram matches the expected histogram
2131  TotalDifference = 0.0;
2132  for (i = 0; i < Buckets->NumberOfBuckets; i++) {
2133  FrequencyDifference = Buckets->Count[i] - Buckets->ExpectedCount[i];
2134  TotalDifference += (FrequencyDifference * FrequencyDifference) /
2135  Buckets->ExpectedCount[i];
2136  }
2137 
2138  // test to see if the difference is more than expected
2139  if (TotalDifference > Buckets->ChiSquared)
2140  return FALSE;
2141  else
2142  return TRUE;
2143 } // DistributionOK
2144 
2153 void FreeStatistics(STATISTICS *Statistics) {
2154  free(Statistics->CoVariance);
2155  free(Statistics->Min);
2156  free(Statistics->Max);
2157  free(Statistics);
2158 } // FreeStatistics
2159 
2165 void FreeBuckets(BUCKETS *buckets) {
2166  Efree(buckets->Count);
2167  Efree(buckets->ExpectedCount);
2168  Efree(buckets);
2169 } // FreeBuckets
2170 
2183 void FreeCluster(CLUSTER *Cluster) {
2184  if (Cluster != NULL) {
2185  FreeCluster (Cluster->Left);
2186  FreeCluster (Cluster->Right);
2187  free(Cluster);
2188  }
2189 } // FreeCluster
2190 
2205 uinT16 DegreesOfFreedom(DISTRIBUTION Distribution, uinT16 HistogramBuckets) {
2206  static uinT8 DegreeOffsets[] = { 3, 3, 1 };
2207 
2208  uinT16 AdjustedNumBuckets;
2209 
2210  AdjustedNumBuckets = HistogramBuckets - DegreeOffsets[(int) Distribution];
2211  if (Odd (AdjustedNumBuckets))
2212  AdjustedNumBuckets++;
2213  return (AdjustedNumBuckets);
2214 
2215 } // DegreesOfFreedom
2216 
2227 int NumBucketsMatch(void *arg1, // BUCKETS *Histogram,
2228  void *arg2) { // uinT16 *DesiredNumberOfBuckets)
2229  BUCKETS *Histogram = (BUCKETS *) arg1;
2230  uinT16 *DesiredNumberOfBuckets = (uinT16 *) arg2;
2231 
2232  return (*DesiredNumberOfBuckets == Histogram->NumberOfBuckets);
2233 
2234 } // NumBucketsMatch
2235 
2244 int ListEntryMatch(void *arg1, //ListNode
2245  void *arg2) { //Key
2246  return (arg1 == arg2);
2247 
2248 } // ListEntryMatch
2249 
2260 void AdjustBuckets(BUCKETS *Buckets, uinT32 NewSampleCount) {
2261  int i;
2262  FLOAT64 AdjustFactor;
2263 
2264  AdjustFactor = (((FLOAT64) NewSampleCount) /
2265  ((FLOAT64) Buckets->SampleCount));
2266 
2267  for (i = 0; i < Buckets->NumberOfBuckets; i++) {
2268  Buckets->ExpectedCount[i] *= AdjustFactor;
2269  }
2270 
2271  Buckets->SampleCount = NewSampleCount;
2272 
2273 } // AdjustBuckets
2274 
2283 void InitBuckets(BUCKETS *Buckets) {
2284  int i;
2285 
2286  for (i = 0; i < Buckets->NumberOfBuckets; i++) {
2287  Buckets->Count[i] = 0;
2288  }
2289 
2290 } // InitBuckets
2291 
2306 int AlphaMatch(void *arg1, //CHISTRUCT *ChiStruct,
2307  void *arg2) { //CHISTRUCT *SearchKey)
2308  CHISTRUCT *ChiStruct = (CHISTRUCT *) arg1;
2309  CHISTRUCT *SearchKey = (CHISTRUCT *) arg2;
2310 
2311  return (ChiStruct->Alpha == SearchKey->Alpha);
2312 
2313 } // AlphaMatch
2314 
2326 CHISTRUCT *NewChiStruct(uinT16 DegreesOfFreedom, FLOAT64 Alpha) {
2328 
2329  NewChiStruct = (CHISTRUCT *) Emalloc (sizeof (CHISTRUCT));
2330  NewChiStruct->DegreesOfFreedom = DegreesOfFreedom;
2331  NewChiStruct->Alpha = Alpha;
2332  return (NewChiStruct);
2333 
2334 } // NewChiStruct
2335 
2351 FLOAT64
2352 Solve (SOLVEFUNC Function,
2353 void *FunctionParams, FLOAT64 InitialGuess, FLOAT64 Accuracy)
2354 #define INITIALDELTA 0.1
2355 #define DELTARATIO 0.1
2356 {
2357  FLOAT64 x;
2358  FLOAT64 f;
2359  FLOAT64 Slope;
2360  FLOAT64 Delta;
2361  FLOAT64 NewDelta;
2362  FLOAT64 xDelta;
2363  FLOAT64 LastPosX, LastNegX;
2364 
2365  x = InitialGuess;
2366  Delta = INITIALDELTA;
2367  LastPosX = MAX_FLOAT32;
2368  LastNegX = -MAX_FLOAT32;
2369  f = (*Function) ((CHISTRUCT *) FunctionParams, x);
2370  while (Abs (LastPosX - LastNegX) > Accuracy) {
2371  // keep track of outer bounds of current estimate
2372  if (f < 0)
2373  LastNegX = x;
2374  else
2375  LastPosX = x;
2376 
2377  // compute the approx. slope of f(x) at the current point
2378  Slope =
2379  ((*Function) ((CHISTRUCT *) FunctionParams, x + Delta) - f) / Delta;
2380 
2381  // compute the next solution guess */
2382  xDelta = f / Slope;
2383  x -= xDelta;
2384 
2385  // reduce the delta used for computing slope to be a fraction of
2386  //the amount moved to get to the new guess
2387  NewDelta = Abs (xDelta) * DELTARATIO;
2388  if (NewDelta < Delta)
2389  Delta = NewDelta;
2390 
2391  // compute the value of the function at the new guess
2392  f = (*Function) ((CHISTRUCT *) FunctionParams, x);
2393  }
2394  return (x);
2395 
2396 } // Solve
2397 
2419  int i, N;
2420  FLOAT64 SeriesTotal;
2421  FLOAT64 Denominator;
2422  FLOAT64 PowerOfx;
2423 
2424  N = ChiParams->DegreesOfFreedom / 2 - 1;
2425  SeriesTotal = 1;
2426  Denominator = 1;
2427  PowerOfx = 1;
2428  for (i = 1; i <= N; i++) {
2429  Denominator *= 2 * i;
2430  PowerOfx *= x;
2431  SeriesTotal += PowerOfx / Denominator;
2432  }
2433  return ((SeriesTotal * exp (-0.5 * x)) - ChiParams->Alpha);
2434 
2435 } // ChiArea
2436 
2464 BOOL8
2466 CLUSTER * Cluster, FLOAT32 MaxIllegal)
2467 #define ILLEGAL_CHAR 2
2468 {
2469  static BOOL8 *CharFlags = NULL;
2470  static inT32 NumFlags = 0;
2471  int i;
2472  LIST SearchState;
2473  SAMPLE *Sample;
2474  inT32 CharID;
2475  inT32 NumCharInCluster;
2476  inT32 NumIllegalInCluster;
2477  FLOAT32 PercentIllegal;
2478 
2479  // initial estimate assumes that no illegal chars exist in the cluster
2480  NumCharInCluster = Cluster->SampleCount;
2481  NumIllegalInCluster = 0;
2482 
2483  if (Clusterer->NumChar > NumFlags) {
2484  free(CharFlags);
2485  NumFlags = Clusterer->NumChar;
2486  CharFlags = (BOOL8 *) Emalloc (NumFlags * sizeof (BOOL8));
2487  }
2488 
2489  for (i = 0; i < NumFlags; i++)
2490  CharFlags[i] = FALSE;
2491 
2492  // find each sample in the cluster and check if we have seen it before
2493  InitSampleSearch(SearchState, Cluster);
2494  while ((Sample = NextSample (&SearchState)) != NULL) {
2495  CharID = Sample->CharID;
2496  if (CharFlags[CharID] == FALSE) {
2497  CharFlags[CharID] = TRUE;
2498  }
2499  else {
2500  if (CharFlags[CharID] == TRUE) {
2501  NumIllegalInCluster++;
2502  CharFlags[CharID] = ILLEGAL_CHAR;
2503  }
2504  NumCharInCluster--;
2505  PercentIllegal = (FLOAT32) NumIllegalInCluster / NumCharInCluster;
2506  if (PercentIllegal > MaxIllegal) {
2507  destroy(SearchState);
2508  return (TRUE);
2509  }
2510  }
2511  }
2512  return (FALSE);
2513 
2514 } // MultipleCharSamples
2515 
2521 double InvertMatrix(const float* input, int size, float* inv) {
2522  // Allocate memory for the 2D arrays.
2523  GENERIC_2D_ARRAY<double> U(size, size, 0.0);
2524  GENERIC_2D_ARRAY<double> U_inv(size, size, 0.0);
2525  GENERIC_2D_ARRAY<double> L(size, size, 0.0);
2526 
2527  // Initialize the working matrices. U starts as input, L as I and U_inv as O.
2528  int row;
2529  int col;
2530  for (row = 0; row < size; row++) {
2531  for (col = 0; col < size; col++) {
2532  U[row][col] = input[row*size + col];
2533  L[row][col] = row == col ? 1.0 : 0.0;
2534  U_inv[row][col] = 0.0;
2535  }
2536  }
2537 
2538  // Compute forward matrix by inversion by LU decomposition of input.
2539  for (col = 0; col < size; ++col) {
2540  // Find best pivot
2541  int best_row = 0;
2542  double best_pivot = -1.0;
2543  for (row = col; row < size; ++row) {
2544  if (Abs(U[row][col]) > best_pivot) {
2545  best_pivot = Abs(U[row][col]);
2546  best_row = row;
2547  }
2548  }
2549  // Exchange pivot rows.
2550  if (best_row != col) {
2551  for (int k = 0; k < size; ++k) {
2552  double tmp = U[best_row][k];
2553  U[best_row][k] = U[col][k];
2554  U[col][k] = tmp;
2555  tmp = L[best_row][k];
2556  L[best_row][k] = L[col][k];
2557  L[col][k] = tmp;
2558  }
2559  }
2560  // Now do the pivot itself.
2561  for (row = col + 1; row < size; ++row) {
2562  double ratio = -U[row][col] / U[col][col];
2563  for (int j = col; j < size; ++j) {
2564  U[row][j] += U[col][j] * ratio;
2565  }
2566  for (int k = 0; k < size; ++k) {
2567  L[row][k] += L[col][k] * ratio;
2568  }
2569  }
2570  }
2571  // Next invert U.
2572  for (col = 0; col < size; ++col) {
2573  U_inv[col][col] = 1.0 / U[col][col];
2574  for (row = col - 1; row >= 0; --row) {
2575  double total = 0.0;
2576  for (int k = col; k > row; --k) {
2577  total += U[row][k] * U_inv[k][col];
2578  }
2579  U_inv[row][col] = -total / U[row][row];
2580  }
2581  }
2582  // Now the answer is U_inv.L.
2583  for (row = 0; row < size; row++) {
2584  for (col = 0; col < size; col++) {
2585  double sum = 0.0;
2586  for (int k = row; k < size; ++k) {
2587  sum += U_inv[row][k] * L[k][col];
2588  }
2589  inv[row*size + col] = sum;
2590  }
2591  }
2592  // Check matrix product.
2593  double error_sum = 0.0;
2594  for (row = 0; row < size; row++) {
2595  for (col = 0; col < size; col++) {
2596  double sum = 0.0;
2597  for (int k = 0; k < size; ++k) {
2598  sum += input[row*size + k] * inv[k *size + col];
2599  }
2600  if (row != col) {
2601  error_sum += Abs(sum);
2602  }
2603  }
2604  }
2605  return error_sum;
2606 }
LIST ProtoList
Definition: cluster.h:92
PROTOSTYLE ProtoStyle
Definition: cluster.h:49
ClusterHeap * heap
Definition: cluster.cpp:196
BUCKETS * bucket_cache[DISTRIBUTION_COUNT][MAXBUCKETS+1 - MINBUCKETS]
Definition: cluster.h:95
#define Mirror(N, R)
Definition: cluster.cpp:206
#define MINSAMPLES
Definition: cluster.cpp:150
DISTRIBUTION * Distrib
Definition: cluster.h:77
FLOAT32 LogMagnitude
Definition: cluster.h:80
#define MAXBUCKETS
Definition: cluster.h:27
void InitBuckets(BUCKETS *Buckets)
Definition: cluster.cpp:2283
unsigned Clustered
Definition: cluster.h:33
#define Odd(N)
Definition: cluster.cpp:205
void KDWalk(KDTREE *Tree, void_proc action, void *context)
Definition: kdtree.cpp:330
void MakeDimUniform(uinT16 i, PROTOTYPE *Proto, STATISTICS *Statistics)
Definition: cluster.cpp:1376
void FillBuckets(BUCKETS *Buckets, CLUSTER *Cluster, uinT16 Dim, PARAM_DESC *ParamDesc, FLOAT32 Mean, FLOAT32 StdDev)
Definition: cluster.cpp:1984
Definition: kdtree.h:49
void KDStore(KDTREE *Tree, FLOAT32 *Key, void *Data)
Definition: kdtree.cpp:218
void Push(Pair *entry)
Definition: genericheap.h:95
FLOAT32 * CoVariance
Definition: cluster.cpp:172
#define TRUE
Definition: capi.h:45
FLOAT32 * Elliptical
Definition: cluster.h:64
FLOAT32 StandardDeviation(PROTOTYPE *Proto, uinT16 Dimension)
Definition: cluster.cpp:657
void MakePotentialClusters(ClusteringContext *context, CLUSTER *Cluster, inT32 Level)
Definition: cluster.cpp:765
#define MINALPHA
int32_t inT32
Definition: host.h:38
void AdjustBuckets(BUCKETS *Buckets, uinT32 NewSampleCount)
Definition: cluster.cpp:2260
BUCKETS * MakeBuckets(DISTRIBUTION Distribution, uinT32 SampleCount, FLOAT64 Confidence)
Definition: cluster.cpp:1735
#define INITIALDELTA
FLOAT64(* DENSITYFUNC)(inT32)
Definition: cluster.cpp:202
LIST destroy(LIST list)
Definition: oldlist.cpp:182
#define Abs(N)
Definition: cluster.cpp:207
PROTOTYPE * MakeEllipticalProto(CLUSTERER *Clusterer, CLUSTER *Cluster, STATISTICS *Statistics, BUCKETS *Buckets)
Definition: cluster.cpp:1249
struct sample * Left
Definition: cluster.h:36
#define LOOKUPTABLESIZE
Definition: cluster.cpp:227
FLOAT64 ChiSquared
Definition: cluster.cpp:191
KDTREE * MakeKDTree(inT16 KeySize, const PARAM_DESC KeyDesc[])
Definition: kdtree.cpp:182
#define MINSAMPLESNEEDED
Definition: cluster.cpp:151
FLOAT64 UniformDensity(inT32 x)
Definition: cluster.cpp:1939
PROTOTYPE * MakeDegenerateProto(uinT16 N, CLUSTER *Cluster, STATISTICS *Statistics, PROTOSTYLE Style, inT32 MinSamples)
Definition: cluster.cpp:1063
voidpf void uLong size
Definition: ioapi.h:39
FLOAT64 Integral(FLOAT64 f1, FLOAT64 f2, FLOAT64 Dx)
Definition: cluster.cpp:1958
FLOAT32 Mean[1]
Definition: cluster.h:39
unsigned Merged
Definition: cluster.h:69
FLOAT32 MidRange
Definition: ocrfeatures.h:53
void * Emalloc(int Size)
Definition: emalloc.cpp:47
uinT16 OptimumNumberOfBuckets(uinT32 SampleCount)
Definition: cluster.cpp:1832
int NumBucketsMatch(void *arg1, void *arg2)
Definition: cluster.cpp:2227
FLOAT32 Range
Definition: ocrfeatures.h:51
void MakeDimRandom(uinT16 i, PROTOTYPE *Proto, PARAM_DESC *ParamDesc)
Definition: cluster.cpp:1352
#define MINBUCKETS
Definition: cluster.h:26
PROTOTYPE * MakeMixedProto(CLUSTERER *Clusterer, CLUSTER *Cluster, STATISTICS *Statistics, BUCKETS *NormalBuckets, FLOAT64 Confidence)
Definition: cluster.cpp:1291
#define tprintf(...)
Definition: tprintf.h:31
BOOL8 DistributionOK(BUCKETS *Buckets)
Definition: cluster.cpp:2125
LIST ClusterSamples(CLUSTERER *Clusterer, CLUSTERCONFIG *Config)
Definition: cluster.cpp:512
PARAM_DESC * ParamDesc
Definition: cluster.h:88
CLUSTER * MakeNewCluster(CLUSTERER *Clusterer, TEMPCLUSTER *TempCluster)
Definition: cluster.cpp:836
#define MAXDISTANCE
FLOAT32 MinSamples
Definition: cluster.h:50
FLOAT64 Confidence
Definition: cluster.cpp:180
uinT32 * Count
Definition: cluster.cpp:184
void CreateClusterTree(CLUSTERER *Clusterer)
Definition: cluster.cpp:698
void KDNearestNeighborSearch(KDTREE *Tree, FLOAT32 Query[], int QuerySize, FLOAT32 MaxDistance, int *NumberOfResults, void **NBuffer, FLOAT32 DBuffer[])
Definition: kdtree.cpp:320
#define NIL_LIST
Definition: oldlist.h:126
FLOAT32 MaxIllegal
Definition: cluster.h:51
CLUSTERCONFIG Config
DISTRIBUTION Distribution
Definition: cluster.cpp:178
FLOAT64 Solve(SOLVEFUNC Function, void *FunctionParams, FLOAT64 InitialGuess, FLOAT64 Accuracy)
Definition: cluster.cpp:2352
FLOATUNION Weight
Definition: cluster.h:83
inT8 Circular
Definition: ocrfeatures.h:47
#define InitSampleSearch(S, C)
Definition: cluster.h:105
LIST pop(LIST list)
Definition: oldlist.cpp:299
FLOAT32 Min
Definition: ocrfeatures.h:49
int16_t inT16
Definition: host.h:36
#define BUCKETTABLESIZE
Definition: cluster.cpp:159
FLOAT64 Confidence
Definition: cluster.h:54
PROTOTYPE * MakeSphericalProto(CLUSTERER *Clusterer, CLUSTER *Cluster, STATISTICS *Statistics, BUCKETS *Buckets)
Definition: cluster.cpp:1212
int MagicSamples
Definition: cluster.h:55
PROTOTYPE * MakePrototype(CLUSTERER *Clusterer, CLUSTERCONFIG *Config, CLUSTER *Cluster)
Definition: cluster.cpp:969
PROTOTYPE * NewSimpleProto(inT16 N, CLUSTER *Cluster)
Definition: cluster.cpp:1600
#define ASSERT_HOST(x)
Definition: errcode.h:84
uinT16 DegreesOfFreedom
Definition: cluster.cpp:189
FLOATUNION Variance
Definition: cluster.h:81
CLUSTERER * MakeClusterer(inT16 SampleSize, const PARAM_DESC ParamDesc[])
Definition: cluster.cpp:399
inT32 NumberOfSamples
Definition: cluster.h:89
PROTOTYPE * NewSphericalProto(uinT16 N, CLUSTER *Cluster, STATISTICS *Statistics)
Definition: cluster.cpp:1499
FLOAT32 Mean(PROTOTYPE *Proto, uinT16 Dimension)
Definition: cluster.cpp:644
#define MINVARIANCE
Definition: cluster.cpp:141
CLUSTER * Neighbor
Definition: cluster.cpp:164
inT16 SampleSize
Definition: cluster.h:87
int ListEntryMatch(void *arg1, void *arg2)
Definition: cluster.cpp:2244
LIST search(LIST list, void *key, int_compare is_equal)
Definition: oldlist.cpp:406
inT8 NonEssential
Definition: ocrfeatures.h:48
CLUSTER * Cluster
Definition: cluster.cpp:163
#define DELTARATIO
unsigned Style
Definition: cluster.h:74
tesseract::KDPairInc< float, TEMPCLUSTER * > ClusterPair
Definition: cluster.cpp:167
uint32_t uinT32
Definition: host.h:39
#define PI
Definition: const.h:19
BUCKETS * GetBuckets(CLUSTERER *clusterer, DISTRIBUTION Distribution, uinT32 SampleCount, FLOAT64 Confidence)
Definition: cluster.cpp:1688
FLOAT32 * Min
Definition: cluster.cpp:173
unsigned char BOOL8
Definition: host.h:44
inT32 CharID
Definition: cluster.h:38
#define FALSE
Definition: capi.h:46
DISTRIBUTION
Definition: cluster.h:58
uinT32 SampleCount
Definition: cluster.cpp:179
T ClipToRange(const T &x, const T &lower_bound, const T &upper_bound)
Definition: helpers.h:122
void FreeProtoList(LIST *ProtoList)
Definition: cluster.cpp:573
PROTOTYPE * TestEllipticalProto(CLUSTERER *Clusterer, CLUSTERCONFIG *Config, CLUSTER *Cluster, STATISTICS *Statistics)
Definition: cluster.cpp:1105
#define ALREADYCLUSTERED
Definition: cluster.h:133
struct sample * Right
Definition: cluster.h:37
PROTOSTYLE
Definition: cluster.h:44
#define MAX_FLOAT32
Definition: host.h:66
FLOAT32 * Mean
Definition: cluster.h:78
#define SqrtOf2Pi
Definition: cluster.cpp:217
FLOAT32 * ExpectedCount
Definition: cluster.cpp:185
uinT16 NumberOfBuckets
Definition: cluster.cpp:182
FLOAT32 AvgVariance
Definition: cluster.cpp:171
uinT16 DegreesOfFreedom(DISTRIBUTION Distribution, uinT16 HistogramBuckets)
Definition: cluster.cpp:2205
#define first_node(l)
Definition: oldlist.h:139
void destroy_nodes(LIST list, void_dest destructor)
Definition: oldlist.cpp:199
void FreeCluster(CLUSTER *Cluster)
Definition: cluster.cpp:2183
PROTOTYPE * NewEllipticalProto(inT16 N, CLUSTER *Cluster, STATISTICS *Statistics)
Definition: cluster.cpp:1532
FLOAT32 Independence
Definition: cluster.h:53
inT32 NumChar
Definition: cluster.h:93
CLUSTER * NextSample(LIST *SearchState)
Definition: cluster.cpp:620
void FreeClusterer(CLUSTERER *Clusterer)
Definition: cluster.cpp:546
unsigned Prototype
Definition: cluster.h:34
float FLOAT32
Definition: host.h:42
#define FTABLE_Y
Definition: cluster.cpp:31
void FreePrototype(void *arg)
Definition: cluster.cpp:587
uinT16 NormalBucket(PARAM_DESC *ParamDesc, FLOAT32 x, FLOAT32 Mean, FLOAT32 StdDev)
Definition: cluster.cpp:2056
STATISTICS * ComputeStatistics(inT16 N, PARAM_DESC ParamDesc[], CLUSTER *Cluster)
Definition: cluster.cpp:1412
Definition: cluster.h:45
FLOAT64 ChiArea(CHISTRUCT *ChiParams, FLOAT64 x)
Definition: cluster.cpp:2418
FLOAT32 Spherical
Definition: cluster.h:63
Definition: cluster.h:59
uinT16 UniformBucket(PARAM_DESC *ParamDesc, FLOAT32 x, FLOAT32 Mean, FLOAT32 StdDev)
Definition: cluster.cpp:2091
#define MAXDEGREESOFFREEDOM
Definition: cluster.cpp:228
void DoError(int Error, const char *Message)
Definition: danerror.cpp:42
#define CHIACCURACY
typedef int(ZCALLBACK *close_file_func) OF((voidpf opaque
void KDDelete(KDTREE *Tree, FLOAT32 Key[], void *Data)
Definition: kdtree.cpp:264
FLOAT32 Max
Definition: ocrfeatures.h:50
uint8_t uinT8
Definition: host.h:35
void FreeKDTree(KDTREE *Tree)
Definition: kdtree.cpp:349
BOOL8 Independent(PARAM_DESC ParamDesc[], inT16 N, FLOAT32 *CoVariance, FLOAT32 Independence)
Definition: cluster.cpp:1641
TEMPCLUSTER * candidates
Definition: cluster.cpp:197
unsigned NumSamples
Definition: cluster.h:75
FLOAT64 Alpha
Definition: cluster.cpp:190
FLOAT64(* SOLVEFUNC)(CHISTRUCT *, double)
Definition: cluster.cpp:203
#define HOTELLING
Definition: cluster.cpp:29
#define RootOf(T)
Definition: kdtree.h:58
double InvertMatrix(const float *input, int size, float *inv)
Definition: cluster.cpp:2521
PROTOTYPE * NewMixedProto(inT16 N, CLUSTER *Cluster, STATISTICS *Statistics)
Definition: cluster.cpp:1576
FLOAT32 * Max
Definition: cluster.cpp:174
#define MAXNEIGHBORS
unsigned Significant
Definition: cluster.h:68
#define FTABLE_X
Definition: cluster.cpp:30
inT32 MergeClusters(inT16 N, register PARAM_DESC ParamDesc[], register inT32 n1, register inT32 n2, register FLOAT32 m[], register FLOAT32 m1[], register FLOAT32 m2[])
FLOAT64 NormalDensity(inT32 x)
Definition: cluster.cpp:1923
#define NORMALEXTENT
Definition: cluster.cpp:160
CLUSTER * Cluster
Definition: cluster.h:76
CLUSTER * Root
Definition: cluster.h:91
unsigned SampleCount
Definition: cluster.h:35
void Efree(void *ptr)
Definition: emalloc.cpp:79
KDTREE * KDTree
Definition: cluster.h:90
Definition: cluster.h:32
tesseract::GenericHeap< ClusterPair > ClusterHeap
Definition: cluster.cpp:168
const double FTable[FTABLE_Y][FTABLE_X]
Definition: cluster.cpp:34
bool Pop(Pair *entry)
Definition: genericheap.h:118
void FreeStatistics(STATISTICS *Statistics)
Definition: cluster.cpp:2153
int AlphaMatch(void *arg1, void *arg2)
Definition: cluster.cpp:2306
#define iterate(l)
Definition: oldlist.h:159
void ComputePrototypes(CLUSTERER *Clusterer, CLUSTERCONFIG *Config)
Definition: cluster.cpp:924
FLOATUNION Magnitude
Definition: cluster.h:82
LIST push(LIST list, void *element)
Definition: oldlist.cpp:317
uint16_t uinT16
Definition: host.h:37
FLOAT32 TotalMagnitude
Definition: cluster.h:79
FLOAT64 ComputeChiSquared(uinT16 DegreesOfFreedom, FLOAT64 Alpha)
Definition: cluster.cpp:1869
uinT16 Bucket[BUCKETTABLESIZE]
Definition: cluster.cpp:183
BOOL8 MultipleCharSamples(CLUSTERER *Clusterer, CLUSTER *Cluster, FLOAT32 MaxIllegal)
Definition: cluster.cpp:2465
void(* void_proc)(...)
Definition: cutil.h:66
#define ILLEGAL_CHAR
double FLOAT64
Definition: host.h:43
FLOAT64 ChiSquared
Definition: cluster.cpp:181
FLOAT32 HalfRange
Definition: ocrfeatures.h:52
CHISTRUCT * NewChiStruct(uinT16 DegreesOfFreedom, FLOAT64 Alpha)
Definition: cluster.cpp:2326
SAMPLE * MakeSample(CLUSTERER *Clusterer, const FLOAT32 *Feature, inT32 CharID)
Definition: cluster.cpp:455
void FreeBuckets(BUCKETS *Buckets)
Definition: cluster.cpp:2165
CLUSTER * FindNearestNeighbor(KDTREE *Tree, CLUSTER *Cluster, FLOAT32 *Distance)
Definition: cluster.cpp:798