ob-julia.el 12 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344
  1. ;;; ob-julia.el --- org-babel functions for julia code evaluation
  2. ;; Copyright (C) 2013, 2014, 2021 G. Jay Kerns
  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. (defun org-babel-edit-prep:julia (info)
  49. (let ((session (cdr (assq :session (nth 2 info)))))
  50. (when (and session
  51. (string-prefix-p "*" session)
  52. (string-suffix-p "*" session))
  53. (org-babel-julia-initiate-session session nil))))
  54. (defun org-babel-expand-body:julia (body params &optional _graphics-file)
  55. "Expand BODY according to PARAMS, return the expanded body."
  56. (mapconcat 'identity
  57. (append
  58. (when (cdr (assq :prologue params))
  59. (list (cdr (assq :prologue params))))
  60. (org-babel-variable-assignments:julia params)
  61. (list body)
  62. (when (cdr (assq :epilogue params))
  63. (list (cdr (assq :epilogue params)))))
  64. "\n"))
  65. (defun org-babel-execute:julia (body params)
  66. "Execute a block of julia code.
  67. This function is called by `org-babel-execute-src-block'."
  68. (save-excursion
  69. (let* ((result-params (cdr (assq :result-params params)))
  70. (result-type (cdr (assq :result-type params)))
  71. (session (org-babel-julia-initiate-session
  72. (cdr (assq :session params)) params))
  73. (graphics-file (and (member "graphics" (assq :result-params params))
  74. (org-babel-graphical-output-file params)))
  75. (colnames-p (unless graphics-file (cdr (assq :colnames params))))
  76. (rownames-p (unless graphics-file (cdr (assq :rownames 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. (or (equal "yes" rownames-p)
  85. (org-babel-pick-name
  86. (cdr (assq :rowname-names params)) rownames-p)))))
  87. (if graphics-file nil result))))
  88. (defun org-babel-normalize-newline (result)
  89. (replace-regexp-in-string
  90. "\\(\n\r?\\)\\{2,\\}"
  91. "\n"
  92. result))
  93. (defun org-babel-prep-session:julia (session params)
  94. "Prepare SESSION according to the header arguments specified in PARAMS."
  95. (let* ((session (org-babel-julia-initiate-session session params))
  96. (var-lines (org-babel-variable-assignments:julia params)))
  97. (org-babel-comint-in-buffer session
  98. (mapc (lambda (var)
  99. (end-of-line 1) (insert var) (comint-send-input nil t)
  100. (org-babel-comint-wait-for-output session)) var-lines))
  101. session))
  102. (defun org-babel-load-session:julia (session body params)
  103. "Load BODY into SESSION."
  104. (save-window-excursion
  105. (let ((buffer (org-babel-prep-session:julia session params)))
  106. (with-current-buffer buffer
  107. (goto-char (process-mark (get-buffer-process (current-buffer))))
  108. (insert (org-babel-chomp body)))
  109. buffer)))
  110. ;; helper functions
  111. (defun org-babel-variable-assignments:julia (params)
  112. "Return list of julia statements assigning the block's variables."
  113. (let ((vars (org-babel--get-vars params)))
  114. (mapcar
  115. (lambda (pair)
  116. (org-babel-julia-assign-elisp
  117. (car pair) (cdr pair)
  118. (equal "yes" (cdr (assq :colnames params)))
  119. (equal "yes" (cdr (assq :rownames params)))))
  120. (mapcar
  121. (lambda (i)
  122. (cons (car (nth i vars))
  123. (org-babel-reassemble-table
  124. (cdr (nth i vars))
  125. (cdr (nth i (cdr (assq :colname-names params))))
  126. (cdr (nth i (cdr (assq :rowname-names params)))))))
  127. (number-sequence 0 (1- (length vars)))))))
  128. (defun org-babel-julia-quote-csv-field (s)
  129. "Quote field S for export to julia."
  130. (if (stringp s)
  131. (concat "\"" (mapconcat 'identity (split-string s "\"") "\"\"") "\"")
  132. (format "%S" s)))
  133. (defun org-babel-julia-assign-elisp (name value colnames-p rownames-p)
  134. "Construct julia code assigning the elisp VALUE to a variable named NAME."
  135. (if (listp value)
  136. (let* ((lengths (mapcar 'length (cl-remove-if-not 'sequencep value)))
  137. (max (if lengths (apply 'max lengths) 0))
  138. (min (if lengths (apply 'min lengths) 0)))
  139. ;; Ensure VALUE has an orgtbl structure (depth of at least 2).
  140. (unless (listp (car value)) (setq value (list value)))
  141. (let ((file (orgtbl-to-csv value '(:fmt org-babel-julia-quote-csv-field)))
  142. (header (if (or (eq (nth 1 value) 'hline) colnames-p)
  143. "TRUE" "FALSE"))
  144. (row-names (if rownames-p "1" "NULL")))
  145. (if (= max min)
  146. (format "%s = begin
  147. using CSV
  148. CSV.read(\"%s\")
  149. end" name file)
  150. (format "%s = begin
  151. using CSV
  152. CSV.read(\"%s\")
  153. end"
  154. name file))))
  155. (format "%s = %s" name (org-babel-julia-quote-csv-field value))))
  156. (defvar ess-ask-for-ess-directory) ; dynamically scoped
  157. (defun org-babel-julia-initiate-session (session params)
  158. "If there is not a current julia process then create one."
  159. (unless (string= session "none")
  160. (let ((session (or session "*Julia*"))
  161. (ess-ask-for-ess-directory
  162. (and (boundp 'ess-ask-for-ess-directory)
  163. ess-ask-for-ess-directory
  164. (not (cdr (assq :dir params))))))
  165. (if (org-babel-comint-buffer-livep session)
  166. session
  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-associate-session (session)
  180. ; "Associate julia code buffer with a julia session.
  181. ; Make SESSION be the inferior ESS process associated with the
  182. ; current code buffer."
  183. ; (setq ess-local-process-name
  184. ; (process-name (get-buffer-process session)))
  185. ; (ess-make-buffer-current))
  186. (defun org-babel-julia-graphical-output-file (params)
  187. "Name of file to which julia should send graphical output."
  188. (and (member "graphics" (cdr (assq :result-params params)))
  189. (cdr (assq :file params))))
  190. (defconst org-babel-julia-eoe-indicator "print(\"org_babel_julia_eoe\")")
  191. (defconst org-babel-julia-eoe-output "org_babel_julia_eoe")
  192. (defconst org-babel-julia-write-object-command "begin
  193. local p_ans = %s
  194. local p_tmp_file = \"%s\"
  195. try
  196. using CSV, DataFrames
  197. if typeof(p_ans) <: DataFrame
  198. p_ans_df = p_ans
  199. else
  200. p_ans_df = DataFrame(:ans => p_ans)
  201. end
  202. CSV.write(p_tmp_file,
  203. p_ans_df,
  204. writeheader = %s,
  205. transform = (col, val) -> something(val, missing),
  206. missingstring = \"nil\",
  207. quotestrings = false)
  208. p_ans
  209. catch e
  210. err_msg = \"Source block evaluation failed. $e\"
  211. CSV.write(p_tmp_file,
  212. DataFrame(:ans => err_msg),
  213. writeheader = false,
  214. transform = (col, val) -> something(val, missing),
  215. missingstring = \"nil\",
  216. quotestrings = false)
  217. err_msg
  218. end
  219. end")
  220. (defun org-babel-julia-evaluate
  221. (session body result-type result-params column-names-p row-names-p)
  222. "Evaluate julia code in BODY."
  223. (if session
  224. (org-babel-julia-evaluate-session
  225. session body result-type result-params column-names-p row-names-p)
  226. (org-babel-julia-evaluate-external-process
  227. body result-type result-params column-names-p row-names-p)))
  228. (defun org-babel-julia-evaluate-external-process
  229. (body result-type result-params column-names-p row-names-p)
  230. "Evaluate BODY in external julia process.
  231. If RESULT-TYPE equals 'output then return standard output as a
  232. string. If RESULT-TYPE equals 'value then return the value of the
  233. last statement in BODY, as elisp."
  234. (cl-case result-type
  235. (value
  236. (let ((tmp-file (org-babel-temp-file "julia-")))
  237. (org-babel-eval org-babel-julia-command
  238. (format org-babel-julia-write-object-command
  239. (format "begin %s end" body)
  240. (org-babel-process-file-name tmp-file 'noquote)
  241. (if column-names-p "true" "false")
  242. ))
  243. (org-babel-julia-process-value-result
  244. (org-babel-result-cond result-params
  245. (with-temp-buffer
  246. (insert-file-contents tmp-file)
  247. (buffer-string))
  248. (org-babel-import-elisp-from-file tmp-file '(4)))
  249. column-names-p)))
  250. (output (org-babel-eval org-babel-julia-command body))))
  251. (defun org-babel-julia-evaluate-session
  252. (session body result-type result-params column-names-p row-names-p)
  253. "Evaluate BODY in SESSION.
  254. If RESULT-TYPE equals 'output then return standard output as a
  255. string. If RESULT-TYPE equals 'value then return the value of the
  256. last statement in BODY, as elisp."
  257. (cl-case result-type
  258. (value
  259. (with-temp-buffer
  260. (insert (org-babel-chomp body))
  261. (let ((ess-local-process-name
  262. (process-name (get-buffer-process session)))
  263. (ess-eval-visibly-p nil))
  264. (ess-eval-buffer nil)))
  265. (let ((tmp-file (org-babel-temp-file "julia-")))
  266. (org-babel-comint-eval-invisibly-and-wait-for-file
  267. session tmp-file
  268. (format org-babel-julia-write-object-command
  269. "ans"
  270. (org-babel-process-file-name tmp-file 'noquote)
  271. (if column-names-p "true" "false")
  272. ))
  273. (org-babel-julia-process-value-result
  274. (org-babel-result-cond result-params
  275. (with-temp-buffer
  276. (insert-file-contents tmp-file)
  277. (buffer-string))
  278. (org-babel-import-elisp-from-file tmp-file '(4)))
  279. column-names-p)))
  280. (output
  281. (mapconcat
  282. 'org-babel-chomp
  283. (butlast
  284. (delq nil
  285. (mapcar
  286. (lambda (line) (when (> (length line) 0) line))
  287. (mapcar
  288. (lambda (line) ;; cleanup extra prompts left in output
  289. (if (string-match
  290. "^\\([>+.]\\([ ][>.+]\\)*[ ]\\)"
  291. (car (split-string line "\n")))
  292. (substring line (match-end 1))
  293. line))
  294. (org-babel-comint-with-output (session org-babel-julia-eoe-output)
  295. (insert (mapconcat 'org-babel-chomp
  296. (list body org-babel-julia-eoe-indicator)
  297. "\n"))
  298. (inferior-ess-send-input)))))) "\n"))))
  299. (defun org-babel-julia-process-value-result (result column-names-p)
  300. "julia-specific processing of return value.
  301. Insert hline if column names in output have been requested."
  302. (if column-names-p
  303. (cons (car result) (cons 'hline (cdr result)))
  304. result))
  305. (provide 'ob-julia)
  306. ;;; ob-julia.el ends here