diff --git a/lib/Clustering/SquaredDistance.php b/lib/Clustering/SquaredDistance.php index ce1ed9591..e64eda7d2 100644 --- a/lib/Clustering/SquaredDistance.php +++ b/lib/Clustering/SquaredDistance.php @@ -45,7 +45,11 @@ public function compatibility(): array { public function compute(array $a, array $b): float { $distance = 0.0; - $count = count($a); + // Only walk the dimensions both vectors share: vectors of different + // lengths (e.g. a truncated embedding row) previously triggered + // "Undefined array key" warnings on every comparison while the cron + // clustering ran (#1611). + $count = min(count($a), count($b)); for ($i = 0; $i < $count; $i++) { $diff = (float)$a[$i] - (float)$b[$i]; $distance += $diff * $diff; diff --git a/tests/SquaredDistanceTest.php b/tests/SquaredDistanceTest.php new file mode 100644 index 000000000..9d6cd0adb --- /dev/null +++ b/tests/SquaredDistanceTest.php @@ -0,0 +1,49 @@ +kernel = new SquaredDistance(); + } + + public function testComputesSquaredEuclideanDistance(): void { + // sqrt-free euclidean: (1-4)^2 + (2-5)^2 = 18 + self::assertSame(18.0, $this->kernel->compute([1, 2], [4, 5])); + } + + public function testZeroDistanceToItself(): void { + self::assertSame(0.0, $this->kernel->compute([0.5, 1.5, -2.5], [0.5, 1.5, -2.5])); + } + + public function testRaggedSecondVectorReturnsNoWarning(): void { + // #1611: $b shorter than $a used to emit "Undefined array key" + // warnings. The distance now covers only the shared dimensions + // (here: (0-3)^2 = 9). + self::assertSame(9.0, $this->kernel->compute([0, 3, 7], [3])); + } + + public function testRaggedFirstVectorIsSymmetric(): void { + // whichever side is shorter, the result must be the same + self::assertSame( + $this->kernel->compute([0, 3, 7], [3]), + $this->kernel->compute([3], [0, 3, 7]) + ); + } + + public function testEmptyVectorsReturnZero(): void { + self::assertSame(0.0, $this->kernel->compute([], [])); + } +}