-
Notifications
You must be signed in to change notification settings - Fork 114
/
Copy pathGraphSaveLoadUtils.java
1062 lines (868 loc) · 37.4 KB
/
GraphSaveLoadUtils.java
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
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
package edu.cmu.tetrad.graph;
import edu.cmu.tetrad.data.DataSet;
import edu.cmu.tetrad.data.SimpleDataLoader;
import edu.cmu.tetrad.util.*;
import edu.pitt.dbmi.data.reader.Data;
import edu.pitt.dbmi.data.reader.Delimiter;
import edu.pitt.dbmi.data.reader.tabular.ContinuousTabularDatasetFileReader;
import nu.xom.*;
import java.io.*;
import java.nio.file.Files;
import java.text.DecimalFormat;
import java.text.NumberFormat;
import java.util.*;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
/**
* Methods to load or save graphs.
*
* @author josephramsey
*/
public class GraphSaveLoadUtils {
public static Graph loadGraph(File file) {
Element root;
Graph graph;
try {
root = getRootElement(file);
graph = parseGraphXml(root, null);
} catch (ParsingException e1) {
throw new IllegalArgumentException("Could not parse " + file, e1);
} catch (IOException e1) {
throw new IllegalArgumentException("Could not read " + file, e1);
}
return graph;
}
public static Graph loadGraphTxt(File file) {
try {
Reader in1 = new FileReader(file);
return readerToGraphTxt(in1);
} catch (Exception e) {
e.printStackTrace();
throw new IllegalStateException();
}
}
public static Graph loadGraphRuben(File file) {
try {
final String commentMarker = "//";
final char quoteCharacter = '"';
final String missingValueMarker = "*";
final boolean hasHeader = false;
DataSet dataSet = SimpleDataLoader.loadContinuousData(file, commentMarker, quoteCharacter, missingValueMarker, hasHeader, Delimiter.COMMA);
List<Node> nodes = dataSet.getVariables();
Graph graph = new EdgeListGraph(nodes);
for (int i = 0; i < nodes.size(); i++) {
for (int j = i + 1; j < nodes.size(); j++) {
if (dataSet.getDouble(i, j) != 0D) {
graph.addDirectedEdge(nodes.get(i), nodes.get(j));
}
}
}
return graph;
} catch (Exception e) {
e.printStackTrace();
throw new IllegalStateException();
}
}
public static Graph loadGraphJson(File file) {
try {
Reader in1 = new FileReader(file);
return readerToGraphJson(in1);
} catch (Exception e) {
e.printStackTrace();
}
throw new IllegalStateException();
}
private static int[][] incidenceMatrix(Graph graph) throws IllegalArgumentException {
List<Node> nodes = graph.getNodes();
int[][] m = new int[nodes.size()][nodes.size()];
for (Edge edge : graph.getEdges()) {
if (!Edges.isDirectedEdge(edge)) {
throw new IllegalArgumentException("Not a directed graph.");
}
}
for (int i = 0; i < nodes.size(); i++) {
for (int j = 0; j < nodes.size(); j++) {
Node x1 = nodes.get(i);
Node x2 = nodes.get(j);
Edge edge = graph.getEdge(x1, x2);
if (edge == null) {
m[i][j] = 0;
} else if (edge.getProximalEndpoint(x1) == Endpoint.ARROW) {
m[i][j] = 1;
} else if (edge.getProximalEndpoint(x1) == Endpoint.TAIL) {
m[i][j] = -1;
}
}
}
return m;
}
// Bayes net toolbox.
public static Graph loadGraphBNTPcMatrix(List<Node> vars, DataSet dataSet) {
Graph graph = new EdgeListGraph(vars);
for (int i = 0; i < dataSet.getNumRows(); i++) {
for (int j = 0; j < dataSet.getNumColumns(); j++) {
int g = dataSet.getInt(i, j);
int h = dataSet.getInt(j, i);
if (g == 1 && h == 1 && !graph.isAdjacentTo(vars.get(i), vars.get(j))) {
graph.addUndirectedEdge(vars.get(i), vars.get(j));
} else if (g == -1 && h == 0) {
graph.addDirectedEdge(vars.get(i), vars.get(j));
}
}
}
return graph;
}
public static String graphRMatrixTxt(Graph graph) throws IllegalArgumentException {
int[][] m = GraphSaveLoadUtils.incidenceMatrix(graph);
TextTable table = new TextTable(m[0].length + 1, m.length + 1);
for (int i = 0; i < m.length; i++) {
for (int j = 0; j < m[0].length; j++) {
table.setToken(i + 1, j + 1, String.valueOf(m[i][j]));
}
}
for (int i = 0; i < m.length; i++) {
table.setToken(i + 1, 0, String.valueOf(i + 1));
}
List<Node> nodes = graph.getNodes();
for (int j = 0; j < m[0].length; j++) {
table.setToken(0, j + 1, nodes.get(j).getName());
}
return table.toString();
}
public static Graph loadRSpecial(File file) {
DataSet eg = null;
try {
ContinuousTabularDatasetFileReader reader = new ContinuousTabularDatasetFileReader(file.toPath(), Delimiter.COMMA);
reader.setHasHeader(false);
Data data = reader.readInData();
eg = (DataSet) DataConvertUtils.toDataModel(data);
} catch (IOException ioException) {
ioException.printStackTrace();
}
if (eg == null) throw new NullPointerException();
List<Node> vars = eg.getVariables();
Graph graph = new EdgeListGraph(vars);
for (int i = 0; i < vars.size(); i++) {
for (int j = 0; j < vars.size(); j++) {
if (i == j) continue;
if (eg.getDouble(i, j) == 1 && eg.getDouble(j, i) == 1) {
if (!graph.isAdjacentTo(vars.get(i), vars.get(j))) {
graph.addUndirectedEdge(vars.get(i), vars.get(j));
}
} else if (eg.getDouble(i, j) == 1 && eg.getDouble(j, i) == 0) {
graph.addDirectedEdge(vars.get(i), vars.get(j));
}
}
}
return graph;
}
public static Graph loadGraphPcalg(File file) {
try {
DataSet dataSet = SimpleDataLoader.loadContinuousData(file, "//", '\"',
"*", true, Delimiter.COMMA);
List<Node> nodes = dataSet.getVariables();
Graph graph = new EdgeListGraph(nodes);
for (int i = 0; i < nodes.size(); i++) {
for (int j = i + 1; j < nodes.size(); j++) {
Node n1 = nodes.get(i);
Node n2 = nodes.get(j);
int e1 = dataSet.getInt(j, i);
int e2 = dataSet.getInt(i, j);
Endpoint e1a;
switch (e1) {
case 0:
e1a = Endpoint.NULL;
break;
case 1:
e1a = Endpoint.CIRCLE;
break;
case 2:
e1a = Endpoint.ARROW;
break;
case 3:
e1a = Endpoint.TAIL;
break;
default:
throw new IllegalArgumentException("Unexpected endpoint type: " + e1);
}
Endpoint e2a;
switch (e2) {
case 0:
e2a = Endpoint.NULL;
break;
case 1:
e2a = Endpoint.CIRCLE;
break;
case 2:
e2a = Endpoint.ARROW;
break;
case 3:
e2a = Endpoint.TAIL;
break;
default:
throw new IllegalArgumentException("Unexpected endpoint type: " + e1);
}
if (e1a != Endpoint.NULL && e2a != Endpoint.NULL) {
Edge edge = new Edge(n1, n2, e1a, e2a);
graph.addEdge(edge);
}
}
}
return graph;
} catch (Exception e) {
e.printStackTrace();
throw new IllegalStateException();
}
}
public static String loadGraphRMatrix(Graph graph) throws IllegalArgumentException {
int[][] m = GraphSaveLoadUtils.incidenceMatrix(graph);
TextTable table = new TextTable(m[0].length + 1, m.length + 1);
for (int i = 0; i < m.length; i++) {
for (int j = 0; j < m[0].length; j++) {
table.setToken(i + 1, j + 1, String.valueOf(m[i][j]));
}
}
for (int i = 0; i < m.length; i++) {
table.setToken(i + 1, 0, String.valueOf(i + 1));
}
List<Node> nodes = graph.getNodes();
for (int j = 0; j < m[0].length; j++) {
table.setToken(0, j + 1, nodes.get(j).getName());
}
return table.toString();
}
public static Graph readerToGraphTxt(String graphString) throws IOException {
return readerToGraphTxt(new CharArrayReader(graphString.toCharArray()));
}
public static Graph readerToGraphTxt(Reader reader) throws IOException {
Graph graph = new EdgeListGraph();
try (BufferedReader in = new BufferedReader(reader)) {
for (String line = in.readLine(); line != null; line = in.readLine()) {
line = line.trim();
switch (line) {
case "Graph Nodes:":
extractGraphNodes(graph, in);
break;
case "Graph Edges:":
extractGraphEdges(graph, in);
break;
}
}
}
return graph;
}
/**
* @param graph The graph to be saved.
* @param file The file to save it in.
* @param xml True if to be saved in XML, false if in text.
* @return I have no idea whey I'm returning this; it's already closed...
*/
public static PrintWriter saveGraph(Graph graph, File file, boolean xml) {
PrintWriter out;
try {
out = new PrintWriter(Files.newOutputStream(file.toPath()));
if (xml) {
out.print(graphToXml(graph));
} else {
out.print(graph);
}
out.flush();
out.close();
} catch (IOException e1) {
throw new IllegalArgumentException("Output file could not " + "be opened: " + file);
}
return out;
}
public static Graph readerToGraphRuben(Reader reader) throws IOException {
Graph graph = new EdgeListGraph();
try (BufferedReader in = new BufferedReader(reader)) {
for (String line = in.readLine(); line != null; line = in.readLine()) {
line = line.trim();
switch (line) {
case "Graph Nodes:":
extractGraphNodes(graph, in);
break;
case "Graph Edges:":
extractGraphEdges(graph, in);
break;
}
}
}
return graph;
}
private static void extractGraphEdges(Graph graph, BufferedReader in) throws IOException {
Pattern lineNumPattern = Pattern.compile("^\\d+.\\s?");
Pattern spacePattern = Pattern.compile("\\s+");
Pattern semicolonPattern = Pattern.compile(";");
Pattern colonPattern = Pattern.compile(":");
for (String line = in.readLine(); line != null; line = in.readLine()) {
line = line.trim();
if (line.isEmpty()) {
return;
}
line = lineNumPattern.matcher(line).replaceAll("");
String[] fields = spacePattern.split(line, 4);
Edge edge = getEdge(fields[0], fields[1], fields[2], graph);
if (fields.length > 3) {
fields = semicolonPattern.split(fields[3]);
if (fields.length > 1) {
for (String prop : fields) {
setEdgeTypeProperties(edge, prop, spacePattern, colonPattern);
}
} else {
getEdgeProperties(fields[0], spacePattern)
.forEach(edge::addProperty);
}
}
graph.addEdge(edge);
}
}
private static void setEdgeTypeProperties(Edge edge, String prop, Pattern spacePattern, Pattern colonPattern) {
prop = prop.replace("[", "").replace("]", "");
String[] fields = colonPattern.split(prop);
if (fields.length == 2) {
String bootstrapEdge = fields[0];
String bootstrapEdgeTypeProb = fields[1];
// edge type
fields = spacePattern.split(bootstrapEdge, 4);
if (fields.length >= 3) {
// edge-type probability
EdgeTypeProbability.EdgeType edgeType = getEdgeType(fields[1]);
List<Edge.Property> properties = new LinkedList<>();
if (fields.length > 3) {
// pags
properties.addAll(getEdgeProperties(fields[3], spacePattern));
}
edge.addEdgeTypeProbability(new EdgeTypeProbability(edgeType, properties, Double.parseDouble(bootstrapEdgeTypeProb)));
} else {
// edge probability
if ("edge".equals(bootstrapEdge)) {
fields = spacePattern.split(bootstrapEdgeTypeProb, 2);
if (fields.length > 1) {
edge.setProbability(Double.parseDouble(fields[0]));
getEdgeProperties(fields[1], spacePattern).forEach(edge::addProperty);
} else {
edge.setProbability(Double.parseDouble(bootstrapEdgeTypeProb));
}
} else if ("no edge".equals(bootstrapEdge)) {
edge.addEdgeTypeProbability(new EdgeTypeProbability(EdgeTypeProbability.EdgeType.nil, Double.parseDouble(bootstrapEdgeTypeProb)));
}
}
}
}
private static EdgeTypeProbability.EdgeType getEdgeType(String edgeType) {
Endpoint endpointFrom = getEndpoint(edgeType.charAt(0));
Endpoint endpointTo = getEndpoint(edgeType.charAt(2));
if (endpointFrom == Endpoint.TAIL && endpointTo == Endpoint.ARROW) {
return EdgeTypeProbability.EdgeType.ta;
} else if (endpointFrom == Endpoint.ARROW && endpointTo == Endpoint.TAIL) {
return EdgeTypeProbability.EdgeType.at;
} else if (endpointFrom == Endpoint.CIRCLE && endpointTo == Endpoint.ARROW) {
return EdgeTypeProbability.EdgeType.ca;
} else if (endpointFrom == Endpoint.ARROW && endpointTo == Endpoint.CIRCLE) {
return EdgeTypeProbability.EdgeType.ac;
} else if (endpointFrom == Endpoint.CIRCLE && endpointTo == Endpoint.CIRCLE) {
return EdgeTypeProbability.EdgeType.cc;
} else if (endpointFrom == Endpoint.ARROW && endpointTo == Endpoint.ARROW) {
return EdgeTypeProbability.EdgeType.aa;
} else if (endpointFrom == Endpoint.TAIL && endpointTo == Endpoint.TAIL) {
return EdgeTypeProbability.EdgeType.tt;
} else {
return EdgeTypeProbability.EdgeType.nil;
}
}
private static List<Edge.Property> getEdgeProperties(String props, Pattern spacePattern) {
List<Edge.Property> properties = new LinkedList<>();
for (String prop : spacePattern.split(props)) {
if ("dd".equals(prop)) {
properties.add(Edge.Property.dd);
} else if ("nl".equals(prop)) {
properties.add(Edge.Property.nl);
} else if ("pd".equals(prop)) {
properties.add(Edge.Property.pd);
} else if ("pl".equals(prop)) {
properties.add(Edge.Property.pl);
}
}
return properties;
}
private static void extractGraphNodes(Graph graph, BufferedReader in) throws IOException {
for (String line = in.readLine(); line != null; line = in.readLine()) {
line = line.trim();
if (line.isEmpty()) {
break;
}
String[] tokens = line.split("[,;]");
for (String token : tokens) {
if (token.startsWith("(") && token.endsWith(")")) {
token = token.replace("(", "");
token = token.replace(")", "");
Node node = new GraphNode(token);
node.setNodeType(NodeType.LATENT);
graph.addNode(node);
} else {
Node node = new GraphNode(token);
node.setNodeType(NodeType.MEASURED);
graph.addNode(node);
}
}
// Arrays.stream(line.split("[,;]")).map(GraphNode::new).forEach(graph::addNode);
}
}
public static Graph readerToGraphJson(Reader reader) throws IOException {
BufferedReader in = new BufferedReader(reader);
StringBuilder json = new StringBuilder();
String line;
while ((line = in.readLine()) != null) {
json.append(line.trim());
}
return JsonUtils.parseJSONObjectToTetradGraph(json.toString());
}
/**
* Converts a graph to a Graphviz .dot file
*/
public static String graphToDot(Graph graph) {
StringBuilder builder = new StringBuilder();
builder.append("digraph g {\n");
List<Edge> edges = new ArrayList<>(graph.getEdges());
Collections.sort(edges);
for (Edge edge : edges) {
String n1 = edge.getNode1().getName();
String n2 = edge.getNode2().getName();
Endpoint end1 = edge.getEndpoint1();
Endpoint end2 = edge.getEndpoint2();
// These may be in the graph, but they represent edges not in the ensemble for which
// bootstrap information is available.
if (end1 == Endpoint.NULL || end2 == Endpoint.NULL) continue;
builder.append(" \"").append(n1).append("\" -> \"").append(n2).append("\" [");
if (end1 != Endpoint.TAIL) {
builder.append("dir=both, ");
}
builder.append("arrowtail=");
if (end1 == Endpoint.ARROW) {
builder.append("normal");
} else if (end1 == Endpoint.TAIL) {
builder.append("none");
} else if (end1 == Endpoint.CIRCLE) {
builder.append("odot");
} else {
builder.append("xdot");
}
builder.append(", arrowhead=");
if (end2 == Endpoint.ARROW) {
builder.append("normal");
} else if (end2 == Endpoint.TAIL) {
builder.append("none");
} else if (end2 == Endpoint.CIRCLE) {
builder.append("odot");
} else {
builder.append("xdot");
}
// Bootstrapping
List<EdgeTypeProbability> edgeTypeProbabilities = edge.getEdgeTypeProbabilities();
if (edgeTypeProbabilities != null && !edgeTypeProbabilities.isEmpty()) {
StringBuilder label = new StringBuilder(n1 + " - " + n2);
for (EdgeTypeProbability edgeTypeProbability : edgeTypeProbabilities) {
EdgeTypeProbability.EdgeType edgeType = edgeTypeProbability.getEdgeType();
double probability = edgeTypeProbability.getProbability();
if (probability > 0) {
StringBuilder edgeTypeString = new StringBuilder();
switch (edgeType) {
case nil:
edgeTypeString = new StringBuilder("no edge");
break;
case ta:
edgeTypeString = new StringBuilder("-->");
break;
case at:
edgeTypeString = new StringBuilder("<--");
break;
case ca:
edgeTypeString = new StringBuilder("o->");
break;
case ac:
edgeTypeString = new StringBuilder("<-o");
break;
case cc:
edgeTypeString = new StringBuilder("o-o");
break;
case aa:
edgeTypeString = new StringBuilder("<->");
break;
case tt:
edgeTypeString = new StringBuilder("---");
break;
}
List<Edge.Property> properties = edgeTypeProbability.getProperties();
if (properties != null && properties.size() > 0) {
for (Edge.Property property : properties) {
edgeTypeString.append(" ").append(property.toString());
}
}
NumberFormat nf = new DecimalFormat("0.000");
label.append("\\n[").append(edgeTypeString).append("]:").append(nf.format(edgeTypeProbability.getProbability()));
}
}
builder.append(", label=\"").append(label).append("\", fontname=courier");
}
builder.append("]; \n");
}
builder.append("}");
return builder.toString();
}
public static void graphToDot(Graph graph, File file) {
try {
Writer writer = new FileWriter(file);
writer.write(graphToDot(graph));
writer.close();
} catch (IOException e) {
e.printStackTrace();
}
}
/**
* @return an XML element representing the given graph. (Well, only a basic graph for now...)
*/
public static Element convertToXml(Graph graph) {
Element element = new Element("graph");
Element variables = new Element("variables");
element.appendChild(variables);
for (Node node : graph.getNodes()) {
Element variable = new Element("variable");
Text text = new Text(node.getName());
variable.appendChild(text);
variables.appendChild(variable);
}
Element edges = new Element("edges");
element.appendChild(edges);
for (Edge edge : graph.getEdges()) {
Element _edge = new Element("edge");
Text text = new Text(edge.toString());
_edge.appendChild(text);
edges.appendChild(_edge);
}
Set<Triple> ambiguousTriples = graph.getAmbiguousTriples();
if (!ambiguousTriples.isEmpty()) {
Element underlinings = new Element("ambiguities");
element.appendChild(underlinings);
for (Triple triple : ambiguousTriples) {
Element underlining = new Element("ambiguities");
Text text = new Text(niceTripleString(triple));
underlining.appendChild(text);
underlinings.appendChild(underlining);
}
}
Set<Triple> underlineTriples = graph.getUnderLines();
if (!underlineTriples.isEmpty()) {
Element underlinings = new Element("underlines");
element.appendChild(underlinings);
for (Triple triple : underlineTriples) {
Element underlining = new Element("underline");
Text text = new Text(niceTripleString(triple));
underlining.appendChild(text);
underlinings.appendChild(underlining);
}
}
Set<Triple> dottedTriples = graph.getDottedUnderlines();
if (!dottedTriples.isEmpty()) {
Element dottedUnderlinings = new Element("dottedUnderlines");
element.appendChild(dottedUnderlinings);
for (Triple triple : dottedTriples) {
Element dottedUnderlining = new Element("dottedUnderline");
Text text = new Text(niceTripleString(triple));
dottedUnderlining.appendChild(text);
dottedUnderlinings.appendChild(dottedUnderlining);
}
}
return element;
}
private static String niceTripleString(Triple triple) {
return triple.getX() + ", " + triple.getY() + ", " + triple.getZ();
}
public static String graphToXml(Graph graph) {
Document document = new Document(convertToXml(graph));
OutputStream out = new ByteArrayOutputStream();
Serializer serializer = new Serializer(out);
serializer.setLineSeparator("\n");
serializer.setIndent(2);
try {
serializer.write(document);
} catch (IOException e) {
throw new RuntimeException(e);
}
return out.toString();
}
public static String graphToLavaan(Graph g) {
boolean includeIntercepts = true;
boolean includeErrors = true;
Map<Node, List<Node>> parents = new HashMap<>();
Map<Node, List<Node>> siblings = new HashMap<>();
StringBuilder lavaan = new StringBuilder();
for (Node a : g.getNodes()) {
if (includeIntercepts) lavaan.append(a.getName()).append(" ~ 1\n");
parents.put(a, new ArrayList<>());
siblings.put(a, new ArrayList<>());
for (Edge e : g.getEdges(a)) {
Node b = e.getDistalNode(a);
if (e.getProximalEndpoint(a) != Endpoint.ARROW) continue;
if (e.getProximalEndpoint(b) == Endpoint.TAIL) parents.get(a).add(b);
if (siblings.containsKey(b)) continue;
if (e.getProximalEndpoint(b) == Endpoint.ARROW) siblings.get(a).add(b);
}
}
if (includeIntercepts) lavaan.append("\n");
boolean hasDirected = false;
for (Node a : g.getNodes()) {
Iterator<Node> itr = parents.get(a).iterator();
if (itr.hasNext()) {
hasDirected = true;
lavaan.append(a.getName()).append(" ~ ").append(itr.next().getName());
} else continue;
while (itr.hasNext()) lavaan.append(" + ").append(itr.next().getName());
lavaan.append("\n");
}
if (hasDirected) lavaan.append("\n");
boolean hasBidirected = false;
for (Node a : g.getNodes()) {
Iterator<Node> itr = siblings.get(a).iterator();
if (itr.hasNext()) {
hasBidirected = true;
lavaan.append(a.getName()).append(" ~~ ").append(itr.next().getName());
} else continue;
while (itr.hasNext()) lavaan.append(" + ").append(itr.next().getName());
lavaan.append("\n");
}
if (hasBidirected) lavaan.append("\n");
for (Node a : g.getNodes()) {
if (includeErrors) lavaan.append(a.getName()).append(" ~~ ").append(a.getName()).append("\n");
}
return lavaan.toString();
}
public static String graphToPcalg(Graph g) {
Map<Endpoint, Integer> mark2Int = new HashMap<>();
mark2Int.put(Endpoint.NULL, 0);
mark2Int.put(Endpoint.CIRCLE, 1);
mark2Int.put(Endpoint.ARROW, 2);
mark2Int.put(Endpoint.TAIL, 3);
int n = g.getNumNodes();
int[][] A = new int[n][n];
List<Node> nodes = g.getNodes();
for (Edge edge : g.getEdges()) {
int i = nodes.indexOf(edge.getNode1());
int j = nodes.indexOf(edge.getNode2());
A[j][i] = mark2Int.get(edge.getEndpoint1());
A[i][j] = mark2Int.get(edge.getEndpoint2());
}
TextTable table = new TextTable(n + 1, n);
table.setDelimiter(TextTable.Delimiter.COMMA);
for (int j = 0; j < n; j++) {
table.setToken(0, j, nodes.get(j).getName());
}
for (int i = 0; i < n; i++) {
for (int j = 0; j < n; j++) {
table.setToken(i + 1, j, String.valueOf(A[i][j]));
}
}
return table.toString();
}
public static Graph parseGraphXml(Element graphElement, Map<String, Node> nodes) throws ParsingException {
if (!"graph".equals(graphElement.getLocalName())) {
throw new IllegalArgumentException("Expecting graph element: " + graphElement.getLocalName());
}
if (!("variables".equals(graphElement.getChildElements().get(0).getLocalName()))) {
throw new ParsingException("Expecting variables element: " + graphElement.getChildElements().get(0).getLocalName());
}
Element variablesElement = graphElement.getChildElements().get(0);
Elements variableElements = variablesElement.getChildElements();
List<Node> variables = new ArrayList<>();
for (int i = 0; i < variableElements.size(); i++) {
Element variableElement = variableElements.get(i);
if (!("variable".equals(variablesElement.getChildElements().get(i).getLocalName()))) {
throw new ParsingException("Expecting variable element.");
}
String value = variableElement.getValue();
if (nodes == null) {
variables.add(new GraphNode(value));
} else {
variables.add(nodes.get(value));
}
}
Graph graph = new EdgeListGraph(variables);
// graphNotes.add(noteAttribute.getValue());
if (!("edges".equals(graphElement.getChildElements().get(1).getLocalName()))) {
throw new ParsingException("Expecting edges element.");
}
Element edgesElement = graphElement.getChildElements().get(1);
Elements edgesElements = edgesElement.getChildElements();
for (int i = 0; i < edgesElements.size(); i++) {
Element edgeElement = edgesElements.get(i);
if (!("edge".equals(edgeElement.getLocalName()))) {
throw new ParsingException("Expecting edge element: " + edgeElement.getLocalName());
}
String value = edgeElement.getValue();
final String regex = "([A-Za-z0-9_-]*:?[A-Za-z0-9_-]*) ?(.)-(.) ?([A-Za-z0-9_-]*:?[A-Za-z0-9_-]*)";
// String regex = "([A-Za-z0-9_-]*) ?([<o])-([o>]) ?([A-Za-z0-9_-]*)";
java.util.regex.Pattern pattern = java.util.regex.Pattern.compile(regex);
Matcher matcher = pattern.matcher(value);
if (!matcher.matches()) {
throw new ParsingException("Edge doesn't match pattern.");
}
String var1 = matcher.group(1);
String leftEndpoint = matcher.group(2);
String rightEndpoint = matcher.group(3);
String var2 = matcher.group(4);
Node node1 = graph.getNode(var1);
Node node2 = graph.getNode(var2);
Endpoint endpoint1;
switch (leftEndpoint) {
case "<":
endpoint1 = Endpoint.ARROW;
break;
case "o":
endpoint1 = Endpoint.CIRCLE;
break;
case "-":
endpoint1 = Endpoint.TAIL;
break;
default:
throw new IllegalStateException("Expecting an endpoint: " + leftEndpoint);
}
Endpoint endpoint2;
switch (rightEndpoint) {
case ">":
endpoint2 = Endpoint.ARROW;
break;
case "o":
endpoint2 = Endpoint.CIRCLE;
break;
case "-":
endpoint2 = Endpoint.TAIL;
break;
default:
throw new IllegalStateException("Expecting an endpoint: " + rightEndpoint);
}
Edge edge = new Edge(node1, node2, endpoint1, endpoint2);
graph.addEdge(edge);
}
int size = graphElement.getChildElements().size();
if (2 >= size) {
return graph;
}
int p = 2;
if ("ambiguities".equals(graphElement.getChildElements().get(p).getLocalName())) {
Element ambiguitiesElement = graphElement.getChildElements().get(p);
Set<Triple> triples = parseTriples(variables, ambiguitiesElement, "ambiguity");
graph.setAmbiguousTriples(triples);
p++;
}
if (p >= size) {
return graph;
}
if ("underlines".equals(graphElement.getChildElements().get(p).getLocalName())) {
Element ambiguitiesElement = graphElement.getChildElements().get(p);
Set<Triple> triples = parseTriples(variables, ambiguitiesElement, "underline");
graph.setUnderLineTriples(triples);
p++;
}
if (p >= size) {
return graph;
}
if ("dottedunderlines".equals(graphElement.getChildElements().get(p).getLocalName())) {
Element ambiguitiesElement = graphElement.getChildElements().get(p);
Set<Triple> triples = parseTriples(variables, ambiguitiesElement, "dottedunderline");
graph.setDottedUnderLineTriples(triples);
}
return graph;
}
/**
* A triples element has a list of three (comman separated) nodes as text.
*/
private static Set<Triple> parseTriples(List<Node> variables, Element triplesElement, String s) {
Elements elements = triplesElement.getChildElements(s);
Set<Triple> triples = new HashSet<>();
for (int q = 0; q < elements.size(); q++) {
Element tripleElement = elements.get(q);
String value = tripleElement.getValue();
String[] tokens = value.split(",");
if (tokens.length != 3) {
throw new IllegalArgumentException("Expecting a triple: " + value);
}
String x = tokens[0].trim();
String y = tokens[1].trim();
String z = tokens[2].trim();
Node _x = getNode(variables, x);
Node _y = getNode(variables, y);
Node _z = getNode(variables, z);
Triple triple = new Triple(_x, _y, _z);
triples.add(triple);
}
return triples;
}
private static Node getNode(List<Node> variables, String x) {
for (Node node : variables) {
if (node.getName().equals(x)) return node;
}
return null;
}
public static Element getRootElement(File file) throws ParsingException, IOException {
Builder builder = new Builder();
Document document = builder.build(file);
return document.getRootElement();
}
private static Edge getEdge(String nodeNameFrom, String edgeType, String nodeNameTo, Graph graph) {
Node nodeFrom = getNode(nodeNameFrom, graph);
Node nodeTo = getNode(nodeNameTo, graph);
Endpoint endpointFrom = getEndpoint(edgeType.charAt(0));
Endpoint endpointTo = getEndpoint(edgeType.charAt(2));
return new Edge(nodeFrom, nodeTo, endpointFrom, endpointTo);
}
private static Endpoint getEndpoint(char endpoint) {
if (endpoint == '>' || endpoint == '<') {
return Endpoint.ARROW;
} else if (endpoint == 'o') {