ob-julia.el 12 KB

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