-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathGraph.elm
More file actions
645 lines (450 loc) · 18 KB
/
Graph.elm
File metadata and controls
645 lines (450 loc) · 18 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
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
module Data.Graph exposing
( Graph, Bounds, Edge, Vertex, Table
, graphFromEdges, graphFromEdges_, buildG
, vertices, edges, outdegree, indegree
, transposeG
, dfs, dff, scc
, SCC(..)
, stronglyConnComp, stronglyConnCompR
, flattenSCC, flattenSCCs
, Array
)
{-| An Elm graph type implementation, inspired by Haskell's Data.Graph.
Reference: <https://hackage.haskell.org/package/containers-0.7/docs/src/Data.Graph.html>
This implementation attempts to adapt the concepts and structure from the
Haskell Graph into the Elm ecosystem.
# Graphs
@docs Graph, Bounds, Edge, Vertex, Table
# Graph Construction
@docs graphFromEdges, graphFromEdges_, buildG
# Graph Properties
@docs vertices, edges, outdegree, indegree
# Graph Transformations
@docs transposeG
# Graph Algorithms
@docs dfs, dff, scc
# Strongly Connected Components
@docs SCC
## Construction
@docs stronglyConnComp, stronglyConnCompR
## Conversion
@docs flattenSCC, flattenSCCs
## Array
@docs Array
-}
import Basics.Extra exposing (flip)
import Data.Graph.Internal as Internal
import Dict
import Set exposing (Set)
import Tree exposing (Tree)
{-| Array structure
-}
type alias Array i e =
Internal.Array i e
-------------------------------------------------------------------------
-- -
-- Strongly Connected Components
-- -
-------------------------------------------------------------------------
{-| Strongly connected component.
-}
type SCC vertex
= AcyclicSCC vertex
| CyclicSCC (List vertex)
{-| The vertices of a list of strongly connected components.
-}
flattenSCCs : List (SCC a) -> List a
flattenSCCs =
List.concatMap flattenSCC
{-| The vertices of a strongly connected component.
-}
flattenSCC : SCC vertex -> List vertex
flattenSCC component =
case component of
AcyclicSCC v ->
[ v ]
CyclicSCC vs ->
vs
{-| The strongly connected components of a directed graph,
reverse topologically sorted.
stronglyConnComp [ ( "a", 0, [ 1 ] ), ( "b", 1, [ 2, 3 ] ), ( "c", 2, [ 1 ] ), ( "d", 3, [ 3 ] ) ]
== [ CyclicSCC [ "d" ], CyclicSCC [ "b", "c" ], AcyclicSCC "a" ]
-}
stronglyConnComp : List ( node, comparable, List comparable ) -> List (SCC node)
stronglyConnComp edges0 =
List.map
(\edge0 ->
case edge0 of
AcyclicSCC ( n, _, _ ) ->
AcyclicSCC n
CyclicSCC triples ->
CyclicSCC (List.map (\( n, _, _ ) -> n) triples)
)
(stronglyConnCompR edges0)
{-| The strongly connected components of a directed graph,
reverse topologically sorted. The function is the same as
'stronglyConnComp', except that all the information about each node retained.
This interface is used when you expect to apply 'SCC' to
(some of) the result of 'SCC', so you don't want to lose the
dependency information.
stronglyConnCompR [ ( "a", 0, [ 1 ] ), ( "b", 1, [ 2, 3 ] ), ( "c", 2, [ 1 ] ), ( "d", 3, [ 3 ] ) ]
== [ CyclicSCC [ ( "d", 3, [ 3 ] ) ], CyclicSCC [ ( "b", 1, [ 2, 3 ] ), ( "c", 2, [ 1 ] ) ], AcyclicSCC ( "a", 0, [ 1 ] ) ]
-}
stronglyConnCompR : List ( node, comparable, List comparable ) -> List (SCC ( node, comparable, List comparable ))
stronglyConnCompR edges0 =
case edges0 of
[] ->
[]
_ ->
let
( graph, vertexFn, _ ) =
graphFromEdges edges0
forest : List (Tree Vertex)
forest =
scc graph
decode : Tree Vertex -> SCC ( node, comparable, List comparable )
decode tree =
let
v : Vertex
v =
Tree.label tree
in
case ( Tree.children tree, mentionsItself v, vertexFn v ) of
( [], True, _ ) ->
CyclicSCC (List.filterMap identity [ vertexFn v ])
( [], False, Just vertex ) ->
AcyclicSCC vertex
( ts, _, _ ) ->
CyclicSCC (List.filterMap identity (vertexFn v :: List.foldr dec [] ts))
dec : Tree Vertex -> List (Maybe ( node, comparable, List comparable )) -> List (Maybe ( node, comparable, List comparable ))
dec node vs =
vertexFn (Tree.label node) :: List.foldr dec vs (Tree.children node)
mentionsItself : Int -> Bool
mentionsItself v =
List.member v (Maybe.withDefault [] (Internal.find v graph))
in
List.map decode forest
-------------------------------------------------------------------------
-- -
-- Graphs
-- -
-------------------------------------------------------------------------
{-| Abstract representation of vertices.
-}
type alias Vertex =
Int
{-| Table indexed by a contiguous set of vertices.
-}
type alias Table a =
Array Vertex a
{-| Adjacency list representation of a graph, mapping each vertex to its
list of successors.
-}
type alias Graph =
Array Vertex (List Vertex)
{-| The bounds of an @Array@.
-}
type alias Bounds =
( Vertex, Vertex )
{-| An edge from the first vertex to the second.
-}
type alias Edge =
( Vertex, Vertex )
{-| (O(V)). Returns the list of vertices in the graph.
==== **Examples**
> vertices (buildG (0,-1) []) == []
> vertices (buildG (0,2) [(0,1),(1,2)]) == [0,1,2]
-}
vertices : Graph -> List Vertex
vertices =
Internal.indices
{-| (O(V+E)). Returns the list of edges in the graph.
==== **Examples**
> edges (buildG (0,-1) []) == []
> edges (buildG (0,2) [(0,1),(1,2)]) == [(0,1),(1,2)]
-}
edges : Graph -> List Edge
edges g =
List.concatMap (\v -> List.map (Tuple.pair v) (Maybe.withDefault [] (Internal.find v g))) (vertices g)
{-| (O(V+E)). Build a graph from a list of edges.
Warning: This function will cause a runtime exception if a vertex in the edge
list is not within the given @Bounds@.
==== **Examples**
> buildG (0,-1) [] == array (0,-1) []
> buildG (0,2) [(0,1), (1,2)] == array (0,2) [(0,[1]),(1,[2]),(2,[])]
> buildG (0,2) [(0,1), (0,2), (1,2)] == array (0,2) [(0,[2,1]),(1,[2]),(2,[])]
-}
buildG : Bounds -> List Edge -> Graph
buildG =
Internal.accumArray (flip (::)) []
{-| (O(V+E)). The graph obtained by reversing all edges.
==== **Examples**
> transposeG (buildG (0,2) [(0,1), (1,2)]) == array (0,2) [(0,[]),(1,[0]),(2,[1])]
-}
transposeG : Graph -> Graph
transposeG g =
buildG (Internal.bounds g) (reverseE g)
reverseE : Graph -> List Edge
reverseE g =
List.map (\( v, w ) -> ( w, v )) (edges g)
{-| (O(V+E)). A table of the count of edges from each node.
==== **Examples**
> outdegree (buildG (0,-1) []) == array (0,-1) []
> outdegree (buildG (0,2) [(0,1), (1,2)]) == array (0,2) [(0,1),(1,1),(2,0)]
-}
outdegree : Graph -> Array Vertex Int
outdegree (Internal.Array l u arr) =
-- This is bizarrely lazy. We build an array filled with thunks, instead
-- of actually calculating anything. This is the historical behavior, and I
-- suppose someone *could* be relying on it, but it might be worth finding
-- out. Note that we *can't* be so lazy with indegree.
Internal.Array l u (Dict.map (\_ -> List.length) arr)
{-| (O(V+E)). A table of the count of edges into each node.
==== **Examples**
> indegree (buildG (0,-1) []) == array (0,-1) []
> indegree (buildG (0,2) [(0,1), (1,2)]) == array (0,2) [(0,0),(1,1),(2,1)]
-}
indegree : Graph -> Array Vertex Int
indegree g =
Internal.accumArray (+) 0 (Internal.bounds g) <|
List.concatMap (\( _, outs ) -> List.map (\v -> ( v, 1 )) (Maybe.withDefault [] outs)) (Internal.assocs g)
{-| (O((V+E) \\log V)). Identical to 'graphFromEdges', except that the return
value does not include the function which maps keys to vertices. This
version of 'graphFromEdges' is for backwards compatibility.
-}
graphFromEdges_ : List ( node, comparable, List comparable ) -> ( Graph, Vertex -> Maybe ( node, comparable, List comparable ) )
graphFromEdges_ x =
let
( a, b, _ ) =
graphFromEdges x
in
( a, b )
{-| (O((V+E) \\log V)). Build a graph from a list of nodes uniquely identified
by keys, with a list of keys of nodes this node should have edges to.
This function takes an adjacency list representing a graph with vertices of
type @key@ labeled by values of type @node@ and produces a @Graph@-based
representation of that list. The @Graph@ result represents the /shape/ of the
graph, and the functions describe a) how to retrieve the label and adjacent
vertices of a given vertex, and b) how to retrieve a vertex given a key.
@(graph, nodeFromVertex, vertexFromKey) = graphFromEdges edgeList@
- @graph :: Graph@ is the raw, array based adjacency list for the graph.
- @nodeFromVertex :: Vertex -> (node, key, [key])@ returns the node
associated with the given 0-based @Int@ vertex; see /warning/ below. This
runs in (O(1)) time.
- @vertexFromKey :: key -> Maybe Vertex@ returns the @Int@ vertex for the
key if it exists in the graph, @Nothing@ otherwise. This runs in
(O(\\log V)) time.
To safely use this API you must either extract the list of vertices directly
from the graph or first call @vertexFromKey k@ to check if a vertex
corresponds to the key @k@. Once it is known that a vertex exists you can use
@nodeFromVertex@ to access the labelled node and adjacent vertices. See below
for examples.
Note: The out-list may contain keys that don't correspond to nodes of the
graph; they are ignored.
Warning: The @nodeFromVertex@ function will cause a runtime exception if the
given @Vertex@ does not exist.
==== **Examples**
An empty graph.
> (graph, nodeFromVertex, vertexFromKey) = graphFromEdges []
> graph = array (0,-1) []
A graph where the out-list references unspecified nodes (@'c'@), these are
ignored.
> (graph, _, _) = graphFromEdges [("a", 'a', ['b']), ("b", 'b', ['c'])]
> array (0,1) [(0,[1]),(1,[])]
A graph with 3 vertices: ("a") -> ("b") -> ("c")
> (graph, nodeFromVertex, vertexFromKey) = graphFromEdges [("a", 'a', ['b']), ("b", 'b', ['c']), ("c", 'c', [])]
> graph == array (0,2) [(0,[1]),(1,[2]),(2,[])]
> nodeFromVertex 0 == Just ("a",'a',['b'])
> vertexFromKey 'a' == Just 0
Get the label for a given key.
> let getNodePart (n, _, _) = n
> (graph, nodeFromVertex, vertexFromKey) = graphFromEdges [("a", 'a', ['b']), ("b", 'b', ['c']), ("c", 'c', [])]
> Maybe.andThen (Maybe.map getNodePart << nodeFromVertex) (vertexFromKey 'a') == Just "A"
-}
graphFromEdges : List ( node, comparable, List comparable ) -> ( Graph, Vertex -> Maybe ( node, comparable, List comparable ), comparable -> Maybe Vertex )
graphFromEdges edges0 =
let
maxV : Int
maxV =
List.length edges0 - 1
bounds0 : ( number, Int )
bounds0 =
( 0, maxV )
sortedEdges : List ( node, comparable, List comparable )
sortedEdges =
List.sortWith (\( _, k1, _ ) ( _, k2, _ ) -> compare k1 k2) edges0
edges1 : List ( Int, ( node, comparable, List comparable ) )
edges1 =
List.map2 Tuple.pair
(List.indexedMap (\i _ -> i) (List.repeat (List.length sortedEdges) ()))
sortedEdges
graph : Array i (List Int)
graph =
edges1
|> List.map (\( v, ( _, _, ks ) ) -> ( v, List.filterMap keyVertex ks ))
|> Internal.array bounds0
keyMap : Array i comparable
keyMap =
edges1
|> List.map (\( v, ( _, k, _ ) ) -> ( v, k ))
|> Internal.array bounds0
vertexMap : Array i ( node, comparable, List comparable )
vertexMap =
Internal.array bounds0 edges1
keyVertex : comparable -> Maybe Int
keyVertex k =
let
findVertex : Int -> Int -> Maybe Int
findVertex a b =
if a > b then
Nothing
else
let
mid : Int
mid =
a + (b - a) // 2
in
Internal.find mid keyMap
|> Maybe.andThen
(\v ->
case compare k v of
LT ->
findVertex a (mid - 1)
EQ ->
Just mid
GT ->
findVertex (mid + 1) b
)
in
findVertex 0 maxV
in
( graph, \v -> Internal.find v vertexMap, keyVertex )
-------------------------------------------------------------------------
-- -
-- Depth first search
-- -
-------------------------------------------------------------------------
{-| (O(V+E)). A spanning forest of the graph, obtained from a depth-first
search of the graph starting from each vertex in an unspecified order.
-}
dff : Graph -> List (Tree Vertex)
dff g =
dfs g (vertices g)
{-| (O(V+E)). A spanning forest of the part of the graph reachable from the
listed vertices, obtained from a depth-first search of the graph starting at
each of the listed vertices in order.
This function deviates from King and Launchbury's implementation by
bundling together the functions generate, prune, and chop for efficiency
reasons.
-}
dfs : Graph -> List Vertex -> List (Tree Vertex)
dfs g vs0 =
let
go : List Vertex -> SetM (List (Tree Vertex))
go vrtcs =
loop goHelp ( vrtcs, identity )
goHelp : ( List Vertex, SetM (List (Tree Vertex)) -> SetM (List (Tree Vertex)) ) -> SetM (Step ( List Vertex, SetM (List (Tree Vertex)) -> SetM (List (Tree Vertex)) ) (List (Tree Vertex)))
goHelp ( vrtcs, cont ) =
case vrtcs of
[] ->
fmap Done <| cont <| pure []
v :: vs ->
contains v
|> bind
(\visited ->
if visited then
pure (Loop ( vs, cont ))
else
include v
|> bind
(\_ ->
pure
(Loop
( Maybe.withDefault [] (Internal.find v g)
, bind
(\subForest ->
go vs
|> fmap (\bs -> Tree.tree v subForest :: bs)
)
>> cont
)
)
)
)
in
run (Internal.bounds g) (go vs0)
-- #else /* !USE_ST_MONAD */
{-| Portable implementation using IntSet.
-}
type alias IntSet =
Set Int
type alias SetM a =
IntSet -> ( a, IntSet )
fmap : (a -> b) -> SetM a -> SetM b
fmap fn ma s0 =
let
( a, s1 ) =
ma s0
in
( fn a, s1 )
bind : (a -> SetM b) -> SetM a -> SetM b
bind f ma =
\s0 ->
let
( x, s1 ) =
ma s0
in
f x s1
pure : a -> SetM a
pure x =
\s -> ( x, s )
run : Bounds -> SetM a -> a
run _ act =
Tuple.first (act Set.empty)
contains : Vertex -> SetM Bool
contains v =
\m -> ( Set.member v m, m )
include : Vertex -> SetM ()
include v =
\m -> ( (), Set.insert v m )
-- LOOP
type Step state a
= Loop state
| Done a
loop : (state -> SetM (Step state a)) -> state -> SetM a
loop callback loopState state =
case callback loopState state of
( Loop newLoopState, newState ) ->
loop callback newLoopState newState
( Done a, newState ) ->
( a, newState )
-------------------------------------------------------------------------
-- -
-- Algorithms
-- -
-------------------------------------------------------------------------
--
------------------------------------------------------------
-- Algorithm 2: topological sorting
------------------------------------------------------------
postorder : Tree a -> List a -> List a
postorder node =
postorderF (Tree.children node) << (::) (Tree.label node)
postorderF : List (Tree a) -> List a -> List a
postorderF ts =
List.foldr (<<) identity <| List.map postorder ts
postOrd : Graph -> List Vertex
postOrd g =
postorderF (dff g) []
------------------------------------------------------------
-- Algorithm 3: connected components
------------------------------------------------------------
{-| The strongly connected components of a graph, in reverse topological order.
scc (buildG ( 0, 3 ) [ ( 3, 1 ), ( 1, 2 ), ( 2, 0 ), ( 0, 1 ) ])
== [ Tree.tree 0 [ Tree.tree 1 [ Tree.tree 2 [] ] ]
, Tree.tree 3 []
]
-}
scc : Graph -> List (Tree Vertex)
scc g =
dfs g (List.reverse (postOrd (transposeG g)))