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.math4.legacy.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 java.util.stream.Collectors;

  26. import org.apache.commons.math4.legacy.exception.NullArgumentException;
  27. import org.apache.commons.math4.legacy.exception.NotPositiveException;
  28. import org.apache.commons.math4.legacy.ml.distance.DistanceMeasure;
  29. import org.apache.commons.math4.legacy.ml.distance.EuclideanDistance;

  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.         this(eps, minPts, new EuclideanDistance());
  78.     }

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

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

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

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

  112.     /**
  113.      * Performs DBSCAN cluster analysis.
  114.      *
  115.      * @param points Points to cluster (cannot be {@code null}).
  116.      * @return the list of clusters.
  117.      */
  118.     @Override
  119.     public List<Cluster<T>> cluster(final Collection<T> points) {
  120.         // sanity checks
  121.         NullArgumentException.check(points);

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

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

  137.         return clusters;
  138.     }

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

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

  168.             if (pStatus != PointStatus.PART_OF_CLUSTER) {
  169.                 visited.put(current, PointStatus.PART_OF_CLUSTER);
  170.                 cluster.addPoint(current);
  171.             }

  172.             index++;
  173.         }
  174.         return cluster;
  175.     }

  176.     /**
  177.      * Returns a list of density-reachable neighbors of a {@code point}.
  178.      *
  179.      * @param point the point to look for
  180.      * @param points possible neighbors
  181.      * @return the List of neighbors
  182.      */
  183.     private List<T> getNeighbors(final T point, final Collection<T> points) {
  184.         return points.stream().filter(neighbor -> point != neighbor && distance(neighbor, point) <= eps)
  185.                               .collect(Collectors.toList());
  186.     }

  187.     /**
  188.      * Merges two lists together.
  189.      *
  190.      * @param one first list
  191.      * @param two second list
  192.      * @return merged lists
  193.      */
  194.     private List<T> merge(final List<T> one, final List<T> two) {
  195.         final Set<T> oneSet = new HashSet<>(one);
  196.         two.stream().filter(item -> !oneSet.contains(item)).forEach(one::add);
  197.         return one;
  198.     }
  199. }