File: Graphs.java

package info (click to toggle)
libgrinvin-core-java 1.2-1
  • links: PTS, VCS
  • area: contrib
  • in suites: squeeze
  • size: 3,904 kB
  • ctags: 5,009
  • sloc: java: 23,494; xml: 423; makefile: 15
file content (217 lines) | stat: -rw-r--r-- 7,776 bytes parent folder | download
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
/* Graphs.java
 * =========================================================================
 * This file is part of the GrInvIn project - http://www.grinvin.org
 * 
 * Copyright (C) 2005-2008 Universiteit Gent
 * 
 * This program is free software; you can redistribute it and/or modify
 * it under the terms of the GNU General Public License as published by
 * the Free Software Foundation; either version 2 of the License, or (at
 * your option) any later version.
 * 
 * This program is distributed in the hope that it will be useful, but
 * WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
 * General Public License for more details.
 * 
 * A copy of the GNU General Public License can be found in the file
 * LICENSE.txt provided with the source distribution of this program (see
 * the META-INF directory in the source jar). This license can also be
 * found on the GNU website at http://www.gnu.org/licenses/gpl.html.
 * 
 * If you did not receive a copy of the GNU General Public License along
 * with this program, contact the lead developer, or write to the Free
 * Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA
 * 02110-1301, USA.
 */

package org.grinvin.graphs;

import java.util.logging.Logger;

import org.grinvin.util.Tridiagonal;

/**
 * Provides some basic helper methods for graphs.<p>
 * Note that adjacency matrix, adjacency list and distance matrix can
 * also be obtained from the graph bundle directory, which may cache
 * their values.
 */
public final class Graphs {
    
    // do not instantiate this class
    private Graphs() {
    }
    
    
    /**
     * Returns a boolean adjacency matrix for the given graph. Row and column
     * indices correspond to vertex indices. Entries are {@code true}
     * when the corresponding vertices are adjacent (and different) and {@code false}
     * otherwise.
     * Note that the contents of this matrix are valid only for as long as the graph
     * given as a parameter remains unaltered.
     */
    public static boolean[][] booleanAdjacencyMatrix(GraphView graph) {
        int n = graph.getNumberOfVertices();
        boolean [][] adj = new boolean [n][n];
        for (Edge edge: graph.edges()) {
            int from = edge.getFirstEndpoint().getIndex();
            int to = edge.getSecondEndpoint().getIndex();
            adj[from][to] = true;
            adj[to][from] = true;
        }
        return adj;
    }
    
    /**
     * Returns the adjacency list representation for the given graph. The resulting array
     * contains an array of neighbour indices for every vertex. The length of each array is exactly
     * the valency of the corresponding vertex.
     */
    public static int[][] adjacencyList(GraphView graph) {
        // TODO: can this be done in a more memory efficient way?
        int n = graph.getNumberOfVertices();
        int[][] list = new int[n][n];
        int[] valency = new int[n];
        
        // compute
        for (Edge edge:  graph.edges()) {
            int from = edge.getFirstEndpoint().getIndex();
            int to = edge.getSecondEndpoint().getIndex();
            list[to][valency[to]++] = from;
            if (from != to)
                list[from][valency[from]++] = to;
        }
        // normalize
        for (int i = 0; i < n; i++) {
            int v = valency[i];
            int[] dest = new int[v];
            System.arraycopy(list[i], 0, dest, 0, v);
            list[i] =dest;
        }
        return list;
    }
    
    /**
     * Returns the distance matrix for the given graph. Row and column
     * indices correspond to vertex indices. Entries contains the distance
     * between corresponding vertices or 0 when vertices are equal or
     * belong to different components of the graph.
     */
    public static int[][] distanceMatrix(GraphView graph) {
        int n = graph.getNumberOfVertices();
        int[][] dist = new int[n][n];
        
        // compute the adjacency matrix
        for (Edge edge: graph.edges()) {
            int from = edge.getFirstEndpoint().getIndex();
            int to = edge.getSecondEndpoint().getIndex();
            dist[from][to] = 1;
            dist[to][from] = 1;
        }
        
        int d = 1;
        int count;
        do {
            int d1 = d++;
            count = 0;
            for (int i = 0; i < n; i++)
                for (int j = i + 1; j < n; j++)
                    if (dist[i][j] == 0)
                        for (int k = 0; k < n; k++)
                            if (dist[i][k] == 1 && dist[j][k] == d1) {
                dist[i][j] = d;
                dist[j][i] = d;
                count++;
                break;
                            }
        } while (count > 0);
        return dist;
    }
    
    /**
     * Returns the list of eigenvalues of the given graph. These are the eigenvalues
     * of the adjacency matrix of the graph. The resulting array contains the
     * eigenvalues in descending order.
     * If an error occurs during the calculation an array with length 0 is returned.
     */
    public static double[] eigenValues(GraphView graph) {
        int n = graph.getNumberOfVertices();
        if(n==0)
            return new double[0];
        double [][] adjMatrix = new double [n][n];
        for (Edge edge: graph.edges()) {
            int from = edge.getFirstEndpoint().getIndex();
            int to = edge.getSecondEndpoint().getIndex();
            adjMatrix[from][to]++;
            adjMatrix[to][from]++;
        }
        
        //compute
        Tridiagonal matrix = new Tridiagonal(adjMatrix);
        double[] eigenValues;
        try {
            eigenValues = matrix.eigenvalues();
        } catch(RuntimeException ex){
            Logger.getLogger("org.grinvin").warning("Error while computing the eigenvalues");
            eigenValues = new double[0];
        }
        
        // round
        // TODO: is this necessary?
        int precision = 10;
        for(int i=0; i < eigenValues.length; i++){
            for(int j=0; j < precision; j++)
                eigenValues[i] *= 10;
            eigenValues[i] = Math.round(eigenValues[i]);
            for(int j=0; j < precision; j++)
                eigenValues[i] /= 10;
        }
        
        //sort
        for(int i=0; i < eigenValues.length; i++)
            for(int j=eigenValues.length-1; j>i; j--)
                if(eigenValues[j] > eigenValues[j-1]){
            double tmp = eigenValues[j];
            eigenValues[j] = eigenValues[j-1];
            eigenValues[j-1] = tmp;
                }
        
        return eigenValues;
    }
    
    //
    private static final int[] DUMMY = new int[0];
    
    //
    private static final int[] DUMMY0 = new int[] {0};
    
    /**
     * Returns the list with eccentricities for the given graph. The resulting array
     * contains an integer for every vertex. If the graph is disconnected the array will
     * contain Integer.MAX_VALUE for every vertex.
     */
    public static int[] eccentricityList(GraphView graph) {
        int[][] distanceMatrix = distanceMatrix(graph);
        int n = graph.getNumberOfVertices();
        if (n == 0)
            return DUMMY;
        else if (n==1)
            return DUMMY0;
        
        int[] ecc = new int[n];
        for (int i=0; i < n; i++) {
            int eccentricity = 0;
            for (int j=0; j < n; j++) {
                int d = distanceMatrix[i][j];
                if (d == 0 && i!=j)
                    eccentricity=Integer.MAX_VALUE;
                if ( d > eccentricity)
                    eccentricity = d;
            }
            ecc[i]=eccentricity;
        }
        return ecc;
    }
}