don't rotate graph
[IRC.git] / Robust / src / Util / GraphNode.java
1 package Util;
2
3 import java.util.*;
4 import java.io.*;
5
6 public class GraphNode {
7     /* NodeStatus enumeration pattern ***********/
8
9     public static final NodeStatus UNVISITED = new NodeStatus("UNVISITED");
10     public static final NodeStatus PROCESSING = new NodeStatus("PROCESSING");
11     public static final NodeStatus FINISHED = new NodeStatus("FINISHED");
12
13     public static class NodeStatus {
14         private static String name;
15         private NodeStatus(String name) { this.name = name; }
16         public String toString() { return name; }
17     }
18
19     int discoverytime = -1;
20     int finishingtime = -1; /* used for searches */
21
22     protected Vector edges = new Vector();
23     protected Vector inedges = new Vector();
24
25     NodeStatus status = UNVISITED;
26     String dotnodeparams = new String();
27     public boolean merge=false;
28
29     public void setMerge() {
30         merge=true;
31     }
32
33     public static void computeclosure(Collection nodes, Collection removed) {
34         Stack tovisit=new Stack();
35         tovisit.addAll(nodes);
36         while(!tovisit.isEmpty()) {
37             GraphNode gn=(GraphNode)tovisit.pop();
38             for(Iterator it=gn.edges();it.hasNext();) {
39                 Edge edge=(Edge)it.next();
40                 GraphNode target=edge.getTarget();
41                 if (!nodes.contains(target)) {
42                     if ((removed==null)||
43                         (!removed.contains(target))) {
44                         nodes.add(target);
45                         tovisit.push(target);
46                     }
47                 }
48             }
49         }
50     }
51
52     public static void boundedcomputeclosure(Collection nodes, Collection removed,int depth) {
53         Stack tovisit=new Stack();
54         Stack newvisit=new Stack();
55         tovisit.addAll(nodes);
56         for(int i=0;i<depth&&!tovisit.isEmpty();i++) {
57             while(!tovisit.isEmpty()) {
58                 GraphNode gn=(GraphNode)tovisit.pop();
59                 for(Iterator it=gn.edges();it.hasNext();) {
60                     Edge edge=(Edge)it.next();
61                     GraphNode target=edge.getTarget();
62                     if (!nodes.contains(target)) {
63                         if ((removed==null)||
64                             (!removed.contains(target))) {
65                             nodes.add(target);
66                             newvisit.push(target);
67                         }
68                     }
69                 }
70             }
71             tovisit=newvisit;
72             newvisit=new Stack();
73         }
74     }
75
76     public void setDotNodeParameters(String param) {
77         if (param == null) {
78             throw new NullPointerException();
79         }
80         if (param.length() > 0) {
81             dotnodeparams = "," + param;
82         } else {
83             dotnodeparams = new String();
84         }
85     }
86
87     public void setStatus(NodeStatus status) {
88         if (status == null) {
89             throw new NullPointerException();
90         }
91         this.status = status;
92     }
93
94     public String getLabel() {
95         return "";
96     }
97
98     public String getTextLabel() {
99         return "";
100     }
101
102     public NodeStatus getStatus() {
103         return this.status;
104     }
105
106     public Iterator edges() {
107         return edges.iterator();
108     }
109
110     public Iterator inedges() {
111         return inedges.iterator();
112     }
113
114     public void addEdge(Edge newedge) {
115         newedge.setSource(this);
116         edges.addElement(newedge);
117         GraphNode tonode=newedge.getTarget();
118         tonode.inedges.addElement(newedge);
119     }
120
121     void reset() {
122             discoverytime = -1;
123             finishingtime = -1;
124             status = UNVISITED;
125     }
126
127     void resetscc() {
128         status = UNVISITED;
129     }
130
131     void discover(int time) {
132         discoverytime = time;
133         status = PROCESSING;
134     }
135
136     void finish(int time) {
137         assert status == PROCESSING;
138         finishingtime = time;
139         status = FINISHED;
140     }
141
142     /** Returns finishing time for dfs */
143
144     public int getFinishingTime() {
145         return finishingtime;
146     }
147
148
149     public static class DOTVisitor {
150
151         java.io.PrintWriter output;
152         int tokennumber;
153         int color;
154         Vector namers;
155
156         private DOTVisitor(java.io.OutputStream output, Vector namers) {
157             tokennumber = 0;
158             color = 0;
159             this.output = new java.io.PrintWriter(output, true);
160             this.namers=namers;
161         }
162
163         private String getNewID(String name) {
164             tokennumber = tokennumber + 1;
165             return new String (name+tokennumber);
166         }
167
168         Collection nodes;
169
170
171         public static void visit(java.io.OutputStream output, Collection nodes, Vector namers) {
172             DOTVisitor visitor = new DOTVisitor(output, namers);
173             visitor.nodes = nodes;
174             visitor.make();
175         }
176
177         public static void visit(java.io.OutputStream output, Collection nodes) {
178             Vector v=new Vector();
179             v.add(new Namer());
180             DOTVisitor visitor = new DOTVisitor(output, v);
181             visitor.nodes = nodes;
182             visitor.make();
183         }
184
185         private void make() {
186             output.println("digraph dotvisitor {");
187             /*            output.println("\tpage=\"8.5,11\";");
188                           output.println("\tnslimit=1000.0;");
189                           output.println("\tnslimit1=1000.0;");
190                           output.println("\tmclimit=1000.0;");
191                           output.println("\tremincross=true;");*/
192             output.println("\tnode [fontsize=10,height=\"0.1\", width=\"0.1\"];");
193             output.println("\tedge [fontsize=6];");
194             traverse();
195             output.println("}\n");
196         }
197
198         private void traverse() {
199             Set cycleset=GraphNode.findcycles(nodes);
200
201             Iterator it = nodes.iterator();
202             while (it.hasNext()) {
203                 GraphNode gn = (GraphNode) it.next();
204                 Iterator edges = gn.edges();
205                 String label = "";
206                 String dotnodeparams="";
207
208                 for(int i=0;i<namers.size();i++) {
209                     Namer name=(Namer) namers.get(i);
210                     String newlabel=name.nodeLabel(gn);
211                     String newparams=name.nodeOption(gn);
212
213                     if (!newlabel.equals("") && !label.equals("")) {
214                         label+=", ";
215                     }
216                     if (!newparams.equals("")) {
217                         dotnodeparams+=", " + name.nodeOption(gn);
218                     }
219                     label+=name.nodeLabel(gn);
220                 }
221
222                 if (!gn.merge)
223                     output.println("\t" + gn.getLabel() + " [label=\"" + label + "\"" + dotnodeparams + "];");
224
225                 if (!gn.merge)
226                 while (edges.hasNext()) {
227                     Edge edge = (Edge) edges.next();
228                     GraphNode node = edge.getTarget();
229                     if (nodes.contains(node)) {
230                         for(Iterator nodeit=nonmerge(node).iterator();nodeit.hasNext();) {
231                             GraphNode node2=(GraphNode)nodeit.next();
232                             String edgelabel = "";
233                             String edgedotnodeparams="";
234
235                             for(int i=0;i<namers.size();i++) {
236                                 Namer name=(Namer) namers.get(i);
237                                 String newlabel=name.edgeLabel(gn, edge);
238                                 String newoption=name.edgeOption(gn, edge);
239                                 if (!newlabel.equals("")&& ! edgelabel.equals(""))
240                                     edgelabel+=", ";
241                                 edgelabel+=newlabel;
242                                 if (!newoption.equals(""))
243                                     edgedotnodeparams+=", "+newoption;
244                             }
245                             
246                             output.println("\t" + gn.getLabel() + " -> " + node2.getLabel() + " [" + "label=\"" + edgelabel + "\"" + edgedotnodeparams + "];");
247                         }
248                     }
249                 }
250             }
251         }
252
253         Set nonmerge(GraphNode gn) {
254             HashSet newset=new HashSet();
255             HashSet toprocess=new HashSet();
256             toprocess.add(gn);
257             while(!toprocess.isEmpty()) {
258                 GraphNode gn2=(GraphNode)toprocess.iterator().next();
259                 toprocess.remove(gn2);
260                 if (!gn2.merge)
261                     newset.add(gn2);
262                 else {
263                     Iterator edges = gn2.edges();
264                     while (edges.hasNext()) {
265                         Edge edge = (Edge) edges.next();
266                         GraphNode node = edge.getTarget();
267                         if (!newset.contains(node)&&nodes.contains(node))
268                             toprocess.add(node);
269                     }
270                 }
271             }
272             return newset;
273         }
274
275     }
276
277     /** This function returns the set of nodes involved in cycles.
278      *  It only considers cycles containing nodes in the set 'nodes'.
279     */
280     public static Set findcycles(Collection nodes) {
281         HashSet cycleset=new HashSet();
282         SCC scc=DFS.computeSCC(nodes);
283         if (!scc.hasCycles())
284             return cycleset;
285         for(int i=0;i<scc.numSCC();i++) {
286             if (scc.hasCycle(i))
287                 cycleset.addAll(scc.getSCC(i));
288         }
289         return cycleset;
290     }
291
292     public static class SCC {
293         boolean acyclic;
294         HashMap map,revmap;
295         int numscc;
296         public SCC(boolean acyclic, HashMap map,HashMap revmap,int numscc) {
297             this.acyclic=acyclic;
298             this.map=map;
299             this.revmap=revmap;
300             this.numscc=numscc;
301         }
302
303         /** Returns whether the graph has any cycles */
304         public boolean hasCycles() {
305             return !acyclic;
306         }
307
308         /** Returns the number of Strongly Connected Components */
309         public int numSCC() {
310             return numscc;
311         }
312
313         /** Returns the strongly connected component number for the GraphNode gn*/
314         public int getComponent(GraphNode gn) {
315             return ((Integer)revmap.get(gn)).intValue();
316         }
317
318         /** Returns the set of nodes in the strongly connected component i*/
319         public Set getSCC(int i) {
320             Integer scc=new Integer(i);
321             return (Set)map.get(scc);
322         }
323
324         /** Returns whether the strongly connected component i contains a cycle */
325         boolean hasCycle(int i) {
326             Integer scc=new Integer(i);
327             Set s=(Set)map.get(scc);
328             if (s.size()>1)
329                 return true;
330             Object [] array=s.toArray();
331             GraphNode gn=(GraphNode)array[0];
332             for(Iterator it=gn.edges();it.hasNext();) {
333                 Edge e=(Edge)it.next();
334                 if (e.getTarget()==gn)
335                     return true; /* Self Cycle */
336             }
337             return false;
338         }
339     }
340
341     /**
342      * DFS encapsulates the depth first search algorithm
343      */
344     public static class DFS {
345
346         int time = 0;
347         int sccindex = 0;
348         Collection nodes;
349         Vector finishingorder=null;
350         HashMap sccmap;
351         HashMap sccmaprev;
352
353         private DFS(Collection nodes) {
354             this.nodes = nodes;
355         }
356         /** Calculates the strong connected components for the graph composed
357          *  of the set of nodes 'nodes'*/
358         public static SCC computeSCC(Collection nodes) {
359             if (nodes==null) {
360                 throw new NullPointerException();
361             }
362             DFS dfs=new DFS(nodes);
363             dfs.sccmap=new HashMap();
364             dfs.sccmaprev=new HashMap();
365             dfs.finishingorder=new Vector();
366             boolean acyclic=dfs.go();
367             for (Iterator it = nodes.iterator();it.hasNext();) {
368                 GraphNode gn = (GraphNode) it.next();
369                 gn.resetscc();
370             }
371             for(int i=dfs.finishingorder.size()-1;i>=0;i--) {
372                 GraphNode gn=(GraphNode)dfs.finishingorder.get(i);
373                 if (gn.getStatus() == UNVISITED) {
374                     dfs.dfsprev(gn);
375                     dfs.sccindex++; /* Increment scc index */
376                 }
377             }
378             return new SCC(acyclic,dfs.sccmap,dfs.sccmaprev,dfs.sccindex);
379         }
380
381         void dfsprev(GraphNode gn) {
382             if (gn.getStatus()==FINISHED||!nodes.contains(gn))
383                 return;
384             gn.setStatus(FINISHED);
385             Integer i=new Integer(sccindex);
386             if (!sccmap.containsKey(i))
387                 sccmap.put(i,new HashSet());
388             ((Set)sccmap.get(i)).add(gn);
389             sccmaprev.put(gn,i);
390             for(Iterator edgeit=gn.inedges();edgeit.hasNext();) {
391                 Edge e=(Edge)edgeit.next();
392                 GraphNode gn2=e.getSource();
393                 dfsprev(gn2);
394             }
395         }
396
397         public static boolean depthFirstSearch(Collection nodes) {
398             if (nodes == null) {
399                 throw new NullPointerException();
400             }
401
402             DFS dfs = new DFS(nodes);
403             return dfs.go();
404         }
405
406         private boolean go() {
407             Iterator i;
408             time = 0;
409             boolean acyclic=true;
410             i = nodes.iterator();
411             while (i.hasNext()) {
412                 GraphNode gn = (GraphNode) i.next();
413                 gn.reset();
414             }
415
416             i = nodes.iterator();
417             while (i.hasNext()) {
418                 GraphNode gn = (GraphNode) i.next();
419                 assert gn.getStatus() != PROCESSING;
420                 if (gn.getStatus() == UNVISITED) {
421                     if (!dfs(gn))
422                         acyclic=false;
423                 }
424             }
425             return acyclic;
426         }
427
428         private boolean dfs(GraphNode gn) {
429             boolean acyclic=true;
430             gn.discover(time++);
431             Iterator edges = gn.edges();
432
433             while (edges.hasNext()) {
434                 Edge edge = (Edge) edges.next();
435                 GraphNode node = edge.getTarget();
436                 if (!nodes.contains(node)) /* Skip nodes which aren't in the set */
437                     continue;
438                 if (node.getStatus() == UNVISITED) {
439                     if (!dfs(node))
440                         acyclic=false;
441                 } else if (node.getStatus()==PROCESSING) {
442                     acyclic=false;
443                 }
444             }
445             if (finishingorder!=null)
446                 finishingorder.add(gn);
447             gn.finish(time++);
448             return acyclic;
449         }
450
451     } /* end DFS */
452
453 }