graph.scm 14 KB

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