Stats.h 8.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389
  1. #pragma once
  2. #include "Types.h"
  3. #include <math.h>
  4. #include <vector>
  5. #include <map>
  6. #include <algorithm> // for std::sort
  7. #include <string.h> // for memset
  8. #include <stdio.h> // for printf
  9. double calcScore ( const int * bins, const int bincount, const int ballcount );
  10. void plot ( double n );
  11. inline double ExpectedCollisions ( double balls, double bins )
  12. {
  13. return balls - bins + bins * pow(1 - 1/bins,balls);
  14. }
  15. double chooseK ( int b, int k );
  16. double chooseUpToK ( int n, int k );
  17. //-----------------------------------------------------------------------------
  18. inline uint32_t f3mix ( uint32_t k )
  19. {
  20. k ^= k >> 16;
  21. k *= 0x85ebca6b;
  22. k ^= k >> 13;
  23. k *= 0xc2b2ae35;
  24. k ^= k >> 16;
  25. return k;
  26. }
  27. //-----------------------------------------------------------------------------
  28. // Sort the hash list, count the total number of collisions and return
  29. // the first N collisions for further processing
  30. template< typename hashtype >
  31. int FindCollisions ( std::vector<hashtype> & hashes,
  32. HashSet<hashtype> & collisions,
  33. int maxCollisions )
  34. {
  35. int collcount = 0;
  36. std::sort(hashes.begin(),hashes.end());
  37. for(size_t i = 1; i < hashes.size(); i++)
  38. {
  39. if(hashes[i] == hashes[i-1])
  40. {
  41. collcount++;
  42. if((int)collisions.size() < maxCollisions)
  43. {
  44. collisions.insert(hashes[i]);
  45. }
  46. }
  47. }
  48. return collcount;
  49. }
  50. //-----------------------------------------------------------------------------
  51. template < class keytype, typename hashtype >
  52. int PrintCollisions ( hashfunc<hashtype> hash, std::vector<keytype> & keys )
  53. {
  54. int collcount = 0;
  55. typedef std::map<hashtype,keytype> htab;
  56. htab tab;
  57. for(size_t i = 1; i < keys.size(); i++)
  58. {
  59. keytype & k1 = keys[i];
  60. hashtype h = hash(&k1,sizeof(keytype),0);
  61. typename htab::iterator it = tab.find(h);
  62. if(it != tab.end())
  63. {
  64. keytype & k2 = (*it).second;
  65. printf("A: ");
  66. printbits(&k1,sizeof(keytype));
  67. printf("B: ");
  68. printbits(&k2,sizeof(keytype));
  69. }
  70. else
  71. {
  72. tab.insert( std::make_pair(h,k1) );
  73. }
  74. }
  75. return collcount;
  76. }
  77. //----------------------------------------------------------------------------
  78. // Measure the distribution "score" for each possible N-bit span up to 20 bits
  79. template< typename hashtype >
  80. double TestDistribution ( std::vector<hashtype> & hashes, bool drawDiagram )
  81. {
  82. printf("Testing distribution - ");
  83. if(drawDiagram) printf("\n");
  84. const int hashbits = sizeof(hashtype) * 8;
  85. int maxwidth = 20;
  86. // We need at least 5 keys per bin to reliably test distribution biases
  87. // down to 1%, so don't bother to test sparser distributions than that
  88. while(double(hashes.size()) / double(1 << maxwidth) < 5.0)
  89. {
  90. maxwidth--;
  91. }
  92. std::vector<int> bins;
  93. bins.resize(1 << maxwidth);
  94. double worst = 0;
  95. int worstStart = -1;
  96. int worstWidth = -1;
  97. for(int start = 0; start < hashbits; start++)
  98. {
  99. int width = maxwidth;
  100. int bincount = (1 << width);
  101. memset(&bins[0],0,sizeof(int)*bincount);
  102. for(size_t j = 0; j < hashes.size(); j++)
  103. {
  104. hashtype & hash = hashes[j];
  105. uint32_t index = window(&hash,sizeof(hash),start,width);
  106. bins[index]++;
  107. }
  108. // Test the distribution, then fold the bins in half,
  109. // repeat until we're down to 256 bins
  110. if(drawDiagram) printf("[");
  111. while(bincount >= 256)
  112. {
  113. double n = calcScore(&bins[0],bincount,(int)hashes.size());
  114. if(drawDiagram) plot(n);
  115. if(n > worst)
  116. {
  117. worst = n;
  118. worstStart = start;
  119. worstWidth = width;
  120. }
  121. width--;
  122. bincount /= 2;
  123. if(width < 8) break;
  124. for(int i = 0; i < bincount; i++)
  125. {
  126. bins[i] += bins[i+bincount];
  127. }
  128. }
  129. if(drawDiagram) printf("]\n");
  130. }
  131. double pct = worst * 100.0;
  132. printf("Worst bias is the %3d-bit window at bit %3d - %5.3f%%",worstWidth,worstStart,pct);
  133. if(pct >= 1.0) printf(" !!!!! ");
  134. printf("\n");
  135. return worst;
  136. }
  137. //----------------------------------------------------------------------------
  138. template < typename hashtype >
  139. bool TestHashList ( std::vector<hashtype> & hashes, std::vector<hashtype> & collisions, bool testDist, bool drawDiagram )
  140. {
  141. bool result = true;
  142. {
  143. size_t count = hashes.size();
  144. double expected = (double(count) * double(count-1)) / pow(2.0,double(sizeof(hashtype) * 8 + 1));
  145. printf("Testing collisions - Expected %8.2f, ",expected);
  146. double collcount = 0;
  147. HashSet<hashtype> collisions;
  148. collcount = FindCollisions(hashes,collisions,1000);
  149. printf("actual %8.2f (%5.2fx)",collcount, collcount / expected);
  150. if(sizeof(hashtype) == sizeof(uint32_t))
  151. {
  152. // 2x expected collisions = fail
  153. // #TODO - collision failure cutoff needs to be expressed as a standard deviation instead
  154. // of a scale factor, otherwise we fail erroneously if there are a small expected number
  155. // of collisions
  156. if(double(collcount) / double(expected) > 2.0)
  157. {
  158. printf(" !!!!! ");
  159. result = false;
  160. }
  161. }
  162. else
  163. {
  164. // For all hashes larger than 32 bits, _any_ collisions are a failure.
  165. if(collcount > 0)
  166. {
  167. printf(" !!!!! ");
  168. result = false;
  169. }
  170. }
  171. printf("\n");
  172. }
  173. //----------
  174. if(testDist)
  175. {
  176. TestDistribution(hashes,drawDiagram);
  177. }
  178. return result;
  179. }
  180. //----------
  181. template < typename hashtype >
  182. bool TestHashList ( std::vector<hashtype> & hashes, bool /*testColl*/, bool testDist, bool drawDiagram )
  183. {
  184. std::vector<hashtype> collisions;
  185. return TestHashList(hashes,collisions,testDist,drawDiagram);
  186. }
  187. //-----------------------------------------------------------------------------
  188. template < class keytype, typename hashtype >
  189. bool TestKeyList ( hashfunc<hashtype> hash, std::vector<keytype> & keys, bool testColl, bool testDist, bool drawDiagram )
  190. {
  191. int keycount = (int)keys.size();
  192. std::vector<hashtype> hashes;
  193. hashes.resize(keycount);
  194. printf("Hashing");
  195. for(int i = 0; i < keycount; i++)
  196. {
  197. if(i % (keycount / 10) == 0) printf(".");
  198. keytype & k = keys[i];
  199. hash(&k,sizeof(k),0,&hashes[i]);
  200. }
  201. printf("\n");
  202. bool result = TestHashList(hashes,testColl,testDist,drawDiagram);
  203. printf("\n");
  204. return result;
  205. }
  206. //-----------------------------------------------------------------------------
  207. // Bytepair test - generate 16-bit indices from all possible non-overlapping
  208. // 8-bit sections of the hash value, check distribution on all of them.
  209. // This is a very good test for catching weak intercorrelations between bits -
  210. // much harder to pass than the normal distribution test. However, it doesn't
  211. // really model the normal usage of hash functions in hash table lookup, so
  212. // I'm not sure it's that useful (and hash functions that fail this test but
  213. // pass the normal distribution test still work well in practice)
  214. template < typename hashtype >
  215. double TestDistributionBytepairs ( std::vector<hashtype> & hashes, bool drawDiagram )
  216. {
  217. const int nbytes = sizeof(hashtype);
  218. const int hashbits = nbytes * 8;
  219. const int nbins = 65536;
  220. std::vector<int> bins(nbins,0);
  221. double worst = 0;
  222. for(int a = 0; a < hashbits; a++)
  223. {
  224. if(drawDiagram) if((a % 8 == 0) && (a > 0)) printf("\n");
  225. if(drawDiagram) printf("[");
  226. for(int b = 0; b < hashbits; b++)
  227. {
  228. if(drawDiagram) if((b % 8 == 0) && (b > 0)) printf(" ");
  229. bins.clear();
  230. bins.resize(nbins,0);
  231. for(size_t i = 0; i < hashes.size(); i++)
  232. {
  233. hashtype & hash = hashes[i];
  234. uint32_t pa = window(&hash,sizeof(hash),a,8);
  235. uint32_t pb = window(&hash,sizeof(hash),b,8);
  236. bins[pa | (pb << 8)]++;
  237. }
  238. double s = calcScore(bins,bins.size(),hashes.size());
  239. if(drawDiagram) plot(s);
  240. if(s > worst)
  241. {
  242. worst = s;
  243. }
  244. }
  245. if(drawDiagram) printf("]\n");
  246. }
  247. return worst;
  248. }
  249. //-----------------------------------------------------------------------------
  250. // Simplified test - only check 64k distributions, and only on byte boundaries
  251. template < typename hashtype >
  252. void TestDistributionFast ( std::vector<hashtype> & hashes, double & dworst, double & davg )
  253. {
  254. const int hashbits = sizeof(hashtype) * 8;
  255. const int nbins = 65536;
  256. std::vector<int> bins(nbins,0);
  257. dworst = -1.0e90;
  258. davg = 0;
  259. for(int start = 0; start < hashbits; start += 8)
  260. {
  261. bins.clear();
  262. bins.resize(nbins,0);
  263. for(size_t j = 0; j < hashes.size(); j++)
  264. {
  265. hashtype & hash = hashes[j];
  266. uint32_t index = window(&hash,sizeof(hash),start,16);
  267. bins[index]++;
  268. }
  269. double n = calcScore(&bins.front(),(int)bins.size(),(int)hashes.size());
  270. davg += n;
  271. if(n > dworst) dworst = n;
  272. }
  273. davg /= double(hashbits/8);
  274. }
  275. //-----------------------------------------------------------------------------