Merge branch 'master' into gcl_cleanup
[maxima/cygwin.git] / src / plot.lisp
blob76b92fc486101519b55c10480154b46a5272d5ad
1 ;;Copyright William F. Schelter 1990, All Rights Reserved
2 ;;
3 ;; Time-stamp: "2022-03-28 12:59:37 villate"
5 (in-package :maxima)
7 #|
8 Examples
10 /* plot of z^(1/3)...*/
11 plot3d(r^.33*cos(th/3),[r,0,1],[th,0,6*%pi],['grid,12,80],['transform_xy,polar_to_xy],['plot_format,geomview]);
13 /* plot of z^(1/2)...*/
14 plot3d(r^.5*cos(th/2),[r,0,1],[th,0,6*%pi],['grid,12,80],['transform_xy,polar_to_xy],['plot_format,xmaxima]);
16 /* moebius */
17 plot3d([cos(x)*(3+y*cos(x/2)),sin(x)*(3+y*cos(x/2)),y*sin(x/2)],[x,-%pi,%pi],[y,-1,1],['grid,50,15]);
19 /* klein bottle */
20 plot3d([5*cos(x)*(cos(x/2)*cos(y)+sin(x/2)*sin(2*y)+3.0) - 10.0,
21 -5*sin(x)*(cos(x/2)*cos(y)+sin(x/2)*sin(2*y)+3.0),
22 5*(-sin(x/2)*cos(y)+cos(x/2)*sin(2*y))],[x,-%pi,%pi],[y,-%pi,%pi],
23 ['grid,40,40]);
24 /* torus */
25 plot3d([cos(y)*(10.0+6*cos(x)), sin(y)*(10.0+6*cos(x)),-6*sin(x)],
26 [x,0,2*%pi],[y,0,2*%pi],['grid,40,40]);
29 (defclass gnuplot-plot ()
30 ((data :initarg :data :initform "")
31 (pipe :initarg :pipe :initform nil)))
33 (defclass xmaxima-plot ()
34 ((data :initarg :data :initform "")
35 (pipe :initarg :pipe :initform nil)))
37 (defclass geomview-plot ()
38 ((data :initarg :data :initform "")
39 (pipe :initarg :pipe :initform nil)))
41 (defgeneric plot-preamble (plot options)
42 (:documentation "Plots the preamble for a plot."))
44 (defgeneric plot2d-command (plot fun options range)
45 (:documentation "Writes the command that creates a plot."))
47 (defgeneric plot3d-command (plot functions options titles)
48 (:documentation "Writes the command that creates a plot."))
50 (defgeneric plot-shipout (plot options &optional output-file)
51 (:documentation "Sends the plot commands to the graphic program."))
53 (defun ensure-string (x)
54 (cond
55 ((stringp x) x)
56 ((symbolp x) (print-invert-case (stripdollar x)))
57 (t (maybe-invert-string-case (string (implode (strgrind x)))))))
59 (defmfun $join (x y)
60 (if (and ($listp x) ($listp y))
61 (cons '(mlist) (loop for w in (cdr x) for u in (cdr y) collect w collect u))
62 (merror (intl:gettext "join: both arguments must be lists."))))
64 (defun coerce-float (x) ($float (meval* x)))
66 (defvar *maxima-plotdir* "")
68 ;; *ROT* AND FRIENDS ($ROT, $ROTATE_PTS, $ROTATE_LIST) CAN PROBABLY GO AWAY !!
69 ;; THEY ARE UNDOCUMENTED AND UNUSED !!
70 (defvar *rot* (make-array 9 :element-type 'flonum))
71 (defvar $rot nil)
73 ;; Global plot options list; this is a property list.. It is not a
74 ;; Maxima variable, to discourage users from changing it directly; it
75 ;; should be changed via set_plot_option
77 (defvar *plot-options*
78 '(:plot_format $gnuplot_pipes
79 :grid (30 30) :run_viewer t :axes t
80 ;; With adaptive plotting, 29 nticks should be enough; adapt_depth
81 ;; controls the number of splittings adaptive-plotting will do.
82 :nticks 29 :adapt_depth 5
83 :color ($blue $red $green $magenta $black $cyan)
84 :point_type ($bullet $box $triangle $plus $times $asterisk)
85 :palette (((mlist) $gradient $green $cyan $blue $violet)
86 ((mlist) $gradient $magenta $violet $blue $cyan $green $yellow
87 $orange $red $brown $black))
88 :gnuplot_preamble "" :gnuplot_term $default))
90 (defvar $plot_options
91 '((mlist) ((mlist) $plot_format $gnuplot_pipes)))
93 ;; $plot_realpart option is false by default but *plot-realpart* is true
94 ;; because coerce-float-fun is used outside of plot package too.
95 (defvar *plot-realpart* t)
97 (defun maybe-realpart (x)
98 (if *plot-realpart*
99 ($realpart x)
100 (if (zerop1 ($imagpart x))
101 ($realpart x)
102 nil)))
104 (defvar *missing-data-indicator* "NaN")
106 (defvar *gnuplot-stream* nil)
107 (defvar *gnuplot-command* "")
109 (defvar $gnuplot_command "gnuplot")
111 (defun start-gnuplot-process (path)
112 ;; TODO: Forward gnuplot's stderr stream to maxima's stderr output
113 #+clisp (setq *gnuplot-stream* (ext:make-pipe-output-stream path))
114 ;; TODO: Forward gnuplot's stderr stream to maxima's stderr output
115 #+lispworks (setq *gnuplot-stream* (system:open-pipe path))
116 #+cmu (setq *gnuplot-stream*
117 (ext:process-input (ext:run-program path nil :input :stream
118 :output *error-output* :wait nil)))
119 #+scl (setq *gnuplot-stream*
120 (ext:process-input (ext:run-program path nil :input :stream
121 :output *error-output* :wait nil)))
122 #+sbcl (setq *gnuplot-stream*
123 (sb-ext:process-input (sb-ext:run-program path nil
124 :input :stream
125 :output *error-output* :wait nil
126 :search t)))
127 #+gcl (setq *gnuplot-stream*
128 (open (concatenate 'string "| " path) :direction :output))
129 #+ecl (progn
130 (setq *gnuplot-stream* (ext:run-program path nil :input :stream :output *error-output* :error :output :wait nil)))
131 #+ccl (setf *gnuplot-stream*
132 (ccl:external-process-input-stream
133 (ccl:run-program path nil
134 :wait nil :output *error-output*
135 :input :stream)))
136 #+allegro (setf *gnuplot-stream* (excl:run-shell-command
137 path :input :stream :output *error-output* :wait nil))
138 #+abcl (setq *gnuplot-stream* (system::process-input (system::run-program path nil :wait nil)))
139 #-(or clisp cmu sbcl gcl scl lispworks ecl ccl allegro abcl)
140 (merror (intl:gettext "plotting: I don't know how to tell this Lisp to run Gnuplot."))
142 (if (null *gnuplot-stream*)
143 (merror (intl:gettext "plotting: I tried to execute ~s but *GNUPLOT-STREAM* is still null.~%") path))
145 ;; set mouse must be the first command send to gnuplot
146 (send-gnuplot-command "set mouse"))
148 (defun check-gnuplot-process ()
149 (if (null *gnuplot-stream*)
150 (start-gnuplot-process $gnuplot_command)))
152 (defmfun $gnuplot_close ()
153 (stop-gnuplot-process)
156 (defmfun $gnuplot_start ()
157 (check-gnuplot-process)
160 (defmfun $gnuplot_restart ()
161 ($gnuplot_close)
162 ($gnuplot_start))
164 (defmfun $gnuplot_send (command)
165 (send-gnuplot-command command))
167 (defun stop-gnuplot-process ()
168 (unless (null *gnuplot-stream*)
169 (progn
170 (close *gnuplot-stream*)
171 (setq *gnuplot-stream* nil))))
173 (defun send-gnuplot-command (command &optional recursive)
174 (if (null *gnuplot-stream*)
175 (start-gnuplot-process $gnuplot_command))
176 (handler-case (unless (null command)
177 (format *gnuplot-stream* "~a ~%" command)
178 (finish-output *gnuplot-stream*))
179 (error (e)
180 ;; allow gnuplot to restart if stream-error, or just an error is signaled
181 ;; only try to restart once, to prevent an infinite loop
182 (cond (recursive
183 (error e))
185 (warn "~a~%Trying new stream.~%" e)
186 (setq *gnuplot-stream* nil)
187 (send-gnuplot-command command t))))))
189 (defmfun $gnuplot_reset ()
190 (send-gnuplot-command "unset output")
191 (send-gnuplot-command "reset"))
193 (defmfun $gnuplot_replot (&optional s)
194 (if (null *gnuplot-stream*)
195 (merror (intl:gettext "gnuplot_replot: Gnuplot is not running.")))
196 (cond ((null s)
197 (send-gnuplot-command "replot"))
198 ((stringp s)
199 (send-gnuplot-command s)
200 (send-gnuplot-command "replot"))
202 (merror (intl:gettext "gnuplot_replot: argument, if present, must be a string; found: ~M") s)))
205 ;; allow this to be set in a system init file (sys-init.lsp)
207 (defmfun $get_plot_option (&optional name n)
208 (let (options)
209 ;; Converts the options property list into a Maxima list
210 (do* ((list (copy-tree *plot-options*) (cddr list))
211 (key (first list) (first list))
212 (value (second list) (second list)))
213 ((endp list))
214 (let ((max-key (intern (concatenate 'string "$" (symbol-name key)))))
215 (if (consp value)
216 (push (cons '(mlist) (cons max-key value)) options)
217 (push (list '(mlist) max-key value) options))))
218 (setf options (cons '(mlist) (nreverse options)))
219 (if name
220 (let ((value (find name (cdr options) :key #'second)))
221 (if n
222 (nth n value)
223 value))
224 options)))
226 (defun quote-strings (opt)
227 (if (atom opt)
228 (if (stringp opt)
229 (format nil "~s" opt)
230 opt)
231 (cons (quote-strings (car opt))
232 (quote-strings (cdr opt)))))
234 (defun get-plot-option-string (option &optional (index 1))
235 (let* ((val ($get_plot_option option 2))
236 (val-list (if ($listp val)
237 (cdr val)
238 `(,val))))
239 (ensure-string (nth (mod (- index 1) (length val-list)) val-list))))
241 (defmfun $set_plot_option (&rest value)
242 (setq *plot-options* (plot-options-parser value *plot-options*))
243 ($get_plot_option))
245 (defmfun $remove_plot_option (name)
246 (remf *plot-options*
247 (case name
248 ($adapt_depth :adapt_depth) ($axes :axes) ($azimuth :azimuth)
249 ($box :box) ($color :color) ($color_bar :color_bar)
250 ($color_bar_tics :color_bar_tics) ($elevation :elevation)
251 ($grid :grid) ($grid2d :grid2d) ($iterations :iterations)
252 ($label :label) ($legend :legend) ($levels :levels)
253 ($logx :logx) ($logy :logy)
254 ($mesh_lines_color :mesh_lines_color) ($nticks :nticks)
255 ($palette :palette) ($plotepsilon :plotepsilon)
256 ($plot_format :plot_format) ($plot_realpart :plot_realpart)
257 ($point_type :point_type) ($pdf_file :pdf_file)
258 ($png_file :png_file) ($ps_file :ps_file)
259 ($run_viewer :run_viewer) ($same_xy :samexy)
260 ($same_xyz :same_xyz) ($sample :sample) ($style :style)
261 ($svg_file :svg_file) ($t :t) ($title :title)
262 ($transform_xy :transform_xy) ($window :window) ($x :x)
263 ($xbounds :xbounds) ($xlabel :xlabel) ($xtics :xtics)
264 ($xy_scale :xy_scale) ($y :y) ($ybounds :ybounds) ($ylabel :ylabel)
265 ($ytics :ytics) ($yx_ratio :yx_ratio) ($z :z) ($zlabel :zlabel)
266 ($zmin :zmin) ($ztics :ztics)
267 ($gnuplot_4_0 :gnuplot_4_0)
268 ($gnuplot_curve_titles :gnuplot_curve_titles)
269 ($gnuplot_curve_styles :gnuplot_curve_styles)
270 ($gnuplot_default_term_command :gnuplot_default_term_command)
271 ($gnuplot_dumb_term_command :gnuplot_dumb_term_command)
272 ($gnuplot_out_file :gnuplot_out_file)
273 ($gnuplot_pm3d :gnuplot_pm3d)
274 ($gnuplot_strings :gnuplot_strings)
275 ($gnuplot_preamble :gnuplot_preamble)
276 ($gnuplot_postamble :gnuplot_postamble)
277 ($gnuplot_pdf_term_command :gnuplot_pdf_term_command)
278 ($gnuplot_png_term_command :gnuplot_png_term_command)
279 ($gnuplot_ps_term_command :gnuplot_ps_term_command)
280 ($gnuplot_svg_term_command :gnuplot_svg_term_command)
281 ($gnuplot_term :gnuplot_term))))
283 (defun get-gnuplot-term (term)
284 (let* ((sterm (string-downcase (ensure-string term)))
285 (pos (search " " sterm)))
286 (if pos
287 (subseq sterm 0 pos)
288 sterm)))
290 (defvar $pstream nil)
292 (defun print-pt1 (f str)
293 (if (floatp f)
294 (format str "~,,,,,,'eg " f)
295 (format str "~a " *missing-data-indicator*)))
297 (defstruct (polygon (:type list)
298 (:constructor %make-polygon (pts edges)))
299 (dummy '($polygon simp))
300 pts edges)
302 (eval-when
303 (:compile-toplevel :execute)
305 (defmacro z-pt (ar i) `(aref ,ar (the fixnum (+ 2 (* ,i 3)))))
306 (defmacro y-pt (ar i) `(aref ,ar (the fixnum (1+ (* ,i 3)))))
307 (defmacro x-pt (ar i) `(aref ,ar (the fixnum (* ,i 3))))
308 (defmacro rot (m i j) `(aref ,m (the fixnum (+ ,i (the fixnum (* 3 ,j))))))
310 (defmacro print-pt (f)
311 `(print-pt1 ,f $pstream ))
313 (defmacro make-polygon (a b)
314 `(list '($polygon) ,a ,b)))
316 (defun draw3d (f minx maxx miny maxy nxint nyint)
317 (let* ((epsx (/ (- maxx minx) nxint))
318 (x 0.0) ( y 0.0)
319 (epsy (/ (- maxy miny) nyint))
320 (nx (+ nxint 1))
321 (l 0)
322 (ny (+ nyint 1))
323 (ar (make-array (+ 12 ; 12 for axes
324 (* 3 nx ny)) :fill-pointer (* 3 nx ny)
325 :element-type t :adjustable t)))
326 (declare (type flonum x y epsy epsx)
327 (fixnum nx ny l)
328 (type (cl:array t) ar))
329 (loop for j below ny
330 initially (setq y miny)
331 do (setq x minx)
332 (loop for i below nx
334 (setf (x-pt ar l) x)
335 (setf (y-pt ar l) y)
336 (setf (z-pt ar l) (funcall f x y))
337 (incf l)
338 (setq x (+ x epsx))
340 (setq y (+ y epsy)))
341 (make-polygon ar (make-grid-vertices nxint nyint))))
343 ;; The following is 3x2 = 6 rectangles
344 ;; call (make-vertices 3 2)
345 ;; there are 4x3 = 12 points.
346 ;; ordering is x0,y0,z0,x1,y1,z1,....,x11,y11,z11
347 ;; ----
348 ;; ||||
349 ;; ----
350 ;; ||||
351 ;; ----
353 (defun make-grid-vertices (nx ny)
354 (declare (fixnum nx ny))
355 (let* ((tem (make-array (+ 15 (* 5 nx ny)) :fill-pointer (* 5 nx ny)
356 :adjustable t
357 :element-type '(mod #x80000000)))
358 (m nx )
359 (nxpt (+ nx 1))
360 (i 0)
362 (declare (fixnum i nxpt m)
363 (type (cl:array (mod #x80000000)) tem))
364 (loop for k below (length tem)
366 (setf (aref tem k) i)
367 (setf (aref tem (incf k))
368 (+ nxpt i))
369 (setf (aref tem (incf k))
370 (+ nxpt (incf i )))
371 (setf (aref tem (incf k)) i)
372 (setf (aref tem (incf k)) 0) ;place for max
373 (setq m (- m 1))
374 (cond ((eql m 0)
375 (setq m nx)
376 (setq i (+ i 1))))
378 tem))
380 (defmfun $rotation1 (phi th)
381 (let ((sinph (sin phi))
382 (cosph (cos phi))
383 (sinth (sin th))
384 (costh (cos th)))
385 `(($matrix simp)
386 ((mlist simp) ,(* cosph costh)
387 ,(* -1.0 cosph sinth)
388 ,sinph)
389 ((mlist simp) ,sinth ,costh 0.0)
390 ((mlist simp) ,(- (* sinph costh))
391 ,(* sinph sinth)
392 ,cosph))))
394 ;; pts is a vector of bts [x0,y0,z0,x1,y1,z1,...] and each tuple xi,yi,zi is rotated
395 #-abcl (defmfun $rotate_pts(pts rotation-matrix)
396 (or ($matrixp rotation-matrix) (merror (intl:gettext "rotate_pts: second argument must be a matrix.")))
397 (let* ((rot *rot*)
398 (l (length pts))
399 (x 0.0) (y 0.0) (z 0.0)
401 (declare (type flonum x y z))
402 (declare (type (cl:array flonum) rot))
403 ($copy_pts rotation-matrix *rot* 0)
405 (loop with j = 0
406 while (< j l)
408 (setq x (aref pts j))
409 (setq y (aref pts (+ j 1)))
410 (setq z (aref pts (+ j 2)))
411 (loop for i below 3 with a of-type flonum = 0.0
413 (setq a (* x (aref rot (+ (* 3 i) 0))))
414 (setq a (+ a (* y (aref rot (+ (* 3 i) 1)))))
415 (setq a (+ a (* z (aref rot (+ (* 3 i) 2)))))
416 (setf (aref pts (+ j i )) a))
417 (setf j (+ j 3)))))
419 (defmfun $rotate_list (x)
420 (cond ((and ($listp x) (not (mbagp (second x))))
421 ($list_matrix_entries (ncmul2 $rot x)))
422 ((mbagp x) (cons (car x) (mapcar '$rotate_list (cdr x))))))
424 (defmfun $get_range (pts k &aux (z 0.0) (max most-negative-flonum) (min most-positive-flonum))
425 (declare (type flonum z max min))
426 (declare (type (vector flonum) pts))
427 (loop for i from k below (length pts) by 3
428 do (setq z (aref pts i))
429 (cond ((< z min) (setq min z)))
430 (cond ((> z max) (setq max z))))
431 (list min max (- max min)))
433 (defmfun $polar_to_xy (pts &aux (r 0.0) (th 0.0))
434 (declare (type flonum r th))
435 (declare (type (cl:array t) pts))
436 (assert (typep pts '(vector t)))
437 (loop for i below (length pts) by 3
438 do (setq r (aref pts i))
439 (setq th (aref pts (+ i 1)))
440 (setf (aref pts i) (* r (cos th)))
441 (setf (aref pts (+ i 1)) (* r (sin th)))))
443 ;; Transformation from spherical coordinates to rectangular coordinates,
444 ;; to be used in plot3d. Example of its use:
445 ;; plot3d (expr, [th, 0, %pi], [ph, 0, 2*%pi], [transform_xy, spherical_to_xyz])
446 ;; where expr gives the value of r in terms of the inclination (th)
447 ;; and azimuth (ph).
449 (defmfun $spherical_to_xyz (pts &aux (r 0.0) (th 0.0) (ph 0.0))
450 (declare (type flonum r th ph))
451 (declare (type (cl:array t) pts))
452 (assert (typep pts '(vector t)))
453 (loop for i below (length pts) by 3
454 do (setq th (aref pts i))
455 (setq ph (aref pts (+ i 1)))
456 (setq r (aref pts (+ i 2)))
457 (setf (aref pts i) (* r (sin th) (cos ph)))
458 (setf (aref pts (+ i 1)) (* r (sin th) (sin ph)))
459 (setf (aref pts (+ i 2)) (* r (cos th)))))
462 ;; return a function suitable for the transform function in plot3d.
463 ;; FX, FY, and FZ are functions of three arguments.
464 (defmfun $make_transform (lvars fx fy fz)
465 (setq fx (coerce-float-fun fx lvars "make_transform"))
466 (setq fy (coerce-float-fun fy lvars "make_transform"))
467 (setq fz (coerce-float-fun fz lvars "make_transform"))
468 (let ((sym (gensym "transform")))
469 (setf (symbol-function sym)
470 #'(lambda (pts &aux (x1 0.0)(x2 0.0)(x3 0.0))
471 (declare (type flonum x1 x2 x3))
472 (declare (type (cl:array t) pts))
473 (loop for i below (length pts) by 3
475 (setq x1 (aref pts i))
476 (setq x2 (aref pts (+ i 1)))
477 (setq x3 (aref pts (+ i 2)))
478 (setf (aref pts i) (funcall fx x1 x2 x3))
479 (setf (aref pts (+ 1 i)) (funcall fy x1 x2 x3))
480 (setf (aref pts (+ 2 i)) (funcall fz x1 x2 x3)))))))
482 ;; Return value is a Lisp function which evaluates EXPR to a float.
483 ;; COERCE-FLOAT-FUN always returns a function and never returns a symbol,
484 ;; even if EXPR is a symbol.
486 ;; Following cases are recognized:
487 ;; EXPR is a symbol
488 ;; name of a Lisp function
489 ;; name of a Maxima function
490 ;; name of a DEFMSPEC function
491 ;; name of a Maxima macro
492 ;; a string which is the name of a Maxima operator (e.g., "!")
493 ;; name of a simplifying function
494 ;; EXPR is a Maxima lambda expression
495 ;; EXPR is a general Maxima expression
497 ;; %COERCE-FLOAT-FUN is the main internal routine for this.
498 ;; COERCE-FLOAT-FUN is the user interface for creating a function that
499 ;; returns floats. COERCE-BFLOAT-FUN is the same, except bfloats are
500 ;; returned.
501 (defun %coerce-float-fun (float-fun expr &rest rest &aux lvars fname)
502 (case (length rest)
503 (0 (setq lvars nil) (setq fname "coerce-float-fun"))
504 (1 (setq lvars (first rest)) (setq fname "coerce-float-fun"))
505 (2 (setq lvars (first rest)) (setq fname (second rest)))
506 (t (merror (intl:gettext "coerce-float-fun: two many arguments given."))))
507 (cond ((and (consp expr) (functionp expr))
508 (let ((args (if lvars (cdr lvars) (list (gensym)))))
509 (coerce-lisp-function-or-lisp-lambda args expr :float-fun float-fun)))
510 ;; expr is a string which names an operator
511 ;; (e.g. "!" "+" or a user-defined operator)
512 ((and (stringp expr) (getopr0 expr))
513 (let ((a (if lvars lvars `((mlist) ,(gensym)))))
514 (%coerce-float-fun float-fun `(($apply) ,(getopr0 expr) ,a) a fname)))
515 ((and (symbolp expr) (not (member expr lvars)) (not ($constantp expr)))
516 (cond
517 ((fboundp expr)
518 (let ((args (if lvars (cdr lvars) (list (gensym)))))
519 (coerce-lisp-function-or-lisp-lambda args expr :float-fun float-fun)))
520 ;; expr is name of a Maxima function defined by := or
521 ;; define
522 ((mget expr 'mexpr)
523 (let*
524 ((mexpr (mget expr 'mexpr))
525 (args (cdr (second mexpr))))
526 (coerce-maxima-function-or-maxima-lambda
527 args expr :float-fun float-fun)))
528 ((or
529 ;; expr is the name of a function defined by defmspec
530 (get expr 'mfexpr*)
531 ;; expr is the name of a Maxima macro defined by ::=
532 (mget expr 'mmacro)
533 ;; expr is the name of a simplifying function, and the
534 ;; simplification property is associated with the noun
535 ;; form
536 (get ($nounify expr) 'operators)
537 ;; expr is the name of a simplifying function, and the
538 ;; simplification property is associated with the verb
539 ;; form
540 (get ($verbify expr) 'operators))
541 (let ((a (if lvars lvars `((mlist) ,(gensym)))))
542 (%coerce-float-fun float-fun `(($apply) ,expr ,a) a fname)))
544 (merror (intl:gettext "~a: unknown function: ~M")
545 fname expr))))
546 ((and (consp expr) (eq (caar expr) 'lambda))
547 (let ((args (cdr (second expr))))
548 (coerce-maxima-function-or-maxima-lambda
549 args expr :float-fun float-fun)))
551 (let* ((vars (or lvars ($sort ($listofvars expr))))
552 (subscripted-vars ($sublist vars '((lambda) ((mlist) $x) ((mnot) (($atom) $x)))))
553 gensym-vars save-list-gensym subscripted-vars-save
554 subscripted-vars-mset subscripted-vars-restore)
556 ;; VARS and SUBSCRIPTED-VARS are Maxima lists. Other lists are
557 ;; Lisp lists.
558 (when (cdr subscripted-vars)
559 (setq gensym-vars (mapcar #'(lambda (ign) (declare (ignore ign)) (gensym))
560 (cdr subscripted-vars)))
561 (mapcar #'(lambda (a b) (setq vars (subst b a vars :test 'equal)))
562 (cdr subscripted-vars) gensym-vars)
564 ;; This stuff about saving and restoring array variables
565 ;; should go into MBINDING, and the lambda expression
566 ;; constructed below should call MBINDING. (At present
567 ;; MBINDING barfs on array variables.)
568 (setq save-list-gensym (gensym))
569 (setq subscripted-vars-save
570 (mapcar #'(lambda (a) `(push (meval ',a) ,save-list-gensym))
571 (cdr subscripted-vars)))
572 (setq subscripted-vars-mset
573 (mapcar #'(lambda (a b) `(mset ',a ,b))
574 (cdr subscripted-vars) gensym-vars))
575 (setq subscripted-vars-restore
576 (mapcar #'(lambda (a) `(mset ',a (pop ,save-list-gensym)))
577 (reverse (cdr subscripted-vars)))))
579 (coerce
580 `(lambda ,(cdr vars)
581 (declare (special ,@(cdr vars)))
583 ;; Nothing interpolated here when there are no subscripted
584 ;; variables.
585 ,@(if save-list-gensym `((declare (special ,save-list-gensym))))
587 ;; Nothing interpolated here when there are no subscripted
588 ;; variables.
589 ,@(if (cdr subscripted-vars)
590 `((progn (setq ,save-list-gensym nil)
591 ,@(append subscripted-vars-save subscripted-vars-mset))))
593 (let (($ratprint nil)
594 ;; We don't want to set $numer to T when coercing
595 ;; to a bigfloat. By doing so, things like
596 ;; log(400)^400 get converted to double-floats,
597 ;; which causes a double-float overflow. But the
598 ;; whole point of coercing to bfloat is to use
599 ;; bfloats, not doubles.
601 ;; Perhaps we don't even need to do this for
602 ;; double-floats? It would be nice to remove
603 ;; this. For backward compatibility, we bind
604 ;; numer to T if we're not trying to bfloat.
605 ($numer ,(not (eq float-fun '$bfloat)))
606 (*nounsflag* t))
607 ;; Catch any errors from evaluating the
608 ;; function. We're assuming that if an error
609 ;; is caught, the result is not a number. We
610 ;; also assume that for such errors, it's
611 ;; because the function is not defined there,
612 ;; not because of some other maxima error.
613 (let ((result
614 (errcatch (,float-fun (maybe-realpart (meval* ',expr))))))
616 ;; Nothing interpolated here when there are no
617 ;; subscripted variables.
618 ,@(if (cdr subscripted-vars) `((progn ,@subscripted-vars-restore)))
620 (if result
621 (car result)
622 t))))
623 'function)))))
624 ;; coerce-float-fun must be given an expression and one or two other optional
625 ;; arguments: a Maxima list of variables on which that expression depends
626 ;; and string that will identify the name of the responsible function
627 ;; when reporting errors.
628 (defun coerce-float-fun (expr &rest rest &aux lvars fname)
629 (case (length rest)
630 (0 (setq lvars nil) (setq fname "coerce-float-fun"))
632 (if (stringp (first rest))
633 (progn (setq lvars nil) (setq fname (first rest)))
634 (if ($listp (first rest))
635 (progn (setq lvars (first rest)) (setq fname "coerce-float-fun"))
636 (merror
637 (intl:gettext "coerce-float-fun: expecting a Maxima list, found: ~M")
638 (first rest)))))
640 (if ($listp (first rest))
641 (setq lvars (first rest))
642 (merror
643 (intl:gettext "coerce-float-fun: expecting a Maxima list, found: ~M")
644 (first rest)))
645 (if (stringp (second rest))
646 (setq fname (second rest))
647 (merror
648 (intl:gettext "coerce-float-fun: expecting a string, found: ~M")
649 (second rest))))
650 (t (merror (intl:gettext "coerce-float-fun: two many arguments given."))))
651 (%coerce-float-fun '$float expr lvars fname))
653 ;; coerce-bfloat-fun must be given an expression and one or two other optional
654 ;; arguments: a Maxima list of variables on which that expression depends
655 ;; and string that will identify the name of the responsible function
656 ;; when reporting errors.
657 (defun coerce-bfloat-fun (expr &rest rest &aux lvars fname)
658 (case (length rest)
659 (0 (setq lvars nil) (setq fname "coerce-bfloat-fun"))
661 (if (stringp (first rest))
662 (progn (setq lvars nil) (setq fname (first rest)))
663 (if ($listp (first rest))
664 (progn (setq lvars (first rest)) (setq fname "coerce-float-fun"))
665 (merror
666 (intl:gettext "coerce-bfloat-fun: expecting a Maxima list, found: ~M")
667 (first rest)))))
669 (if ($listp (first rest))
670 (setq lvars (first rest))
671 (merror
672 (intl:gettext "coerce-bfloat-fun: expecting a Maxima list, found: ~M")
673 (first rest)))
674 (if (stringp (second rest))
675 (setq fname (second rest))
676 (merror
677 (intl:gettext "coerce-bfloat-fun: expecting a string, found: ~M")
678 (second rest))))
679 (t (merror (intl:gettext "coerce-bfloat-fun: two many arguments given."))))
680 (%coerce-float-fun '$bfloat expr lvars fname))
682 (defun coerce-maxima-function-or-maxima-lambda
683 (args expr &key (float-fun '$float))
684 (let ((gensym-args (loop for x in args collect (gensym))))
685 (coerce
686 `(lambda ,gensym-args (declare (special ,@gensym-args))
687 ;; Just always try to convert the result with
688 ;; float-fun, which handles things like $%pi.
689 ;; See also BUG
690 ;; https://sourceforge.net/p/maxima/bugs/1795/
691 (let* (($ratprint nil)
692 ($numer t)
693 (*nounsflag* t)
694 (result
695 (errcatch
696 (,float-fun (maybe-realpart (mapply ',expr (list ,@gensym-args) t))))))
697 (if result
698 (car result)
699 t)))
700 'function)))
702 ;; Same as above, but call APPLY instead of MAPPLY.
704 (defun coerce-lisp-function-or-lisp-lambda
705 (args expr &key (float-fun '$float))
706 (let ((gensym-args (loop for x in args collect (gensym))))
707 (coerce
708 `(lambda ,gensym-args (declare (special ,@gensym-args))
709 (let* (($ratprint nil)
710 ($numer t)
711 (*nounsflag* t)
712 (result (maybe-realpart (apply ',expr (list ,@gensym-args)))))
713 ;; Always use float-fun. See comment for
714 ;; coerce-maxima-function-or-maxima-lambda above.
715 (,float-fun result)))
716 'function)))
718 (defmacro zval (points verts i) `(aref ,points (+ 2 (* 3 (aref ,verts ,i)))))
720 ;;sort the edges array so that drawing the edges will happen from the back towards
721 ;; the front. The if n==4 the edges array coming in looks like
722 ;; v1 v2 v3 v4 0 w1 w2 w3 w4 0 ...
723 ;; where vi,wi are indices pointint into the points array specifying a point
724 ;; in 3 space. After the sorting is done, the 0 is filled in with the vertex
725 ;; which is closer to us (ie highest z component after rotating towards the user)
726 ;; and this is then they are sorted in groups of 5.
727 (defun sort-ngons (points edges n &aux lis )
728 (declare (type (cl:array (flonum)) points)
729 (type (cl:array (mod #x80000000)) edges)
730 (fixnum n))
731 (let ((new (make-array (length edges) :element-type (array-element-type edges)))
732 (i 0)
733 (z 0.0)
734 (z1 0.0)
735 (n1 (- n 1))
736 (at 0)
737 (leng (length edges))
739 (declare (type (cl:array (mod #x80000000)) new)
740 (fixnum i leng n1 at )
742 (declare (type flonum z z1))
744 (setq lis
745 (loop for i0 below leng by (+ n 1)
747 (setq i i0)
748 (setq at 0)
749 (setq z (zval points edges i))
750 (setq i (+ i 1))
751 (loop for j below n1
752 do (if (> (setq z1 (zval points edges i)) z)
753 (setq z z1 at (aref edges i) ))
754 (setq i (+ i 1))
756 (setf (aref edges i) at)
757 collect (cons z i0)))
758 (setq lis (sort lis #'alphalessp :key #'car))
759 (setq i 0)
760 (loop for v in lis
762 (loop for j from (cdr v)
763 for k to n
764 do (setf (aref new i) (aref edges j))
765 (incf i))
767 (copy-array-portion edges new 0 0 (length edges))
770 (defun copy-array-portion (ar1 ar2 i1 i2 n1)
771 (declare (fixnum i1 i2 n1))
772 (loop while (>= (setq n1 (- n1 1)) 0)
773 do (setf (aref ar1 i1) (aref ar2 i2))
774 (setq i1 (+ i1 1))
775 (setq i2 (+ i2 1))))
778 (defmfun $concat_polygons (pl1 pl2 &aux tem new)
779 (setq new
780 (loop for v in pl1
781 for w in pl2
782 for l = (+ (length v) (length w))
783 do (setq tem (make-array l
784 :element-type (array-element-type v)
785 :fill-pointer l
788 collect tem))
789 (setq new (make-polygon (first new) (second new)) )
791 (copy-array-portion (polygon-pts pl1) (polygon-pts new)
792 0 0 (length (polygon-pts pl1)))
793 (copy-array-portion (polygon-pts pl2) (polygon-pts new)
794 (length (polygon-pts pl1))
795 0 (length (polygon-pts pl2)))
796 (copy-array-portion (polygon-edges pl1) (polygon-edges new)
797 0 0 (length (polygon-edges pl1)))
798 (loop for i from (length (polygon-edges pl1))
799 for j from 0 below (length (polygon-edges pl2))
800 with lpts1 = (length (polygon-pts pl1))
801 with ar2 = (polygon-edges pl2)
802 with arnew = (polygon-edges new)
803 do (setf (aref arnew i) (+ lpts1 (aref ar2 j)))))
805 (defmfun $copy_pts(lis vec start)
806 (declare (fixnum start))
807 (let ((tem vec))
808 (declare (type (cl:array flonum) tem))
809 (cond ((numberp lis)
810 (or (typep lis 'flonum) (setq lis (float lis)))
811 (setf (aref tem start) lis)
812 (1+ start))
813 ((typep lis 'cons)
814 ($copy_pts (cdr lis) vec ($copy_pts (car lis) vec start)))
815 ((symbolp lis) start)
816 (t (merror (intl:gettext "copy_pts: unrecognized first argument: ~M") lis)))))
818 ;; Implicit expressions of two variables, for instance, x and y,
819 ;; where expr is of the form f(x,y) = g(x,y).
820 ;; The result is a series of separated line segments.
822 (defun draw2d-implicit (expr options)
823 (let* ((xmin (first (getf options :x)))
824 (ymin (first (getf options :y)))
825 (xmax (second (getf options :x)))
826 (ymax (second (getf options :y)))
827 (gridx (or (first (getf options :sample)) 50))
828 (gridy (or (second (getf options :sample)) 50))
829 (eps (or (getf options :plotepsilon) 1e-6))
830 (f (make-array `(,(1+ gridx) ,(1+ gridy))))
831 vx vy dx dy fun faux fmax fmin levels values result results)
832 (setq dx (/ (- xmax xmin) gridx) dy (/ (- ymax ymin) gridy))
833 (setq vx (getf options :xvar) vy (getf options :yvar))
834 (if (getf options :contour)
835 (setq fun expr)
836 (setq fun (m- ($lhs expr) ($rhs expr))))
837 (setq fun (coerce-float-fun fun `((mlist) ,vx ,vy) "plot2d"))
838 ;; sets up array f with values of the function at corners of sample grid.
839 ;; finds maximum and minimum values in that array.
840 (dotimes (i (1+ gridx))
841 (dotimes (j (1+ gridy))
842 (setq faux (funcall fun (+ xmin (* i dx)) (+ ymin (* j dy))))
843 (setf (aref f i j) faux)
844 (when (and (numberp faux) (plusp i) (plusp j) (< i gridx) (< j gridy))
845 (if (numberp fmin)
846 (if (numberp fmax)
847 (progn
848 (when (< faux fmin) (setq fmin faux))
849 (when (> faux fmax) (setq fmax faux)))
850 (if (< faux fmin)
851 (setq fmax fmin fmin faux)
852 (setq fmax faux)))
853 (if (numberp fmax)
854 (if (> faux fmax)
855 (setq fmin fmax fmax faux)
856 (setq fmin faux))
857 (setq fmin faux))))))
858 ;; checks that the function has a minimum and a maximum
859 (when
861 (not (numberp fmin))
862 (not (numberp fmax)) (not (> fmax fmin)))
863 (merror (intl:gettext "plot2d: nothing to plot for ~M.~%") expr))
864 ;; sets up the levels for contour plots
865 (if (getf options :contour)
866 (if (setq levels (getf options :levels))
867 (unless (listp levels)
868 (setq levels (getlevels fmin fmax levels)))
869 (setq levels (getlevels fmin fmax 8)))
870 (setq levels (list 0.0)))
872 ;; Algorithm for implicit functions, by Jaime Villate. 2021
874 ;; The points at each rectangle in the sample grid are labeled as follows:
876 ;; ij+ ______ i+j+
877 ;; | |
878 ;; | | function fun has the following values at those points:
879 ;; | |
880 ;; ij |____| i+j fij, fi+j, fij+, fi+j+
882 (let (fij fi+j fij+ fi+j+ p1 p2 p3 p4 next)
883 (flet
884 ((interp+ (i j fi fi+ &aux x1 y1 x2 y2 (f1 fi) (f2 fi+) xp yp fp)
885 (if (minusp (* fi fi+))
886 (progn
887 (setq x1 (+ xmin (* dx i)))
888 (setq x2 (+ x1 dx))
889 (setq y1 (+ ymin (* dy j)))
890 (setq y2 (+ y1 dy))
891 (dotimes (n 2
892 (if (< (/ (+ (abs (- fi fp)) (abs (- fi+ fp)))
893 (abs (- fi fi+))) 1.5) (list xp yp) nil))
894 (setq xp (/ (+ x1 x2) 2.0))
895 (setq yp (/ (+ y1 y2) 2.0))
896 (setq fp (- (funcall fun xp yp) level))
897 (when (not (numberp fp)) (return nil))
898 (if (plusp (* f1 fp))
899 (setq x1 xp y1 yp f1 fp)
900 (setq x2 xp y2 yp f2 fp))
901 (setq xp (/ (- (* f1 x2) (* f2 x1)) (- f1 f2)))
902 (setq yp (/ (- (* f1 y2) (* f2 y1)) (- f1 f2)))
903 (setq fp (- (funcall fun xp yp) level))
904 (when (not (numberp fp)) (return nil))
905 (if (plusp (* f1 fp))
906 (setq x1 xp y1 yp f1 fp)
907 (setq x2 xp y2 yp f2 fp))))
908 nil))
909 (interp- (i j fi fi+ &aux x1 y1 x2 y2 (f1 fi) (f2 fi+) xp yp fp)
910 (if (minusp (* fi fi+))
911 (progn
912 (setq x1 (+ xmin (* dx i)))
913 (setq x2 (+ x1 dx))
914 (setq y1 (+ ymin (* dy j)))
915 (setq y2 (- y1 dy))
916 (dotimes (n 2
917 (if (< (/ (+ (abs (- fi fp)) (abs (- fi+ fp)))
918 (abs (- fi fi+))) 1.5) (list xp yp) nil))
919 (setq xp (/ (+ x1 x2) 2.0))
920 (setq yp (/ (+ y1 y2) 2.0))
921 (setq fp (- (funcall fun xp yp) level))
922 (when (not (numberp fp)) (return nil))
923 (if (plusp (* f1 fp))
924 (setq x1 xp y1 yp f1 fp)
925 (setq x2 xp y2 yp f2 fp))
926 (setq xp (/ (- (* f1 x2) (* f2 x1)) (- f1 f2)))
927 (setq yp (/ (- (* f1 y2) (* f2 y1)) (- f1 f2)))
928 (setq fp (- (funcall fun xp yp) level))
929 (when (not (numberp fp)) (return nil))
930 (if (plusp (* f1 fp))
931 (setq x1 xp y1 yp f1 fp)
932 (setq x2 xp y2 yp f2 fp))))
933 nil))
934 (interpx (i j fi fi+ &aux x1 x2 (f1 fi) (f2 fi+) xp yp fp)
935 (if (minusp (* fi fi+))
936 (progn
937 (setq x1 (+ xmin (* dx i)))
938 (setq x2 (+ x1 dx))
939 (setq yp (+ ymin (* dy j)))
940 (dotimes (n 2
941 (if (< (/ (+ (abs (- fi fp)) (abs (- fi+ fp)))
942 (abs (- fi fi+))) 1.5) (list xp yp) nil))
943 (setq xp (/ (+ x1 x2) 2.0))
944 (setq fp (- (funcall fun xp yp) level))
945 (when (not (numberp fp)) (return nil))
946 (if (plusp (* f1 fp))
947 (setq x1 xp f1 fp)
948 (setq x2 xp f2 fp))
949 (setq xp (/ (- (* f1 x2) (* f2 x1)) (- f1 f2)))
950 (setq fp (- (funcall fun xp yp) level))
951 (when (not (numberp fp)) (return nil))
952 (if (plusp (* f1 fp))
953 (setq x1 xp f1 fp)
954 (setq x2 xp f2 fp))))
955 nil))
956 (interpy (i j fj fj+ &aux y1 y2 (f1 fj) (f2 fj+) xp yp fp)
957 (if (minusp (* fj fj+))
958 (progn
959 (setq xp (+ xmin (* dx i)))
960 (setq y1 (+ ymin (* dy j)))
961 (setq y2 (+ y1 dy))
962 (dotimes (n 2
963 (if (< (/ (+ (abs (- fj fp)) (abs (- fj+ fp)))
964 (abs (- fj fj+))) 1.5) (list xp yp) nil))
965 (setq yp (/ (+ y1 y2) 2.0))
966 (setq fp (- (funcall fun xp yp) level))
967 (when (not (numberp fp)) (return nil))
968 (if (plusp (* f1 fp))
969 (setq y1 yp f1 fp)
970 (setq y2 yp f2 fp))
971 (setq yp (/ (- (* f1 y2) (* f2 y1)) (- f1 f2)))
972 (setq fp (- (funcall fun xp yp) level))
973 (when (not (numberp fp)) (return nil))
974 (if (plusp (* f1 fp))
975 (setq y1 yp f1 fp)
976 (setq y2 yp f2 fp))))
977 nil))
978 (coords (i j)
979 (list (+ xmin (* i dx)) (+ ymin (* j dy))))
980 (draw-line (p1 p2)
981 (push (first p1) result)
982 (push (second p1) result)
983 (push (first p2) result)
984 (push (second p2) result)
985 (push 'moveto result)
986 (push 'moveto result))
987 (draw-lines (p1 p2 p3)
988 (push (first p1) result)
989 (push (second p1) result)
990 (push (first p2) result)
991 (push (second p2) result)
992 (push (first p3) result)
993 (push (second p3) result)
994 (push 'moveto result)
995 (push 'moveto result)))
996 (dolist (level (reverse levels))
997 (dotimes (i gridx)
998 (dotimes (j gridy)
999 (if (numberp (aref f i j))
1000 (setq fij (- (aref f i j) level))
1001 (setq fij (aref f i j)))
1002 (if (numberp (aref f i (1+ j)))
1003 (setq fij+ (- (aref f i (1+ j)) level))
1004 (setq fij+ (aref f i (1+ j))))
1005 (if (numberp (aref f (1+ i) j))
1006 (setq fi+j (- (aref f (1+ i) j) level))
1007 (setq fi+j (aref f (1+ i) j)))
1008 (if (numberp (aref f (1+ i) (1+ j)))
1009 (setq fi+j+ (- (aref f (1+ i) (1+ j)) level))
1010 (setq fi+j+ (aref f (1+ i) (1+ j))))
1011 (setq next t)
1012 ;; 1. undefined at ij
1013 (when (not (numberp fij))
1014 (setq next nil)
1015 ;; if undefined also at i+j or ij+, continue to next rectangle
1016 (when (and (numberp fi+j) (numberp fij+))
1017 (if (< (abs fi+j) eps)
1018 (if (< (abs fij+) eps)
1019 ;; real and 0 at i+j and ij+
1020 (draw-line (coords (1+ i) j) (coords i (1+ j)))
1021 (when
1022 (and
1023 (numberp fi+j+)
1024 (setq p2 (interpx i (1+ j) fij+ fi+j+)))
1025 ;; real at i+j, ij+ and i+j+, 0 at i+j and segment
1026 ;; ij+ i+j+
1027 (draw-line (coords (1+ i) j) p2)))
1028 (when (numberp fi+j+)
1029 (if (< (abs fij+) eps)
1030 (when (setq p2 (interpy (1+ i) j fi+j fi+j+))
1031 ;; real at i+j, and i+j+, 0 at ij+ and segment
1032 ;; i+j i+j+
1033 (draw-line (coords i (1+ j)) p2))
1034 (when
1035 (and
1036 (setq p1 (interpx i (1+ j) fij+ fi+j+))
1037 (setq p2 (interpy (1+ i) j fi+j fi+j+)))
1038 ;; real at i+j, ij+ and i+j+, 0 at segments
1039 ;; ij+ i+j+ and i+j i+j+
1040 (draw-line p1 p2)))))))
1041 ;; 2. real at ij and undefined at i+j
1042 (when (and next (not (numberp fi+j)))
1043 (setq next nil)
1044 ;; if undefined at ij+, continue to next rectangle
1045 (when (numberp fij+)
1046 (if (< (abs fij) eps)
1047 (if (< (abs fij+) eps)
1048 ;; zero at ij and ij+
1049 (draw-line (coords i j) (coords i (1+ j)))
1050 (when
1051 (and
1052 (numberp fi+j+)
1053 (setq p2 (interpx i (1+ j) fij+ fi+j+)))
1054 ;; real at ij+ and i+j+, 0 at ij and segment ij+ i+j+
1055 (draw-line (coords i j) p2)))
1056 (when
1057 (and
1058 (numberp fi+j+)
1059 (setq p1 (interpy i j fij fij+))
1060 (setq p2 (interpx i (1+ j) fij+ fi+j+)))
1061 ;; real at ij, ij+ and i+j+, 0 at segments ij ij+
1062 ;; and ij+ i+j+
1063 (draw-line p1 p2)))))
1064 ;; 3. real at fi+j and 0 at ij
1065 (when (and next (< (abs fij) eps))
1066 (setq next nil)
1067 (if (numberp fij+)
1068 (if (< (abs fij+) eps)
1069 ;; real at i+j, 0 at ij and ij+
1070 (draw-line (coords i j) (coords i (1+ j)))
1071 (when (setq p1 (interp- i (1+ j) fij+ fi+j))
1072 (if (numberp fi+j+)
1073 (if (< (abs fi+j+) eps)
1074 ;; real at i+j and ij, 0 at ij, i+j+ and
1075 ;; diagonal ij+ i+j
1076 (draw-lines (coords i j) p1
1077 (coords (1+ i) (1+ j)))
1078 (progn
1079 ;; real at i+j, ij+ and i+j+, 0 at ij,
1080 ;; diagonal ij+ i+j and segment ij+ i+j+
1081 (when (setq p2 (interpx i (1+ j) fij+ fi+j+))
1082 (draw-lines (coords i j) p1 p2))
1083 ;; real at i+j, ij+ and i+j+, 0 at ij,
1084 ;; diagonal ij+ i+j and segment i+j i+j+
1085 (when (setq p2 (interpy (1+ i) j fi+j fi+j+))
1086 (draw-lines (coords i j) p1 p2)))))))
1087 (if (numberp fi+j+)
1088 (if (< (abs fi+j) eps)
1089 ;; undefined at ij+, real at fi+j+, 0 at ij and i+j
1090 (draw-line (coords i j) (coords (1+ i) j))
1091 (when (setq p2 (interpy (1+ i) j fi+j fi+j+))
1092 ;; undefined at ij+, real at fi+j and fi+j+, 0 at
1093 ;; ij and segment i+j i+j+
1094 (draw-line (coords i j) p2)))
1095 (when (< (abs fi+j) eps)
1096 ;; undefined at ij+ and i+j+, 0 at ij and i+j
1097 (draw-line (coords i j) (coords (1+ i) j))))))
1098 ;; 4. real at ij and 0 at i+j
1099 (when (and next (< (abs fi+j) eps))
1100 (setq next nil)
1101 (if (numberp fij+)
1102 (if (numberp fi+j+)
1103 ;; if 0 at i+j but undefined at ij+ or there's no zero
1104 ;; in diagonal ij i+j+, continue to next rectangle
1105 (when (setq p1 (interp+ i j fij fi+j+))
1106 (if (< (abs fij+) eps)
1107 ;; 0 at i+j, ij+ and diagonal ij i+j+
1108 (draw-lines (coords (1+ i) j) p1 (coords i (1+ j)))
1109 (progn
1110 (when (setq p2 (interpy i j fij fij+))
1111 ;; 0 at i+j, diagonal ij i+j+ and segment
1112 ;; ij ij+
1113 (draw-lines (coords (1+ i) j) p1 p2))
1114 (when (setq p2 (interpx i (1+ j) fij+ fi+j+))
1115 ;; 0 at i+j, diagonal ij i+j+ and segment
1116 ;; ij+ i+j+
1117 (draw-lines (coords (1+ i) j) p1 p2)))))
1118 (when (setq p2 (interpy i j fij fij+))
1119 ;; undefined at i+j+, 0 at i+j and segment ij ij+
1120 (draw-line (coords (1+ i) j) p2)))))
1121 ;; 5. real at ij and i+j but undefined at ij+
1122 (when (and next (not (numberp fij+)))
1123 (setq next nil)
1124 (when
1125 (and
1126 (numberp fi+j+)
1127 (setq p1 (interpx i j fij fi+j))
1128 (setq p2 (interpy (1+ i) j fi+j fi+j+)))
1129 ;; 0 at segments ij i+j and i+j i+j+
1130 (draw-line p1 p2)))
1131 ;; 6. real at ij, i+j and ij+, but undefined at i+j+
1132 (when (and next (not (numberp fi+j+)))
1133 (setq next nil)
1134 (when
1135 (and
1136 (setq p1 (interpy i j fij fij+))
1137 (setq p2 (interpx i j fij fi+j)))
1138 ;; 0 at segments ij ij+ and ij i+j
1139 (draw-line p1 p2)))
1140 ;; 7. real at the four corners and 0 at ij+
1141 (when (and next (< (abs fij+) eps))
1142 (setq next nil)
1143 (when (setq p1 (interp+ i j fij fi+j+))
1144 (when (setq p2 (interpx i j fij fi+j))
1145 ;; 0 at diagonal ij i+j+ and segment ij i+j
1146 (draw-lines p2 p1 (coords i (1+ j))))
1147 (when (setq p2 (interpy (1+ i) j fi+j fi+j+))
1148 ;; 0 at diagonal ij i+j+ and segment i+j i+j+
1149 (draw-lines p2 p1 (coords i (1+ j))))))
1150 ;; 8. real at the four corners and 0 at i+j+
1151 (when (and next (< (abs fi+j+) eps))
1152 (setq next nil)
1153 (when (setq p1 (interp- i (1+ j) fij+ fi+j))
1154 (when (setq p2 (interpx i j fij fi+j))
1155 ;; 0 at diagonal ij+ i+j and segment ij i+j
1156 (draw-lines p2 p1 (coords (1+ i) (1+ j))))
1157 (when (setq p2 (interpy i j fij fij+))
1158 ;; 0 at diagonal ij+ i+j and segment ij ij+
1159 (draw-lines p2 p1 (coords (1+ i) (1+ j))))))
1160 ;; 9. real at the four corners and 0 at segment ij i+j
1161 (when (and next (setq p1 (interpx i j fij fi+j)))
1162 (setq next nil)
1163 (if (setq p2 (interpy i j fij fij+))
1164 (if (setq p3 (interpx i (1+ j) fij+ fi+j+))
1165 (when (setq p4 (interpy (1+ i) j fi+j fi+j+))
1166 ;; 0 at the four sides
1167 (draw-line p1 p3)
1168 (draw-line p2 p4))
1169 (when (setq p3 (interp+ i j fij fi+j+))
1170 ;; 0 at segments ij i+j, ij ij+ and diagonal ij i+j+
1171 (draw-lines p1 p3 p2)))
1172 (if (setq p4 (interpy (1+ i) j fi+j fi+j+))
1173 (when (setq p2 (interp- i (1+ j) fij+ fi+j))
1174 ;; 0 at segments ij i+j, i+j i+j+ and diagonal ij+ i+j
1175 (draw-lines p1 p2 p4))
1176 (when
1177 (and
1178 (setq p3 (interpx i (1+ j) fij+ fi+j+))
1179 (setq p2 (interp+ i j fij fi+j+)))
1180 ;; 0 at segments ij i+j, ij+ i+j+ and diagonal ij i+j+
1181 (draw-lines p1 p2 p3)))))
1182 ;; 10. real at the four corners, without zero in segment ij i+j
1183 (when next
1184 (if (setq p2 (interpy i j fij fij+))
1185 (if (setq p3 (interpx i (1+ j) fij+ fi+j+))
1186 (when (setq p4 (interp- i (1+ j) fij+ fi+j))
1187 ;; 0 at segments ij ij+ and ij+ i+j+ and diagonal
1188 ;; ij+ i+j
1189 (draw-lines p2 p4 p3))
1190 (when
1191 (and
1192 (setq p4 (interpy (1+ i) j fi+j fi+j+))
1193 (setq p3 (interp+ i j fij fi+j+)))
1194 ;; 0 at segments ij ij+ and i+j i+j+ and diagonal
1195 ;; ij i+j+
1196 (draw-lines p2 p3 p4)))
1197 (when
1198 (and
1199 (setq p3 (interpx i (1+ j) fij+ fi+j+))
1200 (setq p4 (interpy (1+ i) j fi+j fi+j+))
1201 (setq p1 (interp+ i j fij fi+j+)))
1202 ;; 0 at segments ij+ i+j+ and i+j i+j+ and diagonal
1203 ;; ij i+j+
1204 (draw-lines p4 p1 p3))))))
1205 (when (and (getf options :contour) result)
1206 (push (cons '(mlist) (reverse result)) results)
1207 (push level values)
1208 (setq result nil)))))
1209 ;; When called for a single implicit expression, returns a Maxima list
1210 ;; of points. When called for contours of an expression, returns a
1211 ;; Maxima list whose first element is another Maxima list with the values
1212 ;; of the contours, followed by Maxima lists of points for each contour.
1213 (if (getf options :contour)
1214 (cons '(mlist) (cons (cons '(mlist) values) results))
1215 (cons '(mlist) (reverse result)))))
1217 ;; parametric ; [parametric,xfun,yfun,[t,tlow,thigh],[nticks ..]]
1218 ;; the rest of the parametric list after the list will add to the plot options
1220 (defun draw2d-parametric-adaptive (param options &aux range)
1221 (or (= ($length param) 4)
1222 (merror (intl:gettext "plot2d: parametric plots must include two expressions and an interval")))
1223 (setq range (nth 4 param))
1224 (or (and ($listp range) (symbolp (second range)) (eql ($length range) 3))
1225 (merror (intl:gettext "plot2d: wrong interval for parametric plot: ~M")
1226 range))
1227 (setq range (check-range range))
1228 (let* ((nticks (getf options :nticks))
1229 (trange (cddr range))
1230 (tvar (second range))
1231 (xrange (or (getf options :x) (getf options :xbounds)))
1232 (yrange (or (getf options :y) (getf options :ybounds)))
1233 (tmin (coerce-float (first trange)))
1234 (tmax (coerce-float (second trange)))
1235 (xmin (coerce-float (first xrange)))
1236 (xmax (coerce-float (second xrange)))
1237 (ymin (coerce-float (first yrange)))
1238 (ymax (coerce-float (second yrange)))
1239 f1 f2)
1240 (declare (type flonum ymin ymax xmin xmax tmin tmax))
1241 (setq f1 (coerce-float-fun (third param) `((mlist), tvar) "plot2d"))
1242 (setq f2 (coerce-float-fun (fourth param) `((mlist), tvar) "plot2d"))
1244 (let ((n-clipped 0) (n-non-numeric 0)
1245 (t-step (/ (- tmax tmin) (coerce-float nticks) 2))
1246 t-samples x-samples y-samples result)
1247 ;; Divide the range into 2*NTICKS regions that we then
1248 ;; adaptively plot over.
1249 (dotimes (k (1+ (* 2 nticks)))
1250 (let ((tpar (+ tmin (* k t-step))))
1251 (push tpar t-samples)
1252 (push (funcall f1 tpar) x-samples)
1253 (push (funcall f2 tpar) y-samples)))
1254 (setf t-samples (nreverse t-samples))
1255 (setf x-samples (nreverse x-samples))
1256 (setf y-samples (nreverse y-samples))
1258 ;; Adaptively plot over each region
1259 (do ((t-start t-samples (cddr t-start))
1260 (t-mid (cdr t-samples) (cddr t-mid))
1261 (t-end (cddr t-samples) (cddr t-end))
1262 (x-start x-samples (cddr x-start))
1263 (x-mid (cdr x-samples) (cddr x-mid))
1264 (x-end (cddr x-samples) (cddr x-end))
1265 (y-start y-samples (cddr y-start))
1266 (y-mid (cdr y-samples) (cddr y-mid))
1267 (y-end (cddr y-samples) (cddr y-end)))
1268 ((null t-end))
1269 (setf result
1270 (if result
1271 (append result
1272 (cddr (adaptive-parametric-plot
1273 f1 f2
1274 (car t-start) (car t-mid) (car t-end)
1275 (car x-start) (car x-mid) (car x-end)
1276 (car y-start) (car y-mid) (car y-end)
1277 (getf options :adapt_depth)
1278 1e-5)))
1279 (adaptive-parametric-plot
1280 f1 f2
1281 (car t-start) (car t-mid) (car t-end)
1282 (car x-start) (car x-mid) (car x-end)
1283 (car y-start) (car y-mid) (car y-end)
1284 (getf options :adapt_depth)
1285 1e-5))))
1286 ;; Fix up out-of-range values and clobber non-numeric values.
1287 (do ((x result (cddr x))
1288 (y (cdr result) (cddr y)))
1289 ((null y))
1290 (if (and (numberp (car x)) (numberp (car y)))
1291 (unless (and (<= ymin (car y) ymax)
1292 (<= xmin (car x) xmax))
1293 ;; Let gnuplot do the clipping. See the comment in DRAW2D.
1294 (incf n-clipped)
1295 (unless (member (getf options :plot_format)
1296 '($gnuplot_pipes $gnuplot))
1298 (setf (car x) 'moveto)
1299 (setf (car y) 'moveto)))
1300 (progn
1301 (incf n-non-numeric)
1302 (setf (car x) 'moveto)
1303 (setf (car y) 'moveto))))
1304 ;; Filter out any MOVETO's which do not precede a number.
1305 ;; Code elsewhere in this file expects MOVETO's to
1306 ;; come in pairs, so leave two MOVETO's before a number.
1307 (let ((n (length result)))
1308 (dotimes (i n)
1309 (when
1310 (and
1311 (evenp i)
1312 (eq (nth i result) 'moveto)
1313 (eq (nth (1+ i) result) 'moveto)
1314 (or
1315 (eq i (- n 2))
1316 (eq (nth (+ i 2) result) 'moveto)))
1317 (setf (nth i result) nil)
1318 (setf (nth (1+ i) result) nil))))
1320 (let ((result-sans-nil (delete nil result)))
1321 (if (null result-sans-nil)
1322 (cond
1323 ((= n-non-numeric 0)
1324 (mtell (intl:gettext "plot2d: all values will be clipped.~%")))
1325 ((= n-clipped 0)
1326 (mtell (intl:gettext
1327 "plot2d: expression evaluates to non-numeric value everywhere in plotting range.~%")))
1329 (mtell (intl:gettext
1330 "plot2d: all values are non-numeric, or clipped.~%"))))
1331 (progn
1332 (if (> n-non-numeric 0)
1333 (mtell (intl:gettext
1334 "plot2d: expression evaluates to non-numeric value somewhere in plotting range.~%")))
1335 (if (> n-clipped 0)
1336 (mtell (intl:gettext "plot2d: some values will be clipped.~%")))))
1337 (cons '(mlist) result-sans-nil)))))
1339 ;; draw2d-discrete. Accepts [discrete,[x1,x2,...],[y1,y2,...]]
1340 ;; or [discrete,[[x1,y1]...] and returns [x1,y1,...] or nil, if
1341 ;; non of the points have real values.
1342 ;; Currently any options given are being ignored, because there
1343 ;; are no options specific to the generation of the points.
1344 (defun draw2d-discrete (f)
1345 (let ((x (third f)) (y (fourth f)) data gaps)
1346 (cond
1347 (($listp x) ; x is a list
1348 (cond
1349 (($listp (cadr x)) ; x1 is a list
1350 (cond
1351 ((= (length (cadr x)) 3) ; x1 is a 2D point
1352 (setq data (parse-points-xy x)))
1353 (t ; x1 is not a 2D point
1354 (merror (intl:gettext "draw2d-discrete: Expecting a point with 2 coordinates; found ~M~%") (cadr x)))))
1355 (t ; x1 is not a list
1356 (cond
1357 (($listp y) ; y is a list
1358 (cond
1359 ((symbolp (coerce-float (cadr y))); y is an option
1360 (setq data (parse-points-y x)))
1361 (t ; y is not an option
1362 (cond
1363 (($listp (cadr y)) ; y1 is a list
1364 (merror (intl:gettext "draw2d-discrete: Expecting a y coordinate; found ~M~%") (cadr y)))
1365 (t ; y1 not a list
1366 (cond
1367 ((= (length x) (length y)) ; case [x][y]
1368 (setq data (parse-points-x-y x y)))
1369 (t ; wrong
1370 (merror (intl:gettext "draw2d-discrete: The number of x and y coordinates do not match.~%")))))))))
1371 (t ; y is not a list
1372 (setq data (parse-points-y x)))))))
1373 (t ; x is not a list
1374 (merror (intl:gettext "draw2d-discrete: Expecting a list of x coordinates or points; found ~M~%") x)))
1376 ;; checks for non-real values
1377 (cond
1378 ((some #'realp data)
1379 (setq gaps (count-if #'(lambda (x) (eq x 'moveto)) data))
1380 (when (> gaps 0)
1381 ;; some points have non-real values
1382 (mtell (intl:gettext "Warning: excluding ~M points with non-numerical values.~%") (/ gaps 2))))
1384 ;; none of the points have real values
1385 (mtell (intl:gettext "Warning: none of the points have numerical values.~%"))
1386 (setq data nil)))
1387 data))
1389 ;; Two lists [x1...xn] and [y1...yn] are joined as
1390 ;; [x1 y1...xn yn], converting all expressions to real numbers.
1391 ;; If either xi or yi are not real, both are replaced by 'moveto
1392 (defun parse-points-x-y (x y)
1393 (do ((a (rest x) (cdr a))
1394 (b (rest y) (cdr b))
1395 c af bf)
1396 ((null b) (cons '(mlist) (reverse c)))
1397 (setq af (coerce-float (car a)))
1398 (setq bf (coerce-float (car b)))
1399 (cond
1400 ((or (not (realp af)) (not (realp bf)))
1401 (setq c (cons 'moveto (cons 'moveto c))))
1403 (setq c (cons bf (cons af c)))))))
1405 ;; One list [y1...yn] becomes the list [1 y1...n yn],
1406 ;; converting all expressions to real numbers.
1407 ;; If yi is not real, both i and yi are replaced by 'moveto
1408 (defun parse-points-y (y)
1409 (do ((a 1 (1+ a))
1410 (b (rest y) (cdr b))
1411 c bf)
1412 ((null b) (cons '(mlist) (reverse c)))
1413 (setq bf (coerce-float (car b)))
1414 (cond
1415 ((not (realp bf))
1416 (setq c (cons 'moveto (cons 'moveto c))))
1418 (setq c (cons bf (cons a c)))))))
1420 ;; List [[x1,y1]...[xn,yn]] is transformed into
1421 ;; [x1 y1...xn yn], converting all expressions to real numbers.
1422 ;; If either xi or yi are not real, both are replaced by 'moveto
1423 (defun parse-points-xy (xy)
1424 (do ((ab (rest xy) (cdr ab))
1425 c af bf)
1426 ((null ab) (cons '(mlist) (reverse c)))
1427 (setq af (coerce-float (cadar ab)))
1428 (setq bf (coerce-float (caddar ab)))
1429 (cond
1430 ((or (not (realp af)) (not (realp bf)))
1431 (setq c (cons 'moveto (cons 'moveto c))))
1433 (setq c (cons bf (cons af c)))))))
1435 ;;; Adaptive plotting, based on the adaptive plotting code from
1436 ;;; YACAS. See http://yacas.sourceforge.net/Algo.html#c3s1 for a
1437 ;;; description of the algorithm. More precise details can be found
1438 ;;; in the file yacas/scripts/plots.rep/plot2d.ys.
1441 ;; Determine if we have a slow oscillation of the function.
1442 ;; Basically, for each 3 consecutive function values, we check to see
1443 ;; if the function is monotonic or not. There are 3 such sets, and
1444 ;; the function is considered slowly oscillating if at most 2 of them
1445 ;; are not monotonic.
1446 (defun slow-oscillation-p (f0 f1 f2 f3 f4)
1447 (flet ((sign-change (x y z)
1448 (cond ((not (and (numberp x) (numberp y) (numberp z)))
1449 ;; Something is not a number. Assume the
1450 ;; oscillation is not slow.
1452 ((or (and (> y x) (> y z))
1453 (and (< y x) (< y z)))
1456 0))))
1457 (<= (+ (sign-change f0 f1 f2)
1458 (sign-change f1 f2 f3)
1459 (sign-change f2 f3 f4))
1460 2)))
1462 ;; Determine if the function values are smooth enough. This means
1463 ;; that integrals of the functions on the left part and the right part
1464 ;; of the range are approximately the same.
1467 (defun smooth-enough-p (f-a f-a1 f-b f-b1 f-c eps)
1468 (cond ((every #'numberp (list f-a f-a1 f-b f-b1 f-c))
1469 (let ((quad (/ (+ f-a
1470 (* -5 f-a1)
1471 (* 9 f-b)
1472 (* -7 f-b1)
1473 (* 2 f-c))
1474 24))
1475 (quad-b (/ (+ (* 5 f-b)
1476 (* 8 f-b1)
1477 (- f-c))
1478 12)))
1479 ;; According to the Yacas source code, quad is the Simpson
1480 ;; quadrature for the (fb,fb1) subinterval (using points b,b1,c),
1481 ;; subtracted from the 4-point Newton-Cotes quadrature for the
1482 ;; (fb,fb1) subinterval (using points a, a1, b, b1.
1484 ;; quad-b is the Simpson quadrature for the (fb,f1) subinterval.
1486 ;; This used to test for diff <= 0. But in some
1487 ;; situations, like plot2d(0.99,[x,0,5]), roundoff prevents
1488 ;; this from happening. So we do diff < delta instead, for
1489 ;; some value of delta.
1491 ;; XXX: What is the right value for delta? Does this break
1492 ;; other things? Simple tests thus far show that
1493 ;; 100*flonum-epsilon is ok.
1494 (let ((diff (- (abs quad)
1495 (* eps (- quad-b (min f-a f-a1 f-b f-b1 f-c)))))
1496 (delta (* 150 flonum-epsilon)))
1497 (<= diff delta))))
1499 ;; Something is not a number, so assume it's not smooth enough.
1500 nil)))
1502 (defun adaptive-plot (fcn a b c f-a f-b f-c depth eps)
1503 ;; Step 1: Split the interval [a, c] into 5 points
1504 (let* ((a1 (/ (+ a b) 2))
1505 (b1 (/ (+ b c) 2))
1506 (f-a1 (funcall fcn a1))
1507 (f-b1 (funcall fcn b1))
1509 (cond ((or (not (plusp depth))
1510 (and (slow-oscillation-p f-a f-a1 f-b f-b1 f-c)
1511 (smooth-enough-p f-a f-a1 f-b f-b1 f-c eps)))
1512 ;; Everything is nice and smooth so we're done. Don't
1513 ;; refine anymore.
1514 (list a f-a
1515 a1 f-a1
1516 b f-b
1517 b1 f-b1
1518 c f-c))
1519 ;; We are not plotting the real part of the function and the
1520 ;; function is undefined at all points - assume it has complex value
1521 ;; on [a,b]. Maybe we should refine it a couple of times just to make sure?
1522 ((and (null *plot-realpart*)
1523 (null f-a) (null f-a1) (null f-b) (null f-b1) (null f-c))
1524 (list a f-a
1525 a1 f-a1
1526 b f-b
1527 b1 f-b1
1528 c f-c))
1530 ;; Need to refine. Split the interval in half, and try to plot each half.
1531 (let ((left (adaptive-plot fcn a a1 b f-a f-a1 f-b (1- depth) (* 2 eps)))
1532 (right (adaptive-plot fcn b b1 c f-b f-b1 f-c (1- depth) (* 2 eps))))
1533 (append left (cddr right)))))))
1535 (defun adaptive-parametric-plot (x-fcn y-fcn a b c x-a x-b x-c y-a y-b y-c depth eps)
1536 ;; Step 1: Split the interval [a, c] into 5 points
1537 (let* ((a1 (/ (+ a b) 2))
1538 (b1 (/ (+ b c) 2))
1539 (x-a1 (funcall x-fcn a1))
1540 (x-b1 (funcall x-fcn b1))
1541 (y-a1 (funcall y-fcn a1))
1542 (y-b1 (funcall y-fcn b1)))
1543 (cond ((or (not (plusp depth))
1544 ;; Should we have a different algorithm to determine
1545 ;; slow oscillation and smooth-enough for parametric
1546 ;; plots?
1547 (and (slow-oscillation-p y-a y-a1 y-b y-b1 y-c)
1548 (slow-oscillation-p x-a x-a1 x-b x-b1 x-c)
1549 (smooth-enough-p y-a y-a1 y-b y-b1 y-c eps)
1550 (smooth-enough-p x-a x-a1 x-b x-b1 x-c eps)))
1551 ;; Everything is nice and smooth so we're done. Don't
1552 ;; refine anymore.
1553 (list x-a y-a
1554 x-a1 y-a1
1555 x-b y-b
1556 x-b1 y-b1
1557 x-c y-c))
1558 ;; We are not plotting the real part of the function and the
1559 ;; function is undefined at all points - assume it has complex value
1560 ;; on [a,b]. Maybe we should refine it a couple of times just to make sure?
1561 ((and (null *plot-realpart*)
1562 (null y-a) (null y-a1) (null y-b) (null y-b1) (null y-c)
1563 (null x-a) (null x-a1) (null x-b) (null x-b1) (null x-c))
1564 (list x-a y-a
1565 x-a1 y-a1
1566 x-b y-b
1567 x-b1 y-b1
1568 x-c y-c))
1570 ;; Need to refine. Split the interval in half, and try to plot each half.
1571 (let ((left (adaptive-parametric-plot x-fcn y-fcn
1572 a a1 b
1573 x-a x-a1 x-b
1574 y-a y-a1 y-b
1575 (1- depth) (* 2 eps)))
1576 (right (adaptive-parametric-plot x-fcn y-fcn
1577 b b1 c
1578 x-b x-b1 x-c
1579 y-b y-b1 y-c
1580 (1- depth) (* 2 eps))))
1581 ;; (cddr right) to skip over the point that is duplicated
1582 ;; between the right end-point of the left region and the
1583 ;; left end-point of the right
1584 (append left (cddr right)))))))
1586 (defun draw2d (fcn range plot-options)
1587 (if (and ($listp fcn) (equal '$parametric (cadr fcn)))
1588 (return-from draw2d
1589 (draw2d-parametric-adaptive fcn plot-options)))
1590 (if (and ($listp fcn) (equal '$discrete (cadr fcn)))
1591 (return-from draw2d (draw2d-discrete fcn)))
1592 (when (and ($listp fcn) (equal '$contour (cadr fcn)))
1593 (setf (getf plot-options :contour) t)
1594 (return-from draw2d (draw2d-implicit (caddr fcn) plot-options)))
1595 (when (and (listp fcn) (eq 'mequal (caar fcn)))
1596 (setf (getf plot-options :contour) nil)
1597 (return-from draw2d (draw2d-implicit fcn plot-options)))
1598 (let* ((nticks (getf plot-options :nticks))
1599 (yrange (getf plot-options :ybounds))
1600 (depth (getf plot-options :adapt_depth)))
1602 (setq fcn (coerce-float-fun fcn `((mlist), (second range)) "plot2d"))
1604 (let* ((x-start (coerce-float (third range)))
1605 (xend (coerce-float (fourth range)))
1606 (x-step (/ (- xend x-start) (coerce-float nticks) 2))
1607 (ymin (coerce-float (first yrange)))
1608 (ymax (coerce-float (second yrange)))
1609 (n-clipped 0) (n-non-numeric 0)
1610 ;; What is a good EPS value for adaptive plotting?
1611 ;(eps 1e-5)
1612 x-samples y-samples result
1614 (declare (type flonum ymin ymax))
1615 ;; Divide the region into NTICKS regions. Each region has a
1616 ;; start, mid and endpoint. Then adaptively plot over each of
1617 ;; these regions. So it's probably a good idea not to make
1618 ;; NTICKS too big. Since adaptive plotting splits the sections
1619 ;; in half, it's also probably not a good idea to have NTICKS be
1620 ;; a power of two.
1621 (when (getf plot-options :logx)
1622 (setf x-start (log x-start))
1623 (setf xend (log xend))
1624 (setf x-step (/ (- xend x-start) (coerce-float nticks) 2)))
1626 (flet ((fun (x)
1627 (let ((y (if (getf plot-options :logx)
1628 (funcall fcn (exp x))
1629 (funcall fcn x))))
1630 (if (and (getf plot-options :logy)
1631 (numberp y))
1632 (if (> y 0) (log y) 'und)
1633 y))))
1635 (dotimes (k (1+ (* 2 nticks)))
1636 (let ((x (+ x-start (* k x-step))))
1637 (push x x-samples)
1638 (push (fun x) y-samples)))
1639 (setf x-samples (nreverse x-samples))
1640 (setf y-samples (nreverse y-samples))
1642 ;; For each region, adaptively plot it.
1643 (do ((x-start x-samples (cddr x-start))
1644 (x-mid (cdr x-samples) (cddr x-mid))
1645 (x-end (cddr x-samples) (cddr x-end))
1646 (y-start y-samples (cddr y-start))
1647 (y-mid (cdr y-samples) (cddr y-mid))
1648 (y-end (cddr y-samples) (cddr y-end)))
1649 ((null x-end))
1650 ;; The region is x-start to x-end, with mid-point x-mid.
1652 ;; The cddr is to remove the one extra sample (x and y value)
1653 ;; that adaptive plot returns. But on the first iteration,
1654 ;; result is empty, so we don't want the cddr because we want
1655 ;; all the samples returned from adaptive-plot. On subsequent
1656 ;; iterations, it's a duplicate of the last point of the
1657 ;; previous interval.
1658 (setf result
1659 (if result
1660 (append result
1661 (cddr
1662 (adaptive-plot #'fun (car x-start) (car x-mid) (car x-end)
1663 (car y-start) (car y-mid) (car y-end)
1664 depth 1e-5)))
1665 (adaptive-plot #'fun (car x-start) (car x-mid) (car x-end)
1666 (car y-start) (car y-mid) (car y-end)
1667 depth 1e-5))))
1669 ;; Fix up out-of-range values
1670 ;; and clobber non-numeric values.
1672 (do ((x result (cddr x))
1673 (y (cdr result) (cddr y)))
1674 ((null y))
1675 (if (numberp (car y))
1676 (unless (<= ymin (car y) ymax)
1677 (incf n-clipped)
1678 ;; If the plot format uses gnuplot, we can let gnuplot
1679 ;; do the clipping for us. This results in better
1680 ;; looking plots. For example plot2d(x-floor(x),
1681 ;; [x,0,5], [y, 0, .5]) has lines going all the way to
1682 ;; the limits. Previously, the lines would stop
1683 ;; before the limit.
1684 (unless (member (getf plot-options :plot_format)
1685 '($gnuplot_pipes $gnuplot))
1686 (setf (car x) 'moveto)
1687 (setf (car y) 'moveto)))
1688 (progn
1689 (incf n-non-numeric)
1690 (setf (car x) 'moveto)
1691 (setf (car y) 'moveto)))
1692 (when (and (getf plot-options :logx)
1693 (numberp (car x)))
1694 (setf (car x) (exp (car x))))
1696 (when (and (getf plot-options :logy)
1697 (numberp (car y)))
1698 (setf (car y) (exp (car y)))))
1700 ;; Filter out any MOVETO's which do not precede a number.
1701 ;; Code elsewhere in this file expects MOVETO's to
1702 ;; come in pairs, so leave two MOVETO's before a number.
1703 (let ((n (length result)))
1704 (dotimes (i n)
1705 (when
1706 (and
1707 (evenp i)
1708 (eq (nth i result) 'moveto)
1709 (eq (nth (1+ i) result) 'moveto)
1710 (or
1711 (eq i (- n 2))
1712 (eq (nth (+ i 2) result) 'moveto)))
1713 (setf (nth i result) nil)
1714 (setf (nth (1+ i) result) nil))))
1716 (let ((result-sans-nil (delete nil result)))
1717 (if (null result-sans-nil)
1718 (cond
1719 ((= n-non-numeric 0)
1720 (mtell (intl:gettext "plot2d: all values will be clipped.~%")))
1721 ((= n-clipped 0)
1722 (mtell (intl:gettext "plot2d: expression evaluates to non-numeric value everywhere in plotting range.~%")))
1724 (mtell (intl:gettext "plot2d: all values are non-numeric, or clipped.~%"))))
1725 (progn
1726 (if (> n-non-numeric 0)
1727 (mtell (intl:gettext "plot2d: expression evaluates to non-numeric value somewhere in plotting range.~%")))
1728 (if (> n-clipped 0)
1729 (mtell (intl:gettext "plot2d: some values will be clipped.~%")))))
1730 (cons '(mlist) result-sans-nil))))))
1732 (defun get-range (lis)
1733 (let ((ymin most-positive-flonum)
1734 (ymax most-negative-flonum))
1735 (declare (type flonum ymin ymax))
1736 (do ((l lis (cddr l)))
1737 ((null l))
1738 (or (floatp (car l)) (setf (car l) (float (car l))))
1739 (cond ((< (car l) ymin)
1740 (setq ymin (car l))))
1741 (cond ((< ymax (car l))
1742 (setq ymax (car l)))))
1743 (list '(mlist) ymin ymax)))
1745 #+sbcl (defvar $gnuplot_view_args "-persist ~a")
1746 #-sbcl (defvar $gnuplot_view_args "-persist ~s")
1748 #+(or sbcl openmcl) (defvar $gnuplot_file_args "~a")
1749 #-(or sbcl openmcl) (defvar $gnuplot_file_args "~s")
1751 (defvar $mgnuplot_command "mgnuplot")
1752 (defvar $geomview_command "geomview")
1754 (defvar $xmaxima_plot_command "xmaxima")
1756 (defun plot-set-gnuplot-script-file-name (options)
1757 (let ((gnuplot-term (getf options :gnuplot_term))
1758 (gnuplot-out-file (getf options :gnuplot_out_file)))
1759 (if (and (find (getf options :plot_format) '($gnuplot_pipes $gnuplot))
1760 (eq gnuplot-term '$default) gnuplot-out-file)
1761 (plot-file-path gnuplot-out-file t options)
1762 (plot-file-path
1763 (format nil "maxout~d.~(~a~)"
1764 (getpid)
1765 (ensure-string (getf options :plot_format))) nil options))))
1767 (defun plot-temp-file0 (file &optional (preserve-file nil))
1768 (let ((filename
1769 (if *maxima-tempdir*
1770 (format nil "~a/~a" *maxima-tempdir* file)
1771 file)))
1772 (unless preserve-file
1773 (setf (gethash filename *temp-files-list*) t))
1774 (format nil "~a" filename)
1776 (defun plot-temp-file (file &optional (preserve-file nil) (plot-options nil))
1777 (let (script-name
1778 (script-name-or-fun
1779 (and plot-options (getf plot-options :gnuplot_script_file))))
1780 (if (null script-name-or-fun)
1781 (plot-temp-file0 file preserve-file)
1782 (progn
1783 (setq
1784 script-name
1785 (cond
1786 ((symbolp script-name-or-fun) (mfuncall script-name-or-fun file))
1787 (t script-name-or-fun)))
1788 (if (pathname-directory script-name)
1789 script-name
1790 (plot-temp-file0 script-name preserve-file))))))
1792 ;; If no file path is given, uses temporary directory path
1793 (defun plot-file-path (file &optional (preserve-file nil) (plot-options nil))
1794 (if (pathname-directory file)
1795 file
1796 (plot-temp-file file preserve-file plot-options)))
1798 (defun gnuplot-process (plot-options &optional file out-file)
1799 (let ((gnuplot-term (getf plot-options :gnuplot_term))
1800 (run-viewer (getf plot-options :run_viewer))
1801 #-(or (and sbcl win32) (and sbcl win64) (and ccl windows))
1802 (gnuplot-preamble
1803 (string-downcase (getf plot-options :gnuplot_preamble))))
1805 ;; creates the output file, when there is one to be created
1806 (when (and out-file (not (eq gnuplot-term '$default)))
1807 #+(or (and sbcl win32) (and sbcl win64) (and ccl windows))
1808 ($system $gnuplot_command (format nil $gnuplot_file_args file))
1809 #-(or (and sbcl win32) (and sbcl win64) (and ccl windows))
1810 ($system (format nil "~a ~a" $gnuplot_command
1811 (format nil $gnuplot_file_args file))))
1813 ;; displays contents of the output file, when gnuplot-term is dumb,
1814 ;; or runs gnuplot when gnuplot-term is default
1815 (when run-viewer
1816 (case gnuplot-term
1817 ($default
1818 ;; the options given to gnuplot will be different when the user
1819 ;; redirects the output by using "set output" in the preamble
1820 #+(or (and sbcl win32) (and sbcl win64) (and ccl windows))
1821 ($system $gnuplot_command "-persist" (format nil $gnuplot_file_args file))
1822 #-(or (and sbcl win32) (and sbcl win64) (and ccl windows))
1823 ($system
1824 (format nil "~a ~a" $gnuplot_command
1825 (format nil (if (search "set out" gnuplot-preamble)
1826 $gnuplot_file_args $gnuplot_view_args)
1827 file))))
1828 ($dumb
1829 (if out-file
1830 ($printfile (car out-file))
1831 (merror (intl:gettext "plotting: option 'gnuplot_out_file' not defined."))))))))
1833 ;; plot-options-parser puts the plot options given into a property list.
1834 ;; maxopts: a list (not a Maxima list!) with plot options.
1835 ;; options: a property list, or an empty list.
1836 ;; Example:
1837 ;; (plot-options-parser (list #$[x,-2,2]$ #$[nticks,30]$) '(:nticks 4))
1838 ;; returns:
1839 ;; (:XLABEL "x" :XMAX 2.0 :XMIN -2.0 :NTICKS 30)
1841 (defun plot-options-parser (maxopts options &aux name)
1842 (dolist (opt maxopts)
1843 (unless (or ($listp opt) (symbolp opt))
1844 (merror
1845 (intl:gettext
1846 "plot-options-parser: option \"~M\" should be a list or a symbol")
1847 opt))
1848 (cond
1849 (($listp opt)
1850 (unless ($symbolp (setq name (second opt)))
1851 (merror
1852 (intl:gettext
1853 "plot-options-parser: Expecting option name as a symbol, found: \"~M\"")
1854 opt))
1855 (case name
1856 ($adapt_depth
1857 (setf (getf options :adapt_depth)
1858 (check-option (cdr opt) #'(lambda (n)
1859 ;; N should be a non-negative integer
1860 (and (integerp n)
1861 (>= n 0)))
1862 "a non-negative integer" 1)))
1863 ($axes (setf (getf options :axes)
1864 (check-option-b (cdr opt) #'axesoptionp "x, y, solid" 1)))
1865 ($azimuth (if (caddr opt)
1866 (setf (caddr opt) (parse-azimuth (caddr opt))))
1867 (setf (getf options :azimuth)
1868 (check-option (cdr opt) #'realp "a real number" 1)))
1869 ($box (setf (getf options :box)
1870 (check-option-boole (cdr opt))))
1871 ($color (setf (getf options :color)
1872 (check-option (cdr opt) #'plotcolorp "a color")))
1873 ($color_bar (setf (getf options :color_bar)
1874 (check-option-boole (cdr opt))))
1875 ($color_bar_tics
1876 (if (cddr opt)
1877 (setf (cddr opt) (mapcar #'coerce-float (cddr opt))))
1878 (setf (getf options :color_bar_tics)
1879 (check-option-b (cdr opt) #'realp "a real number" 3)))
1880 ($elevation (if (caddr opt)
1881 (setf (caddr opt) (parse-elevation (caddr opt))))
1882 (setf (getf options :elevation)
1883 (check-option (cdr opt) #'realp "a real number" 1)))
1884 ($grid (setf (getf options :grid)
1885 (check-option (cdr opt) #'naturalp "a natural number" 2)))
1886 ($grid2d (setf (getf options :grid2d)
1887 (check-option-boole (cdr opt))))
1888 ($iterations
1889 (setf (getf options :iterations)
1890 (check-option (cdr opt) #'naturalp "a natural number" 1)))
1891 ($label (setf (getf options :label)
1892 (check-option-label (cdr opt))))
1893 ($legend (setf (getf options :legend)
1894 (check-option-b (cdr opt) #'stringp "a string")))
1895 ($levels (setf (getf options :levels)
1896 (check-option-levels (cdr opt))))
1897 ($logx (setf (getf options :logx)
1898 (check-option-boole (cdr opt))))
1899 ($logy (setf (getf options :logy)
1900 (check-option-boole (cdr opt))))
1901 ($mesh_lines_color
1902 (setf (getf options :mesh_lines_color)
1903 (check-option-b (cdr opt) #'plotcolorp "a color" 1)))
1904 ($nticks (setf (getf options :nticks)
1905 (check-option (cdr opt) #'naturalp "a natural number" 1)))
1906 ($palette (setf (getf options :palette)
1907 (check-option-palette (cdr opt))))
1908 ($plotepsilon (setf (getf options :plotepsilon)
1909 (check-option (cdr opt) #'realp "a real number" 1)))
1910 ($plot_format (setf (getf options :plot_format)
1911 (check-option-format (cdr opt))))
1912 ($plot_realpart (setf (getf options :plot_realpart)
1913 (check-option-boole (cdr opt))))
1914 ($point_type (setf (getf options :point_type)
1915 (check-option (cdr opt) #'pointtypep "a point type")))
1916 ($pdf_file (setf (getf options :pdf_file)
1917 (check-option (cdr opt) #'stringp "a string" 1)))
1918 ($png_file (setf (getf options :png_file)
1919 (check-option (cdr opt) #'stringp "a string" 1)))
1920 ($ps_file (setf (getf options :ps_file)
1921 (check-option (cdr opt) #'stringp "a string" 1)))
1922 ($run_viewer (setf (getf options :run_viewer)
1923 (check-option-boole (cdr opt))))
1924 ($same_xy (setf (getf options :same_xy)
1925 (check-option-boole (cdr opt))))
1926 ($same_xyz (setf (getf options :same_xyz)
1927 (check-option-boole (cdr opt))))
1928 ($sample (setf (getf options :sample)
1929 (check-option (cdr opt) #'naturalp "a natural number" 2)))
1930 ($style (setf (getf options :style)
1931 (check-option-style (cdr opt))))
1932 ($svg_file (setf (getf options :svg_file)
1933 (check-option (cdr opt) #'stringp "a string" 1)))
1934 ($t (setf (getf options :t) (cddr (check-range opt))))
1935 ($title (setf (getf options :title)
1936 (check-option (cdr opt) #'stringp "a string" 1)))
1937 ($transform_xy (setf (getf options :transform_xy)
1938 (check-option-b (cdr opt) #'functionp "a function make_transform" 1)))
1939 ($window (setf (getf options :window)
1940 (check-option (cdr opt)
1941 #'(lambda (n) (and (integerp n) (>= n 0)))
1942 "a non-negative integer" 1)))
1943 ($x (setf (getf options :x) (cddr (check-range opt))))
1944 ($xbounds (setf (getf options :xbounds) (cddr (check-range opt))))
1945 ($xlabel (setf (getf options :xlabel)
1946 (check-option (cdr opt) #'string "a string" 1)))
1947 ($xtics
1948 (if (cddr opt)
1949 (setf (cddr opt) (mapcar #'coerce-float (cddr opt))))
1950 (setf (getf options :xtics)
1951 (check-option-b (cdr opt) #'realp "a real number" 3)))
1952 ($xy_scale
1953 (if (cddr opt)
1954 (setf (cddr opt) (mapcar #'coerce-float (cddr opt))))
1955 (setf (getf options :xy_scale)
1956 (check-option (cdr opt) #'realpositivep
1957 "a positive real number" 2)))
1958 ($y (setf (getf options :y) (cddr (check-range opt))))
1959 ($ybounds (setf (getf options :ybounds) (cddr (check-range opt))))
1960 ($ylabel (setf (getf options :ylabel)
1961 (check-option (cdr opt) #'string "a string" 1)))
1962 ($ytics
1963 (if (cddr opt)
1964 (setf (cddr opt) (mapcar #'coerce-float (cddr opt))))
1965 (setf (getf options :ytics)
1966 (check-option-b (cdr opt) #'realp "a real number" 3)))
1967 ($yx_ratio
1968 (if (caddr opt)
1969 (setf (caddr opt) (coerce-float (caddr opt))))
1970 (setf (getf options :yx_ratio)
1971 (check-option (cdr opt) #'realp "a real number" 1)))
1972 ($z (setf (getf options :z) (cddr (check-range opt))))
1973 ($zlabel (setf (getf options :zlabel)
1974 (check-option (cdr opt) #'string "a string" 1)))
1975 ($zmin
1976 (if (caddr opt)
1977 (setf (caddr opt) (coerce-float (caddr opt))))
1978 (setf (getf options :zmin)
1979 (check-option-b (cdr opt) #'realp "a real number" 1)))
1980 ($ztics
1981 (if (cddr opt)
1982 (setf (cddr opt) (mapcar #'coerce-float (cddr opt))))
1983 (setf (getf options :ztics)
1984 (check-option-b (cdr opt) #'realp "a real number" 3)))
1985 ($gnuplot_4_0 (setf (getf options :gnuplot_4_0)
1986 (check-option-boole (cdr opt))))
1987 ($gnuplot_curve_titles
1988 (setf (getf options :gnuplot_curve_titles)
1989 (check-option (cdr opt) #'stringp "a string")))
1990 ($gnuplot_curve_styles
1991 (setf (getf options :gnuplot_curve_styles)
1992 (check-option (cdr opt) #'stringp "a string")))
1993 ($gnuplot_default_term_command
1994 (setf (getf options :gnuplot_default_term_command)
1995 (check-option (cdr opt) #'stringp "a string" 1)))
1996 ($gnuplot_dumb_term_command
1997 (setf (getf options :gnuplot_dumb_term_command)
1998 (check-option (cdr opt) #'stringp "a string" 1)))
1999 ($gnuplot_out_file
2000 (setf (getf options :gnuplot_out_file)
2001 (check-option (cdr opt) #'stringp "a string" 1)))
2002 ($gnuplot_script_file
2003 (setf (getf options :gnuplot_script_file)
2004 (check-option (cdr opt) #'(lambda(x) (or (stringp x) (symbolp x))) "a string or symbol" 1)
2005 (getf options :plot_format) '$gnuplot))
2006 ($gnuplot_pm3d
2007 (setf (getf options :gnuplot_pm3d)
2008 (check-option-boole (cdr opt))))
2009 ($gnuplot_strings
2010 (setf (getf options :gnuplot_strings)
2011 (check-option-boole (cdr opt))))
2012 ($gnuplot_preamble
2013 (setf (getf options :gnuplot_preamble)
2014 (check-option (cdr opt) #'stringp "a string" 1)))
2015 ($gnuplot_postamble
2016 (setf (getf options :gnuplot_postamble)
2017 (check-option (cdr opt) #'stringp "a string" 1)))
2018 ($gnuplot_pdf_term_command
2019 (setf (getf options :gnuplot_pdf_term_command)
2020 (check-option (cdr opt) #'stringp "a string" 1)))
2021 ($gnuplot_png_term_command
2022 (setf (getf options :gnuplot_png_term_command)
2023 (check-option (cdr opt) #'stringp "a string" 1)))
2024 ($gnuplot_ps_term_command
2025 (setf (getf options :gnuplot_ps_term_command)
2026 (check-option (cdr opt) #'stringp "a string" 1)))
2027 ($gnuplot_svg_term_command
2028 (setf (getf options :gnuplot_svg_term_command)
2029 (check-option (cdr opt) #'stringp "a string" 1)))
2030 ;; gnuplot_term is a tricky one: when it is just default, dumb or
2031 ;; ps, we want it to be a symbol, but when it is more complicated,
2032 ;; i.e. "ps; size 16cm, 12cm", it must be a string and not a symbol
2033 ($gnuplot_term
2034 (let ((s (caddr opt)))
2035 (when (stringp s)
2036 (cond ((string= s "default") (setq s '$default))
2037 ((string= s "dumb") (setq s '$dumb))
2038 ((string= s "ps") (setq s '$ps))))
2039 (if (atom s)
2040 (setf (getf options :gnuplot_term) s)
2041 (merror
2042 (intl:gettext "Wrong argument for plot option \"gnuplot_term\". Expecting a string or a symbol but found \"~M\".") s))))
2044 (merror
2045 (intl:gettext "plot-options-parser: unknown plot option: ~M") opt))))
2046 ((symbolp opt)
2047 (case opt
2048 ($axes (setf (getf options :axes) t))
2049 ($box (setf (getf options :box) t))
2050 ($color_bar (setf (getf options :color_bar) t))
2051 ($color_bar_tics (remf options :color_bar_tics))
2052 ($grid2d (setf (getf options :grid2d) t))
2053 ($legend (remf options :legend))
2054 ($mesh_lines_color (remf options :mesh_lines_color))
2055 ($logx (setf (getf options :logx) t))
2056 ($logy (setf (getf options :logy) t))
2057 ($palette (remf options :palette))
2058 ($plot_realpart (setf (getf options :plot_realpart) t))
2059 ($run_viewer (setf (getf options :run_viewer) t))
2060 ($same_xy (setf (getf options :same_xy) t))
2061 ($same_xyz (setf (getf options :same_xyz) t))
2062 ($xtics (remf options :xtics))
2063 ($ytics (remf options :ytics))
2064 ($zmin (remf options :zmin))
2065 ($gnuplot_4_0 (setf (getf options :gnuplot_4_0) t))
2066 ($gnuplot_pm3d (setf (getf options :gnuplot_pm3d) t))
2067 ($gnuplot_strings (setf (getf options :gnuplot_strings) t))
2068 ($noaxes (setf (getf options :axes) nil))
2069 ($nobox (setf (getf options :box) nil))
2070 ($nocolor_bar (setf (getf options :color_bar) nil))
2071 ($nocolor_bat_tics (setf (getf options :color_bat_tics) nil))
2072 ($nogrid2d (setf (getf options :grid2d) nil))
2073 ($nolegend (setf (getf options :legend) nil))
2074 ($nologx (setf (getf options :logx) nil))
2075 ($nology (setf (getf options :logy) nil))
2076 ($nomesh_lines (setf (getf options :mesh_lines_color) nil))
2077 ($nopalette (setf (getf options :palette) nil))
2078 ($noplot_realpart (setf (getf options :plot_realpart) nil))
2079 ($norun_viewer (setf (getf options :run_viewer) nil))
2080 ($nosame_xy (setf (getf options :same_xy) nil))
2081 ($nosame_xyz (setf (getf options :same_xyz) nil))
2082 ($notransform_xy (remf options :transform_xy))
2083 ($noxtics (setf (getf options :xtics) nil))
2084 ($noytics (setf (getf options :ytics) nil))
2085 ($noztics (setf (getf options :ztics) nil))
2086 ($nognuplot_strings (setf (getf options :gnuplot_strings) nil))
2088 (merror (intl:gettext "Unknown plot option \"~M\".") opt))))))
2089 options)
2091 ;; natural numbers predicate
2092 (defun naturalp (n) (or (and (integerp n) (> n 0)) nil))
2094 ;; positive real numbers predicate
2095 (defun realpositivep (x) (or (and (realp x) (> x 0)) nil))
2097 ;; possible values for the axes option
2098 (defun axesoptionp (o) (if (member o '($x $y $solid)) t nil))
2100 ;; the 13 possibilities for the point types
2101 (defun pointtypep (p)
2102 (if (member p '($bullet $circle $plus $times $asterisk $box $square
2103 $triangle $delta $wedge $nabla $diamond $lozenge)) t nil))
2105 ;; Colors can only one of the named colors or a six-digit hexadecimal
2106 ;; number with a # suffix.
2107 (defun plotcolorp (color)
2108 (cond ((and (stringp color)
2109 (string= (subseq color 0 1) "#")
2110 (= (length color) 7)
2111 (ignore-errors (parse-integer (subseq color 1 6) :radix 16)))
2113 ((member color '($red $green $blue $magenta $cyan $yellow
2114 $orange $violet $brown $gray $black $white))
2116 (t nil)))
2118 ;; tries to convert az into a floating-point number between 0 and 360
2119 (defun parse-azimuth (az) (mod ($float (meval* az)) 360))
2121 ;; tries to convert el into a floating-poitn number between -180 and 180
2122 (defun parse-elevation (el) (- (mod (+ 180 ($float (meval* el))) 360) 180))
2124 ;; The following functions check the value of an option returning an atom
2125 ;; when there is only one argument or a list when there are several arguments
2128 ;; Checks for one or more items of the same type, using the test given
2129 (defun check-option (option test type &optional count)
2130 (when count
2131 (unless (= (1- (length option)) count)
2132 (merror
2133 (intl:gettext
2134 "Wrong number of arguments for plot option \"~M\". Expecting ~M but found ~M.")
2135 (car option) count (1- (length option)))))
2136 (dolist (item (cdr option))
2137 (when (not (funcall test item))
2138 (merror
2139 (intl:gettext "Wrong argument for plot option \"~M\". Expecting ~M but found \"~M\".") (car option) type item)))
2140 (if (= (length option) 2)
2141 (cadr option)
2142 (cdr option)))
2144 ;; Accepts one or more items of the same type or false.
2145 ;; When given, n is the maximum number of items.
2146 (defun check-option-b (option test type &optional count)
2147 (let ((n (- (length option) 1)))
2148 (when count
2149 (unless (< n (1+ count))
2150 (merror
2151 (intl:gettext
2152 "Plot option ~M must have ~M arguments, not ~M.")
2153 (car option) count (1- (length option)))))
2154 (cond
2155 ((= n 0)
2156 (merror
2157 (intl:gettext
2158 "Option ~M should be given arguments, or called by its name (no lists)")
2159 option))
2160 ((= n 1)
2161 (if (or (funcall test (cadr option)) (null (cadr option))
2162 (eq (cadr option) t))
2163 (cadr option)
2164 (merror
2165 (intl:gettext
2166 "Value of option ~M. should be ~M or false, not \"~M\".")
2167 (car option) type (cadr option))))
2168 ((> n 1)
2169 (dotimes (i n)
2170 (unless (funcall test (nth (+ i 1) option))
2171 (merror
2172 (intl:gettext
2173 "Value of option ~M should be ~M, not \"~M\".")
2174 (car option) type (nth (+ i 1) option))))
2175 (cdr option)))))
2177 ;; Boolean options can be [option], [option,true] or [option,false]
2178 (defun check-option-boole (option)
2179 (if (= 1 (length option))
2181 (if (and (= 2 (length option))
2182 (or (eq (cadr option) t) (null (cadr option))))
2183 (cadr option)
2184 (merror (intl:gettext "plot option ~M must be either true or false.")
2185 (car option)))))
2187 ;; label can be either [label, string, real, real] or
2188 ;; [label, [string_1, real, real],...,[string_n, real, real]]
2189 (defun check-option-label (option &aux opt)
2190 (if (not ($listp (cadr option)))
2191 (setq opt (list (cons '(mlist) (cdr option))))
2192 (setq opt (cdr option)))
2193 (dolist (item opt)
2194 (when (not (and ($listp item) (= 4 (length item)) (stringp (second item))
2195 (realp (setf (third item) (coerce-float (third item))))
2196 (realp (setf (fourth item) (coerce-float (fourth item))))))
2197 (merror
2198 (intl:gettext
2199 "Wrong argument ~M for option ~M. Must be either [label,\"text\",x,y] or [label, [\"text 1\",x1,y1],...,[\"text n\",xn,yn]]")
2200 item (car option))))
2201 opt)
2203 ;; one of the possible formats
2204 (defun check-option-format (option &aux formats)
2205 (setq formats '($geomview $gnuplot $gnuplot_pipes $mgnuplot $xmaxima))
2206 (unless (member (cadr option) formats)
2207 (merror
2208 (intl:gettext
2209 "Wrong argument ~M for option ~M. Must one of the following symbols: geomview, gnuplot, mgnuplot, xmaxima (or gnuplot_pipes in Unix)")
2210 (cadr option) (car option)))
2211 (cadr option))
2213 ; palette most be one or more Maxima lists starting with the name of one
2214 ;; of the 5 kinds: hue, saturation, value, gray or gradient.
2215 (defun check-option-palette (option)
2216 (if (and (= (length option) 2) (null (cadr option)))
2218 (progn
2219 (dolist (item (cdr option))
2220 (when (not (and ($listp item)
2221 (member (cadr item)
2222 '($hue $saturation $value $gray $gradient))))
2223 (merror
2224 (intl:gettext
2225 "Wrong argument ~M for option ~M. Not a valid palette.")
2226 item (car option))))
2227 (cdr option))))
2229 ;; style can be one or several of the names of the styles or one or several
2230 ;; Maxima lists starting with the name of one of the styles.
2231 (defun check-option-style (option)
2232 (if (and (= (length option) 2) (null (cadr option)))
2234 (progn
2235 (let (name parsed)
2236 (dolist (item (cdr option))
2237 (if ($listp item)
2238 (setq name (second item))
2239 (setq name item))
2240 (when (not (member name
2241 '($lines $points $linespoints $dots $impulses)))
2242 (merror
2243 (intl:gettext
2244 "Wrong argument ~M for option ~M. Not a valid style")
2245 name (car option)))
2246 (setq parsed (cons item parsed)))
2247 (reverse parsed)))))
2249 ;; Transform can be false or the name of a function for the transformation.
2250 (defun check-option-transform (option)
2251 (if (and (= (length option) 2)
2252 (or (atom (cadr option)) (null (cadr option))))
2253 (cadr option)
2254 (merror
2255 (intl:gettext
2256 "Wrong argument ~M for option ~M. Should be either false or the name of function for the transformation") option (car option))))
2258 ;; levels can be a single natural number (requested number of levels)
2259 ;; or two or more floating-point numbers.
2260 (defun check-option-levels (option)
2261 (cond
2262 ((< (length option) 3)
2263 (check-option option #'naturalp "a natural number" 1))
2265 (mapcar #'coerce-float (cdr option))
2266 (check-option option #'realp "a real number" (1- (length option))))))
2268 ;; Tries to get n numbers between fmin and fmax of the form d*10^e,
2269 ;; where d is either 1, 2 or 5.
2270 ;; It returns a list with n or less numbers
2271 ;; (adapted from procedure getticks of Xmaxima)
2273 (defun getlevels (fmin fmax n)
2274 (let ((len (- fmax fmin)) (best 0) levels val fac j1 j2 ans)
2275 (dolist (v '(0.1 0.2 0.5))
2276 (setq val (ceiling (/ (log (/ len n v)) (log 10))))
2277 (setq fac (/ 1 v (expt 10 val)))
2278 (setq j1 (ceiling (* fmin fac)))
2279 (setq j2 (floor (* fmax fac)))
2280 (setq levels nil)
2281 (do ((j j1 (1+ j))) ((> j j2))
2282 (push (/ j fac) levels))
2283 (when (> (length levels) best)
2284 (setq best (length levels))
2285 (setq ans (copy-list levels))))
2286 (reverse ans)))
2288 #| plot2d
2289 Examples:
2291 plot2d (sec(x), [x, -2, 2], [y, -20, 20]);
2293 plot2d (exp(3*s), [s, -2, 2], logy);
2295 plot2d ([parametric, cos(t), sin(t), [t, -%pi, %pi]], same_xy);
2297 xy:[[10,.6], [20,.9], [30,1.1], [40,1.3], [50,1.4]]$
2298 plot2d ( [ [discrete, xy], 2*%pi*sqrt(l/980) ], [l, 0, 50],
2299 [style, points, lines], [color, red, blue], [point_type, box],
2300 [legend, "experiment", "theory"],
2301 [xlabel, "pendulum's length (cm)"], [ylabel, "period (s)"]);
2303 plot2d ( x^2-1, [x, -3, 3], [y, -2, 10], nobox, [color, red],
2304 [ylabel, "x^2-1"], [plot_format, xmaxima]);
2306 plot2d ( x^2+y^2 = 1, [x, -2, 2], [y, -2 ,2]);
2308 (defmfun $plot2d
2309 (fun &optional xrange &rest extra-options
2310 &aux
2311 ($display2d nil) (*plot-realpart* *plot-realpart*)
2312 (options (copy-tree *plot-options*)) yrange output-file plot)
2313 ;; fun must be a maxima list with several objects: expressions (simple
2314 ;; functions), maxima lists (parametric or discrete cases).
2315 ;; A single parametric or discrete plot is placed inside a maxima list.
2316 (setf (getf options :type) "plot2d")
2317 (when (and (consp fun)
2318 (or (eq (second fun) '$parametric)
2319 (eq (second fun) '$contour)
2320 (eq (second fun) '$discrete)))
2321 (setq fun `((mlist) ,fun)))
2322 ;; If by now fun is not a maxima list, it is then a single expression
2323 (unless ($listp fun ) (setq fun `((mlist) ,fun)))
2324 ;; 2- Get names for the two axis and values for xmin and xmax if needed.
2325 ;; If any of the objects in the fun list is a simple function,
2326 ;; the xrange option is mandatory and will provide the name of
2327 ;; the horizontal axis and the values of xmin and xmax.
2328 (let ((xrange-required nil) (bounds-required nil) (yrange-required nil)
2329 small huge prange)
2330 #-clisp (setq small (- (/ most-positive-flonum 1024)))
2331 #+clisp (setq small (- (/ most-positive-double-float 1024.0)))
2332 #-clisp (setq huge (/ most-positive-flonum 1024))
2333 #+clisp (setq huge (/ most-positive-double-float 1024.0))
2334 (setf (getf options :ybounds) (list small huge))
2335 (dolist (f (rest fun))
2336 (if ($listp f)
2337 (progn
2338 (case ($first f)
2339 ($parametric
2340 (unless bounds-required
2341 (setq bounds-required t)
2342 ;; Default X and Y bound large so parametric plots don't get
2343 ;; prematurely clipped. Don't use most-positive-flonum
2344 ;; because draw2d will overflow.
2345 (setf (getf options :xbounds) (list small huge)))
2346 (setq prange (check-range ($fourth f))))
2347 ($contour
2348 (setq xrange (check-range xrange))
2349 (setq xrange-required t)
2350 (unless yrange-required
2351 (setq yrange-required t)
2352 (if (null extra-options)
2353 (merror
2354 (intl:gettext "plot2d: Missing interval for variable 2."))
2355 (progn
2356 (setq yrange (pop extra-options))
2357 (setq yrange (check-range yrange))
2358 (setf (getf options :xvar) ($first xrange))
2359 (setf (getf options :yvar) ($first yrange))
2360 (setf (getf options :x) (cddr xrange))
2361 (setf (getf options :y) (cddr yrange))))))
2362 ($discrete)
2364 (merror
2365 (intl:gettext
2366 "plot2d: a keyword 'parametric' or 'discrete' missing in ~M")
2367 f))))
2368 ;; The expression represents a function, explicit or implicit
2369 (progn
2370 (unless xrange-required
2371 (setq xrange-required t)
2372 (setq xrange (check-range xrange))
2373 (setq xrange-required t)
2374 (unless (getf options :xlabel)
2375 (setf (getf options :xlabel) (ensure-string (second xrange))))
2376 (setf (getf options :xvar) (cadr xrange))
2377 (setf (getf options :x) (cddr xrange)))
2378 (when (and (listp f) (eq 'mequal (caar f)))
2379 ;; Implicit function
2380 (unless yrange-required
2381 (setq yrange-required t)
2382 (if (null extra-options)
2383 (merror
2384 (intl:gettext "plot2d: Missing interval for variable 2."))
2385 (progn
2386 (setq yrange (pop extra-options))
2387 (setq yrange (check-range yrange))
2388 (setf (getf options :yvar) ($first yrange))
2389 (setf (getf options :y) (cddr yrange)))))))))
2390 (when (not xrange-required)
2391 ;; Make the default ranges on X nd Y large so parametric plots
2392 ;; don't get prematurely clipped. Don't use most-positive-flonum
2393 ;; because draw2d will overflow.
2394 (setf (getf options :xbounds) (list small huge))
2395 (when xrange
2396 ;; second argument was really a plot option, not an xrange
2397 (setq extra-options (cons xrange extra-options)))))
2398 ;; If no global options xlabel or ylabel have been given, choose
2399 ;; a default value for them: the expressions given, converted
2400 ;; to Maxima strings, if their length is less than 50 characters,
2401 ;; or the default "x" and "y" otherwise.
2402 (when (= (length fun) 2)
2403 (let ((v (second fun)) xlabel ylabel)
2404 (cond ((atom v)
2405 (setq xlabel "x") (setq ylabel ($sconcat v)))
2406 ((eq (second v) '$parametric)
2407 (setq xlabel ($sconcat (third v)))
2408 (setq ylabel ($sconcat (fourth v))))
2409 ((eq (second v) '$discrete)
2410 (setq xlabel "x") (setq ylabel "y"))
2411 ((eq (second v) '$contour)
2412 (setq xlabel (ensure-string (getf options :xvar)))
2413 (setq ylabel (ensure-string (getf options :yvar))))
2415 (setq xlabel "x") (setq ylabel ($sconcat v))))
2416 (unless (getf options :xlabel)
2417 (if (< (length xlabel) 50) (setf (getf options :xlabel) xlabel)))
2418 (unless (getf options :ylabel)
2419 (if (< (length ylabel) 50) (setf (getf options :ylabel) ylabel)))))
2420 ;; For explicit functions, default ylabel is the name of the 2nd variable
2421 (when (getf options :yvar)
2422 (setf (getf options :ylabel) ($sconcat (getf options :yvar))))
2423 ;; Parse the given options into the options list
2424 (setq options (plot-options-parser extra-options options))
2425 (when (getf options :y) (setf (getf options :ybounds) (getf options :y)))
2426 ;; Remove axes labels when no box is used in gnuplot
2427 (when (and (member :box options) (not (getf options :box))
2428 (not (eq (getf options :plot_format) '$xmaxima)))
2429 (remf options :xlabel)
2430 (remf options :ylabel))
2431 ;; check options given
2432 (let ((xmin (first (getf options :x))) (xmax (second (getf options :x))))
2433 (when
2434 (and (getf options :logx) xmin xmax)
2435 (if (> xmax 0)
2436 (when (<= xmin 0)
2437 (let ((revised-xmin (/ xmax 1000)))
2438 (mtell
2439 (intl:gettext
2440 "plot2d: lower bound must be positive when using 'logx'.~%plot2d: assuming lower bound = ~M instead of ~M")
2441 revised-xmin xmin)
2442 (setf (getf options :x) (list revised-xmin xmax))
2443 (setq xrange `((mlist) ,(second xrange) ,revised-xmin ,xmax))))
2444 (merror
2445 (intl:gettext
2446 "plot2d: upper bound must be positive when using 'logx'; found: ~M")
2447 xmax))))
2448 (let ((ymin (first (getf options :y)))
2449 (ymax (second (getf options :y))))
2450 (when (and (getf options :logy) ymin ymax)
2451 (if (> ymax 0)
2452 (when (<= ymin 0)
2453 (let ((revised-ymin (/ ymax 1000)))
2454 (mtell
2455 (intl:gettext
2456 "plot2d: lower bound must be positive when using 'logy'.~%plot2d: assuming lower bound = ~M instead of ~M")
2457 revised-ymin ymin)
2458 (setf (getf options :y) (list revised-ymin ymax))))
2459 (merror
2460 (intl:gettext
2461 "plot2d: upper bound must be positive when using 'logy'; found: ~M")
2462 ymax))))
2463 (setq *plot-realpart* (getf options :plot_realpart))
2464 ;; Creates the object that will be passed to the external graphic program
2465 (case (getf options :plot_format)
2466 ($xmaxima
2467 (setq plot (make-instance 'xmaxima-plot)))
2468 ($gnuplot
2469 (setq plot (make-instance 'gnuplot-plot)))
2470 ($gnuplot_pipes
2471 (setq plot (make-instance 'gnuplot-plot))
2472 (setf (slot-value plot 'pipe) T))
2474 (merror (intl:gettext "plot2d: plot format ~M not supported")
2475 (getf options :plot_format))))
2476 ;; Parse plot object and pass it to the graphic program
2477 (setq output-file (plot-preamble plot options))
2478 (plot2d-command plot fun options xrange)
2479 (plot-shipout plot options output-file))
2481 (defun msymbolp (x)
2482 (and (symbolp x) (char= (char (symbol-value x) 0) #\$)))
2484 (defmfun $tcl_output (lis i &optional (skip 2))
2485 (when (not (typep i 'fixnum))
2486 (merror
2487 (intl:gettext "tcl_ouput: second argument must be an integer; found ~M")
2489 (when (not ($listp lis))
2490 (merror
2491 (intl:gettext "tcl_output: first argument must be a list; found ~M") lis))
2492 (format *standard-output* "~% {")
2493 (cond (($listp (second lis))
2494 (loop for v in lis
2496 (format *standard-output* "~,,,,,,'eg " (nth i v))))
2498 (setq lis (nthcdr i lis))
2499 (loop with v = lis while v
2501 (format *standard-output* "~,,,,,,'eg " (car v))
2502 (setq v (nthcdr skip v)))))
2503 (format *standard-output* "~% }"))
2505 (defun tcl-output-list ( st lis )
2506 (cond ((null lis) )
2507 ((atom (car lis))
2508 (princ " { " st)
2509 (loop for v in lis
2510 count t into n
2511 when (eql 0 (mod n 5))
2512 do (terpri st)
2514 (format st "~,,,,,,'eg " v))
2515 (format st " }~%"))
2516 (t (tcl-output-list st (car lis))
2517 (tcl-output-list st (cdr lis)))))
2519 (defun check-range (range &aux tem a b)
2520 (or (and ($listp range)
2521 (setq tem (cdr range))
2522 (or (symbolp (car tem)) ($subvarp (car tem)))
2523 (numberp (setq a ($float (meval* (second tem)))))
2524 (numberp (setq b ($float (meval* (third tem)))))
2525 (< a b))
2526 (if range
2527 (merror
2528 (intl:gettext "plotting: range must be of the form [variable, min, max]; found: ~M")
2529 range)
2530 (merror
2531 (intl:gettext "plotting: no range given; must supply range of the form [variable, min, max]"))))
2532 `((mlist) ,(car tem) ,(float a) ,(float b)))
2534 (defmfun $zero_fun (x y) x y 0.0)
2536 (defun output-points (pl &optional m)
2537 "If m is supplied print blank line every m lines"
2538 (let ((j -1))
2539 (declare (fixnum j))
2540 (loop for i below (length (polygon-pts pl))
2541 with ar = (polygon-pts pl)
2542 do (print-pt (aref ar i))
2543 (setq i (+ i 1))
2544 (print-pt (aref ar i))
2545 (setq i (+ i 1))
2546 (print-pt (aref ar i))
2547 (terpri $pstream)
2548 (cond (m
2549 (setq j (+ j 1))
2550 (cond ((eql j (the fixnum m))
2551 (terpri $pstream)
2552 (setq j -1)))))
2555 (defun output-points-tcl (dest pl m)
2556 (format dest " {matrix_mesh ~%")
2557 ;; x y z are done separately:
2558 (loop for off from 0 to 2
2559 with ar = (polygon-pts pl)
2560 with i of-type fixnum = 0
2561 do (setq i off)
2562 (format dest "~%{")
2563 (loop
2564 while (< i (length ar))
2565 do (format dest "~% {")
2566 (loop for j to m
2567 do (print-pt (aref ar i))
2568 (setq i (+ i 3)))
2569 (format dest "}~%"))
2570 (format dest "}~%"))
2571 (format dest "}~%"))
2573 (defun show-open-plot (ans file)
2574 (cond ($show_openplot
2575 (with-open-file (st1 (plot-temp-file (format nil "maxout~d.xmaxima" (getpid))) :direction :output :if-exists :supersede)
2576 (princ ans st1))
2577 ($system (concatenate 'string *maxima-prefix*
2578 (if (string= *autoconf-windows* "true") "\\bin\\" "/bin/")
2579 $xmaxima_plot_command)
2580 #-(or (and sbcl win32) (and sbcl win64) (and ccl windows))
2581 (format nil " ~s &" file)
2582 #+(or (and sbcl win32) (and sbcl win64) (and ccl windows))
2583 file))
2584 (t (princ ans) "")))
2586 ;; contour_plot now punts to plot2d
2587 (defmfun $contour_plot (expr &rest optional-args)
2588 (let ((command "plot2d ([contour, "))
2589 (setq command ($sconcat command expr "]"))
2590 (when optional-args
2591 (dolist (arg optional-args)
2592 (setq command ($sconcat command ", " arg))))
2593 (setq command ($sconcat command ")"))
2594 (mtell (intl:gettext "contour_plot is now obsolete. Using plot2d instead:~%"))
2595 (mtell "~M~%" command)
2596 (apply #'$plot2d (cons `((mlist) $contour ,expr) optional-args))))
2598 #| plot3d
2599 Examples:
2601 plot3d (2^(-u^2 + v^2), [u, -3, 3], [v, -2, 2], [palette, false]);
2603 plot3d ( log ( x^2*y^2 ), [x, -2, 2], [y, -2, 2], [grid, 29, 29]);
2605 expr_1: cos(y)*(10.0+6*cos(x))$
2606 expr_2: sin(y)*(10.0+6*cos(x))$
2607 expr_3: -6*sin(x)$
2608 plot3d ([expr_1, expr_2, expr_3], [x, 0, 2*%pi], [y, 0, 2*%pi],
2609 ['grid, 40, 40], [z,-8,8]);
2611 plot3d (cos (-x^2 + y^3/4), [x, -4, 4], [y, -4, 4],
2612 [mesh_lines_color, false], [elevation, 0], [azimuth, 0], [grid, 150, 150]);
2614 spherical: make_transform ([th, phi,r], r*sin(phi)*cos(th),
2615 r*sin(phi)*sin(th), r*cos(phi))$
2616 plot3d ( 5, [th, 0, 2*%pi], [phi, 0, %pi], [transform_xy, spherical],
2617 [palette, [value, 0.65, 0.7, 0.1, 0.9]], [plot_format,xmaxima]);
2619 V: 1 / sqrt ( (x+1)^2+y^2 ) - 1 / sqrt( (x-1)^2+y^2 )$
2620 plot3d ( V, [x, -2, 2], [y, -2, 2], [z, -4, 4]);
2622 (defmfun $plot3d
2623 (fun &rest extra-options
2624 &aux
2625 lvars xrange yrange titles output-file functions exprn domain tem
2626 (options (copy-tree *plot-options*)) (*plot-realpart* *plot-realpart*)
2627 (usage (intl:gettext
2628 "plot3d: Usage.
2629 To plot a single function f of 2 variables v1 and v2:
2630 plot3d (f, [v1, min, max], [v2, min, max], options)
2631 A parametric representation of a surface with parameters v1 and v2:
2632 plot3d ([f1, f2, f3], [v1, min, max], [v2, min, max], options)
2633 Several functions depending on the two variables v1 and v2:
2634 plot3d ([f1, f2, ..., fn, [v1, min, max], [v2, min, max]], options)")))
2635 (setf (getf options :type) "plot3d")
2636 ;; Ensure that fun is a list of expressions and maxima lists, followed
2637 ;; by a domain definition
2638 (if ($listp fun)
2639 (if (= 1 (length (check-list-plot3d fun)))
2640 ;; fun consisted of a single parametric expression
2641 (setq fun `(,fun ,(pop extra-options) ,(pop extra-options)))
2642 ;; fun was a maxima list with several independent surfaces
2643 (pop fun))
2644 ;; fun consisted of a single expression
2645 (setq fun `(,fun ,(pop extra-options) ,(pop extra-options))))
2646 ;; go through all the independent surfaces creating the functions stack
2647 (loop
2648 (setq exprn (pop fun))
2649 (if ($listp exprn)
2650 (progn
2651 (setq domain (check-list-plot3d exprn))
2652 (case (length domain)
2654 ;; exprn is a parametric representation of a surface
2655 (let (vars1 vars2 vars3)
2656 ;; list fun should have two valid ranges after exprn
2657 (setq xrange (check-range (pop fun)))
2658 (setq yrange (check-range (pop fun)))
2659 ;; list of the two variables for the parametric equations
2660 (setq lvars `((mlist),(second xrange) ,(second yrange)))
2661 ;; make sure that the 3 parametric equations depend only
2662 ;; on the two variables in lvars
2663 (setq vars1
2664 ($listofvars
2665 (mfuncall
2666 (coerce-float-fun (second exprn) lvars "plot3d")
2667 (second lvars) (third lvars))))
2668 (setq vars2
2669 ($listofvars
2670 (mfuncall
2671 (coerce-float-fun (third exprn) lvars "plot3d")
2672 (second lvars) (third lvars))))
2673 (setq vars3
2674 ($listofvars
2675 (mfuncall
2676 (coerce-float-fun (fourth exprn) lvars "plot3d")
2677 (second lvars) (third lvars))))
2678 (setq lvars ($listofvars `((mlist) ,vars1 ,vars2 ,vars3)))
2679 (if (<= ($length lvars) 2)
2680 ;; we do have a valid parametric set. Push it into
2681 ;; the functions stack, along with their domain
2682 (progn
2683 (push `(,exprn ,xrange ,yrange) functions)
2684 ;; add a title to the titles stack
2685 (push "Parametric function" titles)
2686 ;; unknown variables in the parametric equations
2687 ;; ----- GNUPLOT 4.0 WORK-AROUND -----
2688 (when (and ($constantp (fourth exprn))
2689 (getf options :gnuplot_4_0))
2690 (setf (getf options :const_expr)
2691 ($float (meval (fourth exprn))))))
2692 (merror
2693 (intl:gettext "plot3d: there must be at most two variables; found: ~M")
2694 lvars))))
2696 ;; expr is a simple function with its own domain. Push the
2697 ;; function and its domain into the functions stack
2698 (setq xrange (second domain))
2699 (setq yrange (third domain))
2700 (push `(,(second exprn) ,xrange ,yrange) functions)
2701 ;; push a title for this plot into the titles stack
2702 (if (< (length (ensure-string (second exprn))) 36)
2703 (push (ensure-string (second exprn)) titles)
2704 (push "Function" titles)))
2706 ;; syntax error. exprn does not have the expected form
2707 (merror
2708 (intl:gettext
2709 "plot3d: argument must be a list of three expressions; found: ~M")
2710 exprn))))
2711 (progn
2712 ;; exprn is a simple function, defined in the global domain.
2713 (if (and (getf options :xvar) (getf options :yvar))
2714 ;; the global domain has already been defined; use it.
2715 (progn
2716 (setq xrange `((mlist) ,(getf options :xvar)
2717 ,(first (getf options :x))
2718 ,(second (getf options :x))))
2719 (setq yrange `((mlist) ,(getf options :yvar)
2720 ,(first (getf options :y))
2721 ,(second (getf options :y)))))
2722 ;; the global domain should be defined by the last two lists
2723 ;; in fun. Extract it and check whether it is valid.
2724 (progn
2725 (setq
2726 domain
2727 (check-list-plot3d (append `((mlist) ,exprn) (last fun 2))))
2728 (setq fun (butlast fun 2))
2729 (if (= 3 (length domain))
2730 ;; domain is valid. Make it the global one.
2731 (progn
2732 (setq xrange (second domain))
2733 (setq yrange (third domain))
2734 (setf (getf options :xvar) (second xrange))
2735 (setf (getf options :x) (cddr xrange))
2736 (setf (getf options :yvar) (second yrange))
2737 (setf (getf options :y) (cddr yrange)))
2738 (merror usage))))
2739 ;; ----- GNUPLOT 4.0 WORK-AROUND -----
2740 (when (and ($constantp exprn) (getf options :$gnuplot_4_0))
2741 (setf (getf options :const_expr) ($float (meval exprn))))
2742 ;; push the function and its domain into the functions stack
2743 (push `(,exprn ,xrange ,yrange) functions)
2744 ;; push a title for this plot into the titles stack
2745 (if (< (length (ensure-string exprn)) 36)
2746 (push (ensure-string exprn) titles)
2747 (push "Function" titles))))
2748 (when (= 0 (length fun)) (return)))
2749 ;; recover the original ordering for the functions and titles stacks
2750 (setq functions (reverse functions))
2751 (setq titles (reverse titles))
2752 ;; parse the options given to plot3d
2753 (setq options (plot-options-parser extra-options options))
2754 (setq tem (getf options :transform_xy))
2755 (when (and (member :gnuplot_pm3d options) (null (getf options :gnuplot_pm3d)))
2756 (setf (getf options :palette) nil))
2757 (setq *plot-realpart* (getf options :plot_realpart))
2758 ;; set up the labels for the axes, unless no box is being shown
2759 (unless (and (member :box options) (not (getf options :box)))
2760 (if (and (getf options :xvar) (getf options :yvar) (null tem))
2761 (progn
2762 ;; Don't set xlabel (ylabel) if the user specified one.
2763 (unless (getf options :xlabel)
2764 (setf (getf options :xlabel) (ensure-string (getf options :xvar))))
2765 (unless (getf options :ylabel)
2766 (setf (getf options :ylabel) (ensure-string (getf options :yvar)))))
2767 (progn
2768 (setf (getf options :xlabel) "x")
2769 (setf (getf options :ylabel) "y")))
2770 (unless (getf options :zlabel) (setf (getf options :zlabel) "z")))
2771 ;; x and y should not be bound, when an xy transformation function is used
2772 (when tem (remf options :x) (remf options :y))
2773 ;; Set up the plot command
2774 (let (plot (legend (getf options :legend)))
2775 ;; titles will be a list. Titles given in the legend option prevail
2776 ;; over titles generated by plot3d. No legend if option [legend,false]
2777 (unless (listp legend) (setq legend (list legend)))
2778 (when (member :legend options)
2779 (if (first legend) (setq titles legend)) (setq titles nil))
2780 (case (getf options :plot_format)
2781 ($xmaxima
2782 (setq plot (make-instance 'xmaxima-plot)))
2783 ($gnuplot
2784 (setq plot (make-instance 'gnuplot-plot)))
2785 ($gnuplot_pipes
2786 (setq plot (make-instance 'gnuplot-plot))
2787 (setf (slot-value plot 'pipe) T))
2788 ($geomview
2789 (setq plot (make-instance 'geomview-plot)))
2791 (merror (intl:gettext "plot3d: plot format ~M not supported")
2792 (getf options :plot_format))))
2793 ;; Parse plot object and pass it to the graphic program
2794 (setq output-file (plot-preamble plot options))
2795 (plot3d-command plot functions options titles)
2796 (plot-shipout plot options output-file)))
2798 ;; Given a Maxima list with 3 elements, checks whether it represents a function
2799 ;; defined in a 2-dimensional domain or a parametric representation of a
2800 ;; 3-dimensional surface, depending on two parameters.
2801 ;; The return value will be a Maxima list if the test is successful or nil
2802 ;; otherwise.
2803 ;; In the case of a function and a 2D domain, it returns the domain, validated.
2804 ;; When it is a parametric representation it returns an empty Maxima list.
2806 (defun check-list-plot3d (lis)
2807 (let (xrange yrange)
2808 ;; Makes sure list has the form ((mlist) $atom item1 item2)
2809 (unless (and ($listp lis) (= 3 ($length lis)) (not ($listp (second lis))))
2810 (return-from check-list-plot3d nil))
2811 ;; we might have a function with domain or a parametric representation
2812 (if ($listp (third lis))
2813 ;; lis is probably a function with a valid domain
2814 (if ($listp (fourth lis))
2815 ;; we do have a function and a domain. Return the domain
2816 (progn
2817 (setq xrange (check-range (third lis)))
2818 (setq yrange (check-range (fourth lis)))
2819 (return-from check-list-plot3d `((mlist) ,xrange ,yrange)))
2820 ;; wrong syntax: [expr1, list, expr2]
2821 (return-from check-list-plot3d nil))
2822 ;; lis is probably a parametric representation
2823 (if ($listp (fourth lis))
2824 ;; wrong syntax: [expr1, expr2, list]
2825 (return-from check-list-plot3d nil)
2826 ;; we do have a parametric representation. Return an empty list
2827 (return-from check-list-plot3d '((mlist)))))))