Debian Codegraph @

texmf-dist/source/lualatex/numodel-bundle/numodel.dtx

raw
1 % numodel.dtx
2 %
3 % Docstrip source for numodel.sty, numodel-EN.def and numodel-NL.def.
4 % Run
5 % tex numodel.ins
6 % to extract the derived files. User-facing documentation lives
7 % in numodel-manual.tex (a stand-alone LaTeX file).
8 %
9 % Copyright (C) 2026 Paul Zuurbier <[email protected]>
10 %
11 % This work may be distributed and/or modified under the conditions
12 % of the LaTeX Project Public License, either version 1.3c of this
13 % license or (at your option) any later version. The latest version
14 % of this license is in https://www.latex-project.org/lppl.txt
15 %
16 % This work has the LPPL maintenance status 'maintained'.
17 % The Current Maintainer of this work is Paul Zuurbier.
18 %
19 % This work consists of the files numodel.dtx and numodel.ins, the
20 % derived files numodel.sty, numodel-EN.def and numodel-NL.def, and the
21 % companion Lua module numodel.lua.
22 % \section{Implementation}
23 %
24 % \begin{macrocode}
25 %<*package>
26 \NeedsTeXFormat{LaTeX2e}
27 \ProvidesPackage{numodel}[2026/05/26 v0.6.0
28 Numerical physics models with Euler integration and Forrester diagrams]
29
30 \RequirePackage{expl3}
31 \RequirePackage{xparse}
32 \RequirePackage{l3keys2e}
33 \RequirePackage{amsmath}
34 \RequirePackage{amssymb} % \leqslant / \geqslant in rendered <= / >=
35 \RequirePackage{tikz}
36 \usetikzlibrary{shapes.symbols}
37 \usetikzlibrary{arrows.meta}
38 % Custom Cloud arrow tip used as the open end of inflow / outflow
39 % pipes. The silhouette consists of nine concatenated elliptical
40 % arcs (\pgfpatharc): each arc starts at the current path point,
41 % which pgf treats as lying on an ellipse at angle <start>, and
42 % sweeps through to angle <end>. Varying the start and end angles
43 % per arc produces zigzagging half-circle puffs -- the
44 % characteristic cloud outline. A single factor \puffscale sets the
45 % rx and ry of every ellipse and thus the size of all puffs at once.
46 % The chain has a horizontal span of (4+2*sqrt(2))*rx ~ 6.83*rx;
47 % with puffscale=0.22 that is ~ 1.5*\pgfarrowlength. The path
48 % therefore starts at -0.5*\pgfarrowlength so the silhouette covers
49 % [-0.5L, L] in local arrow coordinates and the apex lands exactly
50 % at \pgfarrowlength -- where the built-in tips (Latex, Stealth,
51 % ...) also place their tip. The line width is set explicitly to
52 % 0.3pt, independent of the arrow's line width, so a thick arrow
53 % does not also get a thick cloud outline.
54 \pgfdeclarearrow{
55 name = Cloud,
56 parameters = { \the\pgfarrowlength \the\pgfarrowwidth },
57 setup code = {
58 \pgfarrowssettipend{\pgfarrowlength}
59 \pgfarrowssetbackend{-0.5\pgfarrowlength}
60 \pgfarrowssetlineend{-0.5\pgfarrowlength}
61 \pgfarrowssetvisualbackend{-0.5\pgfarrowlength}
62 \pgfarrowssetvisualtipend{\pgfarrowlength}
63 },
64 defaults = { length = 1em, width = 1em },
65 drawing code = {
66 \def\puffscale{0.22}
67 \edef\puffrx{\puffscale\pgfarrowlength}
68 \edef\puffry{\puffscale\pgfarrowwidth}
69 \pgfsetlinewidth{0.3pt}
70 \pgfpathmoveto{\pgfqpoint{-0.5\pgfarrowlength}{0pt}}
71 \pgfpatharc{180}{ 90}{\puffrx\space and \puffry}
72 \pgfpatharc{225}{ 45}{\puffrx\space and \puffry}
73 \pgfpatharc{180}{ 0}{\puffrx\space and \puffry}
74 \pgfpatharc{135}{-45}{\puffrx\space and \puffry}
75 \pgfpatharc{ 90}{-90}{\puffrx\space and \puffry}
76 \pgfpatharc{ 45}{-135}{\puffrx\space and \puffry}
77 \pgfpatharc{ 0}{-180}{\puffrx\space and \puffry}
78 \pgfpatharc{-45}{-225}{\puffrx\space and \puffry}
79 \pgfpatharc{-90}{-180}{\puffrx\space and \puffry}
80 \pgfpathclose
81 \pgfusepathqfillstroke
82 },
83 }
84 \RequirePackage{luacode}
85 \RequirePackage{siunitx}
86 \RequirePackage{float} % \diagrammodel uses [H] placement
87 \RequirePackage{tabularray} % \textmodel uses longtblr (page-breakable,
88 % works inside floats/subfigure)
89 % Define a numodel theme for longtblr in \textmodel. The default
90 % `normal' middlehead/lasthead prefixes the continuation marker with
91 % `Table N:' from \tablename/\thetable; we don't issue \caption, so we
92 % want only the conthead text (which is itself localised via
93 % \tblrcontheadname, updated by \__numodel_refresh_kw:). Likewise for
94 % the foot. Activated via `theme = {numodel}' in the longtblr options.
95 \DefTblrTemplate {firsthead} {numodel} {}
96 \DefTblrTemplate {middlehead, lasthead} {numodel} { \UseTblrTemplate {conthead} {default} }
97 \DefTblrTemplate {firstfoot, middlefoot}{numodel} { \UseTblrTemplate {contfoot} {default} }
98 \DefTblrTemplate {lastfoot} {numodel} {}
99 \NewTblrTheme {numodel}
100 {
101 \SetTblrTemplate {firsthead} {numodel}
102 \SetTblrTemplate {middlehead, lasthead} {numodel}
103 \SetTblrTemplate {firstfoot, middlefoot}{numodel}
104 \SetTblrTemplate {lastfoot} {numodel}
105 }
106 % Tighten the default row separation of all tabularray tables: the
107 % \textmodel rule listing is denser and more compact than the
108 % tabularray default. Users who want the default spacing back in
109 % their own tables can simply issue \SetTblrInner{rowsep=<value>} in
110 % their document.
111 \SetTblrInner{rowsep=0pt}
112 \RequirePackage{numodel-plot}
113
114 % ====================================================================
115 % Non-expl3 helpers: `\nm@def@num@cs` / `\nm@def@qty@cs` / `\nm@def@pre@cs`
116 % define `\<fullname><suffix>` macros whose body contains literal
117 % siunitx options. Defined OUTSIDE \ExplSyntaxOn so the option-string
118 % colons (`-3:n`, `-0:0`) and other punctuation keep normal catcodes.
119 % Storing those bodies inside an expl3-context would tokenise `:` as
120 % letter, which then breaks siunitx's option parser at expansion time.
121 % ====================================================================
122 \newcommand{\NumodelDefNumCs}[3]{% #1 = fullname, #2 = start expr, #3 = sigfigs
123 \expandafter\gdef\csname #1num\endcsname{%
124 \num[evaluate-expression=true,
125 round-mode=figures, round-precision=#3,
126 exponent-mode=threshold, exponent-thresholds=-3:#3]
127 {#2}\relax
128 }%
129 }
130 \newcommand{\NumodelDefQtyCs}[4]{% #1 = fullname, #2 = expr, #3 = sigfigs, #4 = unit
131 \expandafter\gdef\csname #1qty\endcsname{%
132 \qty[evaluate-expression=true,
133 round-mode=figures, round-precision=#3,
134 exponent-mode=threshold, exponent-thresholds=-3:#3]
135 {#2}{#4}\relax
136 }%
137 }
138 \newcommand{\NumodelDefPreCs}[4]{% same parameters as above
139 \expandafter\gdef\csname #1pre\endcsname{%
140 \qty[evaluate-expression=true,
141 round-mode=figures, round-precision=#3,
142 prefix-mode=combine-exponent,
143 exponent-mode=engineering,
144 exponent-thresholds=-0:0]
145 {#2}{#4}\relax
146 }%
147 }
148
149 \ExplSyntaxOn
150
151 % ====================================================================
152 % Lua module for data storage (O(1) append, O(N) total)
153 % ====================================================================
154 % All variable values are stored per step in Lua tables. This
155 % replaces the O(N^2) \xdef accumulation for coordinates and makes
156 % min/max tracking efficient. After \computemodel the results are
157 % pushed back to TeX macros.
158
159 \begin{luacode*}
160 local f = kpse.find_file("numodel.lua", "tex")
161 if f and f ~= "" then
162 dofile(f)
163 else
164 tex.error("numodel: cannot find companion Lua module numodel.lua."
165 .. " Install it in a directory searched by kpse"
166 .. " (e.g. TEXMFHOME/tex/lualatex/numodel/).")
167 end
168 \end{luacode*}
169
170 % ====================================================================
171 % Internal data structures
172 % ====================================================================
173
174 \seq_new:N \g_mvar_names_seq % all model variable names
175 \seq_new:N \g_mvar_start_seq % names with an initial value (for the table)
176 \seq_new:N \g_mrule_seq % model rules (display strings)
177 \seq_new:N \g_mrule_type_seq % type per display row: rule | cont
178 \seq_new:N \g_mrule_calc_seq % model rules for execution: {name}{expr}
179 \int_new:N \g_mrule_counter_int % rule counter (display numbering)
180 \tl_new:N \g_numodel_stop_expr_tl % stop-condition expression for execution
181 \int_new:N \g_numodel_steps_int % number of executed steps
182 \int_new:N \g_numodel_maxiter_int % safety limit (init via \numodelsetup)
183 \int_new:N \g_numodel_gridmaxx_int % \graphicmodel wrap threshold (0 = off)
184
185 % --- Graphic-model infrastructure (Phase 1) ---
186 \tl_new:N \l__numodel_tmp_tl % temporary helper
187 \tl_new:N \l__numodel_scratch_tl % scratch for type/text checks
188 \tl_new:N \l__numodel_scratch_y_tl % scratch y-coord (svgy lookup)
189
190 % Diagram style for \graphicmodel (see \numodelsetup):
191 % tight -- valve takes the label of the direct inflow variable;
192 % the aux/const is moved to the valve position and not
193 % drawn as a separate node (compact, default).
194 % forrester -- valve has no label; the aux/const stays at its own
195 % gridy position; causal arrow from aux/const to the
196 % valve.
197 % edu -- combination: valve takes the label *and* a separate
198 % aux/const node remains with a causal arrow to it.
199 \tl_new:N \g__numodel_diagram_style_tl
200
201 % Sub-keys that fine-tune the appearance of the Forrester diagram
202 % (see \numodelsetup). Empty value = "follow diagram-style default".
203 % flowarrow-style : hollow | filled
204 % forrester -> hollow, tight|edu -> filled
205 % valve-style : valve | circle | edu
206 % forrester -> valve, tight|edu -> edu
207 % flowarrow-cloud-tip: true | false
208 % forrester -> true, tight|edu -> false
209 % Per-variable override for flowarrow-cloud-tip is stored in
210 % \<name>flowcloud (set via the [flowarrow-cloud-tip=...] key on
211 % \mvar; empty means "follow global key").
212 \tl_new:N \g__numodel_flowarrow_style_tl
213 \tl_new:N \g__numodel_valve_style_tl
214 \tl_new:N \g__numodel_flowcloud_tl
215
216 % Units in the \textmodel initial-values column (see \numodelsetup):
217 % true (default) -- initial value rendered via \<name>qty
218 % (number + unit)
219 % false -- initial value rendered via \<name>num
220 % (number only)
221 % Per-table override via \textmodel[units=true|false].
222 \bool_new:N \g__numodel_units_bool
223
224 % tabularray environment used by \textmodel (see \numodelsetup{tblrenv}):
225 % longtblr -- default; page-breakable; suitable for body text.
226 % tblr -- basic; no page breaks; choose this when \textmodel sits
227 % inside an outer environment that already suppresses page
228 % breaks (subfigure, minipage, ...).
229 % talltblr -- like tblr (no page breaks) but supports captions/notes.
230 % Per-table override via \textmodel[tblrenv=...].
231 \tl_new:N \g__numodel_tblrenv_tl
232
233 % Decimal separator for \textmodel initial values and \diagrammodel
234 % tick values (see \numodelsetup{decimal-separator}):
235 % point -- '.' (siunitx output-decimal-marker={.})
236 % comma -- ',' (siunitx output-decimal-marker={,})
237 % The default follows syntax: english -> point, coachtaal -> comma.
238 % An explicit decimal-separator key sets
239 % \g__numodel_dsep_explicit_bool so that a later syntax change no
240 % longer overrules the choice.
241 \tl_new:N \g__numodel_dsep_tl
242 \bool_new:N \g__numodel_dsep_explicit_bool
243
244 % ====================================================================
245 % Syntax lookup
246 % ====================================================================
247 % Determines the language of the text-rendered model. Affects display
248 % only (\textmodel, \mruletext, \mstop); \computemodel always uses
249 % \fpeval internally and is language-agnostic. Each value of
250 % \g__numodel_syntax_tl is a tag that selects both the backing
251 % \__numodel_kw_<tag>_<key>: macros and the file numodel-<tag>.def
252 % that defines them; the package ships EN (English/XMILE) and NL
253 % (Dutch/CoachTaal).
254 %
255 % The CTAN default is EN. The initial value is set below via
256 % \numodelsetup.
257
258 \tl_new:N \g__numodel_syntax_tl
259
260 % Lookup (fully expandable): \__numodel_kw:n {<key>} returns the
261 % translation in the current syntax language. The key also controls
262 % the surrounding spaces (see keys 'then' vs 'then_nl' etc.). The
263 % backing macros \__numodel_kw_<LANG>_<key>: are provided by the
264 % language file numodel-<LANG>.def loaded by \__numodel_load_syntax_def:n
265 % (see below).
266 \cs_new:Npn \__numodel_kw:n #1
267 { \use:c { __numodel_kw_ \g__numodel_syntax_tl _ #1 : } }
268
269 % Pre-computed translations in tl variables so they are usable via
270 % \u{} in l3regex replacement text. (l3regex treats {...} in the
271 % replacement as brace groups, so a bare \__numodel_kw:n{key} call
272 % fails there.)
273 \tl_new:N \g__numodel_kw_if_tl
274 \tl_new:N \g__numodel_kw_then_tl
275 \tl_new:N \g__numodel_kw_then_nl_tl
276 \tl_new:N \g__numodel_kw_else_tl
277 \tl_new:N \g__numodel_kw_else_nl_tl
278 \tl_new:N \g__numodel_kw_endif_tl
279 \tl_new:N \g__numodel_kw_endif_nl_tl
280 \tl_new:N \g__numodel_kw_and_tl
281 \tl_new:N \g__numodel_kw_or_tl
282 \tl_new:N \g__numodel_kw_not_tl
283 \tl_new:N \g__numodel_kw_sign_tl
284 \tl_new:N \g__numodel_kw_abs_tl
285 \tl_new:N \g__numodel_kw_sqrt_tl
286 \tl_new:N \g__numodel_kw_exp_tl
287 \tl_new:N \g__numodel_kw_ln_tl
288 \tl_new:N \g__numodel_kw_sin_tl
289 \tl_new:N \g__numodel_kw_cos_tl
290 \tl_new:N \g__numodel_kw_tan_tl
291 \tl_new:N \g__numodel_kw_asin_tl
292 \tl_new:N \g__numodel_kw_acos_tl
293 \tl_new:N \g__numodel_kw_stop_tl
294
295 % Recomputes all tl caches from \g__numodel_syntax_tl. Must be
296 % called after any change to the syntax language.
297 \cs_new_protected:Npn \__numodel_refresh_kw:
298 {
299 \tl_gset:Ne \g__numodel_kw_if_tl { \__numodel_kw:n {if} }
300 \tl_gset:Ne \g__numodel_kw_then_tl { \__numodel_kw:n {then} }
301 \tl_gset:Ne \g__numodel_kw_then_nl_tl { \__numodel_kw:n {then_nl} }
302 \tl_gset:Ne \g__numodel_kw_else_tl { \__numodel_kw:n {else} }
303 \tl_gset:Ne \g__numodel_kw_else_nl_tl { \__numodel_kw:n {else_nl} }
304 \tl_gset:Ne \g__numodel_kw_endif_tl { \__numodel_kw:n {endif} }
305 \tl_gset:Ne \g__numodel_kw_endif_nl_tl { \__numodel_kw:n {endif_nl} }
306 \tl_gset:Ne \g__numodel_kw_and_tl { \__numodel_kw:n {and} }
307 \tl_gset:Ne \g__numodel_kw_or_tl { \__numodel_kw:n {or} }
308 \tl_gset:Ne \g__numodel_kw_not_tl { \__numodel_kw:n {not} }
309 \tl_gset:Ne \g__numodel_kw_sign_tl { \__numodel_kw:n {sign} }
310 \tl_gset:Ne \g__numodel_kw_abs_tl { \__numodel_kw:n {abs} }
311 \tl_gset:Ne \g__numodel_kw_sqrt_tl { \__numodel_kw:n {sqrt} }
312 \tl_gset:Ne \g__numodel_kw_exp_tl { \__numodel_kw:n {exp} }
313 \tl_gset:Ne \g__numodel_kw_ln_tl { \__numodel_kw:n {ln} }
314 \tl_gset:Ne \g__numodel_kw_sin_tl { \__numodel_kw:n {sin} }
315 \tl_gset:Ne \g__numodel_kw_cos_tl { \__numodel_kw:n {cos} }
316 \tl_gset:Ne \g__numodel_kw_tan_tl { \__numodel_kw:n {tan} }
317 \tl_gset:Ne \g__numodel_kw_asin_tl { \__numodel_kw:n {asin} }
318 \tl_gset:Ne \g__numodel_kw_acos_tl { \__numodel_kw:n {acos} }
319 \tl_gset:Ne \g__numodel_kw_stop_tl { \__numodel_kw:n {stop} }
320 % tabularray continuation markers (used by longtblr in \textmodel)
321 \tl_gset:Ne \tblrcontfootname { \__numodel_kw:n {contfoot} }
322 \tl_gset:Ne \tblrcontheadname { \__numodel_kw:n {conthead} }
323 }
324
325 % Helper: \__numodel_kwt:n {<key>} expands to \text{<kw-value>}.
326 % Meant for use inside \tl_set:Ne / \seq_gput_right:Ne -- the kw is
327 % inserted during e-expansion while \text remains protected.
328 \cs_new:Npn \__numodel_kwt:n #1 { \text { \__numodel_kw:n {#1} } }
329
330 % Language-file loader. Each tag <LANG> is backed by a file
331 % numodel-<LANG>.def installed in a kpse-searched directory; the
332 % package ships numodel-EN.def and numodel-NL.def, users can drop
333 % additional files in TEXMFHOME/tex/latex/numodel/ without rebuilding
334 % the package.
335 %
336 % A small alias property maps the historical long names to the
337 % canonical two-letter tag used in the file name and the internal
338 % macro names. Users who add their own file just pass the file's tag
339 % to syntax=<tag> directly; no alias is required.
340 \prop_new:N \g__numodel_syntax_aliases_prop
341 \prop_gput:Nnn \g__numodel_syntax_aliases_prop { english } { EN }
342 \prop_gput:Nnn \g__numodel_syntax_aliases_prop { coachtaal } { NL }
343 \prop_gput:Nnn \g__numodel_syntax_aliases_prop { dutch } { NL }
344
345 % Tags whose .def file has already been input during this run, so the
346 % lookup only triggers \InputIfFileExists the first time.
347 \seq_new:N \g__numodel_loaded_syntax_seq
348
349 \msg_new:nnn { numodel } { unknown-syntax }
350 {
351 Cannot~load~syntax~'#1':~file~'numodel-#1.def'~not~found~by~
352 kpse.~The~package~ships~with~EN~(English)~and~NL~(Dutch~
353 CoachTaal);~drop~your~own~numodel-<LANG>.def~in~
354 TEXMFHOME/tex/latex/numodel/~to~add~more~languages.
355 }
356
357 % \__numodel_load_syntax_def:n {<tag>}
358 % Inputs numodel-<tag>.def the first time it is requested. Raises a
359 % LaTeX error if the file is not found by kpse.
360 \cs_new_protected:Npn \__numodel_load_syntax_def:n #1
361 {
362 \seq_if_in:NnF \g__numodel_loaded_syntax_seq {#1}
363 {
364 \InputIfFileExists { numodel-#1.def }
365 { \seq_gput_right:Nn \g__numodel_loaded_syntax_seq {#1} }
366 { \msg_error:nnn { numodel } { unknown-syntax } {#1} }
367 }
368 }
369
370 \tl_new:N \l__numodel_syntax_tag_tl
371
372 % \__numodel_set_syntax:n {<value>}
373 % Public-facing setter behind the syntax key. Resolves aliases,
374 % loads the matching .def file (once), publishes the canonical tag
375 % in \g__numodel_syntax_tl, refreshes the keyword cache, and -- when
376 % the user has not pinned a decimal separator explicitly -- adopts the
377 % language's preferred decimal mark via the optional
378 % \__numodel_kw_<LANG>_dsep_default: hook.
379 \cs_new_protected:Npn \__numodel_set_syntax:n #1
380 {
381 \prop_get:NnNF \g__numodel_syntax_aliases_prop {#1}
382 \l__numodel_syntax_tag_tl
383 { \tl_set:Nn \l__numodel_syntax_tag_tl {#1} }
384 \exp_args:NV \__numodel_load_syntax_def:n \l__numodel_syntax_tag_tl
385 \tl_gset_eq:NN \g__numodel_syntax_tl \l__numodel_syntax_tag_tl
386 \__numodel_refresh_kw:
387 \bool_if:NF \g__numodel_dsep_explicit_bool
388 {
389 \cs_if_exist:cTF
390 { __numodel_kw_ \g__numodel_syntax_tl _dsep_default: }
391 { \tl_gset:Ne \g__numodel_dsep_tl { \__numodel_kw:n {dsep_default} } }
392 { \tl_gset:Nn \g__numodel_dsep_tl { point } }
393 }
394 }
395
396 % Applies the decimal separator (only for the duration of the
397 % surrounding TeX group, so a document-wide \sisetup is left
398 % untouched). Calls both siunitx (for \num/\qty in \textmodel
399 % initial values) and pgfplots' tick styles (for \diagrammodel tick
400 % labels) so the choice is consistent everywhere.
401 \cs_new_protected:Npn \__numodel_apply_dsep:
402 {
403 \str_if_eq:VnTF \g__numodel_dsep_tl { comma }
404 {
405 \sisetup{ output-decimal-marker = {,} }
406 % Append behind the existing numodel/axis style so our
407 % xticklabel-style replaces what numodel-plot hard-codes.
408 % The \pgfplotsset mutation is \def-based and hence
409 % group-local.
410 \pgfplotsset
411 {
412 numodel/axis/.append~style=
413 {
414 xticklabel~style=
415 { /pgf/number~format/.cd, use~comma, /tikz/.cd } ,
416 yticklabel~style=
417 { /pgf/number~format/.cd, use~comma, /tikz/.cd } ,
418 }
419 }
420 }
421 {
422 \sisetup{ output-decimal-marker = {.} }
423 \pgfplotsset
424 {
425 numodel/axis/.append~style=
426 {
427 xticklabel~style=
428 { /pgf/number~format/.cd, use~period, /tikz/.cd } ,
429 yticklabel~style=
430 { /pgf/number~format/.cd, use~period, /tikz/.cd } ,
431 }
432 }
433 }
434 }
435
436 % ====================================================================
437 % Configuration command \numodelsetup
438 % ====================================================================
439 % Runtime API for settings. Keys:
440 % syntax -- language tag (file numodel-<tag>.def must be on kpse
441 % path). Built-in: EN, NL. Legacy aliases: english,
442 % coachtaal, dutch.
443 % maxiter -- safety limit for \computemodel (default 20000)
444 % graphscalex -- horizontal grid spacing \dgridx for Forrester
445 % diagrams (default 2)
446 % graphscaley -- vertical grid spacing \dgridy for Forrester
447 % diagrams (default 2)
448
449 % Helper for choice-with-empty-reset: validates #4 against #3 (a
450 % comma-separated whitelist) and writes it into #1 (a tl). An empty
451 % value clears the tl (which means "follow the diagram-style
452 % default" for the flowarrow-style / valve-style /
453 % flowarrow-cloud-tip keys). Any other value triggers a warning.
454 \msg_new:nnn { numodel } { bad-choice }
455 { Key~'#1'~accepts~only~#2,~or~empty~to~reset.~Got:~'#3'. }
456
457 \cs_new_protected:Npn \__numodel_setup_choice:Nnnn #1 #2 #3 #4
458 {
459 \tl_if_blank:nTF {#4}
460 { \tl_gclear:N #1 }
461 {
462 \clist_if_in:nnTF {#3} {#4}
463 { \tl_gset:Nn #1 {#4} }
464 { \msg_warning:nnnnn { numodel } { bad-choice } {#2} {#3} {#4} }
465 }
466 }
467
468 % Local-tl variant: same validation, local set/clear. Used by the
469 % \graphicmodel one-render override and the per-\mvar override.
470 \cs_new_protected:Npn \__numodel_local_choice:Nnnn #1 #2 #3 #4
471 {
472 \tl_if_blank:nTF {#4}
473 { \tl_clear:N #1 }
474 {
475 \clist_if_in:nnTF {#3} {#4}
476 { \tl_set:Nn #1 {#4} }
477 { \msg_warning:nnnnn { numodel } { bad-choice } {#2} {#3} {#4} }
478 }
479 }
480
481 \keys_define:nn { numodel / setup }
482 {
483 syntax .code:n =
484 { \__numodel_set_syntax:n {#1} },
485 maxiter .int_gset:N = \g_numodel_maxiter_int,
486 graphscalex .code:n = { \tl_gset:Nn \dgridx {#1} },
487 graphscaley .code:n = { \tl_gset:Nn \dgridy {#1} },
488 gridmaxx .int_gset:N = \g_numodel_gridmaxx_int,
489 diagram-style .choice:,
490 diagram-style / tight .code:n =
491 { \tl_gset:Nn \g__numodel_diagram_style_tl { tight } },
492 diagram-style / forrester .code:n =
493 { \tl_gset:Nn \g__numodel_diagram_style_tl { forrester } },
494 diagram-style / edu .code:n =
495 { \tl_gset:Nn \g__numodel_diagram_style_tl { edu } },
496 flowarrow-style .code:n =
497 { \__numodel_setup_choice:Nnnn \g__numodel_flowarrow_style_tl
498 { flowarrow-style } { hollow , filled } {#1} },
499 valve-style .code:n =
500 { \__numodel_setup_choice:Nnnn \g__numodel_valve_style_tl
501 { valve-style } { valve , circle , edu } {#1} },
502 flowarrow-cloud-tip .code:n =
503 { \__numodel_setup_choice:Nnnn \g__numodel_flowcloud_tl
504 { flowarrow-cloud-tip } { true , false } {#1} },
505 units .choice:,
506 units / true .code:n =
507 { \bool_gset_true:N \g__numodel_units_bool },
508 units / false .code:n =
509 { \bool_gset_false:N \g__numodel_units_bool },
510 tblrenv .choice:,
511 tblrenv / tblr .code:n =
512 { \tl_gset:Nn \g__numodel_tblrenv_tl { tblr } },
513 tblrenv / longtblr .code:n =
514 { \tl_gset:Nn \g__numodel_tblrenv_tl { longtblr } },
515 tblrenv / talltblr .code:n =
516 { \tl_gset:Nn \g__numodel_tblrenv_tl { talltblr } },
517 decimal-separator .choice:,
518 decimal-separator / comma .code:n =
519 {
520 \tl_gset:Nn \g__numodel_dsep_tl { comma }
521 \bool_gset_true:N \g__numodel_dsep_explicit_bool
522 },
523 decimal-separator / point .code:n =
524 {
525 \tl_gset:Nn \g__numodel_dsep_tl { point }
526 \bool_gset_true:N \g__numodel_dsep_explicit_bool
527 },
528 }
529
530 \NewDocumentCommand{\numodelsetup}{ m }
531 { \keys_set:nn { numodel / setup } {#1} }
532
533 % Defaults (this call also initialises \g__numodel_syntax_tl,
534 % \g_numodel_maxiter_int, \dgridx, \dgridy and
535 % \g__numodel_diagram_style_tl).
536 \numodelsetup
537 {
538 syntax = EN,
539 maxiter = 20000,
540 graphscalex = 2,
541 graphscaley = 2,
542 diagram-style = tight,
543 units = true,
544 tblrenv = longtblr,
545 }
546
547 % Package-time options. \usepackage[syntax=NL]{numodel} delegates
548 % to the same key infrastructure as \numodelsetup.
549 \keys_define:nn { numodel / pkg }
550 {
551 syntax .meta:nn = { numodel / setup }{ syntax = #1 },
552 maxiter .meta:nn = { numodel / setup }{ maxiter = #1 },
553 graphscalex .meta:nn = { numodel / setup }{ graphscalex = #1 },
554 graphscaley .meta:nn = { numodel / setup }{ graphscaley = #1 },
555 gridmaxx .meta:nn = { numodel / setup }{ gridmaxx = #1 },
556 diagram-style .meta:nn = { numodel / setup }{ diagram-style = #1 },
557 flowarrow-style .meta:nn = { numodel / setup }{ flowarrow-style = #1 },
558 valve-style .meta:nn = { numodel / setup }{ valve-style = #1 },
559 flowarrow-cloud-tip .meta:nn = { numodel / setup }{ flowarrow-cloud-tip = #1 },
560 units .meta:nn = { numodel / setup }{ units = #1 },
561 tblrenv .meta:nn = { numodel / setup }{ tblrenv = #1 },
562 decimal-separator .meta:nn = { numodel / setup }{ decimal-separator = #1 },
563 }
564 \ProcessKeyOptions [ numodel / pkg ]
565
566 % ====================================================================
567 % Prefix system
568 % ====================================================================
569 % Each model lives under a prefix (a short string). The "live state"
570 % sits in the \g_mvar_*, \g_mrule_*, \g_numodel_* variables above;
571 % \newmodelprefix and \switchmodelprefix swap that state to/from
572 % per-prefix backup storage.
573 %
574 % - \g_numodel_current_prefix_tl: current prefix (empty at package load)
575 % - \g_numodel_prefixes_seq: list of all registered prefixes
576 % - \l__numodel_cmd_prefix_tl: prefix passed via [prefix=...] key
577 % - \l__numodel_eff_prefix_tl: effective prefix for the current command
578
579 \tl_new:N \g_numodel_current_prefix_tl
580 \seq_new:N \g_numodel_prefixes_seq
581 \tl_new:N \l__numodel_cmd_prefix_tl
582 \tl_new:N \l__numodel_eff_prefix_tl
583 \tl_new:N \l__numodel_fullname_tl
584
585 % Per-prefix storage: on swap the current state is copied to
586 % \g__numodel_<P>_<slot>_{seq,tl,int,prop}. Load goes the other way.
587 \cs_new_protected:Npn \__numodel_save_state:n #1
588 {
589 \seq_gset_eq:cN { g__numodel_ #1 _vars_seq } \g_mvar_names_seq
590 \seq_gset_eq:cN { g__numodel_ #1 _starts_seq } \g_mvar_start_seq
591 \seq_gset_eq:cN { g__numodel_ #1 _rules_seq } \g_mrule_seq
592 \seq_gset_eq:cN { g__numodel_ #1 _ruletypes_seq } \g_mrule_type_seq
593 \seq_gset_eq:cN { g__numodel_ #1 _rulecalc_seq } \g_mrule_calc_seq
594 \int_gset:cn { g__numodel_ #1 _rulecounter_int }
595 { \int_use:N \g_mrule_counter_int }
596 \tl_gset_eq:cN { g__numodel_ #1 _stopexpr_tl } \g_numodel_stop_expr_tl
597 \int_gset:cn { g__numodel_ #1 _steps_int }
598 { \int_use:N \g_numodel_steps_int }
599 }
600
601 \cs_new_protected:Npn \__numodel_load_state:n #1
602 {
603 \seq_gset_eq:Nc \g_mvar_names_seq { g__numodel_ #1 _vars_seq }
604 \seq_gset_eq:Nc \g_mvar_start_seq { g__numodel_ #1 _starts_seq }
605 \seq_gset_eq:Nc \g_mrule_seq { g__numodel_ #1 _rules_seq }
606 \seq_gset_eq:Nc \g_mrule_type_seq { g__numodel_ #1 _ruletypes_seq }
607 \seq_gset_eq:Nc \g_mrule_calc_seq { g__numodel_ #1 _rulecalc_seq }
608 \int_gset:Nn \g_mrule_counter_int
609 { \int_use:c { g__numodel_ #1 _rulecounter_int } }
610 \tl_gset_eq:Nc \g_numodel_stop_expr_tl { g__numodel_ #1 _stopexpr_tl }
611 \int_gset:Nn \g_numodel_steps_int
612 { \int_use:c { g__numodel_ #1 _steps_int } }
613 }
614
615 \cs_new_protected:Npn \__numodel_clear_state:
616 {
617 \seq_gclear:N \g_mvar_names_seq
618 \seq_gclear:N \g_mvar_start_seq
619 \seq_gclear:N \g_mrule_seq
620 \seq_gclear:N \g_mrule_type_seq
621 \seq_gclear:N \g_mrule_calc_seq
622 \int_gzero:N \g_mrule_counter_int
623 \tl_gclear:N \g_numodel_stop_expr_tl
624 \int_gzero:N \g_numodel_steps_int
625 }
626
627 % Initialise per-prefix backup variables (once, at \newmodelprefix).
628 \cs_new_protected:Npn \__numodel_init_backup:n #1
629 {
630 \seq_new:c { g__numodel_ #1 _vars_seq }
631 \seq_new:c { g__numodel_ #1 _starts_seq }
632 \seq_new:c { g__numodel_ #1 _rules_seq }
633 \seq_new:c { g__numodel_ #1 _ruletypes_seq }
634 \seq_new:c { g__numodel_ #1 _rulecalc_seq }
635 \int_new:c { g__numodel_ #1 _rulecounter_int }
636 \tl_new:c { g__numodel_ #1 _stopexpr_tl }
637 \int_new:c { g__numodel_ #1 _steps_int }
638 }
639
640 % Public commands for prefix management
641 \NewDocumentCommand{\newmodelprefix}{ m }
642 {
643 \typeout{NEWPREFIX~start:~#1}
644 \seq_if_in:NnTF \g_numodel_prefixes_seq {#1}
645 { \msg_error:nnn { numodel } { prefix-exists } {#1} }
646 {
647 \typeout{NEWPREFIX~save~current:~\g_numodel_current_prefix_tl}
648 % Save current state under the previous prefix (if any)
649 \tl_if_empty:NF \g_numodel_current_prefix_tl
650 { \exp_args:NV \__numodel_save_state:n \g_numodel_current_prefix_tl }
651 \typeout{NEWPREFIX~register}
652 % Register new prefix + init backup vars + Lua state
653 \seq_gput_right:Nn \g_numodel_prefixes_seq {#1}
654 \typeout{NEWPREFIX~init_backup}
655 \__numodel_init_backup:n {#1}
656 \typeout{NEWPREFIX~lua_init}
657 \directlua{ numodel.init_prefix("#1") }
658 \typeout{NEWPREFIX~clear_state}
659 % Clear current state and set the prefix
660 \__numodel_clear_state:
661 \typeout{NEWPREFIX~set_current}
662 \tl_gset:Nn \g_numodel_current_prefix_tl {#1}
663 \typeout{NEWPREFIX~done:~#1}
664 }
665 }
666
667 \NewDocumentCommand{\switchmodelprefix}{ m }
668 {
669 \seq_if_in:NnTF \g_numodel_prefixes_seq {#1}
670 {
671 % Save current state (if any), load the new one
672 \tl_if_empty:NF \g_numodel_current_prefix_tl
673 { \exp_args:NV \__numodel_save_state:n \g_numodel_current_prefix_tl }
674 \__numodel_load_state:n {#1}
675 \tl_gset:Nn \g_numodel_current_prefix_tl {#1}
676 }
677 { \msg_error:nnn { numodel } { prefix-unknown } {#1} }
678 }
679
680 % Iterate over *all* variables from *all* prefixes.
681 % #1 = code that uses ##1 = full variable name (prefix + short).
682 % Public registration API for external tools such as worksheet.tex.
683 \NewDocumentCommand{\NumodelForEachVar}{ +m }
684 {
685 \seq_map_inline:Nn \g_numodel_prefixes_seq
686 {
687 \seq_map_inline:cn { g__numodel_ ##1 _vars_seq } {#1}
688 }
689 }
690
691 % Resolve the effective prefix for a command call. Takes
692 % [prefix=<p>] from the keyval argument; otherwise falls back to the
693 % current prefix. Stores the result in \l__numodel_eff_prefix_tl.
694 \keys_define:nn { numodel / cmd }
695 {
696 prefix .tl_set:N = \l__numodel_cmd_prefix_tl,
697 % \graphicmodel-only: temporary override of the global
698 % diagram-style. Cleared after every \graphicmodel call.
699 diagram-style .choice:,
700 diagram-style / tight .code:n =
701 { \tl_set:Nn \l__numodel_cmd_diagstyle_tl { tight } },
702 diagram-style / forrester .code:n =
703 { \tl_set:Nn \l__numodel_cmd_diagstyle_tl { forrester } },
704 diagram-style / edu .code:n =
705 { \tl_set:Nn \l__numodel_cmd_diagstyle_tl { edu } },
706 % \graphicmodel-only: temporary overrides of the corresponding
707 % global flowarrow/valve/cloud keys. Empty after every call.
708 flowarrow-style .code:n =
709 { \__numodel_local_choice:Nnnn \l__numodel_cmd_flowarrow_tl
710 { flowarrow-style } { hollow , filled } {#1} },
711 valve-style .code:n =
712 { \__numodel_local_choice:Nnnn \l__numodel_cmd_valve_tl
713 { valve-style } { valve , circle , edu } {#1} },
714 flowarrow-cloud-tip .code:n =
715 { \__numodel_local_choice:Nnnn \l__numodel_cmd_flowcloud_tl
716 { flowarrow-cloud-tip } { true , false } {#1} },
717 % \textmodel-only: temporary override of the global units bool.
718 % Cleared after every \textmodel call.
719 units .choice:,
720 units / true .code:n =
721 { \tl_set:Nn \l__numodel_cmd_units_tl { true } },
722 units / false .code:n =
723 { \tl_set:Nn \l__numodel_cmd_units_tl { false } },
724 % \textmodel-only: temporary override of the global tblrenv tl.
725 % Cleared after every \textmodel call.
726 tblrenv .choice:,
727 tblrenv / tblr .code:n =
728 { \tl_set:Nn \l__numodel_cmd_tblrenv_tl { tblr } },
729 tblrenv / longtblr .code:n =
730 { \tl_set:Nn \l__numodel_cmd_tblrenv_tl { longtblr } },
731 tblrenv / talltblr .code:n =
732 { \tl_set:Nn \l__numodel_cmd_tblrenv_tl { talltblr } },
733 }
734 \tl_new:N \l__numodel_cmd_diagstyle_tl
735 \tl_new:N \l__numodel_cmd_flowarrow_tl
736 \tl_new:N \l__numodel_cmd_valve_tl
737 \tl_new:N \l__numodel_cmd_flowcloud_tl
738 \tl_new:N \l__numodel_cmd_units_tl
739 \tl_new:N \l__numodel_cmd_tblrenv_tl
740
741 \cs_new_protected:Npn \__numodel_resolve_prefix:n #1
742 {
743 \tl_clear:N \l__numodel_cmd_prefix_tl
744 \keys_set:nn { numodel / cmd } {#1}
745 \tl_if_empty:NTF \l__numodel_cmd_prefix_tl
746 { \tl_set_eq:NN \l__numodel_eff_prefix_tl \g_numodel_current_prefix_tl }
747 { \tl_set_eq:NN \l__numodel_eff_prefix_tl \l__numodel_cmd_prefix_tl }
748 }
749
750 % Execute code under a temporarily different prefix (via state swap).
751 % #1 = target prefix (tl, in variable)
752 % #2 = code
753 \cs_new_protected:Npn \__numodel_with_prefix:Nn #1 #2
754 {
755 \tl_if_eq:NNTF #1 \g_numodel_current_prefix_tl
756 { #2 } % already the current prefix; no swap needed
757 {
758 \tl_set_eq:NN \l__numodel_saved_prefix_tl \g_numodel_current_prefix_tl
759 \exp_args:NV \switchmodelprefix #1
760 #2
761 \exp_args:NV \switchmodelprefix \l__numodel_saved_prefix_tl
762 }
763 }
764 \tl_new:N \l__numodel_saved_prefix_tl
765
766 % Build the full name = <prefix><shortname>. Stored in
767 % \l__numodel_fullname_tl.
768 \cs_new_protected:Npn \__numodel_set_fullname:n #1
769 {
770 \tl_set:Ne \l__numodel_fullname_tl { \l__numodel_eff_prefix_tl #1 }
771 }
772
773 % Keys for the optional argument of \mvar (grid position +
774 % initial-value aliases + prefix).
775 \tl_new:N \l__numodel_alias_tl
776 \tl_new:N \l__numodel_aliasleft_tl
777 \tl_new:N \l__numodel_aliasright_tl
778
779 \keys_define:nn { numodel / mvar }
780 {
781 prefix .tl_set:N = \l__numodel_cmd_prefix_tl ,
782 gridx .tl_set:N = \l__numodel_gridx_tl ,
783 gridy .tl_set:N = \l__numodel_gridy_tl ,
784 alias .tl_set:N = \l__numodel_alias_tl ,
785 aliasleft .tl_set:N = \l__numodel_aliasleft_tl ,
786 aliasright .tl_set:N = \l__numodel_aliasright_tl ,
787 flowarrow-cloud-tip .code:n =
788 { \__numodel_local_choice:Nnnn \l__numodel_mvar_flowcloud_tl
789 { flowarrow-cloud-tip } { true , false } {#1} },
790 }
791 \tl_new:N \l__numodel_mvar_flowcloud_tl
792
793 % ====================================================================
794 % \mvar[keys]{name}{display}{startvalue}{unit}{sig}{type}
795 % ====================================================================
796 % Declare a model variable. Generates the following macros:
797 %
798 % \<name> -- numeric value (\edef + \fpeval), or warning if empty
799 % \<name>text -- display name for the model table (e.g. F_{res})
800 % \<name>unit -- SI unit (e.g. kN)
801 % \<name>unitraw - raw SI unit (e.g. \kilo\N)
802 % \<name>sign -- number of significant figures
803 % \<name>type -- variable type: stock, constant, aux, system
804 % (Dutch synonyms voorraad/constante/hulp/systeem
805 % are normalised to the canonical English form)
806 % \<name>coord -- coordinate list (empty; filled by \computemodel)
807 % \<name>gridx -- x position in the graphic model (-1 = auto)
808 % \<name>gridy -- y position in the graphic model (-1 = auto)
809 % \<name>num -- number with significance (via \num)
810 % \<name>qty -- number + unit (via \qty)
811 % \<name>pre -- engineering-prefix notation (via \qty)
812 % \<name>alias -- replaces the whole initial-value cell
813 % (empty = default)
814 % \<name>aliasleft -- replaces the left symbol in the initial value
815 % (empty = default)
816 % \<name>aliasright -- replaces the right number in the initial value
817 % (empty = default)
818 %
819 % Keys accepted in [#1]:
820 % gridx, gridy -- position in the graphic model
821 % alias -- replace the entire initial-value cell
822 % (in math mode)
823 % aliasleft -- replace just the left symbol
824 % aliasright -- replace just the right value
825 %
826 % The base value is registered in \g_defqty_names_seq so that
827 % \includeimage expands it automatically.
828 %
829 % With an empty start value (#3 blank), the base value is not
830 % numerically defined; using it issues a warning. Useful for
831 % auxiliary variables computed by \mrule.
832 %
833 % Example:
834 % \mvar{modM}{m}{80}{\kg}{2}{constant}
835 % \mvar{modFres}{F_{res}}{}{\N}{2}{aux}
836 % \mvar[aliasright=\cdots]{modX}{x}{0}{\m}{3}{stock}
837 % \mvar[alias={x \text{?}}]{modX}{x}{0}{\m}{3}{stock}
838
839 % Normalise the variable type (sixth \mvar argument) to its
840 % canonical English form. Accepts the canonical names
841 % {stock, constant, aux, system} and the Dutch synonyms
842 % {voorraad, constante, hulp, systeem}. An unknown value is left
843 % as-is and a warning is issued. The result is returned through
844 % \l__numodel_type_tl.
845 \tl_new:N \l__numodel_type_tl
846 \cs_new_protected:Npn \__numodel_normalize_type:n #1
847 {
848 \str_case:nnF {#1}
849 {
850 { stock } { \tl_set:Nn \l__numodel_type_tl { stock } }
851 { constant } { \tl_set:Nn \l__numodel_type_tl { constant } }
852 { aux } { \tl_set:Nn \l__numodel_type_tl { aux } }
853 { system } { \tl_set:Nn \l__numodel_type_tl { system } }
854 { voorraad } { \tl_set:Nn \l__numodel_type_tl { stock } }
855 { constante } { \tl_set:Nn \l__numodel_type_tl { constant } }
856 { hulp } { \tl_set:Nn \l__numodel_type_tl { aux } }
857 { systeem } { \tl_set:Nn \l__numodel_type_tl { system } }
858 }
859 {
860 \msg_warning:nne { numodel } { unknown-type } {#1}
861 \tl_set:Nn \l__numodel_type_tl {#1}
862 }
863 }
864
865 \makeatletter
866 \NewDocumentCommand{\mvar}{ O{} m m m m m m }{%
867 \typeout{MVAR~start:~#2}
868 % Parse optional keys (prefix, gridx, gridy, alias, aliasleft, aliasright,
869 % flowarrow-cloud-tip)
870 \tl_set:Nn \l__numodel_gridx_tl { -1 }
871 \tl_set:Nn \l__numodel_gridy_tl { -1 }
872 \tl_clear:N \l__numodel_alias_tl
873 \tl_clear:N \l__numodel_aliasleft_tl
874 \tl_clear:N \l__numodel_aliasright_tl
875 \tl_clear:N \l__numodel_cmd_prefix_tl
876 \tl_clear:N \l__numodel_mvar_flowcloud_tl
877 \typeout{MVAR~before-keys-set}
878 \keys_set:nn { numodel / mvar } {#1}
879 \typeout{MVAR~after-keys-set}
880 \__numodel_resolve_eff_prefix:
881 \typeout{MVAR~eff:~\l__numodel_eff_prefix_tl}
882 \__numodel_with_prefix:Nn \l__numodel_eff_prefix_tl
883 { \__numodel_mvar_body:nnnnnn {#2}{#3}{#4}{#5}{#6}{#7} }%
884 \typeout{MVAR~done:~#2}
885 }
886 \makeatother
887
888 % Resolve the effective prefix from \l__numodel_cmd_prefix_tl.
889 \cs_new_protected:Npn \__numodel_resolve_eff_prefix:
890 {
891 \tl_if_empty:NTF \l__numodel_cmd_prefix_tl
892 { \tl_set_eq:NN \l__numodel_eff_prefix_tl \g_numodel_current_prefix_tl }
893 { \tl_set_eq:NN \l__numodel_eff_prefix_tl \l__numodel_cmd_prefix_tl }
894 }
895
896 % The \mvar body runs in the context of the right prefix (live state
897 % has already been swapped).
898 \cs_new_protected:Npn \__numodel_mvar_body:nnnnnn #1 #2 #3 #4 #5 #6
899 {
900 % Guard: current prefix must not be empty (\newmodelprefix required)
901 \tl_if_empty:NT \g_numodel_current_prefix_tl
902 { \msg_error:nn { numodel } { no-prefix } }
903 % Full name = current prefix + short name (#1)
904 \tl_set:Ne \l__numodel_fullname_tl { \g_numodel_current_prefix_tl #1 }
905 \typeout{MVAR~body~fullname:~\l__numodel_fullname_tl}
906 % Register in the per-prefix seq. The defqty registration is
907 % optional: it only fires when the user has loaded the project-
908 % specific 'defqty' system (used for worksheet expansion).
909 % Standalone, the package works without that seq.
910 \seq_gput_right:NV \g_mvar_names_seq \l__numodel_fullname_tl
911 \cs_if_exist:NT \g_defqty_names_seq
912 { \seq_gput_right:NV \g_defqty_names_seq \l__numodel_fullname_tl }
913 \directlua{ numodel.register(
914 "\g_numodel_current_prefix_tl",
915 "\l__numodel_fullname_tl") }
916 \cs_if_exist:cT { \l__numodel_fullname_tl }
917 { \msg_warning:nne { numodel } { redef } { \l__numodel_fullname_tl } }
918 \tl_if_blank:nTF {#3}
919 { \cs_gset:cpe { \l__numodel_fullname_tl } { \fp_eval:n { 0 } } }
920 {
921 \cs_gset:cpe { \l__numodel_fullname_tl } { \fp_eval:n {#3} }
922 \seq_gput_right:NV \g_mvar_start_seq \l__numodel_fullname_tl
923 }
924 \cs_gset:cpn { \l__numodel_fullname_tl text } {#2}
925 \cs_gset:cpn { \l__numodel_fullname_tl unit } { \unit{#4} }
926 \cs_gset:cpn { \l__numodel_fullname_tl unitraw } {#4}
927 \cs_gset:cpn { \l__numodel_fullname_tl sign } {#5}
928 \__numodel_normalize_type:n {#6}
929 \cs_gset:cpe { \l__numodel_fullname_tl type }
930 { \tl_use:N \l__numodel_type_tl }
931 \cs_gset:cpn { \l__numodel_fullname_tl min } { inf }
932 \cs_gset:cpn { \l__numodel_fullname_tl max } { -inf }
933 \cs_gset:cpe { \l__numodel_fullname_tl gridx } { \tl_use:N \l__numodel_gridx_tl }
934 \cs_gset:cpe { \l__numodel_fullname_tl gridy } { \tl_use:N \l__numodel_gridy_tl }
935 % Preserve the original user input so that \__numodel_build_graphic:
936 % can reset auto-placed positions to -1 on a second invocation.
937 \cs_gset:cpe { \l__numodel_fullname_tl gridxinit } { \tl_use:N \l__numodel_gridx_tl }
938 \cs_gset:cpe { \l__numodel_fullname_tl gridyinit } { \tl_use:N \l__numodel_gridy_tl }
939 % Pillar A — Lua-side meta for compute_layout (additive in A1).
940 % Detokenize text so that \luaescapestring works on bare chars.
941 \tl_set:Ne \l__numodel_scratch_tl { \detokenize {#2} }
942 \directlua{ numodel.set_meta(
943 "\g_numodel_current_prefix_tl",
944 "\l__numodel_fullname_tl",
945 { type = "\tl_use:N \l__numodel_type_tl",
946 text = "\luaescapestring{\l__numodel_scratch_tl}",
947 gridx = \tl_use:N \l__numodel_gridx_tl,
948 gridy = \tl_use:N \l__numodel_gridy_tl }) }
949 \cs_gset:cpe { \l__numodel_fullname_tl alias } { \exp_not:V \l__numodel_alias_tl }
950 \cs_gset:cpe { \l__numodel_fullname_tl aliasleft } { \exp_not:V \l__numodel_aliasleft_tl }
951 \cs_gset:cpe { \l__numodel_fullname_tl aliasright } { \exp_not:V \l__numodel_aliasright_tl }
952 \cs_gset:cpe { \l__numodel_fullname_tl flowcloud } { \exp_not:V \l__numodel_mvar_flowcloud_tl }
953 \tl_if_blank:nF {#3}
954 {
955 \exp_args:NV \NumodelDefNumCs \l__numodel_fullname_tl {\fp_eval:n {#3}} {#5}
956 \exp_args:NV \NumodelDefQtyCs \l__numodel_fullname_tl {\fp_eval:n {#3}} {#5} {#4}
957 \exp_args:NV \NumodelDefPreCs \l__numodel_fullname_tl {\fp_eval:n {#3}} {#5} {#4}
958 }
959 }
960
961 % ====================================================================
962 % Warning messages
963 % ====================================================================
964
965 \msg_new:nnn { numodel } { redef }
966 { Model~variable~'#1'~is~being~redefined. }
967 \msg_new:nnn { numodel } { empty-use }
968 { Model~variable~'#1'~has~no~start~value~and~is~used~before~assignment. }
969 \msg_new:nnn { numodel } { maxiter }
970 { computemodel~stopped~after~\int_use:N \g_numodel_maxiter_int ~iterations~
971 (safety~limit).~Check~stop~condition. }
972 \msg_new:nnn { numodel } { no-stop }
973 { computemodel:~no~stop~condition~defined.~Use~\token_to_str:N \mstop\space
974 before~\token_to_str:N \computemodel. }
975 \msg_new:nnn { numodel } { prefix-exists }
976 { Model~prefix~'#1'~is~already~registered.~
977 Use~\token_to_str:N \switchmodelprefix\space to~switch~to~an~existing~prefix. }
978 \msg_new:nnn { numodel } { prefix-unknown }
979 { Model~prefix~'#1'~is~not~registered.~
980 Use~\token_to_str:N \newmodelprefix\space to~create~it~first. }
981 \msg_new:nnn { numodel } { no-prefix }
982 { No~current~model~prefix.~
983 Call~\token_to_str:N \newmodelprefix{<name>}\space before~using~model~commands. }
984 \msg_new:nnn { numodel } { unknown-type }
985 { Unknown~variable~type~'#1'.~
986 Use~one~of~stock,~constant,~aux,~system~
987 (or~the~Dutch~aliases~voorraad,~constante,~hulp,~systeem). }
988 \msg_new:nnn { numodel } { unit-mismatch }
989 { Variable~'#1'~has~a~different~unit~from~the~first~variable~
990 (expected~'#2').~Skipping~it~in~\token_to_str:N \diagrammodel\space
991 so~the~remaining~series~share~a~common~y-axis. }
992
993 % ====================================================================
994 % Display helpers
995 % ====================================================================
996 % Translate computational expressions into syllabus-style display.
997 %
998 % Automatic translations:
999 % \modXxx -> display name (via \<name>text)
1000 % * -> \cdot
1001 % >= <= -> \geqslant \leqslant
1002 % sign(...) -> SIGN(...) / Teken(...) in coachtaal
1003 % abs(...) -> ABS(...) / Abs(...) in coachtaal
1004 % sqrt(...) -> SQRT(...) / Sqrt(...) in coachtaal
1005 % exp(...) -> EXP(...) / Exp(...) in coachtaal
1006 % ln(...) -> LN(...) / Ln(...) in coachtaal
1007 % sin(...) -> SIN(...) / Sin(...) in coachtaal
1008 % cos(...) -> COS(...) / Cos(...) in coachtaal
1009 % tan(...) -> TAN(...) / Tan(...) in coachtaal
1010 % asin(...) -> ARCSIN(...) / Arcsin(...) in coachtaal
1011 % acos(...) -> ARCCOS(...) / Arccos(...) in coachtaal
1012 % && -> AND / EN in coachtaal
1013 % || -> OR / OF in coachtaal
1014 % cond ? a : b -> IF cond THEN ... ELSE ... ENDIF (or coachtaal eq.)
1015
1016 \tl_new:N \l__numodel_display_tl
1017 \tl_new:N \l__numodel_lhs_tl
1018 \tl_new:N \l__numodel_rhs_tl
1019 \tl_new:N \l__numodel_cond_tl
1020 \tl_new:N \l__numodel_true_tl
1021 \tl_new:N \l__numodel_false_tl
1022
1023 \cs_new_protected:Npn \__numodel_vars_to_display:N #1
1024 {
1025 \typeout{VTD~input:~\tl_to_str:N #1}
1026 \typeout{VTD~seq:~\seq_use:Nn \g_mvar_names_seq {|}}
1027 % Variable names -> display names
1028 \seq_map_inline:Nn \g_mvar_names_seq
1029 {
1030 \typeout{VTD~iter:~##1}
1031 \cs_if_exist:cT { ##1 text }
1032 {
1033 \tl_set:Ne \l_tmpa_tl { \use:c { ##1 text } }
1034 \typeout{VTD~replace~\c{##1}~with~\l_tmpa_tl}
1035 \regex_replace_all:nnN { \c{##1} } { \u{l_tmpa_tl} } #1
1036 }
1037 }
1038 % Arithmetic operators
1039 \regex_replace_all:nnN { \* } { \c{cdot} \x{20} } #1
1040 \regex_replace_all:nnN { >= } { \c{geqslant} \x{20} } #1
1041 \regex_replace_all:nnN { <= } { \c{leqslant} \x{20} } #1
1042 % Functions (syllabus notation). Order matters: asin/acos must
1043 % match before sin/cos, otherwise the inner sin/cos gets replaced
1044 % first and the outer arc- prefix is left dangling.
1045 \regex_replace_all:nnN { sign \( }
1046 { \c{text}\cB\{ \u{g__numodel_kw_sign_tl}\cE\}( } #1
1047 \regex_replace_all:nnN { abs \( }
1048 { \c{text}\cB\{ \u{g__numodel_kw_abs_tl}\cE\}( } #1
1049 \regex_replace_all:nnN { sqrt \( }
1050 { \c{text}\cB\{ \u{g__numodel_kw_sqrt_tl}\cE\}( } #1
1051 \regex_replace_all:nnN { exp \( }
1052 { \c{text}\cB\{ \u{g__numodel_kw_exp_tl}\cE\}( } #1
1053 \regex_replace_all:nnN { ln \( }
1054 { \c{text}\cB\{ \u{g__numodel_kw_ln_tl}\cE\}( } #1
1055 \regex_replace_all:nnN { asin \( }
1056 { \c{text}\cB\{ \u{g__numodel_kw_asin_tl}\cE\}( } #1
1057 \regex_replace_all:nnN { acos \( }
1058 { \c{text}\cB\{ \u{g__numodel_kw_acos_tl}\cE\}( } #1
1059 \regex_replace_all:nnN { sin \( }
1060 { \c{text}\cB\{ \u{g__numodel_kw_sin_tl}\cE\}( } #1
1061 \regex_replace_all:nnN { cos \( }
1062 { \c{text}\cB\{ \u{g__numodel_kw_cos_tl}\cE\}( } #1
1063 \regex_replace_all:nnN { \b tan \( }
1064 { \c{text}\cB\{ \u{g__numodel_kw_tan_tl}\cE\}( } #1
1065 % Logical operators (syllabus notation)
1066 \regex_replace_all:nnN { \&\& }
1067 { \c{text}\cB\{\u{g__numodel_kw_and_tl}\cE\} } #1
1068 \regex_replace_all:nnN { \|\| }
1069 { \c{text}\cB\{\u{g__numodel_kw_or_tl}\cE\} } #1
1070 }
1071
1072 % Ternary detection: cond ? true_expr : false_expr
1073 % Converted to: IF cond THEN lhs = true ELSE lhs = false ENDIF
1074 % (or the coachtaal equivalent). Supports only flat (non-nested)
1075 % ternaries.
1076 \bool_new:N \l__numodel_is_ternary_bool
1077
1078 \cs_new_protected:Npn \__numodel_parse_ternary:nN #1 #2
1079 {
1080 \bool_set_false:N \l__numodel_is_ternary_bool
1081 \regex_match:nnT { (.+) \? (.+) \: (.+) } {#1}
1082 {
1083 \bool_set_true:N \l__numodel_is_ternary_bool
1084 \tl_set:Nn \l__numodel_cond_tl {#1}
1085 \regex_replace_once:nnN { \s*(.+?) \s* \? .+ } { \1 } \l__numodel_cond_tl
1086 \tl_set:Nn \l__numodel_true_tl {#1}
1087 \regex_replace_once:nnN { .+? \? \s* (.+?) \s* \: .+ } { \1 } \l__numodel_true_tl
1088 \tl_set:Nn \l__numodel_false_tl {#1}
1089 \regex_replace_once:nnN { .+ \: \s* (.+?) \s* \Z } { \1 } \l__numodel_false_tl
1090 \__numodel_vars_to_display:N \l__numodel_cond_tl
1091 \__numodel_vars_to_display:N \l__numodel_true_tl
1092 \__numodel_vars_to_display:N \l__numodel_false_tl
1093 }
1094 }
1095
1096 % ====================================================================
1097 % \mrule[keys]{varname}{calculation}
1098 % ====================================================================
1099 % Declare a model rule.
1100 %
1101 % #1 (star) -- starred variant: multiline IF/THEN/ELSE/ENDIF
1102 % for ternary expressions
1103 % #2 (optional) -- keys: alias, aliasleft, aliasright
1104 % alias -- replaces the whole display row
1105 % aliasleft -- replaces the left-hand side
1106 % (symbol)
1107 % aliasright -- replaces the right-hand side
1108 % (calculation)
1109 % Use \cdots for omitted parts.
1110 % #3 -- name (string) of the left-hand variable
1111 % #4 -- calculation (with \modXxx macros and \fpeval
1112 % syntax)
1113 %
1114 % With alias or aliasright the ternary logic is skipped (display
1115 % shows the alias content verbatim, not IF/THEN/ELSE). Execution
1116 % always uses the calculation from #4.
1117 %
1118 % The calculation accepts all \fpeval operators:
1119 % +, -, *, /, ^, sign(), abs(), sin(), cos(), sqrt(), round()
1120 % Ternary: cond ? expr_true : expr_false
1121 % Logical: && (AND), || (OR), comparisons (<, >, <=, >=)
1122 %
1123 % The rule is stored for both display (\textmodel) and execution
1124 % (\computemodel).
1125 %
1126 % Examples:
1127 % \mrule{modFres}{\modM * \modA}
1128 % \mrule{modFw}{sign(\modV) * \modK * \modV^2}
1129 % \mrule{modA}{(\modT < \modTq) || (\modT > \modTdq) ? \modA + \modDa : \modA - \modDa}
1130 % \mrule[aliasright=\cdots]{modT}{\modT + \modDt}
1131 % \mrule[aliasleft=a_x]{modAx}{\modFgx / \modM}
1132 % \mrule[alias={\text{(hidden)}}]{modAy}{\modFgy / \modM}
1133
1134 \NewDocumentCommand{\mrule}{ s O{} m m }{%
1135 \typeout{MRULE~start:~#3}
1136 \bool_set_false:N \l__numodel_is_ternary_bool
1137 % Parse keys (prefix, alias, aliasleft, aliasright; gridx/gridy ignored)
1138 \tl_clear:N \l__numodel_alias_tl
1139 \tl_clear:N \l__numodel_aliasleft_tl
1140 \tl_clear:N \l__numodel_aliasright_tl
1141 \tl_clear:N \l__numodel_cmd_prefix_tl
1142 \keys_set:nn { numodel / mvar } {#2}
1143 \__numodel_resolve_eff_prefix:
1144 \__numodel_with_prefix:Nn \l__numodel_eff_prefix_tl
1145 { \__numodel_mrule_body:nnn {#1}{#3}{#4} }%
1146 \typeout{MRULE~done:~#3}
1147 }
1148
1149 \cs_new_protected:Npn \__numodel_mrule_body:nnn #1 #2 #3
1150 {
1151 \int_gincr:N \g_mrule_counter_int
1152 \tl_set:Ne \l__numodel_fullname_tl { \g_numodel_current_prefix_tl #2 }
1153 % Store execution data (target = full name)
1154 \seq_gput_right:Nx \g_mrule_calc_seq
1155 { { \l__numodel_fullname_tl } { \exp_not:n {#3} } }
1156 % Left-hand side: aliasleft or default display name
1157 \tl_if_blank:VTF \l__numodel_aliasleft_tl
1158 { \tl_set:Ne \l__numodel_lhs_tl { \use:c { \l__numodel_fullname_tl text } } }
1159 { \tl_set_eq:NN \l__numodel_lhs_tl \l__numodel_aliasleft_tl }
1160 % Generate display
1161 \tl_if_blank:VTF \l__numodel_alias_tl
1162 {
1163 \tl_if_blank:VTF \l__numodel_aliasright_tl
1164 {
1165 % Automatic display generation (ternary or normal)
1166 \__numodel_parse_ternary:nN {#3} \l__numodel_display_tl
1167 \bool_if:NTF \l__numodel_is_ternary_bool
1168 {
1169 \IfBooleanTF {#1}
1170 {
1171 % Starred ternary -> multiline IF/THEN/ELSE/ENDIF
1172 \tl_set:Ne \l__numodel_display_tl
1173 {
1174 \__numodel_kwt:n {if}
1175 \exp_not:V \l__numodel_cond_tl
1176 \__numodel_kwt:n {then_nl}
1177 }
1178 \seq_gput_right:NV \g_mrule_seq \l__numodel_display_tl
1179 \seq_gput_right:Nn \g_mrule_type_seq { rule }
1180 \tl_set:Ne \l__numodel_display_tl
1181 {
1182 \exp_not:n { \quad }
1183 \exp_not:V \l__numodel_lhs_tl \exp_not:n { \,=\, }
1184 \exp_not:V \l__numodel_true_tl
1185 }
1186 \seq_gput_right:NV \g_mrule_seq \l__numodel_display_tl
1187 \seq_gput_right:Nn \g_mrule_type_seq { cont }
1188 \seq_gput_right:Ne \g_mrule_seq { \__numodel_kwt:n {else_nl} }
1189 \seq_gput_right:Nn \g_mrule_type_seq { cont }
1190 \tl_set:Ne \l__numodel_display_tl
1191 {
1192 \exp_not:n { \quad }
1193 \exp_not:V \l__numodel_lhs_tl \exp_not:n { \,=\, }
1194 \exp_not:V \l__numodel_false_tl
1195 }
1196 \seq_gput_right:NV \g_mrule_seq \l__numodel_display_tl
1197 \seq_gput_right:Nn \g_mrule_type_seq { cont }
1198 \seq_gput_right:Ne \g_mrule_seq { \__numodel_kwt:n {endif_nl} }
1199 \seq_gput_right:Nn \g_mrule_type_seq { cont }
1200 }
1201 {
1202 % Unstarred ternary -> single-line
1203 \tl_set:Ne \l__numodel_display_tl
1204 {
1205 \__numodel_kwt:n {if}
1206 \exp_not:V \l__numodel_cond_tl
1207 \__numodel_kwt:n {then}
1208 \exp_not:V \l__numodel_lhs_tl \exp_not:n { \,=\, }
1209 \exp_not:V \l__numodel_true_tl
1210 \__numodel_kwt:n {else}
1211 \exp_not:V \l__numodel_lhs_tl \exp_not:n { \,=\, }
1212 \exp_not:V \l__numodel_false_tl
1213 \__numodel_kwt:n {endif}
1214 }
1215 }
1216 }
1217 {
1218 % Ordinary assignment: lhs = rhs
1219 \tl_set:Nn \l__numodel_rhs_tl {#3}
1220 \__numodel_vars_to_display:N \l__numodel_rhs_tl
1221 \typeout{MRULE~rhs~after:~\tl_to_str:N \l__numodel_rhs_tl}
1222 \tl_set:Ne \l__numodel_display_tl
1223 {
1224 \exp_not:V \l__numodel_lhs_tl \exp_not:n { \,=\, }
1225 \exp_not:V \l__numodel_rhs_tl
1226 }
1227 \typeout{MRULE~display:~\tl_to_str:N \l__numodel_display_tl}
1228 }
1229 }
1230 {
1231 % aliasright: lhs = aliasright (no ternary processing)
1232 \tl_set:Ne \l__numodel_display_tl
1233 {
1234 \exp_not:V \l__numodel_lhs_tl \exp_not:n { \,=\, }
1235 \exp_not:V \l__numodel_aliasright_tl
1236 }
1237 }
1238 }
1239 {
1240 % alias: replace the whole row
1241 \tl_set:Ne \l__numodel_display_tl { \exp_not:V \l__numodel_alias_tl }
1242 }
1243 % For starred ternary everything is already pushed above
1244 \bool_if:nF { \l__numodel_is_ternary_bool && #1 }
1245 {
1246 \seq_gput_right:NV \g_mrule_seq \l__numodel_display_tl
1247 \seq_gput_right:Nn \g_mrule_type_seq { rule }
1248 }
1249 % Pillar A — Lua-side rule registration. Detokenize the raw
1250 % expression so Lua sees the macro names, not the evaluated
1251 % fp values. Lua handles both the dependency extraction
1252 % (build_deps) and the flow detection (classify_flows) at
1253 % \graphicmodel time.
1254 \tl_set:Ne \l__numodel_scratch_tl { \detokenize {#3} }
1255 \directlua{ numodel.add_rule(
1256 "\g_numodel_current_prefix_tl",
1257 "\l__numodel_fullname_tl",
1258 "\luaescapestring{\l__numodel_scratch_tl}",
1259 "\bool_if:NTF \l__numodel_is_ternary_bool { ternary } { calc }") }
1260 }
1261
1262 % ====================================================================
1263 % \mruletext{free text}
1264 % ====================================================================
1265 % Adds a free-text row in the model table. Useful for structure
1266 % that does not fit as \mrule, e.g.:
1267 % \mruletext{\text{IF } t < T/4 \text{ THEN}}
1268 % \mruletext{\quad a = a + da}
1269 % \mruletext{\text{ENDIF}}
1270 %
1271 % NOT executed by \computemodel (display only).
1272
1273 \NewDocumentCommand{\mruletext}{ O{} m }{%
1274 \tl_clear:N \l__numodel_cmd_prefix_tl
1275 \keys_set:nn { numodel / cmd } {#1}
1276 \__numodel_resolve_eff_prefix:
1277 \__numodel_with_prefix:Nn \l__numodel_eff_prefix_tl
1278 {
1279 \int_gincr:N \g_mrule_counter_int
1280 \seq_gput_right:Nn \g_mrule_seq {#2}
1281 \seq_gput_right:Nn \g_mrule_type_seq { rule }
1282 }
1283 }
1284
1285 % ====================================================================
1286 % \mstop[keys]{condition}
1287 % \mstop*[keys]{condition} (star reserved; currently identical)
1288 % ====================================================================
1289 % Declare the model's stop condition.
1290 % Display: "IF condition THEN STOP ENDIF"
1291 % Execution: the model stops when the condition is true (evaluates to 1).
1292 %
1293 % The condition uses \fpeval syntax with \mvar variables:
1294 % \mstop{\modT >= \modTmax}
1295 % \mstop{\modV <= 0}
1296 %
1297 % Supported keys:
1298 % alias={...} -- replaces the whole display row (execution
1299 % remains intact)
1300 % aliasleft/aliasright are not (yet) supported for \mstop.
1301
1302 \tl_new:N \l__numodel_stop_tl
1303 \NewDocumentCommand{\mstop}{ s O{} m }{%
1304 \typeout{MSTOP~start}
1305 % Parse keys (only alias is honoured; prefix via key resolver)
1306 \tl_clear:N \l__numodel_alias_tl
1307 \tl_clear:N \l__numodel_aliasleft_tl
1308 \tl_clear:N \l__numodel_aliasright_tl
1309 \tl_clear:N \l__numodel_cmd_prefix_tl
1310 \keys_set:nn { numodel / mvar } {#2}
1311 \__numodel_resolve_eff_prefix:
1312 \__numodel_with_prefix:Nn \l__numodel_eff_prefix_tl
1313 { \__numodel_mstop_body:n {#3} }%
1314 \typeout{MSTOP~done}
1315 }
1316
1317 \cs_new_protected:Npn \__numodel_mstop_body:n #1
1318 {
1319 \int_gincr:N \g_mrule_counter_int
1320 % Store expression for execution (always the actual condition)
1321 \tl_gset:Nn \g_numodel_stop_expr_tl {#1}
1322 % Generate display
1323 \tl_if_blank:VTF \l__numodel_alias_tl
1324 {
1325 \tl_set:Nn \l__numodel_stop_tl {#1}
1326 \__numodel_vars_to_display:N \l__numodel_stop_tl
1327 \tl_set:Ne \l__numodel_display_tl
1328 {
1329 \__numodel_kwt:n {if}
1330 \exp_not:V \l__numodel_stop_tl
1331 \__numodel_kwt:n {then_nl}
1332 \__numodel_kwt:n {stop}
1333 \__numodel_kwt:n {endif_nl}
1334 }
1335 }
1336 {
1337 \tl_set:Ne \l__numodel_display_tl { \exp_not:V \l__numodel_alias_tl }
1338 }
1339 \seq_gput_right:NV \g_mrule_seq \l__numodel_display_tl
1340 \seq_gput_right:Nn \g_mrule_type_seq { rule }
1341 }
1342
1343 % ====================================================================
1344 % \textmodel
1345 % ====================================================================
1346 % Builds a tabular with numbered model rules on the left and initial
1347 % values on the right. Can be placed anywhere, e.g. in a subfigure
1348 % next to a graphic model.
1349
1350 \tl_new:N \g__numodel_table_tl
1351 \int_new:N \l__numodel_row_int
1352 \int_new:N \l__numodel_dispnum_int
1353 \int_new:N \l__numodel_startrow_int
1354 \int_new:N \l__numodel_numrules_int
1355 \int_new:N \l__numodel_numstarts_int
1356
1357 % Emit one initial-value cell with alias-key support.
1358 % - \<name>alias not empty -> replaces whole cell (inside $...$)
1359 % - \<name>aliasleft not empty -> replaces left symbol, else
1360 % \<name>text
1361 % - \<name>aliasright not empty -> replaces right value, else
1362 % \<name>qty (units=true) or
1363 % \<name>num (units=false)
1364 \cs_new_protected:Npn \__numodel_emit_startcell:n #1
1365 {
1366 % Alias-key contents are wrapped in a TeX group { ... } before
1367 % being placed in the table. Two reasons:
1368 % - the bare-macro form (\exp_not:c) keeps expansion-fragile
1369 % contents like \cdots or \ldots from expanding at table-build
1370 % time, so amsmath internals (\extrap@, \@cdots, ...) only run
1371 % later inside the proper math context;
1372 % - the surrounding group bounds the \futurelet lookahead that
1373 % \cdots and friends perform when they expand: without it the
1374 % lookahead crosses tabularray's cell boundary into document
1375 % tokens, producing "Undefined control sequence \DN@" cascades.
1376 \str_if_eq:eeTF { \tl_to_str:c { #1 alias } } { }
1377 {
1378 \tl_gput_right:Nn \g__numodel_table_tl { $ }
1379 \str_if_eq:eeTF { \tl_to_str:c { #1 aliasleft } } { }
1380 {
1381 \tl_gput_right:Nx \g__numodel_table_tl
1382 { { \exp_not:c { #1 text } } }
1383 }
1384 {
1385 \tl_gput_right:Nx \g__numodel_table_tl
1386 { { \exp_not:c { #1 aliasleft } } }
1387 }
1388 \tl_gput_right:Nn \g__numodel_table_tl { = }
1389 \str_if_eq:eeTF { \tl_to_str:c { #1 aliasright } } { }
1390 {
1391 % Emit \<name>qty or \<name>num as a token name without
1392 % expanding it; siunitx macros must only expand at
1393 % \tl_use:N time, in the correct tabular context.
1394 \bool_if:NTF \g__numodel_units_bool
1395 {
1396 \tl_gput_right:Nx \g__numodel_table_tl
1397 { \exp_not:c { #1 qty } }
1398 }
1399 {
1400 \tl_gput_right:Nx \g__numodel_table_tl
1401 { \exp_not:c { #1 num } }
1402 }
1403 }
1404 {
1405 \tl_gput_right:Nx \g__numodel_table_tl
1406 { { \exp_not:c { #1 aliasright } } }
1407 }
1408 \tl_gput_right:Nn \g__numodel_table_tl { $ }
1409 }
1410 {
1411 \tl_gput_right:Nn \g__numodel_table_tl { $ }
1412 \tl_gput_right:Nx \g__numodel_table_tl
1413 { { \exp_not:c { #1 alias } } }
1414 \tl_gput_right:Nn \g__numodel_table_tl { $ }
1415 }
1416 }
1417
1418 \cs_new_protected:Npn \__numodel_build_table:
1419 {
1420 \typeout{BUILD_TABLE~rules:~\seq_use:Nn \g_mrule_seq {|}}
1421 \typeout{BUILD_TABLE~types:~\seq_use:Nn \g_mrule_type_seq {|}}
1422 \int_set:Nn \l__numodel_numrules_int { \seq_count:N \g_mrule_seq }
1423 \int_set:Nn \l__numodel_numstarts_int { \seq_count:N \g_mvar_start_seq }
1424 \typeout{BUILD_TABLE~numrules:~\int_use:N \l__numodel_numrules_int}
1425 \typeout{BUILD_TABLE~numstarts:~\int_use:N \l__numodel_numstarts_int}
1426 \int_zero:N \l__numodel_row_int
1427 \int_zero:N \l__numodel_dispnum_int
1428 \int_zero:N \l__numodel_startrow_int
1429 \tl_gset:Nn \g__numodel_table_tl { \begin }
1430 \tl_gput_right:Ne \g__numodel_table_tl
1431 { { \tl_use:N \g__numodel_tblrenv_tl } }
1432 \tl_gput_right:Nn \g__numodel_table_tl
1433 { [theme={numodel}]{colspec={r|l|l}, rowhead=1} & \textbf }
1434 \tl_gput_right:Ne \g__numodel_table_tl
1435 { { \__numodel_kw:n {th_model} } }
1436 \tl_gput_right:Nn \g__numodel_table_tl
1437 { & \textbf }
1438 \tl_gput_right:Ne \g__numodel_table_tl
1439 { { \__numodel_kw:n {th_initvals} } }
1440 \tl_gput_right:Nn \g__numodel_table_tl
1441 { \\ \hline }
1442 \typeout{BUILD_TABLE~before-step~table:~\tl_to_str:N \g__numodel_table_tl}
1443 \int_step_inline:nn { \l__numodel_numrules_int }
1444 {
1445 \typeout{BUILD_TABLE~iter~row:~\int_use:N \l__numodel_row_int}
1446 \int_incr:N \l__numodel_row_int
1447 \int_incr:N \l__numodel_startrow_int
1448 \typeout{BUILD_TABLE~row:~\int_use:N \l__numodel_row_int~type:~\seq_item:Nn \g_mrule_type_seq { \l__numodel_row_int }}
1449 % Check type: rule -> show number, cont -> blank
1450 \str_if_eq:eeTF
1451 { \seq_item:Nn \g_mrule_type_seq { \l__numodel_row_int } }
1452 { cont }
1453 {
1454 % Continuation rows: no number
1455 \tl_gput_right:Ne \g__numodel_table_tl
1456 {
1457 \exp_not:n { \rule{0pt}{2.6ex} }
1458 \exp_not:n { & $ }
1459 \exp_not:e { \seq_item:Nn \g_mrule_seq { \l__numodel_row_int } }
1460 \exp_not:n { $ & }
1461 }
1462 }
1463 {
1464 % Numbered row
1465 \int_incr:N \l__numodel_dispnum_int
1466 \typeout{BUILD_TABLE~emit~rule~num:~\int_use:N \l__numodel_dispnum_int~content:~\seq_item:Nn \g_mrule_seq { \l__numodel_row_int }}
1467 \tl_gput_right:Ne \g__numodel_table_tl
1468 {
1469 \exp_not:n { \rule{0pt}{2.6ex} }
1470 \int_use:N \l__numodel_dispnum_int
1471 \exp_not:n { & $ }
1472 \exp_not:e { \seq_item:Nn \g_mrule_seq { \l__numodel_row_int } }
1473 \exp_not:n { $ & }
1474 }
1475 \typeout{BUILD_TABLE~after-emit~table~tail:~\tl_tail:N \g__numodel_table_tl}
1476 }
1477 % Initial-value column (independent of rule/cont)
1478 \int_compare:nNnTF { \l__numodel_startrow_int } > { \l__numodel_numstarts_int }
1479 {
1480 \tl_gput_right:Nn \g__numodel_table_tl { \\ }
1481 }
1482 {
1483 \exp_args:Ne \__numodel_emit_startcell:n
1484 { \seq_item:Nn \g_mvar_start_seq { \l__numodel_startrow_int } }
1485 \tl_gput_right:Nn \g__numodel_table_tl { \\ }
1486 }
1487 }
1488 \int_while_do:nNnn { \l__numodel_startrow_int } < { \l__numodel_numstarts_int }
1489 {
1490 \int_incr:N \l__numodel_startrow_int
1491 \tl_gput_right:Nn \g__numodel_table_tl { & & }
1492 \exp_args:Ne \__numodel_emit_startcell:n
1493 { \seq_item:Nn \g_mvar_start_seq { \l__numodel_startrow_int } }
1494 \tl_gput_right:Nn \g__numodel_table_tl { \\ }
1495 }
1496 \tl_gput_right:Nn \g__numodel_table_tl { \end }
1497 \tl_gput_right:Ne \g__numodel_table_tl
1498 { { \tl_use:N \g__numodel_tblrenv_tl } }
1499 }
1500
1501 \NewDocumentCommand{\textmodel}{ O{} }{%
1502 \typeout{TEXTMODEL~start}
1503 \tl_clear:N \l__numodel_cmd_prefix_tl
1504 \tl_clear:N \l__numodel_cmd_units_tl
1505 \tl_clear:N \l__numodel_cmd_tblrenv_tl
1506 \keys_set:nn { numodel / cmd } {#1}
1507 \__numodel_resolve_eff_prefix:
1508 % Temporary units override: save the global value, apply the key
1509 % value before build, restore afterwards. This way
1510 % \textmodel[units=false] flips one render without touching the
1511 % global \numodelsetup state.
1512 \bool_set_eq:NN \l__numodel_saved_units_bool \g__numodel_units_bool
1513 \tl_if_empty:NF \l__numodel_cmd_units_tl
1514 {
1515 \str_if_eq:VnTF \l__numodel_cmd_units_tl { true }
1516 { \bool_gset_true:N \g__numodel_units_bool }
1517 { \bool_gset_false:N \g__numodel_units_bool }
1518 }
1519 % Same dance for tblrenv: save, apply per-call override, restore.
1520 \tl_set_eq:NN \l__numodel_saved_tblrenv_tl \g__numodel_tblrenv_tl
1521 \tl_if_empty:NF \l__numodel_cmd_tblrenv_tl
1522 { \tl_gset_eq:NN \g__numodel_tblrenv_tl \l__numodel_cmd_tblrenv_tl }
1523 \__numodel_with_prefix:Nn \l__numodel_eff_prefix_tl
1524 {
1525 \group_begin:
1526 \__numodel_apply_dsep:
1527 \__numodel_build_table:
1528 \typeout{TEXTMODEL~table:~\tl_to_str:N \g__numodel_table_tl}
1529 \tl_use:N \g__numodel_table_tl
1530 \group_end:
1531 }%
1532 \bool_gset_eq:NN \g__numodel_units_bool \l__numodel_saved_units_bool
1533 \tl_gset_eq:NN \g__numodel_tblrenv_tl \l__numodel_saved_tblrenv_tl
1534 \typeout{TEXTMODEL~done}
1535 }
1536 \bool_new:N \l__numodel_saved_units_bool
1537 \tl_new:N \l__numodel_saved_tblrenv_tl
1538
1539 % ====================================================================
1540 % \computemodel
1541 % ====================================================================
1542 % Run the model with the Euler method:
1543 % 1. Record all variable values in Lua
1544 % 2. Check stop condition (\mstop)
1545 % 3. Execute every \mrule rule (in declaration order)
1546 % 4. Repeat until stop or safety limit (default 20000 iterations)
1547 %
1548 % Requires: at least one \mstop and at least one \mrule.
1549 % Performance: ~440 steps in ~4s, ~20000 steps in ~60s.
1550
1551 \cs_new_protected:Npn \__numodel_exec_rule:nn #1 #2
1552 {
1553 \cs_gset:cpe {#1} { \fp_eval:n {#2} }
1554 }
1555
1556 % Record all current variable values in Lua (O(1) per variable).
1557 \cs_new_protected:Npn \__numodel_lua_record_all:
1558 {
1559 \seq_map_inline:Nn \g_mvar_names_seq
1560 {
1561 \directlua{ numodel.record(
1562 "\g_numodel_current_prefix_tl", "##1", \use:c{##1}) }
1563 }
1564 \directlua{ numodel.end_step("\g_numodel_current_prefix_tl") }
1565 }
1566
1567 % Set min/max TeX macros from Lua data after the simulation finishes.
1568 \cs_new_protected:Npn \__numodel_set_minmax_from_lua:
1569 {
1570 \seq_map_inline:Nn \g_mvar_names_seq
1571 {
1572 \cs_gset:cpe { ##1 min }
1573 { \directlua{ numodel.get_min("\g_numodel_current_prefix_tl", "##1") } }
1574 \cs_gset:cpe { ##1 max }
1575 { \directlua{ numodel.get_max("\g_numodel_current_prefix_tl", "##1") } }
1576 }
1577 }
1578
1579
1580 \NewDocumentCommand{\computemodel}{ O{} }{%
1581 \typeout{COMPUTE~start}
1582 \tl_clear:N \l__numodel_cmd_prefix_tl
1583 \keys_set:nn { numodel / cmd } {#1}
1584 \__numodel_resolve_eff_prefix:
1585 \__numodel_with_prefix:Nn \l__numodel_eff_prefix_tl
1586 { \__numodel_compute_body: }%
1587 \typeout{COMPUTE~done}
1588 }
1589
1590 \cs_new_protected:Npn \__numodel_compute_body:
1591 {
1592 \tl_if_empty:NT \g_numodel_stop_expr_tl
1593 { \msg_error:nn { numodel } { no-stop } }
1594 \int_gzero:N \g_numodel_steps_int
1595 % Initialise Lua storage for this prefix
1596 \directlua{ numodel.init("\g_numodel_current_prefix_tl") }
1597 % Main loop
1598 \bool_gset_false:N \g_tmpa_bool
1599 \bool_do_until:Nn \g_tmpa_bool
1600 {
1601 \__numodel_lua_record_all:
1602 \int_gincr:N \g_numodel_steps_int
1603 \int_compare:nNnT
1604 { \fp_eval:n { \g_numodel_stop_expr_tl } } = { 1 }
1605 { \bool_gset_true:N \g_tmpa_bool }
1606 \bool_if:NF \g_tmpa_bool
1607 {
1608 \seq_map_inline:Nn \g_mrule_calc_seq
1609 { \__numodel_exec_rule:nn ##1 }
1610 }
1611 \int_compare:nNnT
1612 { \g_numodel_steps_int } > { \g_numodel_maxiter_int }
1613 {
1614 \bool_gset_true:N \g_tmpa_bool
1615 \msg_warning:nn { numodel } { maxiter }
1616 }
1617 }
1618 \__numodel_set_minmax_from_lua:
1619 % Public per-prefix step-count accessor: \<prefix>steps holds the
1620 % number of recorded samples (= iterations of the loop above).
1621 \cs_gset:cpe { \g_numodel_current_prefix_tl steps }
1622 { \int_use:N \g_numodel_steps_int }
1623 }
1624
1625 % On-demand coordinates from Lua (after \computemodel). Arguments
1626 % are SHORT names; the current prefix is prepended automatically.
1627 % See \mcoordsp for the form with an explicit prefix.
1628 %
1629 % Fully expandable (a plain \def around \directlua, no xparse
1630 % wrapper). Works directly inside \addplot coordinates
1631 % {\mcoords{T}{V}} and pgfplots' math-expression parser, without
1632 % pre-expansion via \edef.
1633 \cs_new:Npn \mcoords #1#2
1634 {
1635 \directlua{ numodel.get_coords(
1636 "\g_numodel_current_prefix_tl",
1637 "\g_numodel_current_prefix_tl" .. "#1",
1638 "\g_numodel_current_prefix_tl" .. "#2") }
1639 }
1640
1641 % Variant with explicit prefix as first argument (instead of an
1642 % optional argument, so the macro stays fully expandable).
1643 \cs_new:Npn \mcoordsp #1#2#3
1644 {
1645 \directlua{ numodel.get_coords(
1646 "#1", "#1" .. "#2", "#1" .. "#3") }
1647 }
1648
1649 % Value of variable #1 at step #2 (0-based). The variable name is
1650 % SHORT (current prefix is prepended automatically). See \mstepp for
1651 % the form with an explicit prefix.
1652 %
1653 % Example -- tangent line at step 0:
1654 % \addplot[domain=0:\modTmax]
1655 % {\mstep{V}{0} + \mstep{A}{1} * (x - \mstep{T}{0})};
1656 \cs_new:Npn \mstep #1#2
1657 {
1658 \directlua{ numodel.get_step(
1659 "\g_numodel_current_prefix_tl",
1660 "\g_numodel_current_prefix_tl" .. "#1", #2) }
1661 }
1662
1663 \cs_new:Npn \mstepp #1#2#3
1664 {
1665 \directlua{ numodel.get_step("#1", "#1" .. "#2", #3) }
1666 }
1667
1668 % ====================================================================
1669 % \modelreset -- REMOVED
1670 % ====================================================================
1671 % \modelreset no longer exists. Use \newmodelprefix{<prefix>} to set
1672 % up a new model and \switchmodelprefix{<prefix>} to switch between
1673 % existing ones. Namespaces are additive -- variables from earlier
1674 % models remain available.
1675
1676 % ====================================================================
1677 % \graphicmodel -- Forrester diagram from \mvar/\mrule data
1678 % ====================================================================
1679 % Builds a tikzpicture with:
1680 % - stock, valve, aux and const nodes based on type and gridx/gridy
1681 % - flow arrows from valve to stock (via \flowarrow)
1682 % - causal arrows from the dependency graph
1683 %
1684 % Positioning: automatic (auto-layout) or manual via
1685 % \mvar[gridx=N, gridy=N]{...}. Mixed mode is supported.
1686 % Auto-layout places stocks+valves at gridy=0, aux at gridy=1, and
1687 % constants at gridy=2. Variables of type system are skipped.
1688 % Auxiliary variables that act as inflow are placed as a valve
1689 % (not as aux).
1690
1691 \tl_new:N \g__numodel_graphic_tl
1692 % Lua-populated cache (filled by numodel.tex_writeback at the start of
1693 % each \graphicmodel call, consumed by the emit helpers below).
1694 \prop_new:N \l__numodel_valve_for_prop % aux/const -> stock (inflow)
1695 % Secondary stocks for a shared inflow valve. Value = comma-list of
1696 % stock names; the renderer iterates it to draw a curved branch from
1697 % the valve, sweeping over the primary stock into each extra target.
1698 \prop_new:N \l__numodel_valve_extras_prop
1699 \prop_new:N \l__numodel_outvalve_for_prop % aux/const -> stock (outflow)
1700 % Mirror of valve_extras_prop for shared outflow valves: a curved
1701 % branch from each extra source stock arcs over the intermediate
1702 % stocks into the shared valve's open end.
1703 \prop_new:N \l__numodel_outvalve_extras_prop
1704 \prop_new:N \l__numodel_between_valve_prop % aux/const -> source_stock (between-flow)
1705 \prop_new:N \l__numodel_between_target_prop % aux/const -> target_stock (between-flow)
1706 \prop_new:N \l__numodel_stock_valve_prop % stock -> source stock (stock-as-flow)
1707 \prop_new:N \l__numodel_stock_phantom_valve_prop % stock -> source stock (phantom flow)
1708 % For diagram-style=forrester|edu: separate valve gridx position next
1709 % to the stock; the variable's own gridx/gridy keeps the natural
1710 % position at gridy=1 (aux) or gridy=2 (constant). vpos_y is always 0
1711 % so it lives implicitly in the emit helpers.
1712 \prop_new:N \l__numodel_vpos_x_prop % varname -> valve gridx
1713 \prop_new:N \l__numodel_vpos_y_prop % varname -> valve gridy (used when gridmaxx wrap shifted the stock row)
1714 \tl_new:N \l__numodel_flows_tl % deferred flow arrows
1715 \tl_new:N \l__numodel_valves_tl % deferred valve nodes (drawn on top)
1716 \tl_new:N \l__numodel_late_causals_tl % causals pointing at valves
1717
1718 % --- Resolved render settings (set per-\graphicmodel call) ---
1719 % These hold the effective values (after resolving diagram-style
1720 % defaults and explicit global/local overrides) used by the emit
1721 % helpers and by the public \flowarrow / \flowoutarrow macros.
1722 \tl_new:N \l__numodel_flowarrow_eff_tl % "hollow" or "filled"
1723 \tl_new:N \l__numodel_valve_eff_tl % "valve" | "circle" | "edu"
1724 \tl_new:N \l__numodel_flowcloud_global_tl % "true" or "false" (global default)
1725
1726 % Resolve flowarrow-style: explicit global key wins; otherwise
1727 % diagram-style picks the default (forrester -> hollow,
1728 % tight|edu -> filled).
1729 \cs_new_protected:Npn \__numodel_resolve_flowarrow:
1730 {
1731 \tl_if_empty:NTF \g__numodel_flowarrow_style_tl
1732 {
1733 \str_if_eq:VnTF \g__numodel_diagram_style_tl { forrester }
1734 { \tl_set:Nn \l__numodel_flowarrow_eff_tl { hollow } }
1735 { \tl_set:Nn \l__numodel_flowarrow_eff_tl { filled } }
1736 }
1737 { \tl_set_eq:NN \l__numodel_flowarrow_eff_tl
1738 \g__numodel_flowarrow_style_tl }
1739 }
1740
1741 % Resolve valve-style: explicit global key wins; otherwise
1742 % diagram-style picks the default (forrester -> valve,
1743 % tight|edu -> edu).
1744 \cs_new_protected:Npn \__numodel_resolve_valve:
1745 {
1746 \tl_if_empty:NTF \g__numodel_valve_style_tl
1747 {
1748 \str_if_eq:VnTF \g__numodel_diagram_style_tl { forrester }
1749 { \tl_set:Nn \l__numodel_valve_eff_tl { valve } }
1750 { \tl_set:Nn \l__numodel_valve_eff_tl { edu } }
1751 }
1752 { \tl_set_eq:NN \l__numodel_valve_eff_tl
1753 \g__numodel_valve_style_tl }
1754 }
1755
1756 % Resolve the global flowarrow-cloud-tip default (no per-stock
1757 % override yet; that's added on top in \__numodel_eff_flowcloud:n).
1758 \cs_new_protected:Npn \__numodel_resolve_flowcloud:
1759 {
1760 \tl_if_empty:NTF \g__numodel_flowcloud_tl
1761 {
1762 \str_if_eq:VnTF \g__numodel_diagram_style_tl { forrester }
1763 { \tl_set:Nn \l__numodel_flowcloud_global_tl { true } }
1764 { \tl_set:Nn \l__numodel_flowcloud_global_tl { false } }
1765 }
1766 { \tl_set_eq:NN \l__numodel_flowcloud_global_tl
1767 \g__numodel_flowcloud_tl }
1768 }
1769
1770 % Per-stock flowcloud lookup. #1 = stock varname. Sets
1771 % \l__numodel_flowcloud_eff_tl to "true" or "false". Order: per-mvar
1772 % override on the stock (via [flowarrow-cloud-tip=...]) wins over the
1773 % global default.
1774 \tl_new:N \l__numodel_flowcloud_eff_tl
1775 \cs_new_protected:Npn \__numodel_eff_flowcloud:n #1
1776 {
1777 \tl_set:Ne \l__numodel_flowcloud_eff_tl { \use:c { #1 flowcloud } }
1778 \tl_if_empty:NT \l__numodel_flowcloud_eff_tl
1779 { \tl_set_eq:NN \l__numodel_flowcloud_eff_tl
1780 \l__numodel_flowcloud_global_tl }
1781 }
1782
1783 % Sets the public \nmflowbody and \nmflowtip macros that the
1784 % \flowarrow / \flowoutarrow / \flowbetweenarrow macros expand to.
1785 % Reads the resolved flowarrow-style.
1786 \cs_new_protected:Npn \__numodel_apply_flowarrow_style:
1787 {
1788 \str_if_eq:VnTF \l__numodel_flowarrow_eff_tl { hollow }
1789 {
1790 \cs_gset:Npn \nmflowbody { flowpipe-hollow }
1791 \cs_gset:Npn \nmflowtip { flowpipe-hollow-tip }
1792 \cs_gset:Npn \nmflowtipcloudin { flowpipe-hollow-cloudin }
1793 \cs_gset:Npn \nmflowtipcloudout { flowpipe-hollow-cloudout }
1794 }
1795 {
1796 \cs_gset:Npn \nmflowbody { flowpipe-filled }
1797 \cs_gset:Npn \nmflowtip { flowpipe-filled-tip }
1798 \cs_gset:Npn \nmflowtipcloudin { flowpipe-filled-cloudin }
1799 \cs_gset:Npn \nmflowtipcloudout { flowpipe-filled-cloudout }
1800 }
1801 }
1802
1803 % Sets the tikz node-style name for the valve and the boolean that
1804 % controls whether the valve carries the variable's display label.
1805 % valve-style=valve -> [valve-forrester], no label
1806 % valve-style=circle -> [valve-circle], no label
1807 % valve-style=edu -> [valve-edu], with label
1808 \tl_new:N \l__numodel_valve_node_tl
1809 \bool_new:N \l__numodel_valve_label_bool
1810 \cs_new_protected:Npn \__numodel_apply_valve_style:
1811 {
1812 \str_case:VnF \l__numodel_valve_eff_tl
1813 {
1814 { valve }
1815 {
1816 \tl_set:Nn \l__numodel_valve_node_tl { valve-forrester }
1817 \bool_set_false:N \l__numodel_valve_label_bool
1818 }
1819 { circle }
1820 {
1821 \tl_set:Nn \l__numodel_valve_node_tl { valve-circle }
1822 \bool_set_false:N \l__numodel_valve_label_bool
1823 }
1824 { edu }
1825 {
1826 \tl_set:Nn \l__numodel_valve_node_tl { valve-edu }
1827 \bool_set_true:N \l__numodel_valve_label_bool
1828 }
1829 }
1830 {
1831 \tl_set:Nn \l__numodel_valve_node_tl { valve-edu }
1832 \bool_set_true:N \l__numodel_valve_label_bool
1833 }
1834 }
1835
1836 % --- Diagram-style mode flag ---
1837 % True at diagram-style=forrester|edu; consulted by \__numodel_place_node
1838 % to decide between single-emit and natural+phantom-valve double-emit.
1839 % Set in \__numodel_build_graphic from \g__numodel_diagram_style_tl.
1840 \bool_new:N \l__numodel_keep_natural_bool
1841
1842
1843 \cs_new_protected:Npn \__numodel_build_graphic:
1844 {
1845 \typeout{BUILD:~step~0~reset~auto-positions}
1846 % --- Reset gridx/gridy to the original user input ---
1847 % Auto-layout writes positions to var.gridx/gridy. On a second
1848 % \graphicmodel call those would, without reset, be treated as
1849 % "manually placed". The initial values are saved in
1850 % gridxinit/gridyinit by \mvar -- copy them back.
1851 \seq_map_inline:Nn \g_mvar_names_seq
1852 {
1853 \cs_gset:cpe { ##1 gridx } { \use:c { ##1 gridxinit } }
1854 \cs_gset:cpe { ##1 gridy } { \use:c { ##1 gridyinit } }
1855 }
1856 % Diagram-style mode: forrester|edu keep aux/const at their natural
1857 % gridy with a phantom valve next to the stock; tight collapses the
1858 % aux/const onto the valve position. Consumed by \__numodel_place_node
1859 % to dispatch between single-emit and natural+phantom emit.
1860 \bool_set_false:N \l__numodel_keep_natural_bool
1861 \str_if_eq:VnT \g__numodel_diagram_style_tl { forrester }
1862 { \bool_set_true:N \l__numodel_keep_natural_bool }
1863 \str_if_eq:VnT \g__numodel_diagram_style_tl { edu }
1864 { \bool_set_true:N \l__numodel_keep_natural_bool }
1865 \typeout{BUILD:~step~1~lua~layout~writeback}
1866 % Pillar A — Lua is the single source of truth for flow detection
1867 % and auto-layout. The writeback clears and fills \<var>gridx/gridy
1868 % and the flow-props that downstream emitters (place_node,
1869 % flow-builders, emit_natural_and_phantom, emit_stock_valve) read.
1870 \__numodel_lua_layout_writeback:
1871 \typeout{BUILD:~step~2~tikzpicture}
1872 % --- Build tikzpicture ---
1873 % Render order matters: each segment overlays the previous one,
1874 % so we draw flows first (one continuous arrow per flow), then
1875 % the valve nodes on top (with white fill so they cover the
1876 % section of the arrow that lies underneath), and finally the
1877 % causal arrows that point at those valves.
1878 \tl_gclear:N \g__numodel_graphic_tl
1879 \tl_clear:N \l__numodel_flows_tl
1880 \tl_clear:N \l__numodel_valves_tl
1881 \tl_clear:N \l__numodel_late_causals_tl
1882 \tl_gput_right:Nn \g__numodel_graphic_tl
1883 { \begin{tikzpicture}[gridscale] }
1884 % Nodes (stocks, aux, const, clouds; flows -> flows_tl,
1885 % valves -> valves_tl)
1886 \seq_map_inline:Nn \g_mvar_names_seq
1887 { \typeout{NODE:~##1} \__numodel_place_node:n {##1} }
1888 \typeout{BUILD:~step~5~stock-valve~nodes}
1889 % Stock-as-flow valve nodes
1890 \prop_map_inline:Nn \l__numodel_stock_valve_prop
1891 {
1892 % ##1 = stock (e.g. modH), ##2 = source stock (e.g. modV)
1893 % Skip entries that are not real stock-valves (e.g. __svgx keys)
1894 \tl_if_in:nnF {##1} { __sv }
1895 { \__numodel_emit_stock_valve:nn {##1} {##2} }
1896 }
1897 % Stock-as-rate phantom-valve nodes (source stock has no matching
1898 % outflow term, so the inflow gets a cloud at the open end)
1899 \prop_map_inline:Nn \l__numodel_stock_phantom_valve_prop
1900 {
1901 \tl_if_in:nnF {##1} { __sv }
1902 { \__numodel_emit_stock_phantom_valve:nn {##1} {##2} }
1903 }
1904 \typeout{BUILD:~step~6~flow~arrows}
1905 % Flow arrows (one segment each; drawn underneath the valves)
1906 \tl_gput_right:NV \g__numodel_graphic_tl \l__numodel_flows_tl
1907 \typeout{BUILD:~step~6a~valve~nodes}
1908 % Valve nodes (white-filled, drawn ON TOP of the flow arrows)
1909 \tl_gput_right:NV \g__numodel_graphic_tl \l__numodel_valves_tl
1910 \typeout{BUILD:~step~6b+7~causal~arrows~(Lua)}
1911 % A2: causal arrows via Lua — emit_causals demultiplexes on
1912 % tgt_is_valve and pushes to \g__numodel_graphic_tl or
1913 % \l__numodel_late_causals_tl respectively. Afterwards append
1914 % late-causals to graphic_tl once: that covers both the pushes
1915 % from the flow-builders (step 6/6a) and those from emit_causals.
1916 \__numodel_lua_emit_causals:
1917 \tl_gput_right:NV \g__numodel_graphic_tl \l__numodel_late_causals_tl
1918 \typeout{BUILD:~step~8~done}
1919 \tl_gput_right:Nn \g__numodel_graphic_tl
1920 { \end{tikzpicture} }
1921 }
1922
1923 % --- Node placement ---
1924 \cs_new_protected:Npn \__numodel_place_node:n #1
1925 {
1926 \bool_set_true:N \l_tmpa_bool
1927 \tl_set:Ne \l__numodel_scratch_tl { \use:c { #1 type } }
1928 \exp_args:NV \str_if_eq:nnT \l__numodel_scratch_tl { system }
1929 { \bool_set_false:N \l_tmpa_bool }
1930 \bool_if:NT \l_tmpa_bool
1931 {
1932 \int_compare:nNnT { \use:c { #1 gridx } } = { -1 }
1933 { \bool_set_false:N \l_tmpa_bool }
1934 }
1935 \bool_if:NT \l_tmpa_bool
1936 {
1937 \tl_set:Ne \l__numodel_tmp_tl { \use:c { #1 text } }
1938 % With forrester|edu, valve vars get a dual emission:
1939 % the natural aux/const node + a phantom valve next to the stock.
1940 \bool_set_false:N \l_tmpb_bool % is this a valve var?
1941 \prop_if_in:NnT \l__numodel_valve_for_prop {#1}
1942 { \bool_set_true:N \l_tmpb_bool }
1943 \prop_if_in:NnT \l__numodel_outvalve_for_prop {#1}
1944 { \bool_set_true:N \l_tmpb_bool }
1945 \prop_if_in:NnT \l__numodel_between_valve_prop {#1}
1946 { \bool_set_true:N \l_tmpb_bool }
1947 \bool_lazy_and:nnTF
1948 { \l__numodel_keep_natural_bool } { \l_tmpb_bool }
1949 { \__numodel_emit_natural_and_phantom:n {#1} }
1950 {
1951 \prop_if_in:NnTF \l__numodel_valve_for_prop {#1}
1952 { \__numodel_emit_valve:n {#1} }
1953 {
1954 \prop_if_in:NnTF \l__numodel_outvalve_for_prop {#1}
1955 { \__numodel_emit_outvalve:n {#1} }
1956 {
1957 \prop_if_in:NnTF \l__numodel_between_valve_prop {#1}
1958 { \__numodel_emit_between_valve:n {#1} }
1959 {
1960 \tl_set:Ne \l__numodel_scratch_tl { \use:c { #1 type } }
1961 \exp_args:NV \str_if_eq:nnT \l__numodel_scratch_tl { stock }
1962 { \__numodel_emit_stock:n {#1} }
1963 \exp_args:NV \str_if_eq:nnT \l__numodel_scratch_tl { aux }
1964 { \__numodel_emit_aux:n {#1} }
1965 \exp_args:NV \str_if_eq:nnT \l__numodel_scratch_tl { constant }
1966 { \__numodel_emit_const:n {#1} }
1967 }
1968 }
1969 }
1970 }
1971 }
1972 }
1973
1974 % --- Helper: emit a coordinate node at the valve position ---
1975 % The flow arrow starts/ends at this coordinate (or at an offset
1976 % relative to it, for the open-end without cloud). The visible
1977 % white-filled valve is added later (valves_tl) at the same
1978 % coordinates so it overlays the arrow.
1979 % #1 = coord id #2 = x #3 = y
1980 \cs_new_protected:Npn \__numodel_emit_valve_coord:nnn #1 #2 #3
1981 {
1982 \tl_gput_right:Ne \g__numodel_graphic_tl
1983 {
1984 \exp_not:N \coordinate ~
1985 (#1) ~ \exp_not:n{at} ~ (#2 , ~ #3) ;
1986 }
1987 }
1988
1989 % --- Helper: append a valve node to the deferred valves_tl ---
1990 % Renders \node[<valve-style>] (id) at (x,y) {<label>}; later in the
1991 % picture so the white fill overlays the flow arrow underneath.
1992 % #1 = node id #2 = x coord #3 = y coord #4 = label tl name
1993 \cs_new_protected:Npn \__numodel_defer_valve:nnnn #1 #2 #3 #4
1994 {
1995 \tl_put_right:Ne \l__numodel_valves_tl
1996 {
1997 \exp_not:N \node ~ [ \tl_use:N \l__numodel_valve_node_tl ] ~
1998 (#1) ~ \exp_not:n{at} ~ (#2 , ~ #3) ~
1999 {
2000 \bool_if:NTF \l__numodel_valve_label_bool
2001 { \exp_not:N $ \exp_not:V #4 \exp_not:N $ }
2002 { }
2003 } ;
2004 }
2005 }
2006
2007 % --- Forrester/edu-mode emission: natural node + phantom valve ---
2008 % The variable sits as an ordinary aux/const node at its own gridy.
2009 % The phantom valve (id #1__v) sits next to the stock at gridy=0; its
2010 % appearance follows the resolved valve-style (label included only
2011 % when valve-style=edu). A causal arrow from #1 -> #1__v is drawn
2012 % (deferred to late_causals_tl so it lands on top of the white-
2013 % filled valve).
2014 \tl_new:N \l__numodel_phantom_label_tl
2015 \cs_new_protected:Npn \__numodel_emit_natural_and_phantom:n #1
2016 {
2017 % --- 1. Natural node (aux or constant) ---
2018 \tl_set:Ne \l__numodel_scratch_tl { \use:c { #1 type } }
2019 \exp_args:NV \str_if_eq:nnT \l__numodel_scratch_tl { aux }
2020 { \__numodel_emit_aux:n {#1} }
2021 \exp_args:NV \str_if_eq:nnT \l__numodel_scratch_tl { constant }
2022 { \__numodel_emit_const:n {#1} }
2023 % --- 2. Locate the phantom valve x/y position ---
2024 \prop_get:NnNT \l__numodel_vpos_x_prop {#1} \l__numodel_phantom_x_tl
2025 {
2026 \prop_get:NnNF \l__numodel_vpos_y_prop {#1} \l__numodel_scratch_y_tl
2027 { \tl_set:Nn \l__numodel_scratch_y_tl { 0 } }
2028 \tl_set:Ne \l__numodel_phantom_label_tl { \use:c { #1 text } }
2029 % --- 3. Coordinate at the phantom valve position ---
2030 \__numodel_emit_valve_coord:nnn { #1 __vc }
2031 { \tl_use:N \l__numodel_phantom_x_tl }
2032 { \tl_use:N \l__numodel_scratch_y_tl }
2033 % --- 4. Flow arrow + (optional) cloud, one segment ---
2034 \prop_if_in:NnTF \l__numodel_valve_for_prop {#1}
2035 {
2036 \tl_set:Ne \l__numodel_tmp_tl
2037 { \prop_item:Nn \l__numodel_valve_for_prop {#1} }
2038 \__numodel_eff_flowcloud:V \l__numodel_tmp_tl
2039 \str_if_eq:VnTF \l__numodel_flowcloud_eff_tl { true }
2040 {
2041 \tl_put_right:Ne \l__numodel_flows_tl
2042 {
2043 \exp_not:N \flowarrow [#1 __cl] {#1 __vc}
2044 { \tl_use:N \l__numodel_tmp_tl }
2045 }
2046 }
2047 {
2048 \tl_put_right:Ne \l__numodel_flows_tl
2049 {
2050 \exp_not:N \flowarrow {#1 __vc}
2051 { \tl_use:N \l__numodel_tmp_tl }
2052 }
2053 }
2054 \__numodel_emit_valve_extras:n {#1}
2055 }
2056 {
2057 \prop_if_in:NnTF \l__numodel_outvalve_for_prop {#1}
2058 {
2059 \tl_set:Ne \l__numodel_tmp_tl
2060 { \prop_item:Nn \l__numodel_outvalve_for_prop {#1} }
2061 \__numodel_eff_flowcloud:V \l__numodel_tmp_tl
2062 \str_if_eq:VnTF \l__numodel_flowcloud_eff_tl { true }
2063 {
2064 \tl_put_right:Ne \l__numodel_flows_tl
2065 {
2066 \exp_not:N \flowoutarrow [#1 __cl]
2067 { \tl_use:N \l__numodel_tmp_tl } {#1 __vc}
2068 }
2069 }
2070 {
2071 \tl_put_right:Ne \l__numodel_flows_tl
2072 {
2073 \exp_not:N \flowoutarrow
2074 { \tl_use:N \l__numodel_tmp_tl } {#1 __vc}
2075 }
2076 }
2077 \__numodel_emit_outvalve_extras:n {#1}
2078 }
2079 {
2080 % between (no cloud: both ends are stocks)
2081 \tl_set:Ne \l__numodel_tmp_tl
2082 { \prop_item:Nn \l__numodel_between_valve_prop {#1} }
2083 \tl_set:Ne \l__numodel_scratch_tl
2084 { \prop_item:Nn \l__numodel_between_target_prop {#1} }
2085 \tl_put_right:Ne \l__numodel_flows_tl
2086 {
2087 \exp_not:N \flowbetweenarrow
2088 { \tl_use:N \l__numodel_tmp_tl }
2089 {#1 __vc}
2090 { \tl_use:N \l__numodel_scratch_tl }
2091 }
2092 }
2093 }
2094 % --- 5. Defer the phantom valve drawing (overlays flow) ---
2095 \__numodel_defer_valve:nnnn { #1 __v }
2096 { \tl_use:N \l__numodel_phantom_x_tl }
2097 { \tl_use:N \l__numodel_scratch_y_tl }
2098 \l__numodel_phantom_label_tl
2099 % --- 6. Causal arrow natural -> phantom valve (deferred) ---
2100 \tl_put_right:Ne \l__numodel_late_causals_tl
2101 {
2102 \exp_not:N \draw ~ [\exp_not:n{causal}] ~
2103 (#1) ~ \exp_not:n{to} ~ (#1 __v) ;
2104 }
2105 }
2106 }
2107 \tl_new:N \l__numodel_phantom_x_tl
2108 \cs_generate_variant:Nn \__numodel_eff_flowcloud:n { V }
2109
2110 \cs_new_protected:Npn \__numodel_emit_stock:n #1
2111 {
2112 \tl_gput_right:Ne \g__numodel_graphic_tl
2113 {
2114 \exp_not:N \node ~ [\exp_not:n{stock}] ~
2115 (#1) ~ \exp_not:n{at} ~
2116 ( \use:c{#1 gridx} , ~ \use:c{#1 gridy} ) ~
2117 { \exp_not:N $ \exp_not:V \l__numodel_tmp_tl \exp_not:N $ } ;
2118 }
2119 }
2120
2121 % Tight-mode helpers: the valve sits at the variable's own gridx/
2122 % gridy. We emit a coordinate node (#1__vc) early so the flow
2123 % arrow has a positioning anchor, and defer the visible valve node
2124 % (#1) to valves_tl so it overlays the arrow with white fill.
2125 \cs_new_protected:Npn \__numodel_emit_tight_valve_setup:n #1
2126 {
2127 \__numodel_emit_valve_coord:nnn { #1 __vc }
2128 { \use:c{#1 gridx} } { \use:c{#1 gridy} }
2129 \__numodel_defer_valve:nnnn {#1}
2130 { \use:c{#1 gridx} } { \use:c{#1 gridy} }
2131 \l__numodel_tmp_tl
2132 }
2133
2134 \cs_new_protected:Npn \__numodel_emit_valve:n #1
2135 {
2136 \__numodel_emit_tight_valve_setup:n {#1}
2137 \tl_set:Ne \l__numodel_scratch_tl
2138 { \prop_item:Nn \l__numodel_valve_for_prop {#1} }
2139 \__numodel_eff_flowcloud:V \l__numodel_scratch_tl
2140 \str_if_eq:VnTF \l__numodel_flowcloud_eff_tl { true }
2141 {
2142 \tl_put_right:Ne \l__numodel_flows_tl
2143 {
2144 \exp_not:N \flowarrow [#1 __cl] {#1 __vc}
2145 { \tl_use:N \l__numodel_scratch_tl }
2146 }
2147 }
2148 {
2149 \tl_put_right:Ne \l__numodel_flows_tl
2150 {
2151 \exp_not:N \flowarrow {#1 __vc}
2152 { \tl_use:N \l__numodel_scratch_tl }
2153 }
2154 }
2155 \__numodel_emit_valve_extras:n {#1}
2156 }
2157
2158 % Emit one curved inflow branch per shared-inflow extra target
2159 % (\l__numodel_valve_extras_prop[fv]). Each branch starts at the
2160 % valve coordinate and sweeps over the primary stock to the extra
2161 % target's north edge. No-op when the valve is not shared.
2162 \cs_new_protected:Npn \__numodel_emit_valve_extras:n #1
2163 {
2164 \prop_get:NnNT \l__numodel_valve_extras_prop {#1} \l__numodel_scratch_tl
2165 {
2166 \clist_set:NV \l__numodel_scratch_clist \l__numodel_scratch_tl
2167 \clist_map_inline:Nn \l__numodel_scratch_clist
2168 {
2169 \tl_put_right:Nn \l__numodel_flows_tl
2170 { \flowarrowbent {#1 __vc} {##1} }
2171 }
2172 }
2173 }
2174
2175 % Mirror of \__numodel_emit_valve_extras:n for shared outflow valves.
2176 % Each extra source stock gets a curved branch arcing over the
2177 % intermediate stocks into the shared valve's open end.
2178 \cs_new_protected:Npn \__numodel_emit_outvalve_extras:n #1
2179 {
2180 \prop_get:NnNT \l__numodel_outvalve_extras_prop
2181 {#1} \l__numodel_scratch_tl
2182 {
2183 \clist_set:NV \l__numodel_scratch_clist \l__numodel_scratch_tl
2184 \clist_map_inline:Nn \l__numodel_scratch_clist
2185 {
2186 \tl_put_right:Nn \l__numodel_flows_tl
2187 { \flowoutarrowbent {##1} {#1 __vc} }
2188 }
2189 }
2190 }
2191 \clist_new:N \l__numodel_scratch_clist
2192
2193 \cs_new_protected:Npn \__numodel_emit_outvalve:n #1
2194 {
2195 \__numodel_emit_tight_valve_setup:n {#1}
2196 \tl_set:Ne \l__numodel_scratch_tl
2197 { \prop_item:Nn \l__numodel_outvalve_for_prop {#1} }
2198 \__numodel_eff_flowcloud:V \l__numodel_scratch_tl
2199 \str_if_eq:VnTF \l__numodel_flowcloud_eff_tl { true }
2200 {
2201 \tl_put_right:Ne \l__numodel_flows_tl
2202 {
2203 \exp_not:N \flowoutarrow [#1 __cl]
2204 { \tl_use:N \l__numodel_scratch_tl } {#1 __vc}
2205 }
2206 }
2207 {
2208 \tl_put_right:Ne \l__numodel_flows_tl
2209 {
2210 \exp_not:N \flowoutarrow
2211 { \tl_use:N \l__numodel_scratch_tl } {#1 __vc}
2212 }
2213 }
2214 \__numodel_emit_outvalve_extras:n {#1}
2215 }
2216
2217 \cs_new_protected:Npn \__numodel_emit_between_valve:n #1
2218 {
2219 \__numodel_emit_tight_valve_setup:n {#1}
2220 \tl_set:Ne \l__numodel_scratch_tl
2221 { \prop_item:Nn \l__numodel_between_valve_prop {#1} }
2222 \tl_set:Ne \l__numodel_tmp_tl
2223 { \prop_item:Nn \l__numodel_between_target_prop {#1} }
2224 \tl_put_right:Ne \l__numodel_flows_tl
2225 {
2226 \exp_not:N \flowbetweenarrow
2227 { \tl_use:N \l__numodel_scratch_tl }
2228 {#1 __vc}
2229 { \tl_use:N \l__numodel_tmp_tl }
2230 }
2231 }
2232
2233 \cs_new_protected:Npn \__numodel_emit_aux:n #1
2234 {
2235 \tl_gput_right:Ne \g__numodel_graphic_tl
2236 {
2237 \exp_not:N \node ~ [\exp_not:n{aux}] ~
2238 (#1) ~ \exp_not:n{at} ~
2239 ( \use:c{#1 gridx} , ~ \use:c{#1 gridy} ) ~
2240 { \exp_not:N $ \exp_not:V \l__numodel_tmp_tl \exp_not:N $ } ;
2241 }
2242 }
2243
2244 \cs_new_protected:Npn \__numodel_emit_const:n #1
2245 {
2246 \tl_gput_right:Ne \g__numodel_graphic_tl
2247 {
2248 \exp_not:N \constnode
2249 {#1}
2250 { \use:c{#1 gridx} , ~ \use:c{#1 gridy} }
2251 { \exp_not:N $ \exp_not:V \l__numodel_tmp_tl \exp_not:N $ }
2252 }
2253 }
2254
2255 % --- Stock-as-flow valve emission ---
2256 \cs_new_protected:Npn \__numodel_emit_stock_valve:nn #1 #2
2257 {
2258 % #1 = target stock (e.g. modH), #2 = source stock (e.g. modV)
2259 % Pull gridx from the saved property
2260 \prop_get:NnNTF \l__numodel_stock_valve_prop { #1 __svgx }
2261 \l__numodel_scratch_tl
2262 {
2263 % Look up the wrap-shifted y-slot; default to 0 (the row that
2264 % the auto layout used before any gridmaxx wrap was applied).
2265 \prop_get:NnNF \l__numodel_stock_valve_prop { #1 __svgy }
2266 \l__numodel_scratch_y_tl
2267 { \tl_set:Nn \l__numodel_scratch_y_tl { 0 } }
2268 % Coordinate at the valve position (used by the flow arrow)
2269 \__numodel_emit_valve_coord:nnn { #1 __svc }
2270 { \tl_use:N \l__numodel_scratch_tl }
2271 { \tl_use:N \l__numodel_scratch_y_tl }
2272 % Flow arrow from source-stock through valve into target-stock
2273 % (no cloud: both ends are stocks). The arrow runs in one
2274 % continuous segment; the visible valve will be drawn ON TOP
2275 % later via valves_tl.
2276 \tl_put_right:Ne \l__numodel_flows_tl
2277 {
2278 \exp_not:N \flowbetweenarrow {#2} {#1 __svc} {#1}
2279 }
2280 % Defer the visible valve node (white fill overlays arrow)
2281 \tl_set:Ne \l__numodel_tmp_tl { \use:c { #2 text } }
2282 \__numodel_defer_valve:nnnn { #1 __sv }
2283 { \tl_use:N \l__numodel_scratch_tl }
2284 { \tl_use:N \l__numodel_scratch_y_tl }
2285 \l__numodel_tmp_tl
2286 % Causal arrow source-stock -> valve. Bend it (curved) only
2287 % when the source stock and the valve sit on the same row —
2288 % then the straight causal would coincide with the flow pipe
2289 % and disappear behind it. When they are on different rows
2290 % (e.g. after a gridmaxx wrap) the causal is vertical-ish and
2291 % stays visible without a bend. Deferred so it lands on top
2292 % of the white-filled valve.
2293 \str_if_eq:eeTF { \tl_use:N \l__numodel_scratch_y_tl }
2294 { \use:c { #2 gridy } }
2295 {
2296 \tl_put_right:Ne \l__numodel_late_causals_tl
2297 {
2298 \exp_not:N \draw ~ [\exp_not:n{causal}] ~
2299 (#2) ~ \exp_not:n{to} ~ [\exp_not:n{bend~left=30}] ~ (#1__sv) ;
2300 }
2301 }
2302 {
2303 \tl_put_right:Ne \l__numodel_late_causals_tl
2304 {
2305 \exp_not:N \draw ~ [\exp_not:n{causal}] ~
2306 (#2) ~ \exp_not:n{to} ~ (#1__sv) ;
2307 }
2308 }
2309 }
2310 { } % no gridx found: skip
2311 }
2312
2313 % --- Stock phantom-valve emission (source stock as rate factor) ---
2314 % Source stock acts as a rate factor for the target stock without a
2315 % matching outflow term; render with a cloud-fed inflow valve next to
2316 % the target stock and link the source stock via a causal arrow.
2317 \cs_new_protected:Npn \__numodel_emit_stock_phantom_valve:nn #1 #2
2318 {
2319 % #1 = target stock (e.g. ballY), #2 = source stock (e.g. ballV)
2320 \prop_get:NnNTF \l__numodel_stock_phantom_valve_prop { #1 __svgx }
2321 \l__numodel_scratch_tl
2322 {
2323 % Look up the wrap-shifted y-slot; default to 0.
2324 \prop_get:NnNF \l__numodel_stock_phantom_valve_prop { #1 __svgy }
2325 \l__numodel_scratch_y_tl
2326 { \tl_set:Nn \l__numodel_scratch_y_tl { 0 } }
2327 % Coordinate at the valve position
2328 \__numodel_emit_valve_coord:nnn { #1 __svc }
2329 { \tl_use:N \l__numodel_scratch_tl }
2330 { \tl_use:N \l__numodel_scratch_y_tl }
2331 % Flow arrow: cloud (open end) -> valve -> target stock
2332 \__numodel_eff_flowcloud:n {#1}
2333 \str_if_eq:VnTF \l__numodel_flowcloud_eff_tl { true }
2334 {
2335 \tl_put_right:Ne \l__numodel_flows_tl
2336 {
2337 \exp_not:N \flowarrow [#1 __svcl] {#1 __svc} {#1}
2338 }
2339 }
2340 {
2341 \tl_put_right:Ne \l__numodel_flows_tl
2342 {
2343 \exp_not:N \flowarrow {#1 __svc} {#1}
2344 }
2345 }
2346 % Defer the visible valve node, labelled with the source stock
2347 \tl_set:Ne \l__numodel_tmp_tl { \use:c { #2 text } }
2348 \__numodel_defer_valve:nnnn { #1 __sv }
2349 { \tl_use:N \l__numodel_scratch_tl }
2350 { \tl_use:N \l__numodel_scratch_y_tl }
2351 \l__numodel_tmp_tl
2352 % Causal arrow source-stock -> valve. Bend (curved) only when
2353 % source and valve sit on the same row — see the equivalent
2354 % comment in \__numodel_emit_stock_valve:nn for the rationale.
2355 \str_if_eq:eeTF { \tl_use:N \l__numodel_scratch_y_tl }
2356 { \use:c { #2 gridy } }
2357 {
2358 \tl_put_right:Ne \l__numodel_late_causals_tl
2359 {
2360 \exp_not:N \draw ~ [\exp_not:n{causal}] ~
2361 (#2) ~ \exp_not:n{to} ~ [\exp_not:n{bend~left=30}] ~ (#1__sv) ;
2362 }
2363 }
2364 {
2365 \tl_put_right:Ne \l__numodel_late_causals_tl
2366 {
2367 \exp_not:N \draw ~ [\exp_not:n{causal}] ~
2368 (#2) ~ \exp_not:n{to} ~ (#1__sv) ;
2369 }
2370 }
2371 }
2372 { } % no gridx found: skip
2373 }
2374
2375 % --------------------------------------------------------------------
2376 % Pillar A — Lua-side layout writeback. A single directlua call
2377 % that runs compute_layout (build_deps, classify_flows,
2378 % populate_occupied, auto_layout, causals) and writes the resulting
2379 % state back to the TeX-side props (\<var>gridx/gridy and the
2380 % flow-props) that the downstream emitters (place_node,
2381 % flow-builders, emit_natural_and_phantom, emit_stock_valve) read.
2382 % Lua is the single source of truth for the decision logic; TeX
2383 % only renders.
2384 % --------------------------------------------------------------------
2385 \cs_new_protected:Npn \__numodel_lua_layout_writeback:
2386 {
2387 % 1. Clear the props that Lua refills, so repeated \graphicmodel
2388 % calls don't produce duplicate entries.
2389 \prop_clear:N \l__numodel_valve_for_prop
2390 \prop_clear:N \l__numodel_valve_extras_prop
2391 \prop_clear:N \l__numodel_outvalve_for_prop
2392 \prop_clear:N \l__numodel_outvalve_extras_prop
2393 \prop_clear:N \l__numodel_between_valve_prop
2394 \prop_clear:N \l__numodel_between_target_prop
2395 \prop_clear:N \l__numodel_stock_valve_prop
2396 \prop_clear:N \l__numodel_stock_phantom_valve_prop
2397 \prop_clear:N \l__numodel_vpos_x_prop
2398 \prop_clear:N \l__numodel_vpos_y_prop
2399 % 2. Run the Lua pipeline.
2400 \directlua{ numodel.compute_layout(
2401 "\g_numodel_current_prefix_tl",
2402 "\g__numodel_diagram_style_tl",
2403 \int_use:N \g_numodel_gridmaxx_int) }
2404 % 3. Write gridx/gridy and all flow-props back.
2405 % tex_writeback emits a list of expl3 statements via tex.print.
2406 \directlua{ numodel.tex_writeback(
2407 "\g_numodel_current_prefix_tl") }
2408 }
2409
2410 \cs_new_protected:Npn \__numodel_lua_emit_causals:
2411 {
2412 \directlua{ numodel.emit_causals(
2413 "\g_numodel_current_prefix_tl") }
2414 }
2415
2416 \NewDocumentCommand{\graphicmodel}{ O{} }{%
2417 \tl_clear:N \l__numodel_cmd_prefix_tl
2418 \tl_clear:N \l__numodel_cmd_diagstyle_tl
2419 \tl_clear:N \l__numodel_cmd_flowarrow_tl
2420 \tl_clear:N \l__numodel_cmd_valve_tl
2421 \tl_clear:N \l__numodel_cmd_flowcloud_tl
2422 \keys_set:nn { numodel / cmd } {#1}
2423 \__numodel_resolve_eff_prefix:
2424 % Temporary overrides: save the global state, apply the per-call
2425 % key values before build, restore afterwards. This way
2426 % \graphicmodel[diagram-style=forrester] flips one render without
2427 % touching the global \numodelsetup state.
2428 \tl_set_eq:NN \l__numodel_saved_diagstyle_tl \g__numodel_diagram_style_tl
2429 \tl_set_eq:NN \l__numodel_saved_flowarrow_tl \g__numodel_flowarrow_style_tl
2430 \tl_set_eq:NN \l__numodel_saved_valve_tl \g__numodel_valve_style_tl
2431 \tl_set_eq:NN \l__numodel_saved_flowcloud_tl \g__numodel_flowcloud_tl
2432 \tl_if_empty:NF \l__numodel_cmd_diagstyle_tl
2433 { \tl_gset_eq:NN \g__numodel_diagram_style_tl \l__numodel_cmd_diagstyle_tl }
2434 \tl_if_empty:NF \l__numodel_cmd_flowarrow_tl
2435 { \tl_gset_eq:NN \g__numodel_flowarrow_style_tl \l__numodel_cmd_flowarrow_tl }
2436 \tl_if_empty:NF \l__numodel_cmd_valve_tl
2437 { \tl_gset_eq:NN \g__numodel_valve_style_tl \l__numodel_cmd_valve_tl }
2438 \tl_if_empty:NF \l__numodel_cmd_flowcloud_tl
2439 { \tl_gset_eq:NN \g__numodel_flowcloud_tl \l__numodel_cmd_flowcloud_tl }
2440 % Resolve the effective values for this render and propagate them
2441 % to \nmflowbody / \nmflowtip used by the flow macros.
2442 \__numodel_resolve_flowarrow:
2443 \__numodel_resolve_valve:
2444 \__numodel_resolve_flowcloud:
2445 \__numodel_apply_flowarrow_style:
2446 \__numodel_apply_valve_style:
2447 \__numodel_with_prefix:Nn \l__numodel_eff_prefix_tl
2448 {
2449 \__numodel_build_graphic:
2450 \tl_use:N \g__numodel_graphic_tl
2451 }%
2452 \tl_gset_eq:NN \g__numodel_diagram_style_tl \l__numodel_saved_diagstyle_tl
2453 \tl_gset_eq:NN \g__numodel_flowarrow_style_tl \l__numodel_saved_flowarrow_tl
2454 \tl_gset_eq:NN \g__numodel_valve_style_tl \l__numodel_saved_valve_tl
2455 \tl_gset_eq:NN \g__numodel_flowcloud_tl \l__numodel_saved_flowcloud_tl
2456 }
2457 \tl_new:N \l__numodel_saved_diagstyle_tl
2458 \tl_new:N \l__numodel_saved_flowarrow_tl
2459 \tl_new:N \l__numodel_saved_valve_tl
2460 \tl_new:N \l__numodel_saved_flowcloud_tl
2461
2462 % ====================================================================
2463 % Plot machinery
2464 % ====================================================================
2465 % \diagrammodel calls the pgfplots/calcplotdims infrastructure
2466 % through internal wrappers \__numodel_calc_plot_dims: and
2467 % \__numodel_draw_plot:n. Those wrappers forward to \calcplotdims
2468 % and \drawplot from the sibling package numodel-plot.
2469 %
2470 % The wrappers are not \cs_new_eq:NN because numodel-plot can load
2471 % after this package; at load time \calcplotdims and \drawplot may
2472 % not yet exist. With a wrapper they are looked up at expansion
2473 % time.
2474
2475 \cs_new:Npn \__numodel_calc_plot_dims: { \calcplotdims }
2476 \cs_new:Npn \__numodel_draw_plot:n #1 { \drawplot {#1} }
2477
2478 % ====================================================================
2479 % \diagrammodel -- convenience command for model graphs
2480 % ====================================================================
2481 % Usage: \diagrammodel{xvar}{yvar}[extra drawplot code]{label}
2482 % \diagrammodel{xvar}{yvar1,yvar2,...,yvarn}[extra]{label}
2483 %
2484 % Builds a complete figure with model points. Sets axis dimensions
2485 % from min/max, axis labels from text/unit, and emits caption and
2486 % label automatically.
2487 %
2488 % When the second argument is a comma-separated list, every y-variable
2489 % whose unit matches the first one is drawn into the same diagram with
2490 % the y-axis scaled to the joint min/max range. Variables with a
2491 % mismatching unit are dropped with a warning. Every series is drawn
2492 % as discrete model points (no connecting lines); the seven colours
2493 % come from Okabe & Ito's colour-blind safe palette (yellow omitted)
2494 % and are ordered so consecutive series differ in luminance, which
2495 % keeps them distinguishable on a greyscale printout. The legend
2496 % lists each kept variable's display text.
2497
2498 \tl_new:N \l__numodel_xname_tl
2499 \tl_new:N \l__numodel_yname_tl
2500 \tl_new:N \l__numodel_yfull_tl
2501 \tl_new:N \l__numodel_yunit_first_tl
2502 \tl_new:N \l__numodel_yqty_tl
2503 \tl_new:N \l__numodel_plotbody_tl
2504 \clist_new:N \l__numodel_yshort_clist
2505 \int_new:N \l__numodel_yidx_int
2506
2507 % Colour-blind safe palette (Okabe & Ito; yellow #F0E442 omitted for
2508 % poor white-background contrast). Ordered so consecutive series
2509 % differ in luminance as well as hue, keeping them distinguishable
2510 % on a greyscale printout.
2511 \definecolor{numodelseriesa}{HTML}{000000} % black (L ~ 0.00)
2512 \definecolor{numodelseriesb}{HTML}{E69F00} % orange (L ~ 0.69)
2513 \definecolor{numodelseriesc}{HTML}{0072B2} % dark blue (L ~ 0.36)
2514 \definecolor{numodelseriesd}{HTML}{56B4E9} % sky blue (L ~ 0.74)
2515 \definecolor{numodelseriese}{HTML}{D55E00} % vermillion (L ~ 0.50)
2516 \definecolor{numodelseriesf}{HTML}{CC79A7} % reddish purple (L ~ 0.62)
2517 \definecolor{numodelseriesg}{HTML}{009E73} % bluish green (L ~ 0.52)
2518
2519 \clist_new:N \g__numodel_series_colors_clist
2520 \clist_gset:Nn \g__numodel_series_colors_clist
2521 {
2522 numodelseriesa , numodelseriesb , numodelseriesc , numodelseriesd ,
2523 numodelseriese , numodelseriesf , numodelseriesg
2524 }
2525
2526 % Return the cycling colour name for series #1 (1-based), modulo 7.
2527 \cs_new:Npn \__numodel_series_color:n #1
2528 {
2529 \clist_item:Nn \g__numodel_series_colors_clist
2530 { 1 + \int_mod:nn { #1 - 1 } { 7 } }
2531 }
2532
2533 \NewDocumentCommand{\diagrammodel}{ O{} m m O{} m }
2534 {
2535 \tl_clear:N \l__numodel_cmd_prefix_tl
2536 \keys_set:nn { numodel / cmd } {#1}
2537 \__numodel_resolve_eff_prefix:
2538 \tl_set:Ne \l__numodel_xname_tl { \l__numodel_eff_prefix_tl #2 }
2539 % --- Parse comma-separated y-variable list ----------------------
2540 % Keep only variables whose unitraw matches the first one's; warn
2541 % about the rest.
2542 \clist_clear:N \l__numodel_yshort_clist
2543 \tl_clear:N \l__numodel_yunit_first_tl
2544 \int_zero:N \l__numodel_yidx_int
2545 \clist_map_inline:nn {#3}
2546 {
2547 \int_incr:N \l__numodel_yidx_int
2548 \tl_set:Ne \l__numodel_yfull_tl { \l__numodel_eff_prefix_tl ##1 }
2549 \int_compare:nNnTF { \l__numodel_yidx_int } = { 1 }
2550 {
2551 \tl_set:Ne \l__numodel_yunit_first_tl
2552 { \use:c { \l__numodel_yfull_tl unitraw } }
2553 \clist_put_right:Nn \l__numodel_yshort_clist {##1}
2554 }
2555 {
2556 \tl_set:Ne \l_tmpa_tl
2557 { \use:c { \l__numodel_yfull_tl unitraw } }
2558 \str_if_eq:VVTF \l_tmpa_tl \l__numodel_yunit_first_tl
2559 { \clist_put_right:Nn \l__numodel_yshort_clist {##1} }
2560 {
2561 \msg_warning:nnee { numodel } { unit-mismatch }
2562 { \tl_use:N \l__numodel_yfull_tl }
2563 { \tl_use:N \l__numodel_yunit_first_tl }
2564 }
2565 }
2566 }
2567 % Canonical y-name = first kept variable (legacy single-series
2568 % accessor used by the caption when only one series is plotted).
2569 \clist_get:NN \l__numodel_yshort_clist \l_tmpa_tl
2570 \tl_set:Ne \l__numodel_yname_tl
2571 { \l__numodel_eff_prefix_tl \l_tmpa_tl }
2572 % --- Axis ranges -----------------------------------------------
2573 \def\xmin{\use:c{\l__numodel_xname_tl min}}
2574 \def\xmax{\use:c{\l__numodel_xname_tl max}}
2575 \def\xlabelqty{\use:c{\l__numodel_xname_tl text}}
2576 \def\xlabelunit{\use:c{\l__numodel_xname_tl unitraw}}
2577 % Reduce over the kept y-variables. Use \edef + \fpeval so the
2578 % per-variable min/max accessors are expanded to numeric literals
2579 % before the fp parser sees them.
2580 \def\ymin{inf}
2581 \def\ymax{-inf}
2582 \clist_map_inline:Nn \l__numodel_yshort_clist
2583 {
2584 \tl_set:Ne \l__numodel_yfull_tl { \l__numodel_eff_prefix_tl ##1 }
2585 \edef\ymin{\fpeval{min(\ymin,\use:c{\l__numodel_yfull_tl min})}}
2586 \edef\ymax{\fpeval{max(\ymax,\use:c{\l__numodel_yfull_tl max})}}
2587 }
2588 % --- y-axis label: comma-joined display texts, common unit -----
2589 \tl_clear:N \l__numodel_yqty_tl
2590 \int_zero:N \l__numodel_yidx_int
2591 \clist_map_inline:Nn \l__numodel_yshort_clist
2592 {
2593 \int_incr:N \l__numodel_yidx_int
2594 \int_compare:nNnF { \l__numodel_yidx_int } = { 1 }
2595 { \tl_put_right:Nn \l__numodel_yqty_tl { ,~ } }
2596 \tl_put_right:Ne \l__numodel_yqty_tl
2597 { \use:c { \l__numodel_eff_prefix_tl ##1 text } }
2598 }
2599 \edef\ylabelqty{\tl_use:N \l__numodel_yqty_tl}
2600 \edef\ylabelunit{\tl_use:N \l__numodel_yunit_first_tl}
2601 \begin{figure}[H]
2602 \centering
2603 \group_begin:
2604 \__numodel_apply_dsep:
2605 % --- Build the plot body ---------------------------------------
2606 \int_compare:nNnTF
2607 { \clist_count:N \l__numodel_yshort_clist } = { 1 }
2608 {
2609 % Single-series: preserve the legacy mark-only rendering.
2610 \edef\dm@coords
2611 { \mcoordsp{\l__numodel_eff_prefix_tl}{#2}{\tl_use:N \l_tmpa_tl} }
2612 \__numodel_draw_plot:n
2613 {
2614 \addplot[only~marks,~mark=*,~mark~size=0.5pt]~coordinates~{\dm@coords};
2615 \addlegendentry{model~point}
2616 #4
2617 }
2618 }
2619 {
2620 % Multi-series: one mark-only \addplot per kept variable, with
2621 % cycling colour-blind safe colour, and a text legend. The
2622 % legend's mark is enlarged so the colour stays visible there.
2623 \tl_clear:N \l__numodel_plotbody_tl
2624 \int_zero:N \l__numodel_yidx_int
2625 \clist_map_inline:Nn \l__numodel_yshort_clist
2626 {
2627 \int_incr:N \l__numodel_yidx_int
2628 \tl_put_right:Ne \l__numodel_plotbody_tl
2629 {
2630 \exp_not:N \addplot
2631 [ only~marks ,~mark=* ,~mark~size=0.5pt ,
2632 color = \__numodel_series_color:n
2633 { \int_use:N \l__numodel_yidx_int } ,
2634 legend~image~post~style = { mark~size=2pt } ]
2635 coordinates {
2636 \mcoordsp { \l__numodel_eff_prefix_tl } { #2 } { ##1 }
2637 } ;
2638 \exp_not:N \addlegendentry
2639 { $ \use:c { \l__numodel_eff_prefix_tl ##1 text } $ }
2640 }
2641 }
2642 \tl_put_right:Nn \l__numodel_plotbody_tl {#4}
2643 \exp_args:NV \__numodel_draw_plot:n \l__numodel_plotbody_tl
2644 }
2645 \group_end:
2646 \caption{$\tl_use:N \l__numodel_yqty_tl$($\use:c{\l__numodel_xname_tl text}$)\text{-diagram}}
2647 % If the project-specific worksheet system is loaded, pick the
2648 % '-ws' label inside a worksheet; otherwise always the bare label.
2649 \cs_if_exist:NTF \ifinworksheet
2650 { \ifinworksheet{\label{fig:#5-ws}}{\label{fig:#5}} }
2651 { \label{fig:#5} }
2652 \end{figure}
2653 }
2654
2655 \ExplSyntaxOff
2656
2657 % ============================================================
2658 % GRAPHIC MODEL - STYLES AND MACROS
2659 % ============================================================
2660 %
2661 % Forrester-diagram conventions:
2662 %
2663 % Stock [stock] Rectangle v, s, T, x
2664 % Valve / inflow [valve] Circle on a thick a, dv, ds
2665 % flow pipe
2666 % Auxiliary [aux] Plain circle F_res, F_air
2667 % Constant \constnode Circle + dashes m, k, g
2668 %
2669 % Use \dgridx and \dgridy as the grid spacings for consistent positioning.
2670 % ============================================================
2671
2672 % === Grid spacing -- defaults set via \numodelsetup {graphscalex, graphscaley} ===
2673
2674 % === Styles ===
2675 \tikzset{
2676 % Scale coordinates to the grid spacing
2677 gridscale/.style={x=\dgridx cm, y=\dgridy cm},
2678 % Stock (state variable): rectangle
2679 stock/.style={
2680 rectangle, draw, thick,
2681 minimum width=3 em,
2682 minimum height=2 em,
2683 font=\small
2684 },
2685 % Auxiliary (intermediate variable): plain circle
2686 aux/.style={
2687 circle, draw, thick,
2688 inner sep=2pt,
2689 minimum size=2 em,
2690 font=\scriptsize
2691 },
2692 % Constant: circle (dashes drawn by the \constnode macro)
2693 const/.style={
2694 circle, draw, thick,
2695 inner sep=2pt,
2696 minimum size=2 em,
2697 font=\scriptsize
2698 },
2699 % Valve (legacy alias): circle on the flow pipe. Kept for
2700 % backwards compatibility with user code that calls \flowarrow
2701 % manually. The package's emit helpers now pick one of the
2702 % style variants below based on \numodelsetup{valve-style=...}.
2703 valve/.style={
2704 circle, draw, thick, fill=white,
2705 minimum size=2 em,
2706 font=\small
2707 },
2708 % Valve variant: Forrester valve symbol -- two filled triangles
2709 % (white inside) whose tips meet at the centre. The symmetry
2710 % axis stands perpendicular to the (horizontal) flow. The
2711 % bounding box is tall and narrow so the apex angle at the
2712 % centre is roughly 60 degrees (sharper than the 90 degrees of
2713 % a square box), and the horizontal "ribs" along the top and
2714 % bottom edges close the two triangles.
2715 valve-forrester/.style={
2716 shape=rectangle,
2717 draw=none, fill=none,
2718 inner sep=0pt, outer sep=0pt,
2719 %minimum width=\dgridx*0.18 cm,
2720 minimum width=1 em,
2721 %minimum height=\dgridy*0.30 cm,
2722 minimum height=2 em,
2723 path picture={%
2724 \draw[thick, fill=white]
2725 (path picture bounding box.north west) --
2726 (path picture bounding box.north east) --
2727 (path picture bounding box.center) --
2728 cycle;
2729 \draw[thick, fill=white]
2730 (path picture bounding box.south west) --
2731 (path picture bounding box.south east) --
2732 (path picture bounding box.center) --
2733 cycle;
2734 }
2735 },
2736 % Valve variant: empty circle (no label).
2737 valve-circle/.style={
2738 circle, draw, thick, fill=white,
2739 minimum size=2 em,
2740 font=\small
2741 },
2742 % Valve variant: circle with the variable's display label inside.
2743 valve-edu/.style={
2744 circle, draw, thick, fill=white,
2745 minimum size=2 em,
2746 font=\small
2747 },
2748 % Flow pipe variants (body without arrow tip, used for the
2749 % segment from open-end / cloud to the valve):
2750 flowpipe/.style={line width=3pt}, % legacy alias
2751 flowpipe-filled/.style={line width=3pt},
2752 flowpipe-hollow/.style={
2753 line width=1pt,
2754 double=white, double distance=3pt
2755 },
2756 % Flow pipe variants WITH arrow tip (used for the segment from
2757 % valve to stock, or the open-end side of an outflow). Both
2758 % variants use the Stealth arrow tip. The hollow form
2759 % uses the double-line magic length 0pt-3-0 so that the arrow
2760 % tip merges cleanly with the gap between the two strokes.
2761 flowpipe-filled-tip/.style={line width=3pt, arrows={-Stealth[inset=0pt, angle=30:1em]}},
2762 flowpipe-hollow-tip/.style={
2763 line width=1pt,
2764 double=white, double distance=3pt,
2765 arrows={-Stealth[inset=0pt, angle=30:1em]}
2766 },
2767 % Flow pipe variants with the Cloud arrow tip on the open end:
2768 % inflow keeps the Stealth arrow head at the stock side.
2769 flowpipe-filled-cloudin/.style={
2770 line width=3pt,
2771 arrows={Cloud[fill=white, line width=0.8pt]-Stealth[inset=0pt, angle=30:1em]}
2772 },
2773 flowpipe-hollow-cloudin/.style={
2774 line width=1pt,
2775 double=white, double distance=3pt,
2776 arrows={Cloud[fill=white, line width=0.8pt]-Stealth[inset=0pt, angle=30:1em]}
2777 },
2778 % Outflow with cloud at the open end: first a Stealth tip at the
2779 % line end, then the cloud behind it (in arrows.meta spec, list
2780 % multiple tips separated by a dot so the shaft stops at the
2781 % Stealth tip and does not extend into the cloud; order = from
2782 % line outwards, hence Stealth.Cloud).
2783 flowpipe-filled-cloudout/.style={
2784 line width=3pt,
2785 arrows={-{Stealth[inset=0pt, angle=30:1em].Cloud[fill=white, line width=0.8pt]}}
2786 },
2787 flowpipe-hollow-cloudout/.style={
2788 line width=1pt,
2789 double=white, double distance=3pt,
2790 arrows={-{Stealth[inset=0pt, angle=30:1em].Cloud[fill=white, line width=0.8pt]}}
2791 },
2792 % Causal arrow (thin arrow for dependencies)
2793 causal/.style={thick, arrows={-Stealth[length=0.5em]}}
2794 }
2795
2796 % Default values for the body / tip macros so a manual call to
2797 % \flowarrow (outside \graphicmodel) keeps working. The
2798 % \graphicmodel pipeline overwrites these per render.
2799 \providecommand{\nmflowbody}{flowpipe-filled}
2800 \providecommand{\nmflowtip}{flowpipe-filled-tip}
2801 \providecommand{\nmflowtipcloudin}{flowpipe-filled-cloudin}
2802 \providecommand{\nmflowtipcloudout}{flowpipe-filled-cloudout}
2803
2804 % === Macro: constant node with dashes ===
2805 % Usage: \constnode{name}{(x,y)}{$label$}
2806 \newcommand{\constnode}[3]{%
2807 \node[const] (#1) at (#2) {#3};%
2808 \draw[thick] ([xshift=-3mm]#1.west) -- (#1.west);%
2809 \draw[thick] (#1.east) -- ([xshift=3mm]#1.east);%
2810 }
2811
2812 % === Macro: flow pipe with valve (inflow) ===
2813 % Draws ONE continuous flow arrow ending at the stock. The starting
2814 % position is the same regardless of cloud presence; passing any
2815 % non-blank optional argument switches to the cloud-tipped variant
2816 % so the arrow's tail becomes a white-filled cloud (drawn as a real
2817 % PGF arrow tip, not a separate node — moves with the line). The
2818 % valve overlays the middle of the arrow as a separate white-filled
2819 % node drawn later by the build pipeline.
2820 % Style keys: \nmflowtip / \nmflowtipcloudin.
2821 % Usage: \flowarrow[<any>]{<valve-coord>}{<stock-node>}
2822 \NewDocumentCommand{\flowarrow}{ O{} m m }{%
2823 \IfBlankTF{#1}{%
2824 \draw[\nmflowtip] ([xshift=-3em]#2) -- ([xshift=0.5mm]#3.west);%
2825 }{%
2826 \draw[\nmflowtipcloudin] ([xshift=-3em]#2) -- ([xshift=0.5mm]#3.west);%
2827 }%
2828 }
2829
2830 % === Macro: flow pipe with valve (outflow) ===
2831 % Mirror of \flowarrow. The arrow always ends at the same offset
2832 % past the valve coordinate; passing a non-blank optional argument
2833 % switches to the cloud-tipped variant (cloud at the open end).
2834 % Usage: \flowoutarrow[<any>]{<stock-node>}{<valve-coord>}
2835 \NewDocumentCommand{\flowoutarrow}{ O{} m m }{%
2836 \IfBlankTF{#1}{%
2837 \draw[\nmflowtip] (#2.east) -- ([xshift=4em]#3);%
2838 }{%
2839 \draw[\nmflowtipcloudout] (#2.east) -- ([xshift=5em]#3);%
2840 }%
2841 }
2842
2843 % === Macro: flow pipe between two stocks ===
2844 % One continuous arrow from source stock through valve coord into
2845 % target stock. No cloud option (no open end exists when both
2846 % sides are stocks).
2847 % Usage: \flowbetweenarrow{<source-stock>}{<valve-coord>}{<target-stock>}
2848 \newcommand{\flowbetweenarrow}[3]{%
2849 \draw[\nmflowtip] (#1.east) -- ([xshift=0.5mm]#3.west);%
2850 }
2851
2852 % === Macro: curved inflow branch for a shared valve ===
2853 % Used when one inflow valve feeds more than one stock. The primary
2854 % target is drawn with the standard straight \flowarrow; every
2855 % secondary target is drawn with this macro, which arcs UNDER the
2856 % intervening stock(s). Stocks sit on the bottom row of the
2857 % Forrester diagram, so the area below is empty -- routing the
2858 % branch below avoids collisions with the aux/const rows and the
2859 % causal arrows that live above. Both endpoints are passed
2860 % unanchored so TikZ picks the border-intersection that best
2861 % matches the curve's tangent at each end.
2862 % Usage: \flowarrowbent{<valve-coord>}{<target-stock>}
2863 \newcommand{\flowarrowbent}[2]{%
2864 \draw[\nmflowtip] (#1) to[bend right=30] (#2);%
2865 }
2866
2867 % === Macro: curved outflow branch for a shared valve ===
2868 % Mirror of \flowarrowbent. Used when one outflow valve drains more
2869 % than one stock. Routes the branch BELOW the intervening stocks
2870 % (same rationale as the inflow variant: nothing else lives below
2871 % the stocks row). Endpoints unanchored so TikZ chooses the
2872 % cleanest border intersection.
2873 % Usage: \flowoutarrowbent{<source-stock>}{<valve-coord>}
2874 \newcommand{\flowoutarrowbent}[2]{%
2875 \draw[\nmflowtip] (#1) to[bend right=30] (#2);%
2876 }
2877 %</package>
2878 % \end{macrocode}
2879 %
2880 % \subsection{Translation files}
2881 %
2882 % Each |numodel-<LANG>.def| file populates the lookup table consulted
2883 % by |\__numodel_kw:n|. The package loads exactly the file matching
2884 % the current |syntax| key, via |\InputIfFileExists| (and hence
2885 % |kpse|), so additional languages can be supplied through
2886 % |TEXMFHOME/tex/latex/numodel/numodel-<LANG>.def| with no package
2887 % rebuild. The two shipped files follow.
2888 %
2889 % \subsubsection{\texttt{numodel-EN.def} -- English (XMILE)}
2890 %
2891 % XMILE v1.0 OASIS style: ALL-CAPS, case sensitive. Sets the default
2892 % decimal mark to |point|.
2893 %
2894 % \begin{macrocode}
2895 %<*EN>
2896 \ProvidesExplFile{numodel-EN.def}{2026/05/26}{0.6.0}
2897 {numodel~keyword~table~--~English~(XMILE)}
2898 \cs_new:Npn \__numodel_kw_EN_if: { IF~ }
2899 \cs_new:Npn \__numodel_kw_EN_then: { ~THEN~ }
2900 \cs_new:Npn \__numodel_kw_EN_then_nl: { ~THEN }
2901 \cs_new:Npn \__numodel_kw_EN_else: { ~ELSE~ }
2902 \cs_new:Npn \__numodel_kw_EN_else_nl: { ELSE }
2903 \cs_new:Npn \__numodel_kw_EN_endif: { ~ENDIF }
2904 \cs_new:Npn \__numodel_kw_EN_endif_nl: { ENDIF }
2905 \cs_new:Npn \__numodel_kw_EN_and: { ~AND~ }
2906 \cs_new:Npn \__numodel_kw_EN_or: { ~OR~ }
2907 \cs_new:Npn \__numodel_kw_EN_not: { NOT~ }
2908 \cs_new:Npn \__numodel_kw_EN_sign: { SIGN }
2909 \cs_new:Npn \__numodel_kw_EN_abs: { ABS }
2910 \cs_new:Npn \__numodel_kw_EN_sqrt: { SQRT }
2911 \cs_new:Npn \__numodel_kw_EN_exp: { EXP }
2912 \cs_new:Npn \__numodel_kw_EN_ln: { LN }
2913 \cs_new:Npn \__numodel_kw_EN_sin: { SIN }
2914 \cs_new:Npn \__numodel_kw_EN_cos: { COS }
2915 \cs_new:Npn \__numodel_kw_EN_tan: { TAN }
2916 \cs_new:Npn \__numodel_kw_EN_asin: { ARCSIN }
2917 \cs_new:Npn \__numodel_kw_EN_acos: { ARCCOS }
2918 \cs_new:Npn \__numodel_kw_EN_stop: { ~STOP~ }
2919 \cs_new:Npn \__numodel_kw_EN_th_model: { model }
2920 \cs_new:Npn \__numodel_kw_EN_th_initvals: { initial~values }
2921 \cs_new:Npn \__numodel_kw_EN_contfoot: { Continued~on~next~page }
2922 \cs_new:Npn \__numodel_kw_EN_conthead: { (Continued) }
2923 \cs_new:Npn \__numodel_kw_EN_dsep_default: { point }
2924 %</EN>
2925 % \end{macrocode}
2926 %
2927 % \subsubsection{\texttt{numodel-NL.def} -- Dutch (CoachTaal)}
2928 %
2929 % CoachTaal convention. Sets the default decimal mark to |comma|.
2930 %
2931 % \begin{macrocode}
2932 %<*NL>
2933 \ProvidesExplFile{numodel-NL.def}{2026/05/26}{0.6.0}
2934 {numodel~keyword~table~--~Dutch~(CoachTaal)}
2935 \cs_new:Npn \__numodel_kw_NL_if: { Als~ }
2936 \cs_new:Npn \__numodel_kw_NL_then: { ~Dan~ }
2937 \cs_new:Npn \__numodel_kw_NL_then_nl: { ~Dan }
2938 \cs_new:Npn \__numodel_kw_NL_else: { ~Anders~ }
2939 \cs_new:Npn \__numodel_kw_NL_else_nl: { Anders }
2940 \cs_new:Npn \__numodel_kw_NL_endif: { ~EindAls }
2941 \cs_new:Npn \__numodel_kw_NL_endif_nl: { EindAls }
2942 \cs_new:Npn \__numodel_kw_NL_and: { ~EN~ }
2943 \cs_new:Npn \__numodel_kw_NL_or: { ~OF~ }
2944 \cs_new:Npn \__numodel_kw_NL_not: { NIET~ }
2945 \cs_new:Npn \__numodel_kw_NL_sign: { Teken }
2946 \cs_new:Npn \__numodel_kw_NL_abs: { Abs }
2947 \cs_new:Npn \__numodel_kw_NL_sqrt: { Sqrt }
2948 \cs_new:Npn \__numodel_kw_NL_exp: { Exp }
2949 \cs_new:Npn \__numodel_kw_NL_ln: { Ln }
2950 \cs_new:Npn \__numodel_kw_NL_sin: { Sin }
2951 \cs_new:Npn \__numodel_kw_NL_cos: { Cos }
2952 \cs_new:Npn \__numodel_kw_NL_tan: { Tan }
2953 \cs_new:Npn \__numodel_kw_NL_asin: { Arcsin }
2954 \cs_new:Npn \__numodel_kw_NL_acos: { Arccos }
2955 \cs_new:Npn \__numodel_kw_NL_stop: { ~Stop~ }
2956 \cs_new:Npn \__numodel_kw_NL_th_model: { model }
2957 \cs_new:Npn \__numodel_kw_NL_th_initvals: { startwaarden }
2958 \cs_new:Npn \__numodel_kw_NL_contfoot: { Wordt~vervolgd~op~volgende~pagina }
2959 \cs_new:Npn \__numodel_kw_NL_conthead: { (Vervolg) }
2960 \cs_new:Npn \__numodel_kw_NL_dsep_default: { comma }
2961 %</NL>
2962 % \end{macrocode}
2963 %
2964 % \Finale
2965 \endinput