Skip to content

Commit 1e59551

Browse files
author
Gilles Sadowski
committed
MATH-1683: Make precondition explicit.
1 parent 3a54177 commit 1e59551

3 files changed

Lines changed: 20 additions & 1 deletion

File tree

commons-math-legacy/src/main/java/org/apache/commons/math4/legacy/ml/clustering/ElkanKMeansPlusPlusClusterer.java

Lines changed: 4 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -234,6 +234,10 @@ private double[][] seed(final List<T> points) {
234234
sumSqDist += minDistances[i];
235235
}
236236

237+
if (sumSqDist == 0d) { // MATH-1683.
238+
throw new IllegalArgumentException("All points are identical");
239+
}
240+
237241
while (++idx < k) {
238242
final double p = sumSqDist * random.nextDouble();
239243
int next = 0;
@@ -253,7 +257,6 @@ private double[][] seed(final List<T> points) {
253257
return result;
254258
}
255259

256-
257260
/**
258261
* Once initial centers are chosen, we can actually go through data points and assign points to the
259262
* cluster based on the distance between initial centers and points.

commons-math-legacy/src/test/java/org/apache/commons/math4/legacy/ml/clustering/ElkanKMeansPlusPlusClustererTest.java

Lines changed: 13 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -112,6 +112,19 @@ public void oneClusterCenterShouldBeTheMean() {
112112
Assert.assertArrayEquals(mean.getResult(), clusters.get(0).getCenter().getPoint(), 1e-6);
113113
}
114114

115+
@Test(expected = IllegalArgumentException.class)
116+
public void testAllPointsIdentical() {
117+
final DoublePoint p = new DoublePoint(new double[] {0.0, 0.0});
118+
// Create 4 identical points.
119+
final List<DoublePoint> points = Arrays.asList(p, p, p, p);
120+
121+
// Attempt to cluster into 2 clusters.
122+
ElkanKMeansPlusPlusClusterer<DoublePoint> clusterer =
123+
new ElkanKMeansPlusPlusClusterer<>(2);
124+
125+
clusterer.cluster(points);
126+
}
127+
115128
/**
116129
* Generates a list of random uncorrelated points to cluster.
117130
*

src/changes/changes.xml

Lines changed: 3 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -96,6 +96,9 @@ Caveat:
9696
to support the whole codebase (it was one of the main reasons for
9797
creating more focused components).
9898
">
99+
<action dev="erans" type="fix" issue="MATH-1683" due-to="Ruiqi Dong">
100+
"ElkanKMeansPlusPlusClusterer": More explicit error message.
101+
</action>
99102
<action dev="erans" type="fix" issue="MATH-1682" due-to="Ruiqi Dong">
100103
"SparseEntryIterator": Prevent exception upon iterating an empty vector.
101104
</action>

0 commit comments

Comments
 (0)