PostGIS  2.5.0rc1dev-r@@SVN_REVISION@@

◆ kmeans()

static int kmeans ( POINT2D **  objs,
int *  clusters,
uint32_t  n,
POINT2D **  centers,
uint32_t  k 
)
static

Definition at line 94 of file lwkmeans.c.

References KMEANS_MAX_ITERATIONS, LW_FALSE, LW_ON_INTERRUPT, lwalloc(), lwerror(), lwfree(), update_means(), and update_r().

Referenced by lwgeom_cluster_2d_kmeans().

95 {
96  uint32_t i = 0;
97  int* clusters_last;
98  int converged = LW_FALSE;
99  size_t clusters_sz = sizeof(int) * n;
100  uint32_t* weights;
101 
102  weights = lwalloc(sizeof(int) * k);
103 
104  /* previous cluster state array */
105  clusters_last = lwalloc(clusters_sz);
106 
107  for (i = 0; i < KMEANS_MAX_ITERATIONS && !converged; i++)
108  {
109  LW_ON_INTERRUPT(break);
110 
111  /* store the previous state of the clustering */
112  memcpy(clusters_last, clusters, clusters_sz);
113 
114  update_r(objs, clusters, n, centers, k);
115  update_means(objs, clusters, n, centers, weights, k);
116 
117  /* if all the cluster numbers are unchanged, we are at a stable solution */
118  converged = memcmp(clusters_last, clusters, clusters_sz) == 0;
119  }
120 
121  lwfree(clusters_last);
122  lwfree(weights);
123  if (!converged)
124  lwerror("%s did not converge after %d iterations", __func__, i);
125  return converged;
126 }
void lwfree(void *mem)
Definition: lwutil.c:244
#define LW_ON_INTERRUPT(x)
static void update_means(POINT2D **objs, int *clusters, uint32_t n, POINT2D **centers, uint32_t *weights, uint32_t k)
Definition: lwkmeans.c:65
unsigned int uint32_t
Definition: uthash.h:78
#define LW_FALSE
Definition: liblwgeom.h:76
#define KMEANS_MAX_ITERATIONS
Definition: lwkmeans.c:23
static void update_r(POINT2D **objs, int *clusters, uint32_t n, POINT2D **centers, uint32_t k)
Definition: lwkmeans.c:26
void * lwalloc(size_t size)
Definition: lwutil.c:229
void lwerror(const char *fmt,...)
Write a notice out to the error handler.
Definition: lwutil.c:190
Here is the call graph for this function:
Here is the caller graph for this function: