ob-julia.el 12 KB

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