DoubleVector[] msgCenters = new DoubleVector[centers.length];
int[] incrementSum = new int[centers.length];
CenterMessage msg;
// basically just summing incoming vectors
while ((msg = peer.getCurrentMessage()) != null) {
DoubleVector oldCenter = msgCenters[msg.getCenterIndex()];
DoubleVector newCenter = msg.getData();
incrementSum[msg.getCenterIndex()] += msg.getIncrementCounter();
if (oldCenter == null) {
msgCenters[msg.getCenterIndex()] = newCenter;
} else {
msgCenters[msg.getCenterIndex()] = oldCenter.addUnsafe(newCenter);
}
}
// divide by how often we globally summed vectors
for (int i = 0; i < msgCenters.length; i++) {
// and only if we really have an update for c
if (msgCenters[i] != null) {
msgCenters[i] = msgCenters[i].divide(incrementSum[i]);
}
}
// finally check for convergence by the absolute difference
long convergedCounter = 0L;
for (int i = 0; i < msgCenters.length; i++) {
final DoubleVector oldCenter = centers[i];
if (msgCenters[i] != null) {
double calculateError = oldCenter.subtractUnsafe(msgCenters[i]).abs()
.sum();
if (calculateError > 0.0d) {
centers[i] = msgCenters[i];
convergedCounter++;
}