DBSCANClusterer.java

  1. /*
  2.  * Licensed to the Apache Software Foundation (ASF) under one or more
  3.  * contributor license agreements.  See the NOTICE file distributed with
  4.  * this work for additional information regarding copyright ownership.
  5.  * The ASF licenses this file to You under the Apache License, Version 2.0
  6.  * (the "License"); you may not use this file except in compliance with
  7.  * the License.  You may obtain a copy of the License at
  8.  *
  9.  *      http://www.apache.org/licenses/LICENSE-2.0
  10.  *
  11.  * Unless required by applicable law or agreed to in writing, software
  12.  * distributed under the License is distributed on an "AS IS" BASIS,
  13.  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  14.  * See the License for the specific language governing permissions and
  15.  * limitations under the License.
  16.  */
  17. package org.apache.commons.math3.ml.clustering;

  18. import java.util.ArrayList;
  19. import java.util.Collection;
  20. import java.util.HashMap;
  21. import java.util.HashSet;
  22. import java.util.List;
  23. import java.util.Map;
  24. import java.util.Set;

  25. import org.apache.commons.math3.exception.NotPositiveException;
  26. import org.apache.commons.math3.exception.NullArgumentException;
  27. import org.apache.commons.math3.ml.distance.DistanceMeasure;
  28. import org.apache.commons.math3.ml.distance.EuclideanDistance;
  29. import org.apache.commons.math3.util.MathUtils;

  30. /**
  31.  * DBSCAN (density-based spatial clustering of applications with noise) algorithm.
  32.  * <p>
  33.  * The DBSCAN algorithm forms clusters based on the idea of density connectivity, i.e.
  34.  * a point p is density connected to another point q, if there exists a chain of
  35.  * points p<sub>i</sub>, with i = 1 .. n and p<sub>1</sub> = p and p<sub>n</sub> = q,
  36.  * such that each pair &lt;p<sub>i</sub>, p<sub>i+1</sub>&gt; is directly density-reachable.
  37.  * A point q is directly density-reachable from point p if it is in the &epsilon;-neighborhood
  38.  * of this point.
  39.  * <p>
  40.  * Any point that is not density-reachable from a formed cluster is treated as noise, and
  41.  * will thus not be present in the result.
  42.  * <p>
  43.  * The algorithm requires two parameters:
  44.  * <ul>
  45.  *   <li>eps: the distance that defines the &epsilon;-neighborhood of a point
  46.  *   <li>minPoints: the minimum number of density-connected points required to form a cluster
  47.  * </ul>
  48.  *
  49.  * @param <T> type of the points to cluster
  50.  * @see <a href="http://en.wikipedia.org/wiki/DBSCAN">DBSCAN (wikipedia)</a>
  51.  * @see <a href="http://www.dbs.ifi.lmu.de/Publikationen/Papers/KDD-96.final.frame.pdf">
  52.  * A Density-Based Algorithm for Discovering Clusters in Large Spatial Databases with Noise</a>
  53.  * @since 3.2
  54.  */
  55. public class DBSCANClusterer<T extends Clusterable> extends Clusterer<T> {

  56.     /** Maximum radius of the neighborhood to be considered. */
  57.     private final double              eps;

  58.     /** Minimum number of points needed for a cluster. */
  59.     private final int                 minPts;

  60.     /** Status of a point during the clustering process. */
  61.     private enum PointStatus {
  62.         /** The point has is considered to be noise. */
  63.         NOISE,
  64.         /** The point is already part of a cluster. */
  65.         PART_OF_CLUSTER
  66.     }

  67.     /**
  68.      * Creates a new instance of a DBSCANClusterer.
  69.      * <p>
  70.      * The euclidean distance will be used as default distance measure.
  71.      *
  72.      * @param eps maximum radius of the neighborhood to be considered
  73.      * @param minPts minimum number of points needed for a cluster
  74.      * @throws NotPositiveException if {@code eps < 0.0} or {@code minPts < 0}
  75.      */
  76.     public DBSCANClusterer(final double eps, final int minPts)
  77.         throws NotPositiveException {
  78.         this(eps, minPts, new EuclideanDistance());
  79.     }

  80.     /**
  81.      * Creates a new instance of a DBSCANClusterer.
  82.      *
  83.      * @param eps maximum radius of the neighborhood to be considered
  84.      * @param minPts minimum number of points needed for a cluster
  85.      * @param measure the distance measure to use
  86.      * @throws NotPositiveException if {@code eps < 0.0} or {@code minPts < 0}
  87.      */
  88.     public DBSCANClusterer(final double eps, final int minPts, final DistanceMeasure measure)
  89.         throws NotPositiveException {
  90.         super(measure);

  91.         if (eps < 0.0d) {
  92.             throw new NotPositiveException(eps);
  93.         }
  94.         if (minPts < 0) {
  95.             throw new NotPositiveException(minPts);
  96.         }
  97.         this.eps = eps;
  98.         this.minPts = minPts;
  99.     }

  100.     /**
  101.      * Returns the maximum radius of the neighborhood to be considered.
  102.      * @return maximum radius of the neighborhood
  103.      */
  104.     public double getEps() {
  105.         return eps;
  106.     }

  107.     /**
  108.      * Returns the minimum number of points needed for a cluster.
  109.      * @return minimum number of points needed for a cluster
  110.      */
  111.     public int getMinPts() {
  112.         return minPts;
  113.     }

  114.     /**
  115.      * Performs DBSCAN cluster analysis.
  116.      *
  117.      * @param points the points to cluster
  118.      * @return the list of clusters
  119.      * @throws NullArgumentException if the data points are null
  120.      */
  121.     @Override
  122.     public List<Cluster<T>> cluster(final Collection<T> points) throws NullArgumentException {

  123.         // sanity checks
  124.         MathUtils.checkNotNull(points);

  125.         final List<Cluster<T>> clusters = new ArrayList<Cluster<T>>();
  126.         final Map<Clusterable, PointStatus> visited = new HashMap<Clusterable, PointStatus>();

  127.         for (final T point : points) {
  128.             if (visited.get(point) != null) {
  129.                 continue;
  130.             }
  131.             final List<T> neighbors = getNeighbors(point, points);
  132.             if (neighbors.size() >= minPts) {
  133.                 // DBSCAN does not care about center points
  134.                 final Cluster<T> cluster = new Cluster<T>();
  135.                 clusters.add(expandCluster(cluster, point, neighbors, points, visited));
  136.             } else {
  137.                 visited.put(point, PointStatus.NOISE);
  138.             }
  139.         }

  140.         return clusters;
  141.     }

  142.     /**
  143.      * Expands the cluster to include density-reachable items.
  144.      *
  145.      * @param cluster Cluster to expand
  146.      * @param point Point to add to cluster
  147.      * @param neighbors List of neighbors
  148.      * @param points the data set
  149.      * @param visited the set of already visited points
  150.      * @return the expanded cluster
  151.      */
  152.     private Cluster<T> expandCluster(final Cluster<T> cluster,
  153.                                      final T point,
  154.                                      final List<T> neighbors,
  155.                                      final Collection<T> points,
  156.                                      final Map<Clusterable, PointStatus> visited) {
  157.         cluster.addPoint(point);
  158.         visited.put(point, PointStatus.PART_OF_CLUSTER);

  159.         List<T> seeds = new ArrayList<T>(neighbors);
  160.         int index = 0;
  161.         while (index < seeds.size()) {
  162.             final T current = seeds.get(index);
  163.             PointStatus pStatus = visited.get(current);
  164.             // only check non-visited points
  165.             if (pStatus == null) {
  166.                 final List<T> currentNeighbors = getNeighbors(current, points);
  167.                 if (currentNeighbors.size() >= minPts) {
  168.                     seeds = merge(seeds, currentNeighbors);
  169.                 }
  170.             }

  171.             if (pStatus != PointStatus.PART_OF_CLUSTER) {
  172.                 visited.put(current, PointStatus.PART_OF_CLUSTER);
  173.                 cluster.addPoint(current);
  174.             }

  175.             index++;
  176.         }
  177.         return cluster;
  178.     }

  179.     /**
  180.      * Returns a list of density-reachable neighbors of a {@code point}.
  181.      *
  182.      * @param point the point to look for
  183.      * @param points possible neighbors
  184.      * @return the List of neighbors
  185.      */
  186.     private List<T> getNeighbors(final T point, final Collection<T> points) {
  187.         final List<T> neighbors = new ArrayList<T>();
  188.         for (final T neighbor : points) {
  189.             if (point != neighbor && distance(neighbor, point) <= eps) {
  190.                 neighbors.add(neighbor);
  191.             }
  192.         }
  193.         return neighbors;
  194.     }

  195.     /**
  196.      * Merges two lists together.
  197.      *
  198.      * @param one first list
  199.      * @param two second list
  200.      * @return merged lists
  201.      */
  202.     private List<T> merge(final List<T> one, final List<T> two) {
  203.         final Set<T> oneSet = new HashSet<T>(one);
  204.         for (T item : two) {
  205.             if (!oneSet.contains(item)) {
  206.                 one.add(item);
  207.             }
  208.         }
  209.         return one;
  210.     }
  211. }