ob-julia.el 12 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333
  1. ;;; ob-julia.el --- org-babel functions for julia code evaluation -*- lexical-binding: t; -*-
  2. ;; Copyright (C) 2013-2022 Free Software Foundation, Inc.
  3. ;; Authors: G. Jay Kerns
  4. ;; Maintainer: Pedro Bruel <pedro.bruel@gmail.com>
  5. ;; Keywords: literate programming, reproducible research, scientific computing
  6. ;; Homepage: https://github.com/phrb/ob-julia
  7. ;; This file is part of GNU Emacs.
  8. ;; GNU Emacs is free software: you can redistribute it and/or modify
  9. ;; it under the terms of the GNU General Public License as published by
  10. ;; the Free Software Foundation, either version 3 of the License, or
  11. ;; (at your option) any later version.
  12. ;; GNU Emacs is distributed in the hope that it will be useful,
  13. ;; but 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. ;; You should have received a copy of the GNU General Public License
  17. ;; along with GNU Emacs. If not, see <https://www.gnu.org/licenses/>.
  18. ;;; Commentary:
  19. ;; Org-Babel support for evaluating julia code
  20. ;;
  21. ;; Based on ob-R.el by Eric Schulte and Dan Davison.
  22. ;;; Code:
  23. (require 'cl-lib)
  24. (require 'ob)
  25. (declare-function orgtbl-to-csv "org-table" (table params))
  26. (declare-function julia "ext:ess-julia" (&optional start-args))
  27. (declare-function inferior-ess-send-input "ext:ess-inf" ())
  28. (declare-function ess-make-buffer-current "ext:ess-inf" ())
  29. (declare-function ess-eval-buffer "ext:ess-inf" (vis))
  30. (declare-function ess-wait-for-process "ext:ess-inf"
  31. (&optional proc sec-prompt wait force-redisplay))
  32. (defvar org-babel-header-args:julia
  33. '((width . :any)
  34. (horizontal . :any)
  35. (results . ((file list vector table scalar verbatim)
  36. (raw org html latex code pp wrap)
  37. (replace silent append prepend)
  38. (output value graphics))))
  39. "Julia-specific header arguments.")
  40. (add-to-list 'org-babel-tangle-lang-exts '("julia" . "jl"))
  41. (defvar org-babel-default-header-args:julia '())
  42. (defcustom org-babel-julia-command "julia"
  43. "Name of command to use for executing julia code."
  44. :version "24.3"
  45. :package-version '(Org . "8.0")
  46. :group 'org-babel
  47. :type 'string)
  48. (defvar ess-current-process-name) ; dynamically scoped
  49. (defvar ess-local-process-name) ; dynamically scoped
  50. (defvar ess-eval-visibly-p) ; dynamically scoped
  51. (defun org-babel-edit-prep:julia (info)
  52. (let ((session (cdr (assq :session (nth 2 info)))))
  53. (when (and session
  54. (string-prefix-p "*" session)
  55. (string-suffix-p "*" session))
  56. (org-babel-julia-initiate-session session nil))))
  57. (defun org-babel-expand-body:julia (body params &optional _graphics-file)
  58. "Expand BODY according to PARAMS, return the expanded body."
  59. (mapconcat #'identity
  60. (append
  61. (when (cdr (assq :prologue params))
  62. (list (cdr (assq :prologue params))))
  63. (org-babel-variable-assignments:julia params)
  64. (list body)
  65. (when (cdr (assq :epilogue params))
  66. (list (cdr (assq :epilogue params)))))
  67. "\n"))
  68. (defun org-babel-execute:julia (body params)
  69. "Execute a block of julia code.
  70. This function is called by `org-babel-execute-src-block'."
  71. (save-excursion
  72. (let* ((result-params (cdr (assq :result-params params)))
  73. (result-type (cdr (assq :result-type params)))
  74. (session (org-babel-julia-initiate-session
  75. (cdr (assq :session params)) params))
  76. (graphics-file (and (member "graphics" (assq :result-params params))
  77. (org-babel-graphical-output-file params)))
  78. (colnames-p (unless graphics-file (cdr (assq :colnames params))))
  79. (full-body (org-babel-expand-body:julia body params graphics-file))
  80. (result
  81. (org-babel-julia-evaluate
  82. session full-body result-type result-params
  83. (or (equal "yes" colnames-p)
  84. (org-babel-pick-name
  85. (cdr (assq :colname-names params)) colnames-p)))))
  86. (if graphics-file nil result))))
  87. (defun org-babel-normalize-newline (result)
  88. (replace-regexp-in-string
  89. "\\(\n\r?\\)\\{2,\\}"
  90. "\n"
  91. result))
  92. (defun org-babel-prep-session:julia (session params)
  93. "Prepare SESSION according to the header arguments specified in PARAMS."
  94. (let* ((session (org-babel-julia-initiate-session session params))
  95. (var-lines (org-babel-variable-assignments:julia params)))
  96. (org-babel-comint-in-buffer session
  97. (mapc (lambda (var)
  98. (end-of-line 1) (insert var) (comint-send-input nil t)
  99. (org-babel-comint-wait-for-output session)) var-lines))
  100. session))
  101. (defun org-babel-load-session:julia (session body params)
  102. "Load BODY into SESSION."
  103. (save-window-excursion
  104. (let ((buffer (org-babel-prep-session:julia session params)))
  105. (with-current-buffer buffer
  106. (goto-char (process-mark (get-buffer-process (current-buffer))))
  107. (insert (org-babel-chomp body)))
  108. buffer)))
  109. ;; helper functions
  110. (defun org-babel-variable-assignments:julia (params)
  111. "Return list of julia statements assigning the block's variables."
  112. (let ((vars (org-babel--get-vars params)))
  113. (mapcar
  114. (lambda (pair) (org-babel-julia-assign-elisp (car pair) (cdr pair)))
  115. (mapcar
  116. (lambda (i)
  117. (cons (car (nth i vars))
  118. (org-babel-reassemble-table
  119. (cdr (nth i vars))
  120. (cdr (nth i (cdr (assq :colname-names params))))
  121. (cdr (nth i (cdr (assq :rowname-names params)))))))
  122. (number-sequence 0 (1- (length vars)))))))
  123. (defun org-babel-julia-quote-csv-field (s)
  124. "Quote field S for export to julia."
  125. (if (stringp s)
  126. (concat "\"" (mapconcat #'identity (split-string s "\"") "\"\"") "\"")
  127. (format "%S" s)))
  128. (defun org-babel-julia-assign-elisp (name value)
  129. "Construct julia code assigning the elisp VALUE to a variable named NAME."
  130. (if (listp value)
  131. (let* ((lengths (mapcar #'length (cl-remove-if-not #'sequencep value)))
  132. (max (if lengths (apply #'max lengths) 0))
  133. (min (if lengths (apply #'min lengths) 0)))
  134. ;; Ensure VALUE has an orgtbl structure (depth of at least 2).
  135. (unless (listp (car value)) (setq value (list value)))
  136. (let ((file (orgtbl-to-csv value '(:fmt org-babel-julia-quote-csv-field))))
  137. (if (= max min)
  138. (format "%s = begin
  139. using CSV
  140. CSV.read(\"%s\")
  141. end" name file)
  142. (format "%s = begin
  143. using CSV
  144. CSV.read(\"%s\")
  145. end"
  146. name file))))
  147. (format "%s = %s" name (org-babel-julia-quote-csv-field value))))
  148. (defvar ess-ask-for-ess-directory) ; dynamically scoped
  149. (defun org-babel-julia-initiate-session (session params)
  150. "If there is not a current julia process then create one."
  151. (unless (string= session "none")
  152. (let ((session (or session "*Julia*"))
  153. (ess-ask-for-ess-directory
  154. (and (bound-and-true-p ess-ask-for-ess-directory)
  155. (not (cdr (assq :dir params))))))
  156. (if (org-babel-comint-buffer-livep session)
  157. session
  158. ;; FIXME: Depending on `display-buffer-alist', (julia) may end up
  159. ;; popping up a new frame which `save-window-excursion' won't be able
  160. ;; to "undo", so we really should call a kind of
  161. ;; `julia-no-select' instead so we don't need to undo any
  162. ;; window-changes afterwards.
  163. (save-window-excursion
  164. (when (get-buffer session)
  165. ;; Session buffer exists, but with dead process
  166. (set-buffer session))
  167. (require 'ess) (set-buffer (julia))
  168. (rename-buffer
  169. (if (bufferp session)
  170. (buffer-name session)
  171. (if (stringp session)
  172. session
  173. (buffer-name))))
  174. (current-buffer))))))
  175. (defun org-babel-julia-graphical-output-file (params)
  176. "Name of file to which julia should send graphical output."
  177. (and (member "graphics" (cdr (assq :result-params params)))
  178. (cdr (assq :file params))))
  179. (defconst org-babel-julia-eoe-indicator "print(\"org_babel_julia_eoe\")")
  180. (defconst org-babel-julia-eoe-output "org_babel_julia_eoe")
  181. (defconst org-babel-julia-write-object-command "begin
  182. local p_ans = %s
  183. local p_tmp_file = \"%s\"
  184. try
  185. using CSV, DataFrames
  186. if typeof(p_ans) <: DataFrame
  187. p_ans_df = p_ans
  188. else
  189. p_ans_df = DataFrame(:ans => p_ans)
  190. end
  191. CSV.write(p_tmp_file,
  192. p_ans_df,
  193. writeheader = %s,
  194. transform = (col, val) -> something(val, missing),
  195. missingstring = \"nil\",
  196. quotestrings = false)
  197. p_ans
  198. catch e
  199. err_msg = \"Source block evaluation failed. $e\"
  200. CSV.write(p_tmp_file,
  201. DataFrame(:ans => err_msg),
  202. writeheader = false,
  203. transform = (col, val) -> something(val, missing),
  204. missingstring = \"nil\",
  205. quotestrings = false)
  206. err_msg
  207. end
  208. end")
  209. (defun org-babel-julia-evaluate
  210. (session body result-type result-params column-names-p)
  211. "Evaluate julia code in BODY."
  212. (if session
  213. (org-babel-julia-evaluate-session
  214. session body result-type result-params column-names-p)
  215. (org-babel-julia-evaluate-external-process
  216. body result-type result-params column-names-p)))
  217. (defun org-babel-julia-evaluate-external-process
  218. (body result-type result-params column-names-p)
  219. "Evaluate BODY in external julia process.
  220. If RESULT-TYPE equals \\='output then return standard output as a
  221. string. If RESULT-TYPE equals \\='value then return the value of the
  222. last statement in BODY, as elisp."
  223. (cl-case result-type
  224. (value
  225. (let ((tmp-file (org-babel-temp-file "julia-")))
  226. (org-babel-eval org-babel-julia-command
  227. (format org-babel-julia-write-object-command
  228. (format "begin %s end" body)
  229. (org-babel-process-file-name tmp-file 'noquote)
  230. (if column-names-p "true" "false")
  231. ))
  232. (org-babel-julia-process-value-result
  233. (org-babel-result-cond result-params
  234. (with-temp-buffer
  235. (insert-file-contents tmp-file)
  236. (buffer-string))
  237. (org-babel-import-elisp-from-file tmp-file '(4)))
  238. column-names-p)))
  239. (output (org-babel-eval org-babel-julia-command body))))
  240. (defun org-babel-julia-evaluate-session
  241. (session body result-type result-params column-names-p)
  242. "Evaluate BODY in SESSION.
  243. If RESULT-TYPE equals \\='output then return standard output as a
  244. string. If RESULT-TYPE equals \\='value then return the value of the
  245. last statement in BODY, as elisp."
  246. (cl-case result-type
  247. (value
  248. (with-temp-buffer
  249. (insert (org-babel-chomp body))
  250. (let ((ess-local-process-name
  251. (process-name (get-buffer-process session)))
  252. (ess-eval-visibly-p nil))
  253. (ess-eval-buffer nil)))
  254. (let ((tmp-file (org-babel-temp-file "julia-")))
  255. (org-babel-comint-eval-invisibly-and-wait-for-file
  256. session tmp-file
  257. (format org-babel-julia-write-object-command
  258. "ans"
  259. (org-babel-process-file-name tmp-file 'noquote)
  260. (if column-names-p "true" "false")
  261. ))
  262. (org-babel-julia-process-value-result
  263. (org-babel-result-cond result-params
  264. (with-temp-buffer
  265. (insert-file-contents tmp-file)
  266. (buffer-string))
  267. (org-babel-import-elisp-from-file tmp-file '(4)))
  268. column-names-p)))
  269. (output
  270. (mapconcat
  271. #'org-babel-chomp
  272. (butlast
  273. (delq nil
  274. (mapcar
  275. (lambda (line) (when (> (length line) 0) line))
  276. (mapcar
  277. (lambda (line) ;; cleanup extra prompts left in output
  278. (if (string-match
  279. "^\\([>+.]\\([ ][>.+]\\)*[ ]\\)"
  280. (car (split-string line "\n")))
  281. (substring line (match-end 1))
  282. line))
  283. (org-babel-comint-with-output (session org-babel-julia-eoe-output)
  284. (insert (mapconcat #'org-babel-chomp
  285. (list body org-babel-julia-eoe-indicator)
  286. "\n"))
  287. (inferior-ess-send-input))))))
  288. "\n"))))
  289. (defun org-babel-julia-process-value-result (result column-names-p)
  290. "Julia-specific processing of return value.
  291. Insert hline if column names in output have been requested."
  292. (if column-names-p
  293. (cons (car result) (cons 'hline (cdr result)))
  294. result))
  295. (provide 'ob-julia)
  296. ;;; ob-julia.el ends here