View Javadoc
1   /**
2    * Copyright (c) 2008, The JUNG Authors 
3    *
4    * All rights reserved.
5    *
6    * This software is open-source under the BSD license; see either
7    * "license.txt" or
8    * https://github.com/jrtom/jung/blob/master/LICENSE for a description.
9    * Created on Jun 7, 2008
10   * 
11   */
12  package edu.uci.ics.jung.algorithms.metrics;
13  
14  import java.util.ArrayList;
15  import java.util.HashMap;
16  import java.util.Map;
17  
18  import edu.uci.ics.jung.graph.Graph;
19  
20  /**
21   * A class consisting of static methods for calculating graph metrics.
22   */
23  public class Metrics 
24  {
25      /**
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:
28       * <ul>
29       * <li><code>degree(v) == {0,1}</code>: 0
30       * <li><code>degree(v) == n, n &gt;= 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       * </ul>
36       * <p><b>Note</b>: This algorithm treats its argument as an undirected graph;
37       * edge direction is ignored. 
38       * @param graph the graph whose clustering coefficients are to be calculated
39       * @param <V> the vertex type
40       * @param <E> the edge type
41       * @return the clustering coefficient for each vertex
42       * @see "The structure and function of complex networks, M.E.J. Newman, aps.arxiv.org/abs/cond-mat/0303516"
43       */
44      public static <V,E> Map<V, Double> clusteringCoefficients(Graph<V,E> graph)
45      {
46          Map<V,Double> coefficients = new HashMap<V,Double>();
47          
48          for (V v : graph.getVertices())
49          {
50              int n = graph.getNeighborCount(v);
51              if (n < 2)
52                  coefficients.put(v, new Double(0));
53              else
54              {
55                  // how many of v's neighbors are connected to each other?
56                  ArrayList<V> neighbors = new ArrayList<V>(graph.getNeighbors(v));
57                  double edge_count = 0;
58                  for (int i = 0; i < n; i++)
59                  {
60                      V w = neighbors.get(i);
61                      for (int j = i+1; j < n; j++ )
62                      {
63                          V x = neighbors.get(j);
64                          edge_count += graph.isNeighbor(w, x) ? 1 : 0;
65                      }
66                  }
67                  double possible_edges = (n * (n - 1))/2.0;
68                  coefficients.put(v, new Double(edge_count / possible_edges));
69              }
70          }
71          
72          return coefficients;
73      }
74  }