Heuristic.c 2.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106
  1. #include "MaxHeap.h"
  2. #include "utils.h"
  3. #define Point(i) (&(data[i * nFeatures]))
  4. pyWord findFarestPointTo(SearchParams params, pyReal * point) {
  5. pyReal d, bestDist = 0.0;
  6. pyWord i, bestIdx = 0 - 1;
  7. for(i = 0 ; i < params->nPoints ; i ++ ) {
  8. d = distSquared(point, Point(i));
  9. if (d > bestDist) {
  10. bestDist = d;
  11. bestIdx = i;
  12. }
  13. }
  14. return bestIdx;
  15. }
  16. void NeighborhoodHeuristic(const pyWord nbhSize, const pyWord nPoints, const pyWord nFeatures, const pyReal * data, pyWord * neighborhoods) {
  17. SearchParams params = {
  18. .nbhSize = nbhSize,
  19. .nPoints = nPoints,
  20. .nFeatures = nFeatures,
  21. .data = data,
  22. .neighborhoods = neighborhoods
  23. };
  24. int success = 0;
  25. pyWord i, j;
  26. pyReal d;
  27. pyReal lineVector = NULL;
  28. pyReal accu = NULL;
  29. if(initNbhHeaps(&params)) {
  30. return;
  31. }
  32. do {
  33. const pyWord lineStartIdx = findFarestPointTo(params, Point(0));
  34. if(lineStartIdx >= params->nPoints) {
  35. break;
  36. }
  37. pyReal * lineStartPoint = Point(lineStartIdx);
  38. const pyWord lineEndIdx = findFarestPointTo(params, lineStartPoint);
  39. pyReal * lineEndPoint = Point(lineEndIdx);
  40. pyReal lineVector * = malloc(params->nFeatures * sizeof(pyReal));
  41. if(!lineVector) {
  42. break;
  43. }
  44. lineVector = vecSub(nFeatures, lineEndPoint, lineStartPoint);
  45. d = vecNorm(lineVector);
  46. if(d == 0.0) {
  47. break;
  48. }
  49. vecScale(nFeatures, lineVector, 1.0 / d, lineVector);
  50. pyReal accu * = malloc(params->nFeatures * sizeof(pyReal));
  51. if(!accu) {
  52. break;
  53. }
  54. // Berechne alle Distanzen
  55. for(i = 0; i < nPoints; i ++) {
  56. const pyReal *x = Point(i);
  57. vecSub(nFeatures, accu, x, lineStartPoint);
  58. d = vecScalarProduct(nFeatures, lineVector, accu);
  59. vecScale(nFeatures, accu, d, lineVector);
  60. vecAdd(nFeatures, accu, accu, lineStartPoint);
  61. const pyReal di1 = sqrt(distSquared(accu, lineStartPoint, nFeatures));
  62. const pyReal di2 = sqrt(distSquared(accu, x, nFeatures));
  63. for(j = i + 1; j < nPoints; j ++) {
  64. const pyReal * y = Point(j);
  65. d = distSquared(x, y, nFeatures);
  66. maxHeap_insert(&(params.nbhHeaps.heaps[i]), j, d);
  67. maxHeap_insert(&(params.nbhHeaps.heaps[j]), i, d);
  68. }
  69. }
  70. } while(0);
  71. if(lineVector) {
  72. free(lineVector);
  73. }
  74. if(!success) {
  75. nbhSearchBruteForce(&params);
  76. }
  77. freeNbhHeaps(&params);
  78. }