org-babel: further cleaning of parameter-passing to language files
[rgr-org-mode.git] / lisp / org-plot.el
blob41073e5394ef99046b4d2fd18e9a1317b72293ef
1 ;;; org-plot.el --- Support for plotting from Org-mode
3 ;; Copyright (C) 2008, 2009 Free Software Foundation, Inc.
4 ;;
5 ;; Author: Eric Schulte <schulte dot eric at gmail dot com>
6 ;; Keywords: tables, plotting
7 ;; Homepage: http://orgmode.org
8 ;; Version: 6.32trans
9 ;;
10 ;; This file is part of GNU Emacs.
12 ;; GNU Emacs is free software: you can redistribute it and/or modify
13 ;; it under the terms of the GNU General Public License as published by
14 ;; the Free Software Foundation, either version 3 of the License, or
15 ;; (at your option) any later version.
17 ;; GNU Emacs is distributed in the hope that it will be useful,
18 ;; but WITHOUT ANY WARRANTY; without even the implied warranty of
19 ;; MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
20 ;; GNU General Public License for more details.
22 ;; You should have received a copy of the GNU General Public License
23 ;; along with GNU Emacs. If not, see <http://www.gnu.org/licenses/>.
25 ;;; Commentary:
27 ;; Borrows ideas and a couple of lines of code from org-exp.el.
29 ;; Thanks to the org-mode mailing list for testing and implementation
30 ;; and feature suggestions
32 ;;; Code:
33 (require 'org)
34 (require 'org-exp)
35 (require 'org-table)
36 (eval-when-compile
37 (require 'cl))
39 (declare-function gnuplot-delchar-or-maybe-eof "ext:gnuplot" (arg))
40 (declare-function gnuplot-mode "ext:gnuplot" ())
41 (declare-function gnuplot-send-buffer-to-gnuplot "ext:gnuplot" ())
43 (defvar org-plot/gnuplot-default-options
44 '((:plot-type . 2d)
45 (:with . lines)
46 (:ind . 0))
47 "Default options to gnuplot used by `org-plot/gnuplot'")
49 (defvar org-plot-timestamp-fmt nil)
51 (defun org-plot/add-options-to-plist (p options)
52 "Parse an OPTIONS line and set values in the property list P.
53 Returns the resulting property list."
54 (let (o)
55 (when options
56 (let ((op '(("type" . :plot-type)
57 ("script" . :script)
58 ("line" . :line)
59 ("set" . :set)
60 ("title" . :title)
61 ("ind" . :ind)
62 ("deps" . :deps)
63 ("with" . :with)
64 ("file" . :file)
65 ("labels" . :labels)
66 ("map" . :map)
67 ("timeind" . :timeind)
68 ("timefmt" . :timefmt)))
69 (multiples '("set" "line"))
70 (regexp ":\\([\"][^\"]+?[\"]\\|[(][^)]+?[)]\\|[^ \t\n\r;,.]*\\)")
71 (start 0)
73 (while (setq o (pop op))
74 (if (member (car o) multiples) ;; keys with multiple values
75 (while (string-match
76 (concat (regexp-quote (car o)) regexp)
77 options start)
78 (setq start (match-end 0))
79 (setq p (plist-put p (cdr o)
80 (cons (car (read-from-string
81 (match-string 1 options)))
82 (plist-get p (cdr o)))))
84 (if (string-match (concat (regexp-quote (car o)) regexp)
85 options)
86 (setq p (plist-put p (cdr o)
87 (car (read-from-string
88 (match-string 1 options)))))))))))
91 (defun org-plot/goto-nearest-table ()
92 "Move the point forward to the beginning of nearest table.
93 Return value is the point at the beginning of the table."
94 (interactive) (move-beginning-of-line 1)
95 (while (not (or (org-at-table-p) (< 0 (forward-line 1)))))
96 (goto-char (org-table-begin)))
98 (defun org-plot/collect-options (&optional params)
99 "Collect options from an org-plot '#+Plot:' line.
100 Accepts an optional property list PARAMS, to which the options
101 will be added. Returns the resulting property list."
102 (interactive)
103 (let ((line (thing-at-point 'line)))
104 (if (string-match "#\\+PLOT: +\\(.*\\)$" line)
105 (org-plot/add-options-to-plist params (match-string 1 line))
106 params)))
108 (defun org-plot-quote-timestamp-field (s)
109 "Convert field S from timestamp to Unix time and export to gnuplot."
110 (format-time-string org-plot-timestamp-fmt (org-time-string-to-time s)))
112 (defun org-plot-quote-tsv-field (s)
113 "Quote field S for export to gnuplot."
114 (if (string-match org-table-number-regexp s) s
115 (if (string-match org-ts-regexp3 s)
116 (org-plot-quote-timestamp-field s)
117 (concat "\"" (mapconcat 'identity (split-string s "\"") "\"\"") "\""))))
119 (defun org-plot/gnuplot-to-data (table data-file params)
120 "Export TABLE to DATA-FILE in a format readable by gnuplot.
121 Pass PARAMS through to `orgtbl-to-generic' when exporting TABLE."
122 (with-temp-file
123 data-file
124 (make-local-variable 'org-plot-timestamp-fmt)
125 (setq org-plot-timestamp-fmt (or
126 (plist-get params :timefmt)
127 "%Y-%m-%d-%H:%M:%S"))
128 (insert (orgtbl-to-generic
129 table
130 (org-combine-plists
131 '(:sep "\t" :fmt org-plot-quote-tsv-field)
132 params))))
133 nil)
135 (defun org-plot/gnuplot-to-grid-data (table data-file params)
136 "Export the data in TABLE to DATA-FILE for gnuplot.
137 This means, in a format appropriate for grid plotting by gnuplot.
138 PARAMS specifies which columns of TABLE should be plotted as independent
139 and dependant variables."
140 (interactive)
141 (let* ((ind (- (plist-get params :ind) 1))
142 (deps (if (plist-member params :deps)
143 (mapcar (lambda (val) (- val 1)) (plist-get params :deps))
144 (let (collector)
145 (dotimes (col (length (first table)))
146 (setf collector (cons col collector)))
147 collector)))
148 row-vals (counter 0))
149 (when (>= ind 0) ;; collect values of ind col
150 (setf row-vals (mapcar (lambda (row) (setf counter (+ 1 counter))
151 (cons counter (nth ind row))) table)))
152 (when (or deps (>= ind 0)) ;; remove non-plotting columns
153 (setf deps (delq ind deps))
154 (setf table (mapcar (lambda (row)
155 (dotimes (col (length row))
156 (unless (memq col deps)
157 (setf (nth col row) nil)))
158 (delq nil row))
159 table)))
160 ;; write table to gnuplot grid datafile format
161 (with-temp-file data-file
162 (let ((num-rows (length table)) (num-cols (length (first table)))
163 front-edge back-edge)
164 (flet ((gnuplot-row (col row value)
165 (setf col (+ 1 col)) (setf row (+ 1 row))
166 (format "%f %f %f\n%f %f %f\n"
167 col (- row 0.5) value ;; lower edge
168 col (+ row 0.5) value))) ;; upper edge
169 (dotimes (col num-cols)
170 (dotimes (row num-rows)
171 (setf back-edge
172 (concat back-edge
173 (gnuplot-row (- col 1) row (string-to-number
174 (nth col (nth row table))))))
175 (setf front-edge
176 (concat front-edge
177 (gnuplot-row col row (string-to-number
178 (nth col (nth row table)))))))
179 ;; only insert once per row
180 (insert back-edge) (insert "\n") ;; back edge
181 (insert front-edge) (insert "\n") ;; front edge
182 (setf back-edge "") (setf front-edge "")))))
183 row-vals))
185 (defun org-plot/gnuplot-script (data-file num-cols params &optional preface)
186 "Write a gnuplot script to DATA-FILE respecting the options set in PARAMS.
187 NUM-COLS controls the number of columns plotted in a 2-d plot.
188 Optional argument PREFACE returns only option parameters in a
189 manner suitable for prepending to a user-specified script."
190 (let* ((type (plist-get params :plot-type))
191 (with (if (equal type 'grid)
192 'pm3d
193 (plist-get params :with)))
194 (sets (plist-get params :set))
195 (lines (plist-get params :line))
196 (map (plist-get params :map))
197 (title (plist-get params :title))
198 (file (plist-get params :file))
199 (ind (plist-get params :ind))
200 (time-ind (plist-get params :timeind))
201 (timefmt (plist-get params :timefmt))
202 (text-ind (plist-get params :textind))
203 (deps (if (plist-member params :deps) (plist-get params :deps)))
204 (col-labels (plist-get params :labels))
205 (x-labels (plist-get params :xlabels))
206 (y-labels (plist-get params :ylabels))
207 (plot-str "'%s' using %s%d%s with %s title '%s'")
208 (plot-cmd (case type
209 ('2d "plot")
210 ('3d "splot")
211 ('grid "splot")))
212 (script "reset") plot-lines)
213 (flet ((add-to-script (line) (setf script (format "%s\n%s" script line))))
214 (when file ;; output file
215 (add-to-script (format "set term %s" (file-name-extension file)))
216 (add-to-script (format "set output '%s'" file)))
217 (case type ;; type
218 ('2d ())
219 ('3d (if map (add-to-script "set map")))
220 ('grid (if map
221 (add-to-script "set pm3d map")
222 (add-to-script "set pm3d"))))
223 (when title (add-to-script (format "set title '%s'" title))) ;; title
224 (when lines (mapc (lambda (el) (add-to-script el)) lines)) ;; line
225 (when sets ;; set
226 (mapc (lambda (el) (add-to-script (format "set %s" el))) sets))
227 (when x-labels ;; x labels (xtics)
228 (add-to-script
229 (format "set xtics (%s)"
230 (mapconcat (lambda (pair)
231 (format "\"%s\" %d" (cdr pair) (car pair)))
232 x-labels ", "))))
233 (when y-labels ;; y labels (ytics)
234 (add-to-script
235 (format "set ytics (%s)"
236 (mapconcat (lambda (pair)
237 (format "\"%s\" %d" (cdr pair) (car pair)))
238 y-labels ", "))))
239 (when time-ind ;; timestamp index
240 (add-to-script "set xdata time")
241 (add-to-script (concat "set timefmt \""
242 (or timefmt ;; timefmt passed to gnuplot
243 "%Y-%m-%d-%H:%M:%S") "\"")))
244 (unless preface
245 (case type ;; plot command
246 ('2d (dotimes (col num-cols)
247 (unless (and (equal type '2d)
248 (or (and ind (equal (+ 1 col) ind))
249 (and deps (not (member (+ 1 col) deps)))))
250 (setf plot-lines
251 (cons
252 (format plot-str data-file
253 (or (and (not text-ind) ind
254 (> ind 0) (format "%d:" ind)) "")
255 (+ 1 col)
256 (if text-ind (format ":xticlabel(%d)" ind) "")
257 with
258 (or (nth col col-labels) (format "%d" (+ 1 col))))
259 plot-lines)))))
260 ('3d
261 (setq plot-lines (list (format "'%s' matrix with %s title ''"
262 data-file with))))
263 ('grid
264 (setq plot-lines (list (format "'%s' with %s title ''"
265 data-file with)))))
266 (add-to-script
267 (concat plot-cmd " " (mapconcat 'identity (reverse plot-lines) ",\\\n "))))
268 script)))
270 ;;-----------------------------------------------------------------------------
271 ;; facade functions
272 ;;;###autoload
273 (defun org-plot/gnuplot (&optional params)
274 "Plot table using gnuplot. Gnuplot options can be specified with PARAMS.
275 If not given options will be taken from the +PLOT
276 line directly before or after the table."
277 (interactive)
278 (require 'gnuplot)
279 (save-window-excursion
280 (delete-other-windows)
281 (when (get-buffer "*gnuplot*") ;; reset *gnuplot* if it already running
282 (with-current-buffer "*gnuplot*"
283 (goto-char (point-max))
284 (gnuplot-delchar-or-maybe-eof nil)))
285 (org-plot/goto-nearest-table)
286 ;; set default options
287 (mapc
288 (lambda (pair)
289 (unless (plist-member params (car pair))
290 (setf params (plist-put params (car pair) (cdr pair)))))
291 org-plot/gnuplot-default-options)
292 ;; collect table and table information
293 (let* ((data-file (make-temp-file "org-plot"))
294 (table (org-table-to-lisp))
295 (num-cols (length (if (eq (first table) 'hline) (second table)
296 (first table)))))
297 (while (equal 'hline (first table)) (setf table (cdr table)))
298 (when (equal (second table) 'hline)
299 (setf params (plist-put params :labels (first table))) ;; headers to labels
300 (setf table (delq 'hline (cdr table)))) ;; clean non-data from table
301 ;; collect options
302 (save-excursion (while (and (equal 0 (forward-line -1))
303 (looking-at "#\\+"))
304 (setf params (org-plot/collect-options params))))
305 ;; dump table to datafile (very different for grid)
306 (case (plist-get params :plot-type)
307 ('2d (org-plot/gnuplot-to-data table data-file params))
308 ('3d (org-plot/gnuplot-to-data table data-file params))
309 ('grid (let ((y-labels (org-plot/gnuplot-to-grid-data
310 table data-file params)))
311 (when y-labels (plist-put params :ylabels y-labels)))))
312 ;; check for timestamp ind column
313 (let ((ind (- (plist-get params :ind) 1)))
314 (when (and (>= ind 0) (equal '2d (plist-get params :plot-type)))
315 (if (= (length
316 (delq 0 (mapcar
317 (lambda (el)
318 (if (string-match org-ts-regexp3 el)
319 0 1))
320 (mapcar (lambda (row) (nth ind row)) table)))) 0)
321 (plist-put params :timeind t)
322 ;; check for text ind column
324 (if (or (string= (plist-get params :with) "hist")
325 (> (length
326 (delq 0 (mapcar
327 (lambda (el)
328 (if (string-match org-table-number-regexp el)
329 0 1))
330 (mapcar (lambda (row) (nth ind row)) table)))) 0))
331 (plist-put params :textind t)))))
332 ;; write script
333 (with-temp-buffer
334 (if (plist-get params :script) ;; user script
335 (progn (insert
336 (org-plot/gnuplot-script data-file num-cols params t))
337 (insert "\n")
338 (insert-file-contents (plist-get params :script))
339 (goto-char (point-min))
340 (while (re-search-forward "$datafile" nil t)
341 (replace-match data-file nil nil)))
342 (insert
343 (org-plot/gnuplot-script data-file num-cols params)))
344 ;; graph table
345 (gnuplot-mode)
346 (gnuplot-send-buffer-to-gnuplot))
347 ;; cleanup
348 (bury-buffer (get-buffer "*gnuplot*"))
349 (run-with-idle-timer 0.1 nil (lambda () (delete-file data-file))))))
351 (provide 'org-plot)
353 ;; arch-tag: 5763f7c6-0c75-416d-b070-398ee4ec0eca
354 ;;; org-plot.el ends here