-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathMyJGraphTUtil.java
More file actions
376 lines (331 loc) · 14 KB
/
Copy pathMyJGraphTUtil.java
File metadata and controls
376 lines (331 loc) · 14 KB
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
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
// Teoria dos Grafos - UFCG
package examples;
import java.io.BufferedReader;
import java.io.FileReader;
import java.io.IOException;
import java.io.Reader;
import java.io.StringReader;
import java.util.ArrayList;
import java.util.Collection;
import java.util.Collections;
import java.util.Comparator;
import java.util.Enumeration;
import java.util.HashMap;
import java.util.HashSet;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.Map.Entry;
import java.util.stream.Collectors;
import javax.swing.JFrame;
import org.jgrapht.Graph;
import org.jgrapht.GraphTests;
import org.jgrapht.Graphs;
import org.jgrapht.ListenableGraph;
import org.jgrapht.alg.connectivity.BiconnectivityInspector;
import org.jgrapht.alg.shortestpath.DijkstraShortestPath;
import org.jgrapht.ext.JGraphXAdapter;
import org.jgrapht.graph.DefaultEdge;
import org.jgrapht.graph.DefaultListenableGraph;
import org.jgrapht.graph.DefaultWeightedEdge;
import org.jgrapht.io.CSVFormat;
import org.jgrapht.io.CSVImporter;
import org.jgrapht.io.EdgeProvider;
import org.jgrapht.io.GmlImporter;
import org.jgrapht.io.ImportException;
import org.jgrapht.io.VertexProvider;
import com.mxgraph.layout.mxCircleLayout;
import com.mxgraph.layout.mxEdgeLabelLayout;
import com.mxgraph.layout.mxFastOrganicLayout;
import com.mxgraph.layout.mxIGraphLayout;
import com.mxgraph.layout.mxOrganicLayout;
import com.mxgraph.layout.hierarchical.mxHierarchicalLayout;
import com.mxgraph.layout.orthogonal.mxOrthogonalLayout;
import com.mxgraph.model.mxGraphModel;
import com.mxgraph.swing.mxGraphComponent;
import com.mxgraph.util.mxConstants;
import com.mxgraph.util.mxStyleUtils;
public class MyJGraphTUtil <V,E> {
///////////////////////////////////
// GRAPH VIEW METHODS
///////////////////////////////////
public static <V,E> void printGraph (Graph <V,E> g ) {
System.out.println(g.vertexSet());
System.out.println(g.edgeSet()+"\n");
}
public static <V,E> void printGraph (Graph <V,E> g, String title ) {
System.out.println(title);
System.out.println(g.vertexSet());
System.out.println(g.edgeSet()+"\n");
}
public static <V,E> void printWeightedGraph (Graph <V,E> g, String title ) {
System.out.println(title);
System.out.println(g.vertexSet());
Iterator <E> it = g.edgeSet().iterator();
while (it.hasNext()) {
E e = it.next();
System.out.print(e + ":" + g.getEdgeWeight(e) + " ");
}
System.out.print("\n");
}
public enum layout_type {CIRCLE,ORGANIC,HIERARCHICAL,ORTHOGONAL;}
// Graphic view for directed graphs
public static <V,E> void createAndShowGui(Graph <V,E> graph, String frameLabel,
boolean directed,
boolean danglingEdges,
boolean labelsVisible,
boolean labelsClipped,
layout_type layoutType
) {
JFrame frame = new JFrame(frameLabel);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
ListenableGraph<V,E> g = new DefaultListenableGraph <> (graph);
JGraphXAdapter<V,E> graphAdapter = new JGraphXAdapter<V,E>(g);
graphAdapter.setAllowDanglingEdges(danglingEdges);
graphAdapter.setLabelsVisible(labelsVisible);
graphAdapter.setLabelsClipped(labelsClipped);
graphAdapter.setCellsMovable(true);
graphAdapter.setCellsSelectable(true);
graphAdapter.setEdgeLabelsMovable(true);
mxIGraphLayout layout;
switch (layoutType) {
case CIRCLE : layout = new mxCircleLayout(graphAdapter); break;
case ORGANIC: layout = new mxFastOrganicLayout(graphAdapter);break;
case HIERARCHICAL : layout = new mxHierarchicalLayout(graphAdapter);break;
case ORTHOGONAL: layout = new mxOrthogonalLayout(graphAdapter);break;
default: layout = new mxCircleLayout(graphAdapter);break;
}
layout.execute(graphAdapter.getDefaultParent());
mxGraphComponent graphComponent = new mxGraphComponent(graphAdapter);
mxGraphModel graphModel = (mxGraphModel)graphComponent.getGraph().getModel();
Collection<Object> cells = graphModel.getCells().values();
if (directed == false) {
mxStyleUtils.setCellStyles(graphComponent.getGraph().getModel(),
cells.toArray(), mxConstants.STYLE_ENDARROW, mxConstants.NONE);
}
frame.add(graphComponent);
frame.pack();
frame.setLocationByPlatform(true);
frame.setVisible(true);
}
static <V> void printOrderedVertexMeasures (Map <V,Double> M, int count, boolean descending) {
// count representa a quantidade de elementos que devem ser exibidos
// em ordem decrescente do score. Se count = 0, ent�o todos ser�o exibidos
Set<Entry<V, Double>> set = M.entrySet();
List<Entry<V, Double>> list = new ArrayList<Entry<V, Double>>(set);
if (descending) {
Collections.sort( list, new Comparator<Map.Entry<V, Double>>()
{
public int compare( Map.Entry<V, Double> o1, Map.Entry<V, Double> o2 ) {
return (o2.getValue()).compareTo( o1.getValue() );
}
} );
} else {
Collections.sort( list, new Comparator<Map.Entry<V, Double>>()
{
public int compare( Map.Entry<V, Double> o1, Map.Entry<V, Double> o2 ) {
return (o1.getValue()).compareTo( o2.getValue() );
}
} );
}
if (count == 0) {
count = list.size();
}
for (int i = 0; i<count; i++) {
Entry<V,Double> e = list.get(i);
System.out.print(e.getKey()+": "+ String.format("%.2f",(e.getValue()))+ "; ");
}
}
/////////////////////////////////////////
// VERTEX AND EGDES UTILITIES
/////////////////////////////////////////
/**
* Os métodos a seguir retornam um vértice ou aresta cujo label eh igual ao passado como parametro.
*
*/
public static DefaultVertex getVertexfromLabel(Set<DefaultVertex> V, String label) {
return V.stream().filter(v-> v.getLabel().equals(label)).findAny().get();
}
public static RelationshipEdge getEdgefromLabel(Set<RelationshipEdge> E, String label) {
return E.stream().filter(e-> e.getLabel().equals(label)).findAny().get();
}
public static RelationshipEdge getEdgefromVertexLabels(Set<RelationshipEdge> E, Set<DefaultVertex> V, String l1, String l2) {
DefaultVertex v1 = getVertexfromLabel(V,l1);
DefaultVertex v2 = getVertexfromLabel(V,l2);
return E.stream().filter(e-> (e.getV1().equals(v1) && e.getV2().equals(v2)) ||
(e.getV1().equals(v2) && e.getV2().equals(v1))).findAny().get();
}
////////////////////////////////////////
// CSV and GML IMPORTERS
////////////////////////////////////////
/**
* Os métodos a seguir realizam a importação de grafos no formato CSV e GML.
*
*/
public static Graph<String,DefaultEdge> importGraphCSV (Graph<String,DefaultEdge> graph, String filename, CSVFormat f) {
VertexProvider<String> vp = (label, attributes) -> label;
EdgeProvider<String, DefaultEdge> ep = (from, to, label, attributes) -> new DefaultEdge();
CSVImporter<String, DefaultEdge> csvImporter = new CSVImporter<>(vp, ep);
csvImporter.setFormat(f);
try {
csvImporter.importGraph(graph, readFile(filename));
} catch (ImportException e) {
throw new RuntimeException(e);
}
return graph;
}
public static Graph<String,DefaultEdge> importGraphCSV (
Graph<String,DefaultEdge> graph,
String filename,
CSVFormat f,
boolean pMATRIX_FORMAT_ZERO_WHEN_NO_EDGE,
boolean pEDGE_WEIGHT,
boolean pMATRIX_FORMAT_NODEID) {
VertexProvider<String> vp = (label, attributes) -> label;
EdgeProvider<String, DefaultEdge> ep = (from, to, label, attributes) -> new DefaultEdge();
CSVImporter<String, DefaultEdge> csvImporter = new CSVImporter<>(vp, ep);
csvImporter.setFormat(f);
csvImporter.setParameter(CSVFormat.Parameter.MATRIX_FORMAT_ZERO_WHEN_NO_EDGE,pMATRIX_FORMAT_ZERO_WHEN_NO_EDGE);
csvImporter.setParameter(CSVFormat.Parameter.EDGE_WEIGHTS, pEDGE_WEIGHT);
csvImporter.setParameter(CSVFormat.Parameter.MATRIX_FORMAT_NODEID, pMATRIX_FORMAT_NODEID);
try {
csvImporter.importGraph(graph, readFile(filename));
} catch (ImportException e) {
throw new RuntimeException(e);
}
return graph;
}
public static Graph<String,DefaultWeightedEdge> importWeightedGraphCSV (
Graph<String,DefaultWeightedEdge> graph,
String filename,
CSVFormat f,
boolean pMATRIX_FORMAT_ZERO_WHEN_NO_EDGE,
boolean pEDGE_WEIGHT,
boolean pMATRIX_FORMAT_NODEID) {
VertexProvider<String> vp = (label, attributes) -> label;
EdgeProvider<String, DefaultWeightedEdge> ep = (from, to, label, attributes) -> new DefaultWeightedEdge();
CSVImporter<String, DefaultWeightedEdge> csvImporter = new CSVImporter<>(vp, ep);
csvImporter.setFormat(f);
csvImporter.setParameter(CSVFormat.Parameter.MATRIX_FORMAT_ZERO_WHEN_NO_EDGE,pMATRIX_FORMAT_ZERO_WHEN_NO_EDGE);
csvImporter.setParameter(CSVFormat.Parameter.EDGE_WEIGHTS, pEDGE_WEIGHT);
csvImporter.setParameter(CSVFormat.Parameter.MATRIX_FORMAT_NODEID, pMATRIX_FORMAT_NODEID);
try {
csvImporter.importGraph(graph, readFile(filename));
} catch (ImportException e) {
throw new RuntimeException(e);
}
return graph;
}
public static Graph<String,DefaultEdge> importDefaultGraphGML (Graph<String,DefaultEdge> graph, String filename) {
VertexProvider<String> vp1 = (label, attributes) -> label;
EdgeProvider<String, DefaultEdge> ep1 = (from, to, label, attributes) -> new DefaultEdge();
GmlImporter<String, DefaultEdge> gmlImporter = new GmlImporter<>(vp1, ep1);
try {
gmlImporter.importGraph(graph, readFile(filename));
} catch (ImportException e) {
throw new RuntimeException(e);
}
return graph;
}
public static Graph<DefaultVertex,RelationshipEdge> importGraphGML (Graph<DefaultVertex,RelationshipEdge> graph, String filename) {
VertexProvider<DefaultVertex> vp1 = (label, attributes) -> new DefaultVertex(label, attributes);
EdgeProvider<DefaultVertex, RelationshipEdge> ep1 = (from, to, label, attributes) -> new RelationshipEdge(from,
to, attributes);
GmlImporter<DefaultVertex, RelationshipEdge> gmlImporter = new GmlImporter<>(vp1, ep1);
try {
gmlImporter.importGraph(graph, readFile(filename));
} catch (ImportException e) {
throw new RuntimeException(e);
}
return graph;
}
public static Graph<DefaultVertex,RelationshipDirectedEdge> importDirectedGraphGML (Graph<DefaultVertex,RelationshipDirectedEdge> graph, String filename) {
VertexProvider<DefaultVertex> vp1 = (label, attributes) -> new DefaultVertex(label, attributes);
EdgeProvider<DefaultVertex, RelationshipDirectedEdge> ep1 = (from, to, label, attributes) -> new RelationshipDirectedEdge(from,
to, attributes);
GmlImporter<DefaultVertex, RelationshipDirectedEdge> gmlImporter = new GmlImporter<>(vp1, ep1);
try {
gmlImporter.importGraph(graph, readFile(filename));
} catch (ImportException e) {
throw new RuntimeException(e);
}
return graph;
}
static Reader readFile(String filename) {
StringBuilder contentBuilder = new StringBuilder();
try (BufferedReader br = new BufferedReader(new FileReader(filename))) {
String sCurrentLine;
while ((sCurrentLine = br.readLine()) != null) {
contentBuilder.append(sCurrentLine).append("\n");
}
} catch (IOException e) {
e.printStackTrace();
}
StringReader readergml = new StringReader(contentBuilder.toString());
return readergml;
}
//////////////////////////////////////////////
/// GRAPH MEASURES
/////////////////////////////////////////////
static <V,E> double assortativityCoefficient (Graph <V, E> graph) {
// from: https://github.com/Infeligo/jgrapht-metrics/blob/master/src/main/java/org/jgrapht/metrics/AssortativityCoefficientMetric.java
double edgeCount = graph.edgeSet().size();
double n1 = 0, n2 = 0, dn = 0;
for (E e : graph.edgeSet()) {
int d1 = graph.degreeOf(graph.getEdgeSource(e));
int d2 = graph.degreeOf(graph.getEdgeTarget(e));
n1 += d1 * d2;
n2 += d1 + d2;
dn += d1 * d1 + d2 * d2;
}
n1 /= edgeCount;
n2 = (n2 / (2 * edgeCount)) * (n2 / (2 * edgeCount));
dn /= (2 * edgeCount);
return (n1 - n2) / (dn - n2);
}
static public <V,E> Set <V> getTreeCentroidPoints (Graph <V,E> graph) {
// graph must be a Tree
if (GraphTests.isTree(graph)==false) {
return new HashSet <> ();
}
Set<Entry<V, Double>> set = getCutPointWeights(graph).entrySet();
List<Entry<V, Double>> list = new ArrayList<Entry<V, Double>>(set);
list = list.stream().sorted((e1,e2) -> (e1.getValue()).compareTo(e2.getValue())).collect(Collectors.toList());
double size = list.get(0).getValue();
return (list.stream().filter(e -> e.getValue().doubleValue() == size).collect(Collectors.toSet())).stream().map(e -> e.getKey()).collect(Collectors.toSet());
}
static public <V,E> Map <V,Double> getCutPointWeights (Graph <V,E> graph) {
// graph must be a Tree
Map <V,Double> weights = new HashMap <> ();
if (GraphTests.isTree(graph)==false) {
return weights;
}
BiconnectivityInspector <V, E> insp =
new BiconnectivityInspector <> (graph);
DijkstraShortestPath <V, E> paths =
new DijkstraShortestPath <> (graph);
Iterator <V> it1 = insp.getCutpoints().iterator();
while (it1.hasNext()) {
V v1 = it1.next();
Iterator <V> it2 = Graphs.neighborListOf(graph, v1).iterator();
int size = 0;
while (it2.hasNext()) {
V v2 = it2.next();
List <E> s = new ArrayList <>();
Iterator <V> it3 = graph.vertexSet().iterator();
while (it3.hasNext()) {
V v3 = it3.next();
if (paths.getPath(v2, v3).getVertexList().contains(v1)==false && graph.degreeOf(v3)==1) {
s.addAll( paths.getPath(v2, v3).getEdgeList().stream().filter(e -> s.contains(e)==false ).collect(Collectors.toList()));
}
}
if(s.size() >= size) {
size = s.size()+1;
}
}
weights.put(v1,new Double(size));
}
return weights;
}
}