Skip to content

Commit

Permalink
added type conversion in array_dist to properly compute hamming distance
Browse files Browse the repository at this point in the history
  • Loading branch information
therealdarkknight committed Oct 3, 2023
1 parent 39b5b00 commit 7225b4c
Showing 1 changed file with 30 additions and 4 deletions.
34 changes: 30 additions & 4 deletions src/hnsw.c
Original file line number Diff line number Diff line change
Expand Up @@ -291,10 +291,36 @@ static float4 array_dist(ArrayType *a, ArrayType *b, usearch_metric_kind_t metri
elog(ERROR, "expected equally sized arrays but got arrays with dimensions %d and %d", a_dim, b_dim);
}

float4 *ax = (float4 *)ARR_DATA_PTR(a);
float4 *bx = (float4 *)ARR_DATA_PTR(b);
float4 *ax;
float4 *bx;

return usearch_dist(ax, bx, metric_kind, a_dim, usearch_scalar_f32_k);
bool convert_to_int = (metric_kind == usearch_metric_hamming_k);

if(convert_to_int) {
int32 *ax_int = (int32*) ARR_DATA_PTR(a);
int32 *bx_int = (int32*) ARR_DATA_PTR(b);

ax = (float4*) palloc(a_dim * sizeof(float4));
bx = (float4*) palloc(b_dim * sizeof(float4));

for (int i = 0; i < a_dim; i++) {
ax[i] = (float4) ax_int[i];
bx[i] = (float4) bx_int[i];
}
}
else {
ax = (float4*)ARR_DATA_PTR(a);
bx = (float4*)ARR_DATA_PTR(b);
}

float4 result = usearch_dist(ax, bx, metric_kind, a_dim, usearch_scalar_f32_k);

if(convert_to_int) {
pfree(ax);
pfree(bx);
}

return result;
}

static float8 vector_dist(Vector *a, Vector *b, usearch_metric_kind_t metric_kind)
Expand Down Expand Up @@ -330,7 +356,7 @@ Datum hamming_dist(PG_FUNCTION_ARGS)
{
ArrayType *a = PG_GETARG_ARRAYTYPE_P(0);
ArrayType *b = PG_GETARG_ARRAYTYPE_P(1);
PG_RETURN_INT32(array_dist(a, b, usearch_metric_hamming_k));
PG_RETURN_INT32((int32)array_dist(a, b, usearch_metric_hamming_k));
}

PGDLLEXPORT PG_FUNCTION_INFO_V1(vector_l2sq_dist);
Expand Down

0 comments on commit 7225b4c

Please sign in to comment.