2 * Copyright (c) 2008, the JUNG Project and the Regents of the University
6 * This software is open-source under the BSD license; see either
8 * http://jung.sourceforge.net/license.txt for a description.
9 * Created on Jun 7, 2008
12 package edu.uci.ics.jung.algorithms.metrics;
14 import java.util.ArrayList;
15 import java.util.HashMap;
18 import edu.uci.ics.jung.graph.Graph;
21 * A class consisting of static methods for calculating graph metrics.
26 * Returns a <code>Map</code> of vertices to their clustering coefficients.
27 * The clustering coefficient cc(v) of a vertex v is defined as follows:
29 * <li/><code>degree(v) == {0,1}</code>: 0
30 * <li/><code>degree(v) == n, n >= 2</code>: given S, the set of neighbors
31 * of <code>v</code>: cc(v) = (the sum over all w in S of the number of
32 * other elements of w that are neighbors of w) / ((|S| * (|S| - 1) / 2).
33 * Less formally, the fraction of <code>v</code>'s neighbors that are also
34 * neighbors of each other.
35 * <p><b>Note</b>: This algorithm treats its argument as an undirected graph;
36 * edge direction is ignored.
37 * @param graph the graph whose clustering coefficients are to be calculated
38 * @see "The structure and function of complex networks, M.E.J. Newman, aps.arxiv.org/abs/cond-mat/0303516"
40 public static <V,E> Map<V, Double> clusteringCoefficients(Graph<V,E> graph)
42 Map<V,Double> coefficients = new HashMap<V,Double>();
44 for (V v : graph.getVertices())
46 int n = graph.getNeighborCount(v);
48 coefficients.put(v, new Double(0));
51 // how many of v's neighbors are connected to each other?
52 ArrayList<V> neighbors = new ArrayList<V>(graph.getNeighbors(v));
53 double edge_count = 0;
54 for (int i = 0; i < n; i++)
56 V w = neighbors.get(i);
57 for (int j = i+1; j < n; j++ )
59 V x = neighbors.get(j);
60 edge_count += graph.isNeighbor(w, x) ? 1 : 0;
63 double possible_edges = (n * (n - 1))/2.0;
64 coefficients.put(v, new Double(edge_count / possible_edges));