Debian Codegraph @

texmf-dist/tex/lualatex/bezierplot/bezierplot.lua

raw
1 #!/usr/bin/env lua
2 -- Linus Romer, published 2018 under LPPL Version 1.3c
3 -- version 1.6 2024-11-02
4 abs = math.abs
5 acos = math.acos
6 asin = math.asin
7 atan = math.atan
8 cos = math.cos
9 cosh = math.cosh
10 deg = math.deg
11 exp = math.exp
12 e = math.exp(1)
13 huge = math.huge
14 log = math.log
15 pi = math.pi
16 rad = math.rad
17 sin = math.sin
18 sinh = math.sinh
19 sqrt = math.sqrt
20 tan = math.tan
21 tanh = math.tanh
22
23 -- just a helper for debugging:
24 local function printdifftable(t)
25 for i = 1,#t do
26 for j = 1, 6 do
27 if j < 5 then
28 io.write(t[i][j].." ")
29 else
30 if t[i][j] then
31 io.write("true ")
32 else
33 io.write("false ")
34 end
35 end
36 end
37 io.write("\n")
38 end
39 end
40
41 -- cube root defined for all real numbers x
42 function cbrt(x)
43 if x < 0 then
44 return -(-x)^(1/3)
45 else
46 return x^(1/3)
47 end
48 end
49
50 function sgn(x)
51 if x<0 then
52 return -1
53 elseif x>0 then
54 return 1
55 else
56 return 0
57 end
58 end
59
60 local function round(num, decimals)
61 local result = tonumber(string.format("%." .. (decimals or 0) .. "f", num))
62 if math.floor(result) == result then
63 return math.floor(result)
64 else
65 return result
66 end
67 end
68
69 -- check if a point (x,y) satisfies xmin <= x <= xmax and ymin <= < <= ymax
70 local function is_in_window(x,y,xmin,xmax,ymin,ymax)
71 if x >= xmin and x <= xmax and y >= ymin and y <= ymax then
72 return true
73 else
74 return false
75 end
76 end
77
78 local function evaluate(s)
79 local tempfunc = assert(load("return " .. s))
80 return tempfunc()
81 end
82
83
84 -- 5-stencil method
85 -- return from a graph from f in the form {{x,y},...}
86 -- the derivatives in form {{x,y,dy/dx,ddy/ddx,extrema,inflection},...}
87 local function diffgraph(func,graph,h)
88 local dgraph = {}
89 local l = #graph
90 if l < 4 then -- this is not worth the pain...
91 for i = 1, l do
92 table.insert(dgraph,{graph[i][1],graph[i][2],0,0,false,false})
93 end
94 else
95 local yh = func(graph[1][1]-h)
96 local yhh = func(graph[1][1]-2*h)
97 if yhh > -math.huge and yhh < math.huge -- if defined at all
98 and yh > -math.huge and yh < math.huge then
99 dgraph[1] = {graph[1][1],graph[1][2],
100 (yhh-8*yh+8*graph[2][2]-graph[3][2])/(12*h),
101 (-yhh+16*yh-30*graph[1][2]+16*graph[2][2]-graph[3][2])
102 /(12*h^2)}
103 dgraph[2] = {graph[2][1],graph[2][2],
104 (yh-8*graph[1][2]+8*graph[3][2]-graph[4][2])/(12*h),
105 (-yh+16*graph[1][2]-30*graph[2][2]+16*graph[3][2]-graph[4][2])
106 /(12*h^2)}
107 else -- take neighbour values
108 dgraph[1] = {graph[1][1],graph[1][2],
109 (graph[1][2]-8*graph[2][2]+8*graph[4][2]-graph[5][2])/(12*h),
110 (-graph[1][2]+16*graph[2][2]-30*graph[3][2]
111 +16*graph[4][2]-graph[5][2])/(12*h^2)}
112 dgraph[2] = {graph[2][1],graph[2][2],
113 (graph[1][2]-8*graph[2][2]+8*graph[4][2]-graph[5][2])/(12*h),
114 (-graph[1][2]+16*graph[2][2]-30*graph[3][2]
115 +16*graph[4][2]-graph[5][2])/(12*h^2)}
116 end
117 for i = 3, l-2 do
118 table.insert(dgraph,{graph[i][1],graph[i][2],
119 (graph[i-2][2]-8*graph[i-1][2]+8*graph[i+1][2]-graph[i+2][2])
120 /(12*h),
121 (-graph[i-2][2]+16*graph[i-1][2]-30*graph[i][2]
122 +16*graph[i+1][2]-graph[i+2][2])
123 /(12*h^2)})
124 end
125 yh = func(graph[l][1]+h)
126 yhh = func(graph[l][1]+2*h)
127 if yhh > -math.huge and yhh < math.huge -- if defined at all
128 and yh > -math.huge and yh < math.huge then
129 dgraph[l-1] = {graph[l-1][1],graph[l-1][2],
130 (graph[l-3][2]-8*graph[l-2][2]+8*graph[l][2]-yh)/(12*h),
131 (-graph[l-3][2]+16*graph[l-2][2]-30*graph[l-1][2]
132 +16*graph[l][2]-yh)/(12*h^2)}
133 dgraph[l] = {graph[l][1],graph[l][2],
134 (graph[l-2][2]-8*graph[l-1][2]+8*yh-yhh)/(12*h),
135 (-graph[l-2][2]+16*graph[l-1][2]-30*graph[l][2]
136 +16*yh-yhh)/(12*h^2)}
137 else
138 -- take neighbour values
139 dgraph[l] = {graph[l][1],graph[l][2],
140 (graph[l-4][2]-8*graph[l-3][2]+8*graph[l-1][2]-graph[l][2])
141 /(12*h),
142 (-graph[l-4][2]+16*graph[l-3][2]-30*graph[l-2][2]
143 +16*graph[l-1][2]-graph[l][2])/(12*h^2)}
144 dgraph[l-1] = {graph[l-1][1],graph[l-2][2],
145 (graph[l-4][2]-8*graph[l-3][2]+8*graph[l-1][2]-graph[l][2])
146 /(12*h),
147 (-graph[l-4][2]+16*graph[l-3][2]-30*graph[l-2][2]
148 +16*graph[l-1][2]-graph[l][2])/(12*h^2)}
149 end
150 -- add information about being extremum / inflection point (true/false)
151 for i = 1, l do
152 dgraph[i][5] = false -- dy/dx == 0 ? default, may change later
153 dgraph[i][6] = false -- ddy/ddx == 0 ? default, may change later
154 end
155 for i = 1, l-1 do
156 -- if no gap is inbetween
157 if not (dgraph[i+1][1] - dgraph[i][1] > 1.5*h) then
158 -- check for dy/dx == 0
159 -- if not already determined as near dy/dx=0
160 if dgraph[i][3] == 0 then
161 if dgraph[i+1][3] == 0 then --take the later
162 dgraph[i+1][5] = true
163 dgraph[i][5] = false
164 else
165 dgraph[i][5] = true
166 end
167 elseif abs(dgraph[i][3]*dgraph[i+1][3])
168 ~= dgraph[i][3]*dgraph[i+1][3] then -- this must be near
169 if abs(dgraph[i][4]) <= abs(dgraph[i+1][4]) then
170 dgraph[i][5] = true
171 else
172 dgraph[i+1][5] = true
173 end
174 end
175 -- check for ddy/ddx == 0
176 -- if not already determined as near ddy/ddx=0
177 if (not dgraph[i][6]) and (abs(dgraph[i][4]*dgraph[i+1][4])
178 ~= dgraph[i][4]*dgraph[i+1][4]) then -- this must be near
179 if abs(dgraph[i][4]) <= abs(dgraph[i+1][4]) then
180 dgraph[i][6] = true
181 else
182 dgraph[i+1][6] = true
183 end
184 end
185 end
186 end
187 end
188 return dgraph
189 end
190
191 -- simplified diffgraph function, the function is derived only once
192 -- return from a graph from f in the form {{x,y},...}
193 -- the derivatives in form {{x,y,dy/dx},...}
194 -- we start with index 1 and then always jump indexjump to the next
195 -- index
196 local function diffgraphsimple(func,graph,h,indexjump)
197 local dgraph = {}
198 local l = math.floor((#graph-1)/indexjump)*indexjump+1
199 if l < 2 then -- this is not worth the pain...
200 dgraph = {graph[1][1],graph[1][2],0}
201 else
202 local yh = func(graph[1][1]-h)
203 local yhh = func(graph[1][1]-2*h)
204 if yhh > -math.huge and yhh < math.huge -- if defined at all
205 and yh > -math.huge and yh < math.huge then
206 dgraph[1] = {graph[1][1],graph[1][2],
207 (yhh-8*yh+8*graph[2][2]-graph[3][2])/(12*h)}
208 else -- take neighbour values
209 dgraph[1] = {graph[1][1],graph[1][2],
210 (graph[1][2]-8*graph[2][2]+8*graph[4][2]-graph[5][2])
211 /(12*h)}
212 end
213 for i = 1+indexjump, l-1, indexjump do
214 table.insert(dgraph,{graph[i][1],graph[i][2],
215 (graph[i-2][2]-8*graph[i-1][2]+8*graph[i+1][2]-graph[i+2][2])
216 /(12*h)})
217 end
218 yh = func(graph[l][1]+h)
219 yhh = func(graph[l][1]+2*h)
220 if yhh > -math.huge and yhh < math.huge -- if defined at all
221 and yh > -math.huge and yh < math.huge then
222
223 table.insert(dgraph,{graph[l][1],graph[l][2],
224 (graph[l-2][2]-8*graph[l-1][2]+8*yh-yhh)/(12*h)})
225 else
226 -- take neighbour values
227 table.insert(dgraph,{graph[l][1],graph[l][2],
228 (graph[l-4][2]-8*graph[l-3][2]+8*graph[l-1][2]-graph[l][2])
229 /(12*h)})
230 end
231 end
232 return dgraph
233 end
234
235 -- diffgraph for cubic function ax^3+bx^2+cx+d
236 -- returns the derivatives in form {{x,y,dy/dx,ddy/ddx},...}
237 -- if isinverse = true then the coordinates will be inversed
238 local function diffgraphcubic(graph,a,b,c,d,isinverse)
239 local dgraph = {}
240 local l = #graph
241 for i = 1, l do
242 if isinverse then
243 dgraph[#dgraph+1] = {graph[i][2],graph[i][1],c
244 +graph[i][2]*(2*b+3*a*graph[i][2]),6*a*graph[i][2]+2*b}
245 else
246 dgraph[#dgraph+1] = {graph[i][1],graph[i][2],c
247 +graph[i][1]*(2*b+3*a*graph[i][1]),6*a*graph[i][1]+2*b}
248 end
249 end
250 return dgraph
251 end
252
253 -- checks for 100 x, if the function given by funcstring
254 -- fits the graph g (up to maxerror) after filling in
255 -- the parameters a, b, c, d
256 -- if the graph is inverted, then isinverse has to be set true
257 local function do_parameters_fit(a,b,c,d,funcstring,funcgraph,maxerror,isinverse)
258 if not (a > -math.huge and a < math.huge and b > -math.huge and b < math.huge and
259 c > -math.huge and c < math.huge and d > -math.huge and d < math.huge) then
260 return false
261 end
262 local funcx = string.gsub(funcstring, "a", a)
263 local funcx = string.gsub(funcx, "b", b)
264 local funcx = string.gsub(funcx, "c", c)
265 local funcx = string.gsub(funcx, "d", d)
266 local func = assert(load("local x = ...; return "..funcx))
267 for i = 1, #funcgraph, math.max(1,math.floor(0.01*#funcgraph)) do
268 if isinverse then
269 if abs(func(funcgraph[i][2])-funcgraph[i][1])
270 > maxerror then
271 return false
272 end
273 else
274 if abs(func(funcgraph[i][1])-funcgraph[i][2])
275 > maxerror then
276 return false
277 end
278 end
279 end
280 return true
281 end
282
283 -- f(x)=a*x^3+b*x^2+c*x +d
284 local function parameters_cubic(xp,yp,xq,yq,xr,yr,xs,ys)
285 return (((xq-xp)*xr^2+(xp^2-xq^2)*xr+xp*xq^2-xp^2*xq)*ys+((xp-xq)
286 *xs^2+(xq^2-xp^2)*xs-xp*xq^2+xp^2*xq)*yr+((xr-xp)*xs^2+(xp^2-xr^2)
287 *xs+xp*xr^2-xp^2*xr)*yq+((xq-xr)*xs^2+(xr^2-xq^2)*xs-xq*xr^2+xq^2
288 *xr)*yp)/((xq-xp)*(xr-xp)*(xr-xq)*(xs-xp)*(xs-xq)*(xs-xr)),
289 -(((xq-xp)*xr^3+(xp^3-xq^3)*xr+xp*xq^3-xp^3*xq)*ys+((xp-
290 xq)*xs^3+(xq^3-xp^3)*xs-xp*xq^3+xp^3*xq)*yr+((xr-xp)*xs^3+(xp^3
291 -xr^3)*xs+xp*xr^3-xp^3*xr)*yq+((xq-xr)*xs^3+(xr^3-xq^3)*xs-xq*xr^3
292 +xq^3*xr)*yp)/((xq-xp)*(xr-xp)*(xr-xq)*(xs-xp)*(xs-xq)*(xs-xr)),
293 (((xq^2-xp^2)*xr^3+(xp^3-xq^3)*xr^2+xp^2*xq^3-xp^3*xq^2)
294 *ys+((xp^2-xq^2)*xs^3+(xq^3-xp^3)*xs^2-xp^2*xq^3+xp^3*xq^2)*yr
295 +((xr^2-xp^2)*xs^3+(xp^3-xr^3)*xs^2+xp^2*xr^3-xp^3*xr^2)*yq+((xq^2
296 -xr^2)*xs^3+(xr^3-xq^3)*xs^2-xq^2*xr^3+xq^3*xr^2)*yp)/((xq-xp)
297 *(xr-xp)*(xr-xq)*(xs-xp)*(xs-xq)*(xs-xr)),
298 -(((xp*xq^2-xp^2*xq)*xr^3+(xp^3*xq-xp*xq^3)*xr^2+(xp^2
299 *xq^3-xp^3*xq^2)*xr)*ys+((xp^2*xq-xp*xq^2)*xs^3+(xp*xq^3-xp^3*xq)
300 *xs^2+(xp^3*xq^2-xp^2*xq^3)*xs)*yr+((xp*xr^2-xp^2*xr)*xs^3+(xp^3*xr
301 -xp*xr^3)*xs^2+(xp^2*xr^3-xp^3*xr^2)*xs)*yq+((xq^2*xr-xq*xr^2)*xs^3
302 +(xq*xr^3-xq^3*xr)*xs^2+(xq^3*xr^2-xq^2*xr^3)*xs)*yp)/((xq-xp)
303 *(xr-xp)*(xr-xq)*(xs-xp)*(xs-xq)*(xs-xr))
304 end
305
306 -- f(x)=a*x+b
307 local function parameters_affine(xp,yp,xq,yq)
308 local a = (yp - yq) / (xp - xq)
309 local b = ((xp * yq) - (xq * yp)) / (xp - xq)
310 return a, b
311 end
312
313 -- what is the sum of the squared error
314 -- when comparing the bezier path
315 -- p.. control q and r .. s
316 -- with the graph g from index starti to endi
317 -- (looking at the points at roughly t=.33 and t=.67)
318 local function squareerror(f,g,starti,endi,qx,qy,rx,ry)
319 local result = 0
320 for t = .1, .9, .1 do
321 x = (1-t)^3*g[starti][1]+3*t*(1-t)^2*qx+3*t^2*(1-t)*rx+t^3*g[endi][1]
322 y = (1-t)^3*g[starti][2]+3*t*(1-t)^2*qy+3*t^2*(1-t)*ry+t^3*g[endi][2]
323 result = result + (y-f(x))^2
324 end
325 return result
326 end
327
328 -- converts a table with bezier point information
329 -- to a string with rounded values
330 -- the path is reversed, if rev is true
331 -- e.g. if bezierpoints = {{0,1},{2,3,4,5,6,7},{8,9,10,11,12,13}}
332 -- then
333 -- (0,1) .. controls (2,3) and (4,5) .. (6,7) .. controls
334 -- (8,9) and (10,11) .. (12,13)
335 -- will be returned
336 -- the notation "pgfplots" will change the notation to
337 -- YES: \addplot coordinates {(0,1) (6,7) (2,3) (4,5) (6,7) (12,13) (8,9) (10,11)}
338 -- NO: 0 1 \\ 6 7 \\ 2 3 \\ 4 5 \\ \\ 6 7 \\ 12 13 \\ 8 9 \\ 10 11 \\
339 -- As pgfplots does not connect the bezier segments
340 -- reverse paths are not implemented
341 local function beziertabletostring(bezierpoints,rndx,rndy,rev,notation)
342 local bezierstring = ""
343 local b = {{round(bezierpoints[1][1],rndx),round(bezierpoints[1][2],rndy)}} -- rounded and then
344 -- reduced points (if identical after rounding)
345 -- rounding
346 for i = 2, #bezierpoints do
347 -- check if x--coordinates are identical
348 if round(bezierpoints[i][#bezierpoints[i]-1],rndx) ~= b[#b][#b[#b]-1] then
349 b[#b+1] = {}
350 for j = 1, #bezierpoints[i] do
351 if j % 2 == 0 then -- x coordinate
352 b[#b][j] = round(bezierpoints[i][j],rndx)
353 else
354 b[#b][j] = round(bezierpoints[i][j],rndy)
355 end
356 end
357 end
358 end
359 if #b > 1 then -- if not empty or single point
360 -- check if bezierstring contains only straight lines
361 local onlystraightlines = true
362 for i = 1, #b do
363 if #b[i] > 2 then
364 onlystraightlines = false
365 break
366 end
367 end
368 if onlystraightlines then
369 if rev then
370 bezierstring = "(" .. b[#b][1] .. "," .. b[#b][2] ..")"
371 for i = #b-1, 1, -1 do
372 bezierstring = bezierstring ..
373 " -- (" .. b[i][1] .. "," .. b[i][2] ..")"
374 end
375 else
376 if notation == "pgfplots" then
377 bezierstring = "\\addplot coordinates {("
378 .. b[1][1] .. "," .. b[1][2] .. ") ("
379 .. b[2][1] .. "," .. b[2][2] .. ") ("
380 .. b[1][1] .. "," .. b[1][2] .. ") ("
381 .. b[2][1] .. "," .. b[2][2] .. ") }"
382 else -- notation = tikz
383 bezierstring = "(" .. b[1][1] .. "," .. b[1][2] ..")"
384 for i = 2, #b do
385 bezierstring = bezierstring ..
386 " -- (" .. b[i][1] .. "," .. b[i][2] ..")"
387 end
388 end
389 end
390 else
391 if rev then
392 bezierstring = "(" .. b[#b][#b[#b]-1] .. ","
393 .. b[#b][#b[#b]] ..")" -- initial point
394 for i = #b, 2, -1 do
395 if #b[i] >= 6 then -- cubic bezier spline
396 bezierstring = bezierstring .. " .. controls ("
397 .. b[i][3] .. "," .. b[i][4] ..") and ("
398 .. b[i][1] .. "," .. b[i][2] .. ") .. ("
399 .. b[i-1][#b[i-1]-1] .. "," .. b[i-1][#b[i-1]]..")"
400 else
401 bezierstring = bezierstring .. " ("
402 .. b[i-1][#b[i-1]-1] .. "," .. b[i-1][#b[i-1]] ..")"
403 end
404 end
405 else
406 if notation == "pgfplots" then
407 bezierstring = "\\addplot coordinates {"
408 for i = 1, #b-1 do
409 if #b[i+1] >= 6 then -- cubic bezier spline
410 bezierstring = bezierstring .. "("
411 .. b[i][#b[i]-1] .. "," .. b[i][#b[i]] .. ") ("
412 .. b[i+1][5] .. "," .. b[i+1][6] .. ") ("
413 .. b[i+1][1] .. "," .. b[i+1][2] .. ") ("
414 .. b[i+1][3] .. "," .. b[i+1][4] .. ") "
415 end
416 end
417 bezierstring = bezierstring .. "}"
418 else -- notation = tikz
419 bezierstring = "(" .. b[1][1] .. ","
420 .. b[1][2] ..")" -- initial point
421 for i = 2, #b do
422 if #b[i] >= 6 then -- cubic bezier spline
423 bezierstring = bezierstring .. " .. controls ("
424 .. b[i][1] .. "," .. b[i][2] ..") and ("
425 .. b[i][3] .. "," .. b[i][4] .. ") .. ("
426 .. b[i][5] .. "," .. b[i][6]..")"
427 else
428 bezierstring = bezierstring .. " ("
429 .. b[i][1] .. "," .. b[i][2] ..")"
430 end
431 end
432 end
433 end
434 end
435 end
436 return bezierstring
437 end
438
439 -- take end points of a graph g of the function f
440 -- (from indices starti to endi)
441 -- without extrema or inflection points inbetween
442 -- and try to approximate it with a cubic bezier curve
443 -- (round to rndx and rndy when printing)
444 -- if maxerror <= 0, the function will not be recursive anymore
445 local function graphtobezierapprox(f,g,starti,endi,maxerror,recursiondepth)
446 local px = g[starti][1]
447 local py = g[starti][2]
448 local dp = g[starti][3]
449 local sx = g[endi][1]
450 local sy = g[endi][2]
451 local ds = g[endi][3]
452 -- we compute the corner point c, where the controls would meet
453 local cx = ((dp * px) - (ds * sx) - py + sy) / (dp - ds)
454 local cy = (dp * ((ds * px) - (ds * sx) - py + sy) / (dp - ds)) + py
455 local delta_cpx = .01*(cx-px)
456 local delta_cpy = .01*(cy-py)
457 local delta_csx = .01*(cx-sx)
458 local delta_csy = .01*(cy-sy)
459 -- now we slide q between p and c & r between s and c
460 -- and search for the best qx and best rx
461 local qx = px+delta_cpx
462 local qy = py+delta_cpy
463 local rx = sx+delta_csx
464 local ry = sy+delta_csy
465 local err = squareerror(f,g,starti,endi,qx,qy,rx,ry)
466 local newerror
467 local best_j = 1
468 for i = 2, 99 do
469 xa = px+i*delta_cpx
470 ya = py+i*delta_cpy
471 for j = 10, 90, 10 do -- determine j roughly
472 xb = sx+j*delta_csx
473 yb = sy+j*delta_csy
474 -- now check, if xa and xb fit better
475 -- than the last qx and rx did
476 -- (sum of squares must be smaller)
477 newerror = squareerror(f,g,starti,endi,xa,ya,xb,yb)
478 if newerror < err then
479 best_j = j
480 qx = xa
481 qy = ya
482 rx = xb
483 ry = yb
484 err = newerror
485 end
486 end
487 for j = best_j-9, best_j+9 do -- determine j better
488 xb = sx+j*delta_csx
489 yb = sy+j*delta_csy
490 -- now check, if xa and xb fit better
491 -- than the last qx and rx did
492 -- (sum of squares must be smaller)
493 newerror = squareerror(f,g,starti,endi,xa,ya,xb,yb)
494 if newerror < err then
495 best_j = j
496 qx = xa
497 qy = ya
498 rx = xb
499 ry = yb
500 err = newerror
501 end
502 end
503 end
504 if maxerror > 0 and recursiondepth > 0 then
505 -- check if it is close enough: (recycling err, xa, ya)
506 err = 0
507 for t = .1, .9, .1 do
508 xa = (1-t)^3*g[starti][1]+3*t*(1-t)^2*qx+3*t^2*(1-t)*rx+t^3*g[endi][1]
509 ya = (1-t)^3*g[starti][2]+3*t*(1-t)^2*qy+3*t^2*(1-t)*ry+t^3*g[endi][2]
510 if abs(ya-f(xa)) > err then
511 err = abs(ya-f(xa))
512 err = abs(ya-f(xa))
513 end
514 end
515 if (err <= maxerror)
516 and qx > -math.huge and qx < math.huge
517 and qy > -math.huge and qy < math.huge
518 and rx > -math.huge and ry < math.huge
519 and sx > -math.huge and sy < math.huge
520 then
521 return {qx,qy,rx,ry,sx,sy}
522 else
523 -- search for an intermediate point where the graph has the same
524 -- slope as the line from the start point to the end point:
525 local interindex = math.floor(.5*starti+.5*endi) -- will change
526 for i = starti + 1, endi - 1 do
527 if abs(g[i][3]-(g[endi][2]-g[starti][2])
528 /(g[endi][1]-g[starti][1]))
529 < abs(g[interindex][3]-(g[endi][2]-g[starti][2])
530 /(g[endi][1]-g[starti][1])) then
531 interindex = i
532 end
533 end
534 local left = graphtobezierapprox(f,g,starti,interindex,maxerror,recursiondepth-1)
535 local right = graphtobezierapprox(f,g,interindex,endi,maxerror,recursiondepth-1)
536 for i=1, #right do --now append the right to the left:
537 left[#left+1] = right[i]
538 end
539 return left
540 end
541 elseif qx > -math.huge and qx < math.huge
542 and qy > -math.huge and qy < math.huge
543 and rx > -math.huge and ry < math.huge
544 and sx > -math.huge and sy < math.huge
545 then
546 return {qx,qy,rx,ry,sx,sy}
547 end
548 end
549
550 -- like above but exact for quadratic and cubic (if not inverse)
551 -- resp. exact for squareroot and cuberoot (if inverse)
552 local function graphtobezier(g,starti,endi,isinverse)
553 local px = g[starti][1]
554 local py = g[starti][2]
555 local dp = g[starti][3]
556 local sx = g[endi][1]
557 local sy = g[endi][2]
558 local ds = g[endi][3]
559 local qx = px+(sx-px)/3
560 local rx = px+2*(sx-px)/3
561 local qy = py+(qx-px)*dp
562 local ry = sy+(rx-sx)*ds
563 if isinverse then
564 return {qy,qx,ry,rx,sy,sx}
565 else
566 return {qx,qy,rx,ry,sx,sy}
567 end
568 end
569
570 -- main function
571 function bezierplot(functionstring,xminstring,xmaxstring,yminstring,ymaxstring,samplesstring,notation)
572 local fstringreplaced = string.gsub(functionstring, "%*%*", "^")
573 local f = assert(load("local x = ...; return " .. fstringreplaced))
574 local xmin = evaluate(xminstring)
575 local xmax = evaluate(xmaxstring)
576 local ymin = evaluate(yminstring)
577 local ymax = evaluate(ymaxstring)
578 local samples = evaluate(samplesstring)
579 local isreverse = false
580 if xmin > xmax then
581 isreverse = true
582 elseif xmin == xmax then
583 xmax = xmin + 10
584 end
585 xmin, xmax = math.min(xmin,xmax), math.max(xmin,xmax)
586 if ymin == ymax then
587 ymax = ymin + 10
588 end
589 ymin, ymax = math.min(ymin,ymax), math.max(ymin,ymax)
590 local xsteps = 50000
591 -- if samples < 2 the samples will be chosen as wisely as possible
592 local arbitrary_samples = true
593 if samples >= 2 then
594 arbitrary_samples = false
595 xsteps = (samples-1)*math.max(2,math.floor(xsteps/(samples-1)))
596 end
597 local xstep = (xmax-xmin)/xsteps
598 -- the output of the x coordinates will be rounded to rndx digits
599 local rndx = math.max(0,math.floor(5.5-log(xmax-xmin)/log(10)))
600 local xerror = abs(xmax-xmin)/(10^rndx)
601 -- the output of the y coordinates will be rounded to rndy digits
602 local rndy = math.max(0,math.floor(5.5-log(ymax-ymin)/log(10)))
603 local yerror = (ymax-ymin)/(10^rndy)
604 -- determine parts of the graph that are inside window
605 local graphs = {} -- graph split to the connected parts
606 local graph = {} -- graphs concatenated (needed for function type)
607 local outside = true -- value is outside window
608 local i = 0
609 local j = 0
610 local yminreal -- determine the real minimimum of the y coord.
611 local ymaxreal -- just decring
612 local yminrealfound = false
613 local ymaxrealfound = false
614 for n = 0, xsteps do
615 local x = xmin + n/xsteps*(xmax-xmin)
616 if n == xsteps then
617 x = xmax
618 end
619 local y = f(x)
620 if (y >= ymin-.1*yerror and ymin ~= -huge or y > ymin and ymin == -huge)
621 and (y <= ymax+.1*yerror and ymax ~= huge or y < ymax and ymax == huge)
622 then -- inside
623 if outside then -- if it was outside before
624 outside = false
625 j = 0
626 i = i + 1
627 graphs[i] = {}
628 end
629 j = j + 1
630 graphs[i][j] = {x,y}
631 graph[#graph+1] = {x,y}
632 if not yminrealfound or yminrealfound and y < yminreal then
633 yminreal = y
634 yminrealfound = true
635 end
636 if not ymaxrealfound or ymaxrealfound and y > ymaxreal then
637 ymaxreal = y
638 ymaxrealfound = true
639 end
640 else
641 outside = true
642 end
643 end
644
645 -- some redefinitions
646 if #graph ~= 0 and yminreal ~= ymaxreal then
647 ymin = yminreal
648 ymax = ymaxreal
649 rndy = math.max(0,math.floor(5.5-log(ymax-ymin)/log(10)))
650 yerror = (ymax-ymin)/(10^rndy)
651 end
652
653 -- check for the function type (for this, we need the concatenated
654 -- parts of the graph)
655 -- go through the connected parts
656 local functiontype = "unknown"
657 local a, b, c, d -- possible function parameter
658 -- check for affine functions:
659 local l = #graph
660 a, b = parameters_affine(graph[1][1],graph[1][2],
661 graph[l][1],graph[l][2])
662 if do_parameters_fit(a,b,0,0,"a*x+b",graph,yerror,false) then
663 functiontype = "affine"
664 else -- check for cubic functions (includes quadratic functions)
665 a, b, c, d = parameters_cubic(graph[1][1],graph[1][2],
666 graph[math.floor(l/3)][1],graph[math.floor(l/3)][2],
667 graph[math.floor(2*l/3)][1],graph[math.floor(2*l/3)][2],
668 graph[l][1],graph[l][2])
669 if do_parameters_fit(a,b,c,d,"a*x^3+b*x^2+c*x+d",graph,
670 yerror,false) then
671 functiontype = "cubic"
672 else -- check for cuberoot functions (includes squareroots)
673 a, b, c, d = parameters_cubic(graph[1][2],graph[1][1],
674 graph[math.floor(l/3)][2],graph[math.floor(l/3)][1],
675 graph[math.floor(2*l/3)][2],graph[math.floor(2*l/3)][1],
676 graph[l][2],graph[l][1])
677 if do_parameters_fit(a,b,c,d,"a*x^3+b*x^2+c*x+d",graph,
678 xerror,true) then
679 functiontype = "cuberoot"
680 end
681 end
682 end
683
684 local bezierpoints = {}
685 -- the bezier path (0,1) .. controls
686 -- (2,3) and (4,5) .. (6,7) .. controls
687 -- (8,9) and (10,11) .. (12,13)
688 -- will be stored as
689 -- bezierpoints={{0,1},{2,3,4,5,6,7},{8,9,10,11,12,13}}
690
691 if functiontype == "affine" then
692 if arbitrary_samples then
693 bezierpoints = {{graph[1][1],graph[1][2]},{graph[#graph][1],
694 graph[#graph][2]}}
695 else -- we can here savely assume that graphs has only one part,
696 -- therefore graphs[1]=graph
697 for i = 1, #graph, math.floor(xsteps/(samples-1)) do
698 bezierpoints[#bezierpoints+1] = {graph[i][1],graph[i][2]}
699 end
700 end
701 elseif functiontype == "cubic" then
702 local extrema_inflections = {} -- store the extrema and
703 -- inflection points for arbitrary samples
704 if arbitrary_samples then
705 if math.abs(a) < yerror*1e-10 then -- quadratic case (one extremum)
706 if is_in_window(-c/(2*b),(-c^2+4*b*d)/(4*b),xmin,xmax,
707 ymin,ymax) then
708 extrema_inflections = {{-c/(2*b),(-c^2+4*b*d)/(4*b)}}
709 end
710 else -- cubic case (two extrema and one inflection point)
711 -- we order the points with the help of sgn
712 -- check for first extrema
713 if is_in_window((-sgn(a)*sqrt(-3*a*c+b^2)-b)/(3*a),
714 (2*b^3+27*a^2*d-9*a*b*c+sqrt(b^2-3*a*c)*sgn(a)*
715 (2*b^2-6*a*c))/(27*a^2),xmin,xmax,ymin,ymax) then
716 extrema_inflections[#extrema_inflections+1] =
717 {(-sgn(a)*sqrt(-3*a*c+b^2)-b)/(3*a),(2*b^3+27*a^2*d-
718 9*a*b*c+sqrt(b^2-3*a*c)*sgn(a)*(2*b^2-6*a*c))/(27*a^2)}
719 end
720 -- check for inflection point (has to be inbetween)
721 if is_in_window(-b/(3*a),(2*b^3+27*a^2*d-9*a*b*c)
722 /(27*a^2),xmin,xmax,ymin,ymax) then
723 extrema_inflections[#extrema_inflections+1]={-b/(3*a),
724 (2*b^3+27*a^2*d-9*a*b*c)/(27*a^2)}
725 end
726 -- check for second extrema
727 if is_in_window((sgn(a)*sqrt(-3*a*c+b^2)-b)/(3*a),
728 (2*b^3+27*a^2*d-9*a*b*c+sqrt(b^2-3*a*c)*sgn(a)*
729 (-2*b^2+6*a*c))/(27*a^2),xmin,xmax,ymin,ymax) then
730 extrema_inflections[#extrema_inflections+1] =
731 {(sgn(a)*sqrt(-3*a*c+b^2)-b)/(3*a),(2*b^3+27*a^2*d-
732 9*a*b*c+sqrt(b^2-3*a*c)*sgn(a)*(-2*b^2+6*a*c))/(27*a^2)}
733 end
734 end
735 end
736 for part = 1, #graphs do
737 bezierpoints[#bezierpoints+1] = {graphs[part][1][1],
738 graphs[part][1][2]} -- initial points
739 local graphsamples = {}-- will be the graph reduced to the
740 -- samples (or the most important points)
741 local dg -- will be the differentiated graph
742 if arbitrary_samples then -- add extrema and inflection
743 -- points to the border points
744 graphsamples = {{graphs[part][1][1],
745 graphs[part][1][2]}}
746 for j = 1, #extrema_inflections do
747 if extrema_inflections[j][1] > math.min(
748 graphs[part][1][1] ,graphs[part][#graphs[part]][1])
749 and extrema_inflections[j][1] < math.max(
750 graphs[part][1][1] ,graphs[part][#graphs[part]][1])
751 then
752 graphsamples[#graphsamples+1] =
753 {extrema_inflections[j][1],
754 extrema_inflections[j][2]}
755 end
756 end
757 graphsamples[#graphsamples+1] =
758 {graphs[part][#graphs[part]][1],
759 graphs[part][#graphs[part]][2]}
760 else
761 for i = 1, #graphs[part], xsteps/(samples-1) do
762 graphsamples[#graphsamples+1] =
763 {graphs[part][i][1],graphs[part][i][2]}
764 end
765 end
766 dg = diffgraphcubic(graphsamples,a,b,c,d,false)
767 for i = 2, #dg do
768 bezierpoints[#bezierpoints+1] = graphtobezier(dg,i-1,i,false)
769 end
770 end
771 elseif functiontype == "cuberoot" then
772 local inflection = {} -- store the inflection point
773 if arbitrary_samples and math.abs(a) ~= 0
774 and is_in_window((2*b^3+27*a^2*d-9*a*b*c)/(27*a^2),-b/(3*a),
775 xmin,xmax,ymin,ymax) then
776 inflection = {(2*b^3+27*a^2*d-9*a*b*c)/(27*a^2),-b/(3*a)}
777 end
778 -- (there cannot be more than one part)
779 bezierpoints[#bezierpoints+1] = {graphs[1][1][1],
780 graphs[1][1][2]} -- initial points
781 local graphsamples = {}-- will be the graph reduced to the
782 -- samples (or the most important points)
783 local dg -- will be the differentiated graph
784 if arbitrary_samples then -- add inflection point (if exis.)
785 graphsamples = {{graphs[1][1][1],
786 graphs[1][1][2]}}
787 if #inflection > 0 and inflection[1] > math.min(
788 graphs[1][1][1],graphs[1][#graphs[1]][1])
789 and inflection[1] < math.max(
790 graphs[1][1][1],graphs[1][#graphs[1]][1])
791 then
792 graphsamples[#graphsamples+1] =
793 {inflection[1],inflection[2]}
794 end
795 graphsamples[#graphsamples+1] =
796 {graphs[1][#graphs[1]][1],
797 graphs[1][#graphs[1]][2]}
798 else
799 for i = 1, #graphs[1], xsteps/(samples-1) do
800 graphsamples[#graphsamples+1] =
801 {graphs[1][i][1],graphs[1][i][2]}
802 end
803 end
804 dg = diffgraphcubic(graphsamples,a,b,c,d,true)
805 for i = 2, #dg do
806 bezierpoints[#bezierpoints+1] = graphtobezier(dg,i-1,i,true)
807 end
808 else
809 ---------- generic case (no special function) ----------------
810 if arbitrary_samples then
811 -- go through the connected parts...
812 -- due to numerical errors we have to use a maximal
813 -- recursion depth, which is hard wired here
814 -- (a small number should suffice since there are
815 -- no extrema nor inflection points inbetween)
816 local maxrecursiondepth = 2
817 for part = 1, #graphs do
818 local dg = diffgraph(f,graphs[part],xstep)
819 --printdifftable(dg) -- for debugging
820 bezierpoints[#bezierpoints+1] = {dg[1][1],dg[1][2]}
821 local startindex = 1
822 for k = 2, #dg do
823 if dg[k][5] or dg[k][6] then -- extrema and inflection points
824 local tobeadded = graphtobezierapprox(
825 f,dg,startindex,k,10*yerror,maxrecursiondepth)
826 -- tobeadded may contain a multiple of 6 entries
827 -- e.g. {1,2,3,4,5,6,7,8,9,10,11,12}
828 for i = 1, math.floor(#tobeadded/6) do
829 bezierpoints[#bezierpoints+1] = {}
830 for j = 1, 6 do
831 bezierpoints[#bezierpoints][j] = tobeadded[(i-1)*6+j]
832 end
833 end
834 startindex = k
835 end
836 end
837 if startindex ~= #dg then -- if no special points inbetween
838 local tobeadded = graphtobezierapprox(f,dg,
839 startindex,#dg,10*yerror,maxrecursiondepth)
840 -- tobeadded may contain a multiple of 6 entries
841 -- e.g. {1,2,3,4,5,6,7,8,9,10,11,12}
842 for i = 1, math.floor(#tobeadded/6) do
843 bezierpoints[#bezierpoints+1] = {}
844 for j = 1, 6 do
845 bezierpoints[#bezierpoints][j] = tobeadded[(i-1)*6+j]
846 end
847 end
848 end
849 end
850 else -- fixed samples in the generic case
851 -- go through the connected parts
852 for part = 1, #graphs do
853 local dg = diffgraphsimple(f,graphs[part],xstep,
854 math.floor(0.5+xsteps/(samples-1)))
855 bezierpoints[#bezierpoints+1] = {dg[1][1],dg[1][2]} -- initial points
856 for i = 2, #dg do
857 bezierpoints[#bezierpoints+1] = graphtobezier(dg,i-1,i,false)
858 end
859 end
860 end
861 end
862 return beziertabletostring(bezierpoints,rndx,rndy,isreverse,notation)
863 end
864
865 -- This Lua script has to work as a "main" with an external
866 -- call from pdfLaTeX as well as a "library" with a direct lua use
867 -- of the function bezierplot() when used with LuaLaTeX
868 -- However, Lua does not seem to support a natural distinction
869 -- of the main and the library:
870 -- https://stackoverflow.com/questions/4521085/main-function-in-lua
871 -- As https://www.tug.org/pipermail/luatex/2024-February/007935.html
872 -- states, LuaTeX 1.18 has disabled the use of the debug library.
873 -- Hence, using "pcall(debug.getlocal, 4, 1)" is no longer possible
874 -- without restriction. The problem with the now chosen method is
875 -- that arg could be defined as a global variable in the calling code.
876
877 -- main program --
878 if (arg ~= nil and arg[-1] ~= nil) then
879 if #arg >= 1 then
880 local xmin = -5
881 local xmax = 5
882 if #arg >= 2 then
883 xmin = arg[2]
884 end
885 if #arg >= 3 then
886 xmax = arg[3]
887 end
888 local ymin = -5
889 local ymax = 5
890 if #arg >= 4 then
891 ymin = arg[4]
892 end
893 if #arg >= 5 then
894 ymax = arg[5]
895 end
896 local samples = 0
897 if #arg >= 6 then
898 samples = arg[6]
899 end
900 local notation = "tikz"
901 if #arg >= 7 then
902 notation = arg[7]
903 end
904 print(bezierplot(arg[1],xmin,xmax,ymin,ymax,samples,notation))
905 end
906 end