summaryrefslogtreecommitdiff
path: root/Source/Core/GraphAlgorithms.cs
blob: a19cf96caa6956ce354a7e1a9346e37a31ff6da4 (plain)
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
//-----------------------------------------------------------------------------
//
// Copyright (C) Microsoft Corporation.  All Rights Reserved.
//
//-----------------------------------------------------------------------------
using System.Collections.Generic;
using System.Diagnostics.Contracts;

namespace Microsoft.Boogie {
  public delegate System.Collections.IEnumerable/*<Node!>*//*!*/ Adjacency<T>(T/*!*/ node);


  // An SCC is a set of nodes
  public sealed class SCC<Node> : ICollection<Node> {
    [ContractInvariantMethod]
    void ObjectInvariant() {
      Contract.Invariant(nodesMap != null);
    }

    private IDictionary<Node, object>/*!*/ nodesMap = new Dictionary<Node, object>();
    private ICollection<Node>/*!*/ nodes {
      get {
        return cce.NonNull(nodesMap.Keys);
      }
    }

    [Pure]
    [GlobalAccess(false)]
    [Escapes(true, false)]
    System.Collections.IEnumerator/*!*/ System.Collections.IEnumerable.GetEnumerator() {
      Contract.Ensures(Contract.Result<System.Collections.IEnumerator>() != null);

      return ((System.Collections.IEnumerable)nodes).GetEnumerator();
    }

    [Pure]
    [GlobalAccess(false)]
    [Escapes(true, false)]
    IEnumerator<Node>/*!*/ IEnumerable<Node>.GetEnumerator() {
      Contract.Ensures(Contract.Result<IEnumerator<Node>>() != null);

      return ((IEnumerable<Node>)nodes).GetEnumerator();
    }

    public int Count {
      get {
        return nodes.Count;
      }
    }
    public bool IsReadOnly {
      get {
        return nodesMap.IsReadOnly;
      }
    }
    public void Add(Node item) {
      nodesMap.Add(item, null);
    }
    public void Clear() {
      nodesMap.Clear();
    }
    [Pure]
    public bool Contains(Node item) {
      return nodesMap.ContainsKey(item);
    }
    public void CopyTo(Node[] array, int arrayIndex) {
      //Contract.Requires(array != null);
      nodes.CopyTo(array, arrayIndex);
    }
    public bool Remove(Node item) {
      return nodesMap.Remove(item);
    }
  }

  public sealed class StronglyConnectedComponents<Node> : IEnumerable<SCC<Node>/*!*/> where Node : class {
    private readonly IDictionary<Node/*!*/, object>/*!*/ graph;
    [ContractInvariantMethod]
    void graphInvariantMethod() {
      Contract.Invariant(Contract.ForAll(graph, entry => entry.Key != null));
      Contract.Invariant(preds != null);
      Contract.Invariant(succs != null);
    }
    private readonly Adjacency<Node>/*!*/ preds;
    private readonly Adjacency<Node>/*!*/ succs;

    private bool computed = false;
    public bool Computed {
      get {
        return computed;
      }
    }

    [NotDelayed]
    public StronglyConnectedComponents(System.Collections.IEnumerable/*<Node!>*/ graph, Adjacency<Node> preds, Adjacency<Node> succs)
      : base() {//BASEMOVE DANGER
      Contract.Requires(succs != null);
      Contract.Requires(preds != null);
      Contract.Requires(graph != null);
      Contract.Ensures(!Computed);
      IDictionary<Node/*!*/, object>/*!*/ dict = new Dictionary<Node/*!*/, object>();
      foreach (Node/*!*/ n in graph) {
        Contract.Assert(n != null);
        dict.Add(n, null);
      }

      this.graph = dict;
      this.preds = preds;
      this.succs = succs;
      //:base();
    }

    [Pure]
    [GlobalAccess(false)]
    [Escapes(true, false)]
    System.Collections.IEnumerator/*!*/ System.Collections.IEnumerable.GetEnumerator() {
      Contract.Ensures(Contract.Result<System.Collections.IEnumerator>() != null);

      return ((System.Collections.IEnumerable)sccs).GetEnumerator();
    }

