graph.scm 13 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376
  1. ;;; GNU Guix --- Functional package management for GNU
  2. ;;; Copyright © 2015, 2016, 2020, 2021 Ludovic Courtès <ludo@gnu.org>
  3. ;;; Copyright © 2016 Ricardo Wurmus <rekado@elephly.net>
  4. ;;;
  5. ;;; This file is part of GNU Guix.
  6. ;;;
  7. ;;; GNU Guix is free software; you can redistribute it and/or modify it
  8. ;;; under the terms of the GNU General Public License as published by
  9. ;;; the Free Software Foundation; either version 3 of the License, or (at
  10. ;;; your option) any later version.
  11. ;;;
  12. ;;; GNU Guix is distributed in the hope that it will be useful, but
  13. ;;; WITHOUT ANY WARRANTY; without even the implied warranty of
  14. ;;; MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
  15. ;;; GNU General Public License for more details.
  16. ;;;
  17. ;;; You should have received a copy of the GNU General Public License
  18. ;;; along with GNU Guix. If not, see <http://www.gnu.org/licenses/>.
  19. (define-module (guix graph)
  20. #:use-module (guix store)
  21. #:use-module (guix monads)
  22. #:use-module (guix records)
  23. #:use-module (guix sets)
  24. #:use-module (rnrs io ports)
  25. #:use-module (srfi srfi-1)
  26. #:use-module (srfi srfi-9)
  27. #:use-module (srfi srfi-26)
  28. #:use-module (ice-9 match)
  29. #:use-module (ice-9 vlist)
  30. #:export (node-type
  31. node-type?
  32. node-type-identifier
  33. node-type-label
  34. node-type-edges
  35. node-type-convert
  36. node-type-name
  37. node-type-description
  38. node-edges
  39. node-back-edges
  40. traverse/depth-first
  41. node-transitive-edges
  42. node-reachable-count
  43. shortest-path
  44. %graph-backends
  45. %d3js-backend
  46. %graphviz-backend
  47. graph-backend?
  48. graph-backend
  49. graph-backend-name
  50. graph-backend-description
  51. export-graph))
  52. ;;; Commentary:
  53. ;;;
  54. ;;; This module provides an abstract way to represent graphs and to manipulate
  55. ;;; them. It comes with several such representations for packages,
  56. ;;; derivations, and store items. It also provides a generic interface for
  57. ;;; exporting graphs in an external format, including a Graphviz
  58. ;;; implementation thereof.
  59. ;;;
  60. ;;; Code:
  61. ;;;
  62. ;;; Node types.
  63. ;;;
  64. (define-record-type* <node-type> node-type make-node-type
  65. node-type?
  66. (identifier node-type-identifier) ;node -> M identifier
  67. (label node-type-label) ;node -> string
  68. (edges node-type-edges) ;node -> M list of nodes
  69. (convert node-type-convert ;any -> M list of nodes
  70. (default (lift1 list %store-monad)))
  71. (name node-type-name) ;string
  72. (description node-type-description)) ;string
  73. (define (%node-edges type nodes cons-edge)
  74. (with-monad %store-monad
  75. (match type
  76. (($ <node-type> identifier label node-edges)
  77. (define (add-edge node edges)
  78. (>>= (node-edges node)
  79. (lambda (nodes)
  80. (return (fold (cut cons-edge node <> <>)
  81. edges nodes)))))
  82. (mlet %store-monad ((edges (foldm %store-monad
  83. add-edge vlist-null nodes)))
  84. (return (lambda (node)
  85. (reverse (vhash-foldq* cons '() node edges)))))))))
  86. (define (node-edges type nodes)
  87. "Return, as a monadic value, a one-argument procedure that, given a node of TYPE,
  88. returns its edges. NODES is taken to be the sinks of the global graph."
  89. (%node-edges type nodes
  90. (lambda (source target edges)
  91. (vhash-consq source target edges))))
  92. (define (node-back-edges type nodes)
  93. "Return, as a monadic value, a one-argument procedure that, given a node of TYPE,
  94. returns its back edges. NODES is taken to be the sinks of the global graph."
  95. (%node-edges type nodes
  96. (lambda (source target edges)
  97. (vhash-consq target source edges))))
  98. (define (traverse/depth-first proc seed nodes node-edges)
  99. "Do a depth-first traversal of NODES along NODE-EDGES, calling PROC with
  100. each node and the current result, and visiting each reachable node exactly
  101. once. NODES must be a list of nodes, and NODE-EDGES must be a one-argument
  102. procedure as returned by 'node-edges' or 'node-back-edges'."
  103. (let loop ((nodes (append-map node-edges nodes))
  104. (result seed)
  105. (visited (setq)))
  106. (match nodes
  107. (()
  108. result)
  109. ((head . tail)
  110. (if (set-contains? visited head)
  111. (loop tail result visited)
  112. (let ((edges (node-edges head)))
  113. (loop (append edges tail)
  114. (proc head result)
  115. (set-insert head visited))))))))
  116. (define (node-transitive-edges nodes node-edges)
  117. "Return the list of nodes directly or indirectly connected to NODES
  118. according to the NODE-EDGES procedure. NODE-EDGES must be a one-argument
  119. procedure that, given a node, returns its list of direct dependents; it is
  120. typically returned by 'node-edges' or 'node-back-edges'."
  121. (traverse/depth-first cons '() nodes node-edges))
  122. (define (node-reachable-count nodes node-edges)
  123. "Return the number of nodes reachable from NODES along NODE-EDGES."
  124. (traverse/depth-first (lambda (_ count)
  125. (+ 1 count))
  126. 0
  127. nodes node-edges))
  128. (define (shortest-path node1 node2 type)
  129. "Return as a monadic value the shortest path, represented as a list, from
  130. NODE1 to NODE2 of the given TYPE. Return #f when there is no path."
  131. (define node-edges
  132. (node-type-edges type))
  133. (define (find-shortest lst)
  134. ;; Return the shortest path among LST, where each path is represented as a
  135. ;; vlist.
  136. (let loop ((lst lst)
  137. (best +inf.0)
  138. (shortest #f))
  139. (match lst
  140. (()
  141. shortest)
  142. ((head . tail)
  143. (let ((len (vlist-length head)))
  144. (if (< len best)
  145. (loop tail len head)
  146. (loop tail best shortest)))))))
  147. (define (find-path node path paths)
  148. ;; Return the a vhash that maps nodes to paths, with each path from the
  149. ;; given node to NODE2.
  150. (define (augment-paths child paths)
  151. ;; When using %REFERENCE-NODE-TYPE, nodes can contain self references,
  152. ;; hence this test.
  153. (if (eq? child node)
  154. (store-return paths)
  155. (find-path child vlist-null paths)))
  156. (cond ((eq? node node2)
  157. (store-return (vhash-consq node (vlist-cons node path)
  158. paths)))
  159. ((vhash-assq node paths)
  160. (store-return paths))
  161. (else
  162. ;; XXX: We could stop recursing if one if CHILDREN is NODE2, but in
  163. ;; practice it's good enough.
  164. (mlet* %store-monad ((children (node-edges node))
  165. (paths (foldm %store-monad
  166. augment-paths
  167. paths
  168. children)))
  169. (define sub-paths
  170. (filter-map (lambda (child)
  171. (match (vhash-assq child paths)
  172. (#f #f)
  173. ((_ . path) path)))
  174. children))
  175. (match sub-paths
  176. (()
  177. (return (vhash-consq node #f paths)))
  178. (lst
  179. (return (vhash-consq node
  180. (vlist-cons node (find-shortest sub-paths))
  181. paths))))))))
  182. (mlet %store-monad ((paths (find-path node1
  183. (vlist-cons node1 vlist-null)
  184. vlist-null)))
  185. (return (match (vhash-assq node1 paths)
  186. ((_ . #f) #f)
  187. ((_ . path) (vlist->list path))))))
  188. ;;;
  189. ;;; Graphviz export.
  190. ;;;
  191. (define-record-type <graph-backend>
  192. (graph-backend name description prologue epilogue node edge)
  193. graph-backend?
  194. (name graph-backend-name)
  195. (description graph-backend-description)
  196. (prologue graph-backend-prologue)
  197. (epilogue graph-backend-epilogue)
  198. (node graph-backend-node)
  199. (edge graph-backend-edge))
  200. (define %colors
  201. ;; See colortbl.h in Graphviz.
  202. #("red" "magenta" "blue" "cyan3" "darkseagreen"
  203. "peachpuff4" "darkviolet" "dimgrey" "darkgoldenrod"))
  204. (define (pop-color hint)
  205. "Return a Graphviz color based on HINT, an arbitrary object."
  206. (let ((index (hash hint (vector-length %colors))))
  207. (vector-ref %colors index)))
  208. (define (emit-prologue name port)
  209. (format port "digraph \"Guix ~a\" {\n"
  210. name))
  211. (define (emit-epilogue port)
  212. (display "\n}\n" port))
  213. (define (emit-node id label port)
  214. (format port " \"~a\" [label = \"~a\", shape = box, fontname = sans];~%"
  215. id label))
  216. (define (emit-edge id1 id2 port)
  217. (format port " \"~a\" -> \"~a\" [color = ~a];~%"
  218. id1 id2 (pop-color id1)))
  219. (define %graphviz-backend
  220. (graph-backend "graphviz"
  221. "Generate graph in DOT format for use with Graphviz."
  222. emit-prologue emit-epilogue
  223. emit-node emit-edge))
  224. ;;;
  225. ;;; d3js export.
  226. ;;;
  227. (define (emit-d3js-prologue name port)
  228. (format port "\
  229. <!DOCTYPE html>
  230. <html>
  231. <head>
  232. <meta charset=\"utf-8\">
  233. <style>
  234. text {
  235. font: 10px sans-serif;
  236. pointer-events: none;
  237. }
  238. </style>
  239. <script type=\"text/javascript\" src=\"~a\"></script>
  240. </head>
  241. <body>
  242. <script type=\"text/javascript\">
  243. var nodes = {},
  244. nodeArray = [],
  245. links = [];
  246. " (search-path %load-path "guix/d3.v3.js")))
  247. (define (emit-d3js-epilogue port)
  248. (format port "</script><script type=\"text/javascript\" src=\"~a\"></script></body></html>"
  249. (search-path %load-path "guix/graph.js")))
  250. (define (emit-d3js-node id label port)
  251. (format port "\
  252. nodes[\"~a\"] = {\"id\": \"~a\", \"label\": \"~a\", \"index\": nodeArray.length};
  253. nodeArray.push(nodes[\"~a\"]);~%"
  254. id id label id))
  255. (define (emit-d3js-edge id1 id2 port)
  256. (format port "links.push({\"source\": \"~a\", \"target\": \"~a\"});~%"
  257. id1 id2))
  258. (define %d3js-backend
  259. (graph-backend "d3js"
  260. "Generate chord diagrams with d3js."
  261. emit-d3js-prologue emit-d3js-epilogue
  262. emit-d3js-node emit-d3js-edge))
  263. ;;;
  264. ;;; Cypher export.
  265. ;;;
  266. (define (emit-cypher-prologue name port)
  267. (format port ""))
  268. (define (emit-cypher-epilogue port)
  269. (format port ""))
  270. (define (emit-cypher-node id label port)
  271. (format port "MERGE (p:Package { id: ~s }) SET p.name = ~s;~%"
  272. id label ))
  273. (define (emit-cypher-edge id1 id2 port)
  274. (format port "MERGE (a:Package { id: ~s });~%" id1)
  275. (format port "MERGE (b:Package { id: ~s });~%" id2)
  276. (format port "MATCH (a:Package { id: ~s }), (b:Package { id: ~s }) CREATE UNIQUE (a)-[:NEEDS]->(b);~%"
  277. id1 id2))
  278. (define %cypher-backend
  279. (graph-backend "cypher"
  280. "Generate Cypher queries."
  281. emit-cypher-prologue emit-cypher-epilogue
  282. emit-cypher-node emit-cypher-edge))
  283. ;;;
  284. ;;; Shared.
  285. ;;;
  286. (define %graph-backends
  287. (list %graphviz-backend
  288. %d3js-backend
  289. %cypher-backend))
  290. (define* (export-graph sinks port
  291. #:key
  292. reverse-edges? node-type
  293. (backend %graphviz-backend))
  294. "Write to PORT the representation of the DAG with the given SINKS, using the
  295. given BACKEND. Use NODE-TYPE to traverse the DAG. When REVERSE-EDGES? is
  296. true, draw reverse arrows."
  297. (match backend
  298. (($ <graph-backend> _ _ emit-prologue emit-epilogue emit-node emit-edge)
  299. (emit-prologue (node-type-name node-type) port)
  300. (match node-type
  301. (($ <node-type> node-identifier node-label node-edges)
  302. (let loop ((nodes sinks)
  303. (visited (set)))
  304. (match nodes
  305. (()
  306. (with-monad %store-monad
  307. (emit-epilogue port)
  308. (store-return #t)))
  309. ((head . tail)
  310. (mlet %store-monad ((id (node-identifier head)))
  311. (if (set-contains? visited id)
  312. (loop tail visited)
  313. (mlet* %store-monad ((dependencies (node-edges head))
  314. (ids (mapm %store-monad
  315. node-identifier
  316. dependencies)))
  317. (emit-node id (node-label head) port)
  318. (for-each (lambda (dependency dependency-id)
  319. (if reverse-edges?
  320. (emit-edge dependency-id id port)
  321. (emit-edge id dependency-id port)))
  322. dependencies ids)
  323. (loop (append dependencies tail)
  324. (set-insert id visited)))))))))))))
  325. ;;; graph.scm ends here