ob-julia.el 12 KB

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