Debian Codegraph @

texmf-dist/tex/latex/tkz-elements/tkz_elements_utils.lua

raw
1 -- File: tkz_elements_utils.lua
2 -- Copyright (c) 2026 Alain Matthes
3 -- SPDX-License-Identifier: LPPL-1.3c
4 -- Maintainer: Alain Matthes
5
6 utils = {}
7
8 -- ----------------------------
9 -- Parsing / formatting helpers
10 -- ----------------------------
11
12 -- Parse a string of the form "(x,y)" into two numbers.
13 function utils.parse_point(str)
14 local x, y = tostring(str):match("^%s*%(?%s*([%+%-%.%deE]+)%s*,%s*([%+%-%.%deE]+)%s*%)%s*$")
15 if not x or not y then
16 tex.error("Invalid point string: " .. tostring(str))
17 end
18 return tonumber(x), tonumber(y)
19 end
20
21 -- Internal: format a number to fixed decimals (with checks)
22 local function _fmt_number(x, decimals, ctx)
23 decimals = decimals or 5
24 local n = tonumber(x)
25 if not n then
26 tex.error((ctx or "Invalid number") .. ": " .. tostring(x))
27 end
28 return string.format("%." .. decimals .. "f", n)
29 end
30
31 -- Public: format a number with a specified number of decimal places.
32 function utils.format_number(x, decimals)
33 return _fmt_number(x, decimals, "Invalid input to format_number")
34 end
35
36 -- Public: alias (kept for backward compatibility)
37 utils.checknumber = utils.format_number
38
39
40 -- Coordinates formatting (single component)
41 function utils.format_coord(x, decimals)
42 return _fmt_number(x, decimals, "Invalid coordinate")
43 end
44
45 -- Format a complex number (table with .re and .im) as a coordinate string.
46 function utils.format_point(z, decimals)
47 if type(z) ~= "table" or type(z.re) ~= "number" or type(z.im) ~= "number" then
48 tex.error("format_point expects a table with fields 're' and 'im'")
49 end
50 decimals = decimals or 5
51 local x = _fmt_number(z.re, decimals, "Invalid x in format_point")
52 local y = _fmt_number(z.im, decimals, "Invalid y in format_point")
53 return "(" .. x .. "," .. y .. ")"
54 end
55
56 -- ----------------------------
57 -- Numeric helpers
58 -- ----------------------------
59
60 -- Compare two numbers with tolerance (robust default).
61 function utils.almost_equal(a, b, EPS)
62 EPS = EPS or (tkz and tkz.epsilon) or 1e-9
63 local na, nb = tonumber(a), tonumber(b)
64 if not na or not nb then
65 tex.error("almost_equal expects numbers: " .. tostring(a) .. ", " .. tostring(b))
66 end
67 return math.abs(na - nb) <= EPS
68 end
69
70 -- Optional: Clamp a number between min and max.
71 function utils.clamp(x, min_val, max_val)
72 return math.max(min_val, math.min(max_val, x))
73 end
74
75 -- Optional: Return the sign of a number.
76 function utils.sign(x)
77 return (x > 0 and 1) or (x < 0 and -1) or 0
78 end
79
80 -- ----------------------------
81 -- Logging helpers
82 -- ----------------------------
83
84 -- Print formatted message to terminal and log.
85 function utils.w(...)
86 texio.write_nl("term and log", "[tkz-elements] " .. string.format(...))
87 end
88
89 -- Print formatted message to log only.
90 function utils.wlog(...)
91 texio.write_nl("log", "[tkz-elements] " .. string.format(...))
92 end
93
94 -- ----------------------------
95 -- Table helpers
96 -- ----------------------------
97
98 -- Length of contiguous array part 1..n (stops at first nil).
99 -- (Name explicit to avoid confusion with #t on sparse tables.)
100 function utils.table_len_contiguous(t)
101 if type(t) ~= "table" then
102 tex.error("bad argument #1 (table expected)", 2)
103 end
104 local i = 0
105 while t[i + 1] ~= nil do
106 i = i + 1
107 end
108 return i
109 end
110
111 -- Backward compatibility
112 utils.table_getn = utils.table_len_contiguous
113
114
115 -- --- internal helper: compile a chunk returning a function -------------------
116 local function compile_func_(chunk, where, payload, fallback)
117 fallback = fallback or function(_) return 0 end
118
119 local loader, err = load(chunk, where, "t", math)
120 if not loader then
121 tex.error("Invalid function expression", {
122 payload or chunk,
123 err
124 })
125 return fallback
126 end
127
128 local ok, fn = pcall(loader)
129 if not ok or type(fn) ~= "function" then
130 tex.error("Invalid function expression", {
131 payload or chunk,
132 tostring(fn)
133 })
134 return fallback
135 end
136
137 return fn
138 end
139
140 -- Compile a TeX-provided expression into a Lua function y = f(x)
141 function utils.compile_fx_(expr)
142 local chunk = "return function(x) return (" .. expr .. ") end"
143 return compile_func_(
144 chunk,
145 "tkz.compile_fx",
146 expr,
147 function(_) return 0 end
148 )
149 end
150
151 -- Compile a parametric TeX-provided expression into a Lua function (x,y) = f(t)
152 function utils.compile_ft_(exprx, expry)
153 local chunk = ("return function(t) return (%s), (%s) end"):format(exprx, expry)
154 -- fallback paramétrique : renvoie (0,0) pour rester compatible avec build_path
155 return compile_func_(
156 chunk,
157 "tkz.compile_ft",
158 ("x(t)=%s ; y(t)=%s"):format(exprx, expry),
159 function(_) return 0, 0 end
160 )
161 end
162
163
164 -- Build a path from a function f(x)
165 function utils.build_path_(f, xmin, xmax, n)
166 xmin = tonumber(xmin)
167 xmax = tonumber(xmax)
168 n = tonumber(n) or 100
169
170 local p = path()
171 local step = (xmax - xmin) / n
172 for i = 0, n do
173 local x = xmin + i * step
174 local y = f(x)
175 if y == y and y ~= math.huge and y ~= -math.huge then
176 p:add_point(point(x, y))
177 end
178 end
179 return p
180 end
181
182 -- Build a path from a parametric function g(t) -> x, y
183 function utils.build_param_path_(g, tmin, tmax, n)
184 tmin = tonumber(tmin)
185 tmax = tonumber(tmax)
186 n = tonumber(n) or 200
187
188 local p = path()
189 local step = (tmax - tmin) / n
190
191 for i = 0, n do
192 local t = tmin + i * step
193 local x, y = g(t)
194
195 if x == x and y == y
196 and x ~= math.huge and x ~= -math.huge
197 and y ~= math.huge and y ~= -math.huge then
198 p:add_point(point(x, y))
199 end
200 end
201 return p
202 end
203
204 return utils