ob-julia.el 13 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353
  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 not part of GNU Emacs.
  8. ;; This program 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. ;; This program 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 this program. 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. ;; (rownames-p (unless graphics-file (cdr (assq :rownames params))))
  78. (full-body (org-babel-expand-body:julia body params graphics-file))
  79. (result
  80. (org-babel-julia-evaluate
  81. session full-body result-type result-params
  82. (or (equal "yes" colnames-p)
  83. (org-babel-pick-name
  84. (cdr (assq :colname-names params)) colnames-p))
  85. ;; (or (equal "yes" rownames-p)
  86. ;; (org-babel-pick-name
  87. ;; (cdr (assq :rowname-names params)) rownames-p))
  88. )))
  89. (if graphics-file nil result))))
  90. (defun org-babel-normalize-newline (result)
  91. (replace-regexp-in-string
  92. "\\(\n\r?\\)\\{2,\\}"
  93. "\n"
  94. result))
  95. (defun org-babel-prep-session:julia (session params)
  96. "Prepare SESSION according to the header arguments specified in PARAMS."
  97. (let* ((session (org-babel-julia-initiate-session session params))
  98. (var-lines (org-babel-variable-assignments:julia params)))
  99. (org-babel-comint-in-buffer session
  100. (mapc (lambda (var)
  101. (end-of-line 1) (insert var) (comint-send-input nil t)
  102. (org-babel-comint-wait-for-output session)) var-lines))
  103. session))
  104. (defun org-babel-load-session:julia (session body params)
  105. "Load BODY into SESSION."
  106. (save-window-excursion
  107. (let ((buffer (org-babel-prep-session:julia session params)))
  108. (with-current-buffer buffer
  109. (goto-char (process-mark (get-buffer-process (current-buffer))))
  110. (insert (org-babel-chomp body)))
  111. buffer)))
  112. ;; helper functions
  113. (defun org-babel-variable-assignments:julia (params)
  114. "Return list of julia statements assigning the block's variables."
  115. (let ((vars (org-babel--get-vars params)))
  116. (mapcar
  117. (lambda (pair)
  118. (org-babel-julia-assign-elisp
  119. (car pair) (cdr pair)
  120. ;; (equal "yes" (cdr (assq :colnames params)))
  121. ;; (equal "yes" (cdr (assq :rownames params)))
  122. ))
  123. (mapcar
  124. (lambda (i)
  125. (cons (car (nth i vars))
  126. (org-babel-reassemble-table
  127. (cdr (nth i vars))
  128. (cdr (nth i (cdr (assq :colname-names params))))
  129. (cdr (nth i (cdr (assq :rowname-names params)))))))
  130. (number-sequence 0 (1- (length vars)))))))
  131. (defun org-babel-julia-quote-csv-field (s)
  132. "Quote field S for export to julia."
  133. (if (stringp s)
  134. (concat "\"" (mapconcat #'identity (split-string s "\"") "\"\"") "\"")
  135. (format "%S" s)))
  136. (defun org-babel-julia-assign-elisp (name value) ;; colnames-p rownames-p
  137. "Construct julia code assigning the elisp VALUE to a variable named NAME."
  138. (if (listp value)
  139. (let* ((lengths (mapcar #'length (cl-remove-if-not #'sequencep value)))
  140. (max (if lengths (apply #'max lengths) 0))
  141. (min (if lengths (apply #'min lengths) 0)))
  142. ;; Ensure VALUE has an orgtbl structure (depth of at least 2).
  143. (unless (listp (car value)) (setq value (list value)))
  144. (let ((file (orgtbl-to-csv value '(:fmt org-babel-julia-quote-csv-field)))
  145. ;; (header (if (or (eq (nth 1 value) 'hline) colnames-p)
  146. ;; "TRUE" "FALSE"))
  147. ;; (row-names (if rownames-p "1" "NULL"))
  148. )
  149. (if (= max min)
  150. (format "%s = begin
  151. using CSV
  152. CSV.read(\"%s\")
  153. end" name file)
  154. (format "%s = begin
  155. using CSV
  156. CSV.read(\"%s\")
  157. end"
  158. name file))))
  159. (format "%s = %s" name (org-babel-julia-quote-csv-field value))))
  160. (defvar ess-ask-for-ess-directory) ; dynamically scoped
  161. (defun org-babel-julia-initiate-session (session params)
  162. "If there is not a current julia process then create one."
  163. (unless (string= session "none")
  164. (let ((session (or session "*Julia*"))
  165. (ess-ask-for-ess-directory
  166. (and (bound-and-true-p ess-ask-for-ess-directory)
  167. (not (cdr (assq :dir params))))))
  168. (if (org-babel-comint-buffer-livep session)
  169. session
  170. ;; FIXME: Depending on `display-buffer-alist', (julia) may end up
  171. ;; popping up a new frame which `save-window-excursion' won't be able
  172. ;; to "undo", so we really should call a kind of
  173. ;; `julia-no-select' instead so we don't need to undo any
  174. ;; window-changes afterwards.
  175. (save-window-excursion
  176. (when (get-buffer session)
  177. ;; Session buffer exists, but with dead process
  178. (set-buffer session))
  179. (require 'ess) (set-buffer (julia))
  180. (rename-buffer
  181. (if (bufferp session)
  182. (buffer-name session)
  183. (if (stringp session)
  184. session
  185. (buffer-name))))
  186. (current-buffer))))))
  187. ; (defun org-babel-julia-associate-session (session)
  188. ; "Associate julia code buffer with a julia session.
  189. ; Make SESSION be the inferior ESS process associated with the
  190. ; current code buffer."
  191. ; (setq ess-local-process-name
  192. ; (process-name (get-buffer-process session)))
  193. ; (ess-make-buffer-current))
  194. (defun org-babel-julia-graphical-output-file (params)
  195. "Name of file to which julia should send graphical output."
  196. (and (member "graphics" (cdr (assq :result-params params)))
  197. (cdr (assq :file params))))
  198. (defconst org-babel-julia-eoe-indicator "print(\"org_babel_julia_eoe\")")
  199. (defconst org-babel-julia-eoe-output "org_babel_julia_eoe")
  200. (defconst org-babel-julia-write-object-command "begin
  201. local p_ans = %s
  202. local p_tmp_file = \"%s\"
  203. try
  204. using CSV, DataFrames
  205. if typeof(p_ans) <: DataFrame
  206. p_ans_df = p_ans
  207. else
  208. p_ans_df = DataFrame(:ans => p_ans)
  209. end
  210. CSV.write(p_tmp_file,
  211. p_ans_df,
  212. writeheader = %s,
  213. transform = (col, val) -> something(val, missing),
  214. missingstring = \"nil\",
  215. quotestrings = false)
  216. p_ans
  217. catch e
  218. err_msg = \"Source block evaluation failed. $e\"
  219. CSV.write(p_tmp_file,
  220. DataFrame(:ans => err_msg),
  221. writeheader = false,
  222. transform = (col, val) -> something(val, missing),
  223. missingstring = \"nil\",
  224. quotestrings = false)
  225. err_msg
  226. end
  227. end")
  228. (defun org-babel-julia-evaluate
  229. (session body result-type result-params column-names-p) ;; row-names-p
  230. "Evaluate julia code in BODY."
  231. (if session
  232. (org-babel-julia-evaluate-session
  233. session body result-type result-params column-names-p) ;; row-names-p
  234. (org-babel-julia-evaluate-external-process
  235. body result-type result-params column-names-p))) ;; row-names-p
  236. (defun org-babel-julia-evaluate-external-process
  237. (body result-type result-params column-names-p) ;; row-names-p
  238. "Evaluate BODY in external julia process.
  239. If RESULT-TYPE equals 'output then return standard output as a
  240. string. If RESULT-TYPE equals 'value then return the value of the
  241. last statement in BODY, as elisp."
  242. (cl-case result-type
  243. (value
  244. (let ((tmp-file (org-babel-temp-file "julia-")))
  245. (org-babel-eval org-babel-julia-command
  246. (format org-babel-julia-write-object-command
  247. (format "begin %s end" body)
  248. (org-babel-process-file-name tmp-file 'noquote)
  249. (if column-names-p "true" "false")
  250. ))
  251. (org-babel-julia-process-value-result
  252. (org-babel-result-cond result-params
  253. (with-temp-buffer
  254. (insert-file-contents tmp-file)
  255. (buffer-string))
  256. (org-babel-import-elisp-from-file tmp-file '(4)))
  257. column-names-p)))
  258. (output (org-babel-eval org-babel-julia-command body))))
  259. (defun org-babel-julia-evaluate-session
  260. (session body result-type result-params column-names-p) ;; row-names-p
  261. "Evaluate BODY in SESSION.
  262. If RESULT-TYPE equals 'output then return standard output as a
  263. string. If RESULT-TYPE equals 'value then return the value of the
  264. last statement in BODY, as elisp."
  265. (cl-case result-type
  266. (value
  267. (with-temp-buffer
  268. (insert (org-babel-chomp body))
  269. (let ((ess-local-process-name
  270. (process-name (get-buffer-process session)))
  271. (ess-eval-visibly-p nil))
  272. (ess-eval-buffer nil)))
  273. (let ((tmp-file (org-babel-temp-file "julia-")))
  274. (org-babel-comint-eval-invisibly-and-wait-for-file
  275. session tmp-file
  276. (format org-babel-julia-write-object-command
  277. "ans"
  278. (org-babel-process-file-name tmp-file 'noquote)
  279. (if column-names-p "true" "false")
  280. ))
  281. (org-babel-julia-process-value-result
  282. (org-babel-result-cond result-params
  283. (with-temp-buffer
  284. (insert-file-contents tmp-file)
  285. (buffer-string))
  286. (org-babel-import-elisp-from-file tmp-file '(4)))
  287. column-names-p)))
  288. (output
  289. (mapconcat
  290. #'org-babel-chomp
  291. (butlast
  292. (delq nil
  293. (mapcar
  294. (lambda (line) (when (> (length line) 0) line))
  295. (mapcar
  296. (lambda (line) ;; cleanup extra prompts left in output
  297. (if (string-match
  298. "^\\([>+.]\\([ ][>.+]\\)*[ ]\\)"
  299. (car (split-string line "\n")))
  300. (substring line (match-end 1))
  301. line))
  302. (org-babel-comint-with-output (session org-babel-julia-eoe-output)
  303. (insert (mapconcat #'org-babel-chomp
  304. (list body org-babel-julia-eoe-indicator)
  305. "\n"))
  306. (inferior-ess-send-input))))))
  307. "\n"))))
  308. (defun org-babel-julia-process-value-result (result column-names-p)
  309. "Julia-specific processing of return value.
  310. Insert hline if column names in output have been requested."
  311. (if column-names-p
  312. (cons (car result) (cons 'hline (cdr result)))
  313. result))
  314. (provide 'ob-julia)
  315. ;;; ob-julia.el ends here