    [Pure]
    [GlobalAccess(false)]
    [Escapes(true, false)]
    IEnumerator<SCC<Node>/*!*/>/*!*/ IEnumerable<SCC<Node>/*!*/>.GetEnumerator() {
      Contract.Ensures(Contract.Result<IEnumerator<SCC<Node>>>() != null);

      Contract.Assume(Computed);
      Contract.Assert(cce.NonNullElements((IEnumerable<SCC<Node>/*!*/>)sccs));//REVIEW
      return ((IEnumerable<SCC<Node>/*!*/>)sccs).GetEnumerator();
    }

    private readonly IList<SCC<Node>/*!*/>/*!*/ sccs = new List<SCC<Node>/*!*/>();
    [ContractInvariantMethod]
    void sccsInvariant() {
      Contract.Invariant(cce.NonNullElements(sccs));
    }


    public void Compute() {
      Contract.Requires(!Computed);
      Contract.Ensures(Computed);
      // Compute post times on graph with edges reversed
      this.dfsNext = this.preds;
      foreach (Node/*!*/ n in cce.NonNull(graph.Keys)) {
        Contract.Assert(n != null);
        if (!seen.ContainsKey(n)) {
          OrderNodes(n);
        }
      }

      // Clear seen
      seen.Clear();

      // Compute SCCs
      this.dfsNext = this.succs;
      while (postOrder.Count > 0) {
        Node/*!*/ n = postOrder.Pop();
        Contract.Assert(n != null);

        if (!seen.ContainsKey(n)) {
          SCC<Node>/*!*/ curr = new SCC<Node>();
          FindSCCs(n, curr);
          sccs.Add(curr);
        }
      }

      // Clear seen
      seen.Clear();

      this.computed = true;
    }

    private Adjacency<Node>/*?*/ dfsNext = null;

    private readonly IDictionary<Node/*!*/, object>/*!*/ seen = new Dictionary<Node/*!*/, object>();
    private readonly Stack<Node/*!*/>/*!*/ postOrder = new Stack<Node/*!*/>();
    [ContractInvariantMethod]
    void ObjectInvariant() {
      Contract.Invariant(seen != null);
      Contract.Invariant(cce.NonNullElements(postOrder));
    }


    // DFS to order nodes by post times
    private void OrderNodes(Node node) {
      Contract.Requires(node != null);
      seen.Add(node, null);

      Contract.Assert(dfsNext != null);
      System.Collections.IEnumerable/*!*/ nexts = dfsNext(node);
      Contract.Assert(nexts != null);
      foreach (Node/*!*/ n in nexts) {
        Contract.Assert(n != null);
        if (graph.ContainsKey(n) && !seen.ContainsKey(n)) {
          OrderNodes(n);
        }
      }

      postOrder.Push(node);
    }

    // DFS to compute SCCs
    private void FindSCCs(Node node, SCC<Node> currSCC) {
      Contract.Requires(currSCC != null);
      Contract.Requires(node != null);
      //modifies currSCC.*;
      seen.Add(node, null);
      currSCC.Add(node);

      Contract.Assert(dfsNext != null);
      System.Collections.IEnumerable/*!*/ nexts = dfsNext(node);
      Contract.Assert(nexts != null);
      foreach (Node/*!*/ n in nexts) {
        Contract.Assert(n != null);
        if (graph.ContainsKey(n) && !seen.ContainsKey(n)) {
          FindSCCs(n, currSCC);
        }
      }
    }

    [Pure]
    public override string ToString() {
      Contract.Ensures(Contract.Result<string>() != null);
      string outStr = "";
      int i = 0;

      foreach (ICollection<Node> component in this) {
        string/*!*/ tmp = System.String.Format("\nComponent #{0} = ", i++);
        Contract.Assert(tmp != null);
        outStr += tmp;

        bool firstInRow = true;

        foreach (Node b in component) {
          string/*!*/ tmpComponent = System.String.Format("{0}{1}", firstInRow ? "" : ", ", b);
          Contract.Assert(tmpComponent != null);
          outStr += tmpComponent;
          firstInRow = false;
        }
      }
      return outStr;
    }

  }
}