001/* 002 * Licensed to the Apache Software Foundation (ASF) under one or more 003 * contributor license agreements. See the NOTICE file distributed with 004 * this work for additional information regarding copyright ownership. 005 * The ASF licenses this file to You under the Apache License, Version 2.0 006 * (the "License"); you may not use this file except in compliance with 007 * the License. You may obtain a copy of the License at 008 * 009 * http://www.apache.org/licenses/LICENSE-2.0 010 * 011 * Unless required by applicable law or agreed to in writing, software 012 * distributed under the License is distributed on an "AS IS" BASIS, 013 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 014 * See the License for the specific language governing permissions and 015 * limitations under the License. 016 */ 017 018package org.apache.commons.math4.legacy.ml.clustering; 019 020import java.util.ArrayList; 021import java.util.List; 022 023/** 024 * Cluster holding a set of {@link Clusterable} points. 025 * @param <T> the type of points that can be clustered 026 * @since 3.2 027 */ 028public class Cluster<T extends Clusterable> { 029 030 /** The points contained in this cluster. */ 031 private final List<T> points; 032 033 /** 034 * Build a cluster centered at a specified point. 035 */ 036 public Cluster() { 037 points = new ArrayList<>(); 038 } 039 040 /** 041 * Add a point to this cluster. 042 * @param point point to add 043 */ 044 public void addPoint(final T point) { 045 points.add(point); 046 } 047 048 /** 049 * Get the points contained in the cluster. 050 * @return points contained in the cluster 051 */ 052 public List<T> getPoints() { 053 return points; 054 } 055 056 /** 057 * Computes the centroid of the cluster. 058 * 059 * @return the centroid for the cluster, or {@code null} if the 060 * cluster does not contain any points. 061 */ 062 public Clusterable centroid() { 063 if (points.isEmpty()) { 064 return null; 065 } else { 066 final int dimension = points.get(0).getPoint().length; 067 final double[] centroid = new double[dimension]; 068 for (final T p : points) { 069 final double[] point = p.getPoint(); 070 for (int i = 0; i < centroid.length; i++) { 071 centroid[i] += point[i]; 072 } 073 } 074 for (int i = 0; i < centroid.length; i++) { 075 centroid[i] /= points.size(); 076 } 077 return new DoublePoint(centroid); 078 } 079 } 080}