graph.scm 14 KB

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