@johnhenry/mallory-cli 0.0.0-stage → 0.1.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (760) hide show
  1. package/README.md +60 -2
  2. package/bin/mallory.mjs +51 -0
  3. package/package.json +51 -4
  4. package/src/a2a/client.js +511 -0
  5. package/src/a2a/demo-agent.js +396 -0
  6. package/src/a2a/hub.js +578 -0
  7. package/src/a2a/settings.js +88 -0
  8. package/src/a2a/task.js +358 -0
  9. package/src/acp/client.js +573 -0
  10. package/src/acp/demo-agent.js +332 -0
  11. package/src/acp/hub.js +632 -0
  12. package/src/acp/settings.js +78 -0
  13. package/src/actions/map.js +524 -0
  14. package/src/agent/cloud.js +77 -0
  15. package/src/agent/compact.js +84 -0
  16. package/src/agent/constants.js +39 -0
  17. package/src/agent/diff.js +101 -0
  18. package/src/agent/fork.js +159 -0
  19. package/src/agent/grounding.js +73 -0
  20. package/src/agent/guards.js +129 -0
  21. package/src/agent/local-transport.js +152 -0
  22. package/src/agent/loop.js +479 -0
  23. package/src/agent/park-store.js +77 -0
  24. package/src/agent/park.js +76 -0
  25. package/src/agent/ports.js +28 -0
  26. package/src/agent/providers.js +591 -0
  27. package/src/agent/restart.js +51 -0
  28. package/src/agent/router.js +380 -0
  29. package/src/agent/run.js +861 -0
  30. package/src/agent/tools.js +247 -0
  31. package/src/agent-library/engine.js +43 -0
  32. package/src/ai/bridge.js +155 -0
  33. package/src/ai/policy.js +131 -0
  34. package/src/aimatey/vendor.js +18 -0
  35. package/src/audio/container-duration.js +35 -0
  36. package/src/audio/instruments.js +776 -0
  37. package/src/audio/lanes.js +230 -0
  38. package/src/audio/patch.js +1410 -0
  39. package/src/audio/plan.js +276 -0
  40. package/src/audio/rack.js +1006 -0
  41. package/src/audio/sample-trim.js +293 -0
  42. package/src/audio/soundfont.js +243 -0
  43. package/src/audio/take-store.js +87 -0
  44. package/src/audio/takes.js +129 -0
  45. package/src/audio/wav.js +170 -0
  46. package/src/audio/zzfx.js +333 -0
  47. package/src/autonomy/bundle.js +207 -0
  48. package/src/autonomy/confine.js +61 -0
  49. package/src/autonomy/enforce.js +155 -0
  50. package/src/autonomy/file-kv.js +88 -0
  51. package/src/autonomy/ledger.js +203 -0
  52. package/src/autonomy/pins.js +50 -0
  53. package/src/autonomy/psl/index.js +32 -0
  54. package/src/autonomy/psl/suffixes.json +1 -0
  55. package/src/autonomy/record.js +28 -0
  56. package/src/autonomy/routines.js +107 -0
  57. package/src/autonomy/server.js +175 -0
  58. package/src/autonomy/signer-node.js +167 -0
  59. package/src/autonomy/store.js +43 -0
  60. package/src/autonomy/unattended.js +13 -0
  61. package/src/bytes/bytes.js +378 -0
  62. package/src/calc/syntax.js +125 -0
  63. package/src/calc/tex.js +28 -0
  64. package/src/calendar/vendor.js +2 -0
  65. package/src/clipboard.js +130 -0
  66. package/src/clsh/clsh.js +3417 -0
  67. package/src/codec/capnp.js +1804 -0
  68. package/src/codec/core.js +2043 -0
  69. package/src/codec/vendor/avro.js +136 -0
  70. package/src/codec/vendor/cbor.js +25 -0
  71. package/src/codec/vendor/flatbuffers.js +206 -0
  72. package/src/codec/vendor/msgpack.js +9 -0
  73. package/src/codec/vendor/protobuf.js +53 -0
  74. package/src/delegation/caps.js +60 -0
  75. package/src/delegation/config.js +32 -0
  76. package/src/device/model.js +246 -0
  77. package/src/device/recording.js +198 -0
  78. package/src/device/stream-model.js +151 -0
  79. package/src/documents/documents.js +1224 -0
  80. package/src/effects/catalog.js +63 -0
  81. package/src/effects/extras.js +133 -0
  82. package/src/effects/parse.js +339 -0
  83. package/src/embed/protocol.js +131 -0
  84. package/src/env/env.js +159 -0
  85. package/src/exact/vendor.js +45 -0
  86. package/src/example-meta.js +164 -0
  87. package/src/examples.js +94 -0
  88. package/src/export/canvas-image.js +217 -0
  89. package/src/export/expr-latex-lazy.js +8 -0
  90. package/src/export/formats.js +322 -0
  91. package/src/export/latex.js +183 -0
  92. package/src/export/pane.js +184 -0
  93. package/src/export/value.js +452 -0
  94. package/src/export/zip.js +214 -0
  95. package/src/ext/access.js +58 -0
  96. package/src/ext/btasks.js +225 -0
  97. package/src/ext/client.js +209 -0
  98. package/src/ext/tools.js +69 -0
  99. package/src/ext/view.js +105 -0
  100. package/src/ext/webmcp-tabs.js +299 -0
  101. package/src/files/archive.js +232 -0
  102. package/src/files/files.js +317 -0
  103. package/src/formats/json.js +24 -0
  104. package/src/formats/jupyter.js +188 -0
  105. package/src/formats/markdown.js +254 -0
  106. package/src/formats/n8n.js +276 -0
  107. package/src/formats/node-red.js +363 -0
  108. package/src/formats/registry.js +177 -0
  109. package/src/formats/rivet.js +259 -0
  110. package/src/formats/shared.js +98 -0
  111. package/src/formats/structure.js +182 -0
  112. package/src/formats/yaml.js +127 -0
  113. package/src/frame/frame.js +962 -0
  114. package/src/frame/vendor.js +1484 -0
  115. package/src/gate/audit.js +116 -0
  116. package/src/gate/gate.js +365 -0
  117. package/src/gate/policy.js +295 -0
  118. package/src/gate/scripted.js +110 -0
  119. package/src/gate/seams.js +32 -0
  120. package/src/gate/store.js +66 -0
  121. package/src/geometry/model.js +533 -0
  122. package/src/grant-key.js +149 -0
  123. package/src/graph/model.js +381 -0
  124. package/src/headless/a2a-push.js +123 -0
  125. package/src/headless/channels/config.js +142 -0
  126. package/src/headless/channels/connectors.js +283 -0
  127. package/src/headless/channels/index.js +257 -0
  128. package/src/headless/channels/mail.js +197 -0
  129. package/src/headless/channels/mailnet.js +223 -0
  130. package/src/headless/channels/platforms.js +194 -0
  131. package/src/headless/channels/replay.js +49 -0
  132. package/src/headless/cli.js +1397 -0
  133. package/src/headless/companion-client.js +182 -0
  134. package/src/headless/cost-cli.js +177 -0
  135. package/src/headless/deprecations-cli.js +102 -0
  136. package/src/headless/examples.js +48 -0
  137. package/src/headless/ffmpeg-exec.js +217 -0
  138. package/src/headless/gateways/config.js +213 -0
  139. package/src/headless/gateways/homeassistant.js +159 -0
  140. package/src/headless/gateways/index.js +121 -0
  141. package/src/headless/gateways/matter.js +150 -0
  142. package/src/headless/gateways/mqtt-client.js +177 -0
  143. package/src/headless/gateways/mqtt.js +70 -0
  144. package/src/headless/gateways/netway.js +226 -0
  145. package/src/headless/gateways/serverpod-worker.mjs +16 -0
  146. package/src/headless/gateways/serverpod.js +71 -0
  147. package/src/headless/gateways/util.js +27 -0
  148. package/src/headless/grant-cli.js +208 -0
  149. package/src/headless/guard.js +125 -0
  150. package/src/headless/guards.js +124 -0
  151. package/src/headless/machine-cli.js +853 -0
  152. package/src/headless/mcp-endpoint.js +287 -0
  153. package/src/headless/mcp-roots.js +38 -0
  154. package/src/headless/model-endpoint.js +88 -0
  155. package/src/headless/net.js +151 -0
  156. package/src/headless/node.js +263 -0
  157. package/src/headless/npm-tarball.js +29 -0
  158. package/src/headless/operator-page.js +112 -0
  159. package/src/headless/operator.js +242 -0
  160. package/src/headless/people.js +34 -0
  161. package/src/headless/pkg-cli.js +1103 -0
  162. package/src/headless/pkg-serve.js +138 -0
  163. package/src/headless/process-worker.js +88 -0
  164. package/src/headless/runner-remote.js +477 -0
  165. package/src/headless/sandbox-child.mjs +21 -0
  166. package/src/headless/scheduled.js +557 -0
  167. package/src/headless/serve-stream.js +97 -0
  168. package/src/headless/serve.js +2238 -0
  169. package/src/headless/short-links.js +158 -0
  170. package/src/headless/static-dirs.js +207 -0
  171. package/src/headless/trust-file.js +51 -0
  172. package/src/headless/watch.js +291 -0
  173. package/src/headless/ws-connect.js +65 -0
  174. package/src/headless/ws-connections.js +44 -0
  175. package/src/headless/ws-echo.js +150 -0
  176. package/src/headless/ws-proxy.js +354 -0
  177. package/src/headless/ws-ticket.js +48 -0
  178. package/src/hooks/config.js +50 -0
  179. package/src/hooks/engine.js +189 -0
  180. package/src/input/log.js +613 -0
  181. package/src/input/player.js +217 -0
  182. package/src/input/replay.js +209 -0
  183. package/src/jth/vendor.js +28 -0
  184. package/src/ledger/tx.js +94 -0
  185. package/src/machine/apply.js +193 -0
  186. package/src/machine/diff.js +168 -0
  187. package/src/machine/drive.js +296 -0
  188. package/src/machine/engine.js +478 -0
  189. package/src/machine/files-tool.js +76 -0
  190. package/src/machine/lint.js +139 -0
  191. package/src/machine/llmtm-trace.js +117 -0
  192. package/src/machine/llmtm.js +475 -0
  193. package/src/machine/otel.js +80 -0
  194. package/src/machine/pane-provider.js +51 -0
  195. package/src/machine/propose.js +159 -0
  196. package/src/machine/random.js +52 -0
  197. package/src/machine/risk.js +107 -0
  198. package/src/machine/session.js +1017 -0
  199. package/src/machine/shell-tool.js +45 -0
  200. package/src/machine/tape.js +349 -0
  201. package/src/machine/templates.js +104 -0
  202. package/src/machine/trace.js +664 -0
  203. package/src/machine/view.js +73 -0
  204. package/src/machine/vm-tool.js +47 -0
  205. package/src/machine/watchdog.js +46 -0
  206. package/src/mcp/app-args.js +51 -0
  207. package/src/mcp/app-run.js +56 -0
  208. package/src/mcp/apps.js +468 -0
  209. package/src/mcp/cache.js +232 -0
  210. package/src/mcp/client.js +507 -0
  211. package/src/mcp/demo-app.js +183 -0
  212. package/src/mcp/demo-server.js +602 -0
  213. package/src/mcp/elicitation.js +116 -0
  214. package/src/mcp/hub.js +1326 -0
  215. package/src/mcp/roots.js +139 -0
  216. package/src/mcp/sampling.js +105 -0
  217. package/src/mcp/settings.js +125 -0
  218. package/src/mcp/tape.js +292 -0
  219. package/src/mcp/uri-template.js +156 -0
  220. package/src/mcp/wsh-client.js +164 -0
  221. package/src/media/animated-codec.js +7 -0
  222. package/src/media/animated.js +623 -0
  223. package/src/media/compare-agent.js +70 -0
  224. package/src/media/compare-job.js +63 -0
  225. package/src/media/compare-page.js +296 -0
  226. package/src/media/compare-worker.js +14 -0
  227. package/src/media/compare.js +600 -0
  228. package/src/media/contract.js +62 -0
  229. package/src/media/decode-frame.js +57 -0
  230. package/src/media/decode-pool.js +188 -0
  231. package/src/media/ffmpeg-edit.js +344 -0
  232. package/src/media/ffmpeg-wasm-client.js +121 -0
  233. package/src/media/ffmpeg-wasm-session.js +79 -0
  234. package/src/media/ffmpeg-wasm.js +139 -0
  235. package/src/media/ffmpeg-worker.js +23 -0
  236. package/src/media/ffmpeg.js +903 -0
  237. package/src/media/helpers.js +419 -0
  238. package/src/media/keep.js +108 -0
  239. package/src/media/metadata-worker.js +16 -0
  240. package/src/media/metadata.js +2518 -0
  241. package/src/media/mime.js +102 -0
  242. package/src/media/page-decode.js +74 -0
  243. package/src/media/persist.js +114 -0
  244. package/src/media/png.js +226 -0
  245. package/src/media/sample-input.js +67 -0
  246. package/src/media/store.js +86 -0
  247. package/src/media/wav.js +109 -0
  248. package/src/midi/mappings.js +250 -0
  249. package/src/midi/message.js +125 -0
  250. package/src/model/action-hub.js +143 -0
  251. package/src/model/adapters.js +284 -0
  252. package/src/model/agent-runs.js +12 -0
  253. package/src/model/arrange.js +308 -0
  254. package/src/model/automation-clock.js +494 -0
  255. package/src/model/automation.js +653 -0
  256. package/src/model/batches.js +78 -0
  257. package/src/model/binary-view.js +195 -0
  258. package/src/model/breakpoints.js +392 -0
  259. package/src/model/calc-settings.js +65 -0
  260. package/src/model/calendar.js +254 -0
  261. package/src/model/canvas-id.js +5 -0
  262. package/src/model/canvas.js +5048 -0
  263. package/src/model/channel-names.js +29 -0
  264. package/src/model/channels.js +692 -0
  265. package/src/model/chart-clock.js +631 -0
  266. package/src/model/chart-code.js +69 -0
  267. package/src/model/codecs.js +60 -0
  268. package/src/model/companion-access.js +271 -0
  269. package/src/model/companion-pane.js +50 -0
  270. package/src/model/composite.js +324 -0
  271. package/src/model/context.js +380 -0
  272. package/src/model/controls.js +231 -0
  273. package/src/model/converter-presets.js +368 -0
  274. package/src/model/cost.js +580 -0
  275. package/src/model/curve-transform.js +122 -0
  276. package/src/model/cycles.js +176 -0
  277. package/src/model/debug-log.js +168 -0
  278. package/src/model/decision-clock.js +100 -0
  279. package/src/model/decisions.js +265 -0
  280. package/src/model/desk.js +87 -0
  281. package/src/model/device-hub.js +400 -0
  282. package/src/model/diff.js +445 -0
  283. package/src/model/emit-events.js +179 -0
  284. package/src/model/errors.js +238 -0
  285. package/src/model/event-presets.js +297 -0
  286. package/src/model/events.js +1303 -0
  287. package/src/model/explicit-setters.js +139 -0
  288. package/src/model/field-mapping.js +623 -0
  289. package/src/model/files-pane.js +263 -0
  290. package/src/model/flow-idle.js +89 -0
  291. package/src/model/foreach.js +549 -0
  292. package/src/model/frame-loop.js +71 -0
  293. package/src/model/frame-pressure.js +180 -0
  294. package/src/model/function-scaffold.js +1000 -0
  295. package/src/model/geometry-settings.js +54 -0
  296. package/src/model/goals.js +176 -0
  297. package/src/model/graph-settings.js +76 -0
  298. package/src/model/grid-widget.js +175 -0
  299. package/src/model/groups.js +332 -0
  300. package/src/model/hash.js +21 -0
  301. package/src/model/history.js +259 -0
  302. package/src/model/http-copy.js +88 -0
  303. package/src/model/http-send-companion.js +110 -0
  304. package/src/model/http-send.js +163 -0
  305. package/src/model/http-tap.js +521 -0
  306. package/src/model/http-tools.js +1138 -0
  307. package/src/model/import-lock.js +78 -0
  308. package/src/model/imports.js +258 -0
  309. package/src/model/infer-outputs.js +822 -0
  310. package/src/model/ink-connect.js +150 -0
  311. package/src/model/ink-diff.js +75 -0
  312. package/src/model/ink-gone.js +71 -0
  313. package/src/model/ink-route.js +120 -0
  314. package/src/model/ink-svg.js +206 -0
  315. package/src/model/ink.js +739 -0
  316. package/src/model/input-log-hub.js +456 -0
  317. package/src/model/input-split.js +69 -0
  318. package/src/model/json-schema-host.js +9 -0
  319. package/src/model/json-schema.js +368 -0
  320. package/src/model/jth.js +78 -0
  321. package/src/model/latex-expr.js +528 -0
  322. package/src/model/layout-history.js +120 -0
  323. package/src/model/lazy-map.js +88 -0
  324. package/src/model/ledger-pane.js +101 -0
  325. package/src/model/legacy-viaframe.js +90 -0
  326. package/src/model/lessons.js +448 -0
  327. package/src/model/links.js +981 -0
  328. package/src/model/live.js +411 -0
  329. package/src/model/math-widget.js +53 -0
  330. package/src/model/memory-settings.js +33 -0
  331. package/src/model/midi-controls.js +350 -0
  332. package/src/model/nl-time.js +408 -0
  333. package/src/model/notebook.js +137 -0
  334. package/src/model/pane-view-store.js +15 -0
  335. package/src/model/partial.js +115 -0
  336. package/src/model/pause-clock.js +53 -0
  337. package/src/model/peer-pane.js +32 -0
  338. package/src/model/persist-state.js +290 -0
  339. package/src/model/person-only.js +122 -0
  340. package/src/model/pin.js +209 -0
  341. package/src/model/plot-3d.js +213 -0
  342. package/src/model/plot-series.js +157 -0
  343. package/src/model/plot-settings.js +531 -0
  344. package/src/model/ports.js +312 -0
  345. package/src/model/presentation.js +222 -0
  346. package/src/model/preset-apply.js +316 -0
  347. package/src/model/preset-banks.js +335 -0
  348. package/src/model/preset-morph.js +263 -0
  349. package/src/model/preset-ops.js +205 -0
  350. package/src/model/preset-player.js +283 -0
  351. package/src/model/preset-states.js +172 -0
  352. package/src/model/profile-settings.js +109 -0
  353. package/src/model/promote.js +103 -0
  354. package/src/model/protected.js +10 -0
  355. package/src/model/proxy-log.js +230 -0
  356. package/src/model/proxy.js +367 -0
  357. package/src/model/quantity-widget.js +61 -0
  358. package/src/model/queue-book.js +359 -0
  359. package/src/model/quick-add.js +224 -0
  360. package/src/model/rate-limit.js +313 -0
  361. package/src/model/rate.js +95 -0
  362. package/src/model/recovery.js +216 -0
  363. package/src/model/rename-follow.js +113 -0
  364. package/src/model/repeater.js +1126 -0
  365. package/src/model/retention.js +664 -0
  366. package/src/model/route-edit.js +132 -0
  367. package/src/model/router.js +155 -0
  368. package/src/model/runaway.js +232 -0
  369. package/src/model/runlog.js +1033 -0
  370. package/src/model/runners/a2a.js +2 -0
  371. package/src/model/runners/acp.js +2 -0
  372. package/src/model/runners/actions.js +4 -0
  373. package/src/model/runners/agent.js +4 -0
  374. package/src/model/runners/audio.js +21 -0
  375. package/src/model/runners/automation.js +2 -0
  376. package/src/model/runners/calc.js +23 -0
  377. package/src/model/runners/catch.js +10 -0
  378. package/src/model/runners/codec.js +24 -0
  379. package/src/model/runners/companion-run.js +2 -0
  380. package/src/model/runners/device.js +7 -0
  381. package/src/model/runners/dom.js +13 -0
  382. package/src/model/runners/effects.js +2 -0
  383. package/src/model/runners/embed.js +11 -0
  384. package/src/model/runners/eval.js +2 -0
  385. package/src/model/runners/files.js +19 -0
  386. package/src/model/runners/geometry.js +23 -0
  387. package/src/model/runners/goals.js +18 -0
  388. package/src/model/runners/graph.js +23 -0
  389. package/src/model/runners/html.js +2 -0
  390. package/src/model/runners/http-proxy.js +185 -0
  391. package/src/model/runners/http-send.js +61 -0
  392. package/src/model/runners/http-static.js +83 -0
  393. package/src/model/runners/http-tap.js +26 -0
  394. package/src/model/runners/http.js +40 -0
  395. package/src/model/runners/import.js +2 -0
  396. package/src/model/runners/index.js +74 -0
  397. package/src/model/runners/input.js +14 -0
  398. package/src/model/runners/inputlog.js +7 -0
  399. package/src/model/runners/ledger.js +15 -0
  400. package/src/model/runners/machine.js +4 -0
  401. package/src/model/runners/mcp.js +2 -0
  402. package/src/model/runners/mcpapp.js +2 -0
  403. package/src/model/runners/media.js +18 -0
  404. package/src/model/runners/memory.js +28 -0
  405. package/src/model/runners/mesh-inspect.js +13 -0
  406. package/src/model/runners/peer.js +14 -0
  407. package/src/model/runners/plot.js +22 -0
  408. package/src/model/runners/render.js +14 -0
  409. package/src/model/runners/respond.js +2 -0
  410. package/src/model/runners/sample-soundfont.js +85 -0
  411. package/src/model/runners/sample.js +159 -0
  412. package/src/model/runners/scene.js +8 -0
  413. package/src/model/runners/score.js +24 -0
  414. package/src/model/runners/secret.js +10 -0
  415. package/src/model/runners/select.js +2 -0
  416. package/src/model/runners/shared.js +4 -0
  417. package/src/model/runners/shares.js +15 -0
  418. package/src/model/runners/shell.js +7 -0
  419. package/src/model/runners/skill.js +26 -0
  420. package/src/model/runners/state.js +2 -0
  421. package/src/model/runners/statechart.js +4 -0
  422. package/src/model/runners/subgraph.js +9 -0
  423. package/src/model/runners/tabs.js +25 -0
  424. package/src/model/runners/terminal.js +5 -0
  425. package/src/model/runners/text.js +4 -0
  426. package/src/model/runners/timer.js +7 -0
  427. package/src/model/runners/traffic.js +65 -0
  428. package/src/model/runners/trigger.js +2 -0
  429. package/src/model/runners/verdict.js +29 -0
  430. package/src/model/runners/vm.js +7 -0
  431. package/src/model/runners/wait.js +4 -0
  432. package/src/model/runners/ws-client.js +57 -0
  433. package/src/model/safe-regex.js +719 -0
  434. package/src/model/sample-settings.js +43 -0
  435. package/src/model/sample-source.js +47 -0
  436. package/src/model/saved-mapping.js +153 -0
  437. package/src/model/score-controllers.js +87 -0
  438. package/src/model/score-edit.js +399 -0
  439. package/src/model/score-instruments.js +300 -0
  440. package/src/model/score-library.js +407 -0
  441. package/src/model/score-markup.js +235 -0
  442. package/src/model/score-mix.js +248 -0
  443. package/src/model/score-patterns.js +276 -0
  444. package/src/model/score-selection.js +34 -0
  445. package/src/model/score-time.js +139 -0
  446. package/src/model/score-transforms.js +336 -0
  447. package/src/model/score-transport.js +192 -0
  448. package/src/model/selection.js +351 -0
  449. package/src/model/serial-controls.js +328 -0
  450. package/src/model/shares-pane.js +17 -0
  451. package/src/model/shell-pane.js +106 -0
  452. package/src/model/signature.js +1122 -0
  453. package/src/model/size-hints.js +106 -0
  454. package/src/model/size-ratio.js +12 -0
  455. package/src/model/skill-settings.js +23 -0
  456. package/src/model/snapping.js +466 -0
  457. package/src/model/split.js +375 -0
  458. package/src/model/spring-player.js +222 -0
  459. package/src/model/statecharts.js +1369 -0
  460. package/src/model/states-preset.js +208 -0
  461. package/src/model/static-route.js +100 -0
  462. package/src/model/step-words.js +45 -0
  463. package/src/model/subgraph.js +1042 -0
  464. package/src/model/switch.js +98 -0
  465. package/src/model/tabs-store.js +10 -0
  466. package/src/model/tensor-view.js +146 -0
  467. package/src/model/timer-clock.js +361 -0
  468. package/src/model/timers.js +422 -0
  469. package/src/model/timing.js +212 -0
  470. package/src/model/traffic-agent.js +111 -0
  471. package/src/model/traffic-store.js +20 -0
  472. package/src/model/traffic.js +665 -0
  473. package/src/model/transport.js +364 -0
  474. package/src/model/turns.js +86 -0
  475. package/src/model/types.js +425 -0
  476. package/src/model/value-path.js +138 -0
  477. package/src/model/versions.js +535 -0
  478. package/src/model/view-outputs.js +144 -0
  479. package/src/model/viewport-bookmarks.js +194 -0
  480. package/src/model/virtual-clock.js +85 -0
  481. package/src/model/vm-pane.js +258 -0
  482. package/src/model/wait-clock.js +715 -0
  483. package/src/model/wait-persist.js +248 -0
  484. package/src/model/waits.js +431 -0
  485. package/src/model/watch.js +80 -0
  486. package/src/model/webhook.js +496 -0
  487. package/src/model/when.js +48 -0
  488. package/src/model/widget-values.js +392 -0
  489. package/src/model/window-commands.js +278 -0
  490. package/src/model/windows.js +348 -0
  491. package/src/model/wire-inspect.js +343 -0
  492. package/src/model/wire-ops.js +324 -0
  493. package/src/model/wire-pipeline.js +378 -0
  494. package/src/model/wire-route.js +637 -0
  495. package/src/model/workspaces.js +122 -0
  496. package/src/model/ws-client.js +155 -0
  497. package/src/model/ws-demo.js +31 -0
  498. package/src/model/ws-frames.js +141 -0
  499. package/src/model/ws-hub.js +219 -0
  500. package/src/model/ws-served.js +13 -0
  501. package/src/model/xstate.js +374 -0
  502. package/src/narrative/narrative.js +1557 -0
  503. package/src/network/auth.js +224 -0
  504. package/src/network/csp-frame.js +197 -0
  505. package/src/network/declarative-shadow.js +27 -0
  506. package/src/network/frame-net-shim.js +962 -0
  507. package/src/network/hosts.js +157 -0
  508. package/src/network/policy.js +520 -0
  509. package/src/network/rtc-shim.js +418 -0
  510. package/src/network/secret-gate.js +78 -0
  511. package/src/network/secrets.js +261 -0
  512. package/src/network/sockets.js +287 -0
  513. package/src/network/store.js +186 -0
  514. package/src/network/streams.js +99 -0
  515. package/src/packages/asset-values.js +50 -0
  516. package/src/packages/assets.js +99 -0
  517. package/src/packages/deprecation.js +203 -0
  518. package/src/packages/fetch.js +152 -0
  519. package/src/packages/function-canvas.js +73 -0
  520. package/src/packages/module.js +120 -0
  521. package/src/packages/package.js +474 -0
  522. package/src/packages/published.js +27 -0
  523. package/src/packages/requires.js +83 -0
  524. package/src/packages/signing.js +145 -0
  525. package/src/packages/trust.js +107 -0
  526. package/src/panes/a2a.js +51 -0
  527. package/src/panes/acp.js +60 -0
  528. package/src/panes/actions.js +54 -0
  529. package/src/panes/agent.js +83 -0
  530. package/src/panes/audio.js +103 -0
  531. package/src/panes/automation.js +112 -0
  532. package/src/panes/calc.js +67 -0
  533. package/src/panes/catch.js +52 -0
  534. package/src/panes/codec.js +59 -0
  535. package/src/panes/colors.js +12 -0
  536. package/src/panes/companion.js +54 -0
  537. package/src/panes/decision.js +65 -0
  538. package/src/panes/device.js +56 -0
  539. package/src/panes/dom.js +37 -0
  540. package/src/panes/effects.js +118 -0
  541. package/src/panes/embed.js +30 -0
  542. package/src/panes/eval.js +186 -0
  543. package/src/panes/fields.js +299 -0
  544. package/src/panes/files.js +45 -0
  545. package/src/panes/gate.js +70 -0
  546. package/src/panes/geometry.js +64 -0
  547. package/src/panes/goals.js +75 -0
  548. package/src/panes/graph.js +66 -0
  549. package/src/panes/html.js +54 -0
  550. package/src/panes/http.js +82 -0
  551. package/src/panes/import.js +38 -0
  552. package/src/panes/input.js +124 -0
  553. package/src/panes/inputlog.js +66 -0
  554. package/src/panes/ledger.js +56 -0
  555. package/src/panes/machine.js +138 -0
  556. package/src/panes/mcp.js +85 -0
  557. package/src/panes/mcpapp.js +64 -0
  558. package/src/panes/media.js +38 -0
  559. package/src/panes/memory.js +46 -0
  560. package/src/panes/mesh-inspect.js +49 -0
  561. package/src/panes/note.js +38 -0
  562. package/src/panes/peer.js +44 -0
  563. package/src/panes/plot.js +196 -0
  564. package/src/panes/registry.js +475 -0
  565. package/src/panes/render.js +87 -0
  566. package/src/panes/respond.js +44 -0
  567. package/src/panes/router.js +84 -0
  568. package/src/panes/sample.js +75 -0
  569. package/src/panes/scene.js +55 -0
  570. package/src/panes/score.js +87 -0
  571. package/src/panes/secret.js +38 -0
  572. package/src/panes/select.js +67 -0
  573. package/src/panes/shader.js +166 -0
  574. package/src/panes/shared.js +33 -0
  575. package/src/panes/shares.js +43 -0
  576. package/src/panes/shell.js +47 -0
  577. package/src/panes/skill.js +44 -0
  578. package/src/panes/state.js +91 -0
  579. package/src/panes/statechart.js +63 -0
  580. package/src/panes/story.js +33 -0
  581. package/src/panes/subgraph.js +94 -0
  582. package/src/panes/tabs.js +52 -0
  583. package/src/panes/terminal.js +57 -0
  584. package/src/panes/text.js +36 -0
  585. package/src/panes/timer.js +55 -0
  586. package/src/panes/traffic.js +59 -0
  587. package/src/panes/verdict.js +62 -0
  588. package/src/panes/vm.js +46 -0
  589. package/src/panes/wait.js +61 -0
  590. package/src/panes/watch.js +57 -0
  591. package/src/panes/webhook.js +67 -0
  592. package/src/panes/ws-client.js +67 -0
  593. package/src/persist.js +281 -0
  594. package/src/plot/tex.js +19 -0
  595. package/src/plot/vendor.js +59 -0
  596. package/src/plot/view-vendor.js +5 -0
  597. package/src/privacy/levels.js +108 -0
  598. package/src/protocol/devtools.js +116 -0
  599. package/src/protocol/inspector.js +368 -0
  600. package/src/render/time.js +381 -0
  601. package/src/rooms/mesh-metrics.js +162 -0
  602. package/src/run/companion.js +355 -0
  603. package/src/run/describe.js +114 -0
  604. package/src/run/local-model.js +150 -0
  605. package/src/run/monitor.js +208 -0
  606. package/src/run/publish.js +360 -0
  607. package/src/run/respond-outcome.js +12 -0
  608. package/src/run/run.js +820 -0
  609. package/src/run/runner-pairing.js +243 -0
  610. package/src/run/values.js +122 -0
  611. package/src/runtime/compile.js +122 -0
  612. package/src/runtime/console-tag.js +64 -0
  613. package/src/runtime/frame-signals.js +126 -0
  614. package/src/runtime/iteration-push.js +19 -0
  615. package/src/runtime/keys.js +474 -0
  616. package/src/runtime/midi-input.js +170 -0
  617. package/src/runtime/person-waits.js +140 -0
  618. package/src/runtime/resource-timing.js +56 -0
  619. package/src/runtime/runtime.js +2150 -0
  620. package/src/runtime/sandbox-modules.js +163 -0
  621. package/src/runtime/spring.js +246 -0
  622. package/src/runtime/strict.js +215 -0
  623. package/src/runtime/transfer.js +75 -0
  624. package/src/runtime/tween.js +158 -0
  625. package/src/runtime/wasm-fuel.js +596 -0
  626. package/src/runtime/worker/00-prelude.js +88 -0
  627. package/src/runtime/worker/10-helpers.js +295 -0
  628. package/src/runtime/worker/20-io.js +645 -0
  629. package/src/runtime/worker/30-previews.js +210 -0
  630. package/src/runtime/worker/40-profile-lineage.js +278 -0
  631. package/src/runtime/worker/50-own-worker.js +233 -0
  632. package/src/runtime/worker/60-timers.js +172 -0
  633. package/src/runtime/worker/70-state-keyed.js +193 -0
  634. package/src/runtime/worker/80-each-compile-generators.js +619 -0
  635. package/src/runtime/worker/90-events-operators.js +655 -0
  636. package/src/runtime/worker/95-agents-batches.js +1820 -0
  637. package/src/runtime/worker/96-plot.js +47 -0
  638. package/src/runtime/worker/97-calc.js +28 -0
  639. package/src/runtime/worker/98-geometry.js +24 -0
  640. package/src/runtime/worker/99-graph.js +30 -0
  641. package/src/runtime/worker/99-shell.js +30 -0
  642. package/src/safety/config.js +57 -0
  643. package/src/safety/engine.js +324 -0
  644. package/src/scene/pixi-scene.js +806 -0
  645. package/src/scene/scene-assets.js +241 -0
  646. package/src/scene/scene-edit.js +319 -0
  647. package/src/secret/settings.js +41 -0
  648. package/src/security/multipart.js +257 -0
  649. package/src/security/redact.js +261 -0
  650. package/src/serial/broker.js +473 -0
  651. package/src/serial/config.js +185 -0
  652. package/src/serial/framers.js +389 -0
  653. package/src/serial/packets.js +64 -0
  654. package/src/shader/audio-texture.js +87 -0
  655. package/src/shader/channels.js +496 -0
  656. package/src/shader/common.js +90 -0
  657. package/src/shader/model.js +867 -0
  658. package/src/shader/passes.js +150 -0
  659. package/src/shader/shadertoy.js +198 -0
  660. package/src/shell/hub.js +287 -0
  661. package/src/sim/checkpoints.js +850 -0
  662. package/src/sim/compile.js +37 -0
  663. package/src/sim/fixed.js +377 -0
  664. package/src/sim/headless.js +205 -0
  665. package/src/sim/physics.js +399 -0
  666. package/src/smf-helper/vendor.js +2 -0
  667. package/src/sources/config.js +435 -0
  668. package/src/storage.js +153 -0
  669. package/src/table/table-geo.js +2344 -0
  670. package/src/table/table-lineage.js +808 -0
  671. package/src/table/table-quality.js +355 -0
  672. package/src/table/table-schema.js +392 -0
  673. package/src/table/table-sql.js +1650 -0
  674. package/src/table/table-stats.js +480 -0
  675. package/src/table/table.js +2102 -0
  676. package/src/tensor/tensor.js +1153 -0
  677. package/src/terminal/hub.js +715 -0
  678. package/src/terminal/screen.js +516 -0
  679. package/src/tests/capture.js +88 -0
  680. package/src/tests/compare.js +480 -0
  681. package/src/tests/dataset.js +170 -0
  682. package/src/tests/evaluate.js +286 -0
  683. package/src/tests/from-runs.js +99 -0
  684. package/src/tests/judge.js +134 -0
  685. package/src/tests/matchers.js +263 -0
  686. package/src/tests/matrix-spec.js +87 -0
  687. package/src/tests/matrix.js +397 -0
  688. package/src/tests/metrics.js +369 -0
  689. package/src/tests/no-value.js +42 -0
  690. package/src/tests/pane-check.js +45 -0
  691. package/src/tests/report.js +124 -0
  692. package/src/tests/reporters.js +140 -0
  693. package/src/tests/run.js +155 -0
  694. package/src/tilemap/tilemap.js +1122 -0
  695. package/src/units/units.js +3 -0
  696. package/src/util/bytes-text.js +21 -0
  697. package/src/util/num.js +10 -0
  698. package/src/util/regexp.js +2 -0
  699. package/src/util/text.js +38 -0
  700. package/src/verdict/engine.js +154 -0
  701. package/src/vm/guest-wsh.js +108 -0
  702. package/src/vm/hub.js +457 -0
  703. package/src/vm/image-files.js +4 -0
  704. package/src/vm/image.js +33 -0
  705. package/src/vm/image.lock.json +13 -0
  706. package/src/vm/link.js +266 -0
  707. package/src/vm/mount.js +212 -0
  708. package/src/vm/net.js +85 -0
  709. package/src/vm/pipe-ws.js +187 -0
  710. package/src/vm/v86-loader.js +11 -0
  711. package/src/webmcp/args.js +212 -0
  712. package/src/webmcp/hidden.js +218 -0
  713. package/src/webmcp/text.js +250 -0
  714. package/src/webmcp/tools/bookmark-tools.js +106 -0
  715. package/src/webmcp/tools/breakpoint-tools.js +48 -0
  716. package/src/webmcp/tools/canvases.js +208 -0
  717. package/src/webmcp/tools/context-tools.js +84 -0
  718. package/src/webmcp/tools/core.js +170 -0
  719. package/src/webmcp/tools/devices.js +41 -0
  720. package/src/webmcp/tools/edit.js +357 -0
  721. package/src/webmcp/tools/event-tools.js +145 -0
  722. package/src/webmcp/tools/image-tools.js +173 -0
  723. package/src/webmcp/tools/ink-tools.js +247 -0
  724. package/src/webmcp/tools/input-log-tools.js +163 -0
  725. package/src/webmcp/tools/live.js +166 -0
  726. package/src/webmcp/tools/machine-tools.js +74 -0
  727. package/src/webmcp/tools/media.js +161 -0
  728. package/src/webmcp/tools/midi-tools.js +32 -0
  729. package/src/webmcp/tools/preset-tools.js +184 -0
  730. package/src/webmcp/tools/quick-add-tools.js +95 -0
  731. package/src/webmcp/tools/reshape.js +152 -0
  732. package/src/webmcp/tools/run-tools.js +309 -0
  733. package/src/webmcp/tools/runs.js +101 -0
  734. package/src/webmcp/tools/scaffold-tools.js +161 -0
  735. package/src/webmcp/tools/serial-tools.js +36 -0
  736. package/src/webmcp/tools/shared.js +338 -0
  737. package/src/webmcp/tools/subgraphs.js +360 -0
  738. package/src/webmcp/tools/tests.js +170 -0
  739. package/src/webmcp/tools/traffic-tools.js +70 -0
  740. package/src/webmcp/tools/transport-tools.js +65 -0
  741. package/src/webmcp/tools/version-tools.js +126 -0
  742. package/src/webmcp/tools/versions.js +11 -0
  743. package/src/webmcp/tools/wire-tools.js +90 -0
  744. package/src/webmcp/tools/workspace-tools.js +93 -0
  745. package/src/webmcp/tools.js +1323 -0
  746. package/src/wsh/connect.js +347 -0
  747. package/src/wsh/demo-host.js +361 -0
  748. package/src/wsh/e2e.js +27 -0
  749. package/src/wsh/keys.js +154 -0
  750. package/src/wsh/known-hosts.js +39 -0
  751. package/src/wsh/private-key.js +95 -0
  752. package/src/wsh/reverse.js +34 -0
  753. package/src/wsh/settings.js +118 -0
  754. package/src/wsh/transfer.js +62 -0
  755. package/src/wsh/vendor.js +5 -0
  756. package/src/x402/challenge.js +171 -0
  757. package/src/x402/demo-server.js +127 -0
  758. package/src/x402/pay.js +125 -0
  759. package/src/x402/retry.js +95 -0
  760. package/src/x402/store.js +76 -0
@@ -0,0 +1,59 @@
1
+ /*! mallory plot: src/plot/source.js with @johnhenry/math-sample@0.1.0 (MIT) and @johnhenry/math@0.3.0 (MIT), bundled into one ES module by scripts/build-plot-vendor.mjs. Do not edit. */
2
+ var wt=class extends Error{constructor(){super("sampling cancelled"),this.name="SampleCancelledError"}},yi=256,xi=4,bi=.001,wi=1e-4,vi=.5,Mi=.8;function tn(e,t){if(!Number.isFinite(e.min)||!Number.isFinite(e.max)||!(e.max>e.min))throw new RangeError(`domain must be finite with min < max, got [${e.min}, ${e.max}]`);if(!Number.isInteger(t)||t<2)throw new RangeError(`resolution must be an integer >= 2, got ${t}`)}function en(e,t){let{signal:r,isCancelled:n}=t;if(!r&&!n)return e;let s=0,o=()=>{if(r?.aborted||n?.())throw new wt};return o(),i=>(++s%yi===0&&o(),e(i))}function Hr(e,t){if(!t)return!1;let r=t.max-t.min;return Math.abs(e)>Math.abs(t.min)+Math.abs(t.max)+5*r}function ns(e,t,r,n,s){if(!s||!Number.isFinite(t)||!Number.isFinite(n)||t===n)return null;let o=s.max-s.min,i=n>t?s.max-.03*o:s.min+.03*o,a=(i-t)/(n-t);return!Number.isFinite(a)||a<0||a>1?null:[e+a*(r-e),i]}function ss(e,t,r){let n=[],s=[],o=!1,i=0,a=0,c=!1;for(let u=0;u<e.length;u++){let l=e[u],f=t[u],h=Number.isFinite(f),m=h&&!Hr(f,r);if(m){if(!o&&c){let p=ns(i,a,l,f,r);p&&(n.push(p[0]),s.push(p[1]))}n.push(l),s.push(f)}else if(s.length>0&&!Number.isNaN(s[s.length-1])){if(o&&h){let p=ns(i,a,l,f,r);p&&(n.push(p[0]),s.push(p[1]))}n.push(l),s.push(Number.NaN)}i=l,a=f,o=m,c=!0}return s.length>0&&Number.isNaN(s[s.length-1])&&(n.pop(),s.pop()),{x:Float64Array.from(n),y:Float64Array.from(s)}}function wr(e,t,r,n={}){tn(t,r);let s=en(e,n),o=new Array(r),i=new Array(r),a=t.max-t.min;for(let c=0;c<r;c++){let u=c===r-1?t.max:t.min+c/(r-1)*a;o[c]=u,i[c]=s(u)}return ss(o,i,n.visibleYRange)}function ye(e,t,r,n={}){tn(t,r);let s=n.visibleYRange,o=n.maxDepth??xi,i=n.tolerance??(s?(s.max-s.min)*wi:bi),a=n.jumpFraction??(s?vi:Number.POSITIVE_INFINITY),c=s?a*(s.max-s.min):Number.POSITIVE_INFINITY,u=en(e,n),l=[],f=[],h=(d,w,g,M,v,N)=>{if(!Number.isFinite(w)||!Number.isFinite(M)||Hr(w,s)||Hr(M,s)){l.push(d),f.push(w);return}if(v>=o){l.push(d),f.push(w);let S=Math.abs(M-w);S>c&&S>=Mi*N&&(l.push((d+g)/2),f.push(Number.NaN));return}let $=(d+g)/2,b=u($);if(!Number.isFinite(b)){l.push(d,$),f.push(w,b);return}if(Math.abs(b-(w+M)/2)<=i){l.push(d),f.push(w);return}let x=Math.abs(M-w);h(d,w,$,b,v+1,x),h($,b,g,M,v+1,x)},m=t.max-t.min,p=t.min,y=u(p);for(let d=1;d<r;d++){let w=d===r-1?t.max:t.min+d/(r-1)*m,g=u(w);h(p,y,w,g,0,Number.POSITIVE_INFINITY),p=w,y=g}return l.push(p),f.push(y),ss(l,f,s)}function rn(e){let t=[],r=-1;for(let n=0;n<e.y.length;n++)Number.isNaN(e.y[n])?(r>=0&&t.push([r,n]),r=-1):r<0&&(r=n);return r>=0&&t.push([r,e.y.length]),t}function er(e,t,r={}){let n=r.resolution??1e3;tn(t,n);let s=en(e,r),o=t.max-t.min,i=[],a=t.min,c=s(a);c===0&&i.push(a);for(let u=1;u<n;u++){let l=u===n-1?t.max:t.min+u/(n-1)*o,f=s(l);if(f===0)i.push(l);else if(Number.isFinite(c)&&Number.isFinite(f)&&c!==0&&c<0!=f<0){let h=a,m=l,p=c;for(let w=0;w<100;w++){let g=(h+m)/2;if(g===h||g===m)break;let M=s(g);if(M===0){h=m=g;break}p<0==M<0?(h=g,p=M):m=g}let y=(h+m)/2,d=s(y);Math.abs(d)<=Math.max(Math.abs(c),Math.abs(f))&&i.push(y)}a=l,c=f}return i}function rr(e,t,r,n={}){return er(s=>e(s)-t(s),r,n).map(s=>({x:s,y:e(s)}))}var Wt=class{start;spent=0;now;budget;cancel;constructor(t,r){this.budget=t,this.cancel=r,this.now=t?.now??(typeof performance<"u"?()=>performance.now():()=>Date.now()),this.start=this.now()}check(t){if(this.cancel?.signal?.aborted||this.cancel?.isCancelled?.())throw new wt;let r=this.budget;if(r?.maxCells!==void 0&&this.spent+t>r.maxCells)return"cells";if(r?.maxMillis!==void 0&&this.now()-this.start>r.maxMillis)return"time"}spend(t){this.spent+=t}get cells(){return this.spent}};function ne(e,t,r){return r===void 0?{rows:e,of:t,complete:e>=t}:{rows:e,of:t,complete:!1,reason:r}}function pt(e,t,r=2){if(!Number.isInteger(t)||t<r)throw new RangeError(`${e} must be an integer >= ${r}, got ${t}`)}function dt(e,t){if(!Number.isFinite(t.min)||!Number.isFinite(t.max)||!(t.min<t.max))throw new RangeError(`${e} must be finite with min < max`)}function nn(e,t,r,n={}){let s=n.width??128,o=n.height??128;pt("width",s,1),pt("height",o,1),dt("re domain",t),dt("im domain",r);let i=new Wt(n,n),a=new Float32Array(s*o).fill(Number.NaN),c=new Float32Array(s*o).fill(Number.NaN),u=new Float32Array(s*o).fill(Number.NaN),l=new Float32Array(s*o).fill(Number.NaN),f=0,h;for(let m=0;m<o&&(h=i.check(s),!h);m++){let p=r.min+(r.max-r.min)*(m+.5)/o;for(let y=0;y<s;y++){let d=t.min+(t.max-t.min)*(y+.5)/s,w=e(d,p),g=m*s+y;Number.isFinite(w[0])&&Number.isFinite(w[1])&&(a[g]=w[0],c[g]=w[1],u[g]=Math.hypot(w[0],w[1]),l[g]=Math.atan2(w[1],w[0]))}i.spend(s),f++}return{width:s,height:f,re:a.slice(0,s*f),im:c.slice(0,s*f),abs:u.slice(0,s*f),arg:l.slice(0,s*f),progress:ne(f,o,h)}}function sn(e,t,r,n={}){let s=n.reLines??11,o=n.imLines??11,i=n.samplesPerLine??200,a=n.bound??1e6;pt("reLines",s,1),pt("imLines",o,1),pt("samplesPerLine",i),dt("re domain",t),dt("im domain",r);let c=[],u=(l,f,h)=>{let m=[],p=[],y=!1,d=Number.NaN,w=Number.NaN;for(let g=0;g<i;g++){let M=g===i-1?h.max:h.min+(h.max-h.min)*g/(i-1),v=l==="re"?e(f,M):e(M,f);if(!(Number.isFinite(v[0])&&Number.isFinite(v[1])&&Math.hypot(v[0],v[1])<=a)){y=m.length>0,d=Number.NaN;continue}let $=n.maxStep!==void 0&&!Number.isNaN(d)&&Math.hypot(v[0]-d,v[1]-w)>n.maxStep;(y||$)&&m.length>0&&(m.push(Number.NaN),p.push(Number.NaN)),m.push(v[0]),p.push(v[1]),d=v[0],w=v[1],y=!1}return{kind:l,value:f,x:Float64Array.from(m),y:Float64Array.from(p)}};for(let l=0;l<s;l++)c.push(u("re",s===1?t.min:t.min+(t.max-t.min)*l/(s-1),r));for(let l=0;l<o;l++)c.push(u("im",o===1?r.min:r.min+(r.max-r.min)*l/(o-1),t));return c}var Ni=e=>{for(;e>Math.PI;)e-=2*Math.PI;for(;e<-Math.PI;)e+=2*Math.PI;return e};function on(e,t,r,n={}){let s=n.grid??24;pt("grid",s,1),dt("re domain",t),dt("im domain",r);let o=Math.max(t.max-t.min,r.max-r.min),i=(n.tolerance??1e-10)*o,a=new Wt(n,n),c=(t.max-t.min)/s,u=(r.max-r.min)/s,l=[],f=(b,x)=>{let S=e(b,x);return S[0]===0&&S[1]===0?Number.NaN:Math.atan2(S[1],S[0])},h=(b,x,S,O,A,F,k)=>{let I=Ni(F-S);if(k>=4&&Math.abs(I)<1||k>=14)return I;let E=(b+O)/2,P=(x+A)/2,j=f(E,P);return h(b,x,S,E,P,j,k+1)+h(E,P,j,O,A,F,k+1)},m=(b,x,S,O)=>{let A=[[b,x],[S,x],[S,O],[b,O],[b,x]],F=A.map(([I,E])=>f(I,E));if(F.some(I=>!Number.isFinite(I)))return Number.NaN;let k=0;for(let I=0;I<4;I++){let E=A[I],P=A[I+1];k+=h(E[0],E[1],F[I],P[0],P[1],F[I+1],0)}return Math.round(k/(2*Math.PI))},p=(b,x,S,O,A)=>{let F=(E,P)=>{let j=e(E,P);if(S==="zero")return[j[0],j[1]];let L=j[0]*j[0]+j[1]*j[1];return[j[0]/L,-j[1]/L]},k=b,I=x;for(let E=0;E<60;E++){let[P,j]=F(k,I);if(!Number.isFinite(P)||!Number.isFinite(j))return;let L=1e-7*Math.max(1,Math.abs(k),Math.abs(I)),[U,J]=F(k+L,I),Bt=(U-P)/L,Pt=(J-j)/L,mt=Bt*Bt+Pt*Pt;if(!(mt>0)||!Number.isFinite(mt))return;let Xt=O*(P*Bt+j*Pt)/mt,Gt=O*(j*Bt-P*Pt)/mt;if(k-=Xt,I-=Gt,Math.hypot(Xt,Gt)<i){let Jt=.5*Math.max(c,u);return k<A[0]-Jt||k>A[1]+Jt||I<A[2]-Jt||I>A[3]+Jt?void 0:[k,I]}if(!Number.isFinite(k)||!Number.isFinite(I))return}},y=.3819660112501051,d=t.min-(1-y)*c,w=r.min-(1-y)*u,g=s+1,M=1e-9*o,v=(b,x)=>b>=t.min-M&&b<=t.max+M&&x>=r.min-M&&x<=r.max+M,N=0,$;for(let b=0;b<g&&($=a.check(g*4),!$);b++){for(let x=0;x<g;x++){let S=d+x*c,O=w+b*u,A=m(S,O,S+c,O+u),F=0;if(Number.isNaN(A)&&(F=.0123*c,A=m(S-F,O-.0123*u,S+c+F,O+u+.0123*u)),!Number.isFinite(A)||A===0)continue;let k=A>0?"zero":"pole",I=Math.abs(A),E=S+c/2,P=O+u/2,j=p(E,P,k,I,[S,S+c,O,O+u]),[L,U]=j??[E,P];v(L,U)&&(l.some(J=>J.kind===k&&Math.hypot(J.re-L,J.im-U)<Math.max(i*1e3,1e-7*o))||l.push({re:L,im:U,kind:k,order:I,refined:j!==void 0}))}a.spend(g*4),N++}return l.sort((b,x)=>b.re-x.re||b.im-x.im),{items:l,progress:ne(N,g,$)}}var an=(e,t,r)=>Number.isFinite(e)&&Number.isFinite(t)&&Number.isFinite(r);function os(e,t,r,n,s,o){let i=n.columns??64,a=n.rows??64;pt("columns",i),pt("rows",a),dt("u domain",t),dt("v domain",r);let c=new Wt(n,n),u=new Float64Array(i*a*3).fill(Number.NaN),l=new Uint8Array(i*a),f=0,h;for(let b=0;b<a&&(h=c.check(i),!h);b++){let x=b===a-1?r.max:r.min+(r.max-r.min)*b/(a-1);for(let S=0;S<i;S++){let O=S===i-1?t.max:t.min+(t.max-t.min)*S/(i-1),A=e(O,x),F=b*i+S;an(A[0],A[1],A[2])&&!(s&&(A[2]<s.min||A[2]>s.max))&&(u[3*F]=A[0],u[3*F+1]=A[1],u[3*F+2]=A[2],l[F]=1)}c.spend(i),f++}let m=f,p=i*m,y=new Float32Array(p*3),d=new Float32Array(p*3),w=l.slice(0,p),g=[1/0,1/0,1/0],M=[-1/0,-1/0,-1/0];for(let b=0;b<p;b++)for(let x=0;x<3;x++){let S=u[3*b+x];y[3*b+x]=S,w[b]&&(S<g[x]&&(g[x]=S),S>M[x]&&(M[x]=S))}let v=(b,x)=>3*(x*i+b),N=(b,x)=>b>=0&&b<i&&x>=0&&x<m&&w[x*i+b]===1;for(let b=0;b<m;b++)for(let x=0;x<i;x++){if(!N(x,b))continue;let S=N(x-1,b)?x-1:x,O=N(x+1,b)?x+1:x,A=N(x,b-1)?b-1:b,F=N(x,b+1)?b+1:b,k=[0,1,2].map(U=>u[v(O,b)+U]-u[v(S,b)+U]),I=[0,1,2].map(U=>u[v(x,F)+U]-u[v(x,A)+U]),E=k[1]*I[2]-k[2]*I[1],P=k[2]*I[0]-k[0]*I[2],j=k[0]*I[1]-k[1]*I[0],L=Math.hypot(E,P,j);if(L>0&&Number.isFinite(L)){let U=(o?-1:1)/L;E*=U,P*=U,j*=U;let J=v(x,b);d[J]=E,d[J+1]=P,d[J+2]=j}}for(let b=0;b<m;b++)for(let x=0;x<i;x++){let S=v(x,b);if(!(!N(x,b)||d[S]!==0||d[S+1]!==0||d[S+2]!==0))for(let[O,A]of[[0,1],[0,-1],[1,0],[-1,0],[0,2],[0,-2]]){if(!N(x+O,b+A))continue;let F=v(x+O,b+A);if(d[F]!==0||d[F+1]!==0||d[F+2]!==0){d[S]=d[F],d[S+1]=d[F+1],d[S+2]=d[F+2];break}}}if(!w.some(b=>b===1))for(let b=0;b<3;b++)g[b]=Number.NaN,M[b]=Number.NaN;let $=[];for(let b=0;b+1<m;b++)for(let x=0;x+1<i;x++){let S=b*i+x,O=S+1,A=S+i,F=A+1,[k,I,E,P]=[w[S],w[O],w[A],w[F]];k&&I&&P&&$.push(S,O,F),k&&P&&E&&$.push(S,F,A),!(k&&I&&P)&&!(k&&P&&E)&&(k&&I&&E?$.push(S,O,A):I&&P&&E&&$.push(O,F,A))}return{positions:y,normals:d,indices:Uint32Array.from($),valid:w,vertexCount:p,columns:i,rows:m,bounds:{min:g,max:M},progress:ne(m,a,h)}}function vr(e,t,r,n={}){return os((s,o)=>[s,o,e(s,o)],t,r,n,n.zRange,!1)}function Mr(e,t,r,n={}){return os(e,t,r,{...n,zRange:void 0},void 0,!1)}function cn(e,t,r={}){let n=r.samples??512;pt("samples",n),dt("t domain",t);let s=new Wt(r,r),o=[],i=[],a=0,c,u=256;for(let p=0;p<n&&!(p%u===0&&(c=s.check(Math.min(u,n-p)),c));p++){let y=p===n-1?t.max:t.min+(t.max-t.min)*p/(n-1),d=e(y);i.push(y),o.push(an(d[0],d[1],d[2])?d[0]:Number.NaN,d[1],d[2]),s.spend(1),a++}let l=[],f=[],h,m=!1;for(let p=0;p<a;p++){let y=o[3*p];if(Number.isNaN(y)){m=l.length>0,h=void 0;continue}let d=o[3*p+1],w=o[3*p+2],g=m;h!==void 0&&r.maxStep!==void 0&&Math.hypot(y-o[3*h],d-o[3*h+1],w-o[3*h+2])>r.maxStep&&(g=!0),g&&l.length>0&&(l.push(Number.NaN,Number.NaN,Number.NaN),f.push(Number.NaN)),l.push(y,d,w),f.push(i[p]),h=p,m=!1}return{positions:Float64Array.from(l),t:Float64Array.from(f),count:f.length,progress:ne(a,n,c)}}function un(e){let t=[],r=-1;for(let n=0;n<e.count;n++)Number.isNaN(e.positions[3*n])?(r>=0&&t.push([r,n]),r=-1):r<0&&(r=n);return r>=0&&t.push([r,e.count]),t}function ln(e,t,r,n,s={}){let o=s.grid??8,[i,a,c]=typeof o=="number"?[o,o,o]:o;pt("grid",i),pt("grid",a),pt("grid",c),dt("x domain",t),dt("y domain",r),dt("z domain",n);let u=new Wt(s,s),l=[],f=[],h=[],m=0,p=0,y,d=(g,M,v)=>M===v-1?g.max:g.min+(g.max-g.min)*M/(v-1);for(let g=0;g<c&&(y=u.check(i*a),!y);g++){for(let M=0;M<a;M++)for(let v=0;v<i;v++){let N=d(t,v,i),$=d(r,M,a),b=d(n,g,c),x=e(N,$,b);if(!an(x[0],x[1],x[2])){m++;continue}l.push(N,$,b),f.push(x[0],x[1],x[2]),h.push(Math.hypot(x[0],x[1],x[2]))}u.spend(i*a),p++}let w=0;for(let g of h)g>w&&(w=g);return{origins:Float32Array.from(l),vectors:Float32Array.from(f),magnitudes:Float32Array.from(h),maxMagnitude:w,count:h.length,skipped:m,progress:ne(p,c,y)}}function mn(e,t,r,n={}){let s=n.columns??20,o=n.rows??20;pt("columns",s),pt("rows",o),dt("x domain",t),dt("y domain",r);let i=new Wt(n,n),a=s*o,c=new Float64Array(a),u=new Float64Array(a),l=new Float64Array(a).fill(Number.NaN),f=new Float64Array(a).fill(Number.NaN),h=new Float64Array(a).fill(Number.NaN),m=0,p;for(let d=0;d<o&&(p=i.check(s),!p);d++){let w=d===o-1?r.max:r.min+(r.max-r.min)*d/(o-1);for(let g=0;g<s;g++){let M=g===s-1?t.max:t.min+(t.max-t.min)*g/(s-1),v=d*s+g;c[v]=M,u[v]=w;let N=e(M,w);if(l[v]=N,!Number.isNaN(N))if(!Number.isFinite(N))f[v]=0,h[v]=N>0?1:-1;else{let $=Math.hypot(1,N);f[v]=1/$,h[v]=N/$}}i.spend(s),m++}let y=s*m;return{columns:s,rows:m,x:c.slice(0,y),y:u.slice(0,y),slope:l.slice(0,y),dirX:f.slice(0,y),dirY:h.slice(0,y),progress:ne(m,o,p)}}function is(e,t){for(let r of e)if(!Number.isFinite(r)||Math.abs(r)>t)return!0;return!1}function fn(e,t,r,n){return{t:Float64Array.from(e),y:Float64Array.from(t),dim:r,steps:e.length,reason:n}}function as(e){if(e.signal?.aborted||e.isCancelled?.())throw new wt}function $i(e,t,r,n){let s=r.length,o=e(t,r),i=e(t+n/2,r.map((l,f)=>l+n/2*o[f])),a=e(t+n/2,r.map((l,f)=>l+n/2*i[f])),c=e(t+n,r.map((l,f)=>l+n*a[f])),u=new Array(s);for(let l=0;l<s;l++)u[l]=r[l]+n/6*(o[l]+2*i[l]+2*a[l]+c[l]);return u}function cs(e,t,r,n,s={}){let o=s.steps??200;if(pt("steps",o,1),!Number.isFinite(t)||!Number.isFinite(n))throw new RangeError("t0 and tEnd must be finite");let i=s.blowup??1e12,a=Math.max(s.maxSteps??1e5,o+1),c=r.length,u=(n-t)/o,l=[t],f=[...r],h=r,m="end";for(let p=0;p<o;p++){if(l.length>=a){m="maxSteps";break}p%64===0&&as(s);let y=t+p*u,d=$i(e,y,h,u);if(is(d,i)){m="blowup";break}h=d;let w=p===o-1?n:t+(p+1)*u;if(l.push(w),f.push(...h),s.stop?.(w,h)){m="stopped";break}}return fn(l,f,c,m)}var Si=[0,1/5,3/10,4/5,8/9,1,1],Ei=[[],[1/5],[3/40,9/40],[44/45,-56/15,32/9],[19372/6561,-25360/2187,64448/6561,-212/729],[9017/3168,-355/33,46732/5247,49/176,-5103/18656],[35/384,0,500/1113,125/192,-2187/6784,11/84]],Ai=[35/384,0,500/1113,125/192,-2187/6784,11/84,0],Ii=[5179/57600,0,7571/16695,393/640,-92097/339200,187/2100,1/40];function Ae(e,t,r,n,s={}){if(!Number.isFinite(t)||!Number.isFinite(n))throw new RangeError("t0 and tEnd must be finite");let o=Math.abs(n-t),i=n>=t?1:-1,a=r.length,c=s.atol??1e-8,u=s.rtol??1e-6,l=s.blowup??1e12,f=s.maxSteps??1e5,h=s.hMin??o*1e-12,m=s.hMax??o,p=Math.min(s.h0??o/100,m),y=[t],d=[...r];if(o===0)return fn(y,d,a,"end");let w=t,g=r,M="end",v=0,N=0,$=Number.POSITIVE_INFINITY;for(;i*(n-w)>0;){if(y.length>=f||v++>f*20){M="maxSteps";break}if(v%64===0&&as(s),p<h){M="stepTooSmall";break}let b=i*(w+i*p-n)>=0,x=b?Math.abs(n-w):p,S=i*x,O=[];for(let E=0;E<7;E++){let P=g.map((j,L)=>{let U=0;for(let J=0;J<E;J++)U+=Ei[E]?.[J]*O[J][L];return j+S*U});O.push(e(w+Si[E]*S,P))}let A=g.map((E,P)=>E+S*Ai.reduce((j,L,U)=>j+L*O[U][P],0)),F=g.map((E,P)=>E+S*Ii.reduce((j,L,U)=>j+L*O[U][P],0));if(is(A,l)){if($>10&&(N=0),$=0,++N>12||x<=h*2){M="blowup";break}p=x/4;continue}let k=0;for(let E=0;E<a;E++){let P=c+u*Math.max(Math.abs(g[E]),Math.abs(A[E]));k=Math.max(k,Math.abs(A[E]-F[E])/P)}if((k<=1||x<=h)&&(w=b?n:w+S,g=A,$++,y.push(w),d.push(...g),s.stop?.(w,g))){M="stopped";break}let I=k===0?5:Math.min(5,Math.max(.2,.9*k**-.2));p=Math.min(m,x*I)}return fn(y,d,a,M)}function pn(e,t,r,n,s={}){dt("x domain",n);let o=(h,m)=>[e(h,m[0])],i=s.yLimit??1e6,a=h=>{let m={...s,blowup:i};return s.method==="rk4"?cs(o,t,[r],h,{...m,steps:s.steps??200}):Ae(o,t,[r],h,m)},c=[],u=[],l="end",f="end";if(t<n.min||t>n.max){let h=t<n.min?n.min:n.max,m=a(h);if(m.reason!=="end"){let p=m.reason;return{x:new Float64Array(0),y:new Float64Array(0),reasonBefore:p,reasonAfter:p}}t=h,r=m.y[m.steps-1]}if(t>n.min){let h=a(n.min);l=h.reason;for(let m=h.steps-1;m>=1;m--)c.push(h.t[m]),u.push(h.y[m])}if(c.push(t),u.push(r),t<n.max){let h=a(n.max);f=h.reason;for(let m=1;m<h.steps;m++)c.push(h.t[m]),u.push(h.y[m])}return{x:Float64Array.from(c),y:Float64Array.from(u),reasonBefore:l,reasonAfter:f}}function hn(e,t,r){let n=1e-6*Math.max(1,Math.abs(t),Math.abs(r)),s=e(t+n,r),o=e(t-n,r),i=e(t,r+n),a=e(t,r-n);return[[(s[0]-o[0])/(2*n),(i[0]-a[0])/(2*n)],[(s[1]-o[1])/(2*n),(i[1]-a[1])/(2*n)]]}function us(e,t=1e-7){let r=e[0][0]+e[1][1],n=e[0][0]*e[1][1]-e[0][1]*e[1][0],s=r*r-4*n,o=Math.max(1,Math.abs(r),Math.abs(n)),i;if(s>=0){let c=Math.sqrt(s);i=[[(r+c)/2,0],[(r-c)/2,0]]}else{let c=Math.sqrt(-s)/2;i=[[r/2,c],[r/2,-c]]}let a;return Math.abs(n)<=t*o?a="non-hyperbolic":n<0?a="saddle":Math.abs(r)<=t*o?a="center":s>t*o*o?a=r<0?"stable node":"unstable node":s>=-t*o*o?a=r<0?"stable star or degenerate node":"unstable star or degenerate node":a=r<0?"stable spiral":"unstable spiral",{trace:r,determinant:n,eigenvalues:i,type:a}}function dn(e,t,r,n={}){dt("x domain",t),dt("y domain",r);let s=n.grid??15,[o,i]=typeof s=="number"?[s,s]:s;pt("columns",o),pt("rows",i);let a=new Wt(n,n),c=o*i,u=new Float64Array(c),l=new Float64Array(c),f=new Float64Array(c).fill(Number.NaN),h=new Float64Array(c).fill(Number.NaN),m=new Float64Array(c).fill(Number.NaN),p=0,y;for(let A=0;A<i&&(y=a.check(o),!y);A++){let F=A===i-1?r.max:r.min+(r.max-r.min)*A/(i-1);for(let k=0;k<o;k++){let I=k===o-1?t.max:t.min+(t.max-t.min)*k/(o-1),E=A*o+k;u[E]=I,l[E]=F;let P=e(I,F);Number.isFinite(P[0])&&Number.isFinite(P[1])&&(f[E]=P[0],h[E]=P[1],m[E]=Math.hypot(P[0],P[1]))}a.spend(o),p++}let d=o*p,w={field:{columns:o,rows:p,x:u.slice(0,d),y:l.slice(0,d),u:f.slice(0,d),v:h.slice(0,d),magnitude:m.slice(0,d)},trajectories:[],fixedPoints:[],progress:ne(p,i,y)};if(y)return w;let g=t.max-t.min,M=r.max-r.min,v=n.margin??.5,N=(A,F)=>A>=t.min-v*g&&A<=t.max+v*g&&F>=r.min-v*M&&F<=r.max+v*M,$=(A,F)=>{let k=e(F[0],F[1]);return[k[0],k[1]]},b=n.tMax??10,x=n.seeds??Array.from({length:25},(A,F)=>[t.min+g*(F%5+.5)/5,r.min+M*(Math.floor(F/5)+.5)/5]);for(let A of x){let F={...n,stop:(j,L)=>!N(L[0],L[1]),hMax:b/20},k=Ae($,0,A,b,F),I=Ae($,0,A,-b,F),E=[],P=[];for(let j=I.steps-1;j>=1;j--)E.push(I.y[2*j]),P.push(I.y[2*j+1]);for(let j=0;j<k.steps;j++)E.push(k.y[2*j]),P.push(k.y[2*j+1]);w.trajectories.push({seed:A,x:Float64Array.from(E),y:Float64Array.from(P),reasonBefore:I.reason,reasonAfter:k.reason})}let S=n.fixedPointStarts??8,O=1e-8*Math.max(g,M);for(let A=0;A<S&&S>0;A++)for(let F=0;F<S;F++){let k=t.min+g*(A+.5)/S,I=r.min+M*(F+.5)/S,E=!1;for(let L=0;L<50;L++){let U=e(k,I);if(!Number.isFinite(U[0])||!Number.isFinite(U[1]))break;let J=hn(e,k,I),Bt=J[0][0]*J[1][1]-J[0][1]*J[1][0];if(!Number.isFinite(Bt)||Math.abs(Bt)<1e-14)break;let Pt=(J[1][1]*U[0]-J[0][1]*U[1])/Bt,mt=(-J[1][0]*U[0]+J[0][0]*U[1])/Bt;if(k-=Pt,I-=mt,Math.hypot(Pt,mt)<O){E=!0;break}}if(!E||!N(k,I)||k<t.min||k>t.max||I<r.min||I>r.max)continue;let P=e(k,I);if(Math.hypot(P[0],P[1])>1e-6||w.fixedPoints.some(L=>Math.hypot(L.x-k,L.y-I)<1e-5*Math.max(g,M)))continue;let j=hn(e,k,I);w.fixedPoints.push({x:k,y:I,jacobian:j,...us(j)})}return w.fixedPoints.sort((A,F)=>A.x-F.x||A.y-F.y),w}function gn(e,t,r,n=e.length-1){let s=Math.min(n,e.length-1),o=0;for(let i=s;i>=0;i--)o=o*(r-t)+e[i];return o}function yn(e,t,r){if(!Number.isInteger(t)||!Number.isInteger(r)||r<t)throw new RangeError("need integers from <= to");let n=new Float64Array(r-t+1),s=0;for(let a=t;a<=r;a++)s+=e(a),n[a-t]=s;let o=Number.NaN,i=n.length;if(i>=3){let a=n[i-3],c=n[i-2],u=n[i-1],l=u-2*c+a;o=l===0?u:u-(u-c)*(u-c)/l}return{partial:n,from:t,limitEstimate:o}}function xn(e,t,r,n=4096){dt("period",t),pt("terms",r,1),pt("samples",n,4);let s=(t.max-t.min)/2,o=(t.max+t.min)/2,i=new Float64Array(r),a=new Float64Array(r),c=new Float64Array(n);for(let l=0;l<n;l++)c[l]=e(t.min+(t.max-t.min)*(l+.5)/n);let u=0;for(let l=0;l<n;l++)u+=c[l];u=2*u/n;for(let l=1;l<=r;l++){let f=0,h=0;for(let m=0;m<n;m++){let p=Math.PI*l*((m+.5)/n*2-1);f+=c[m]*Math.cos(p),h+=c[m]*Math.sin(p)}i[l-1]=2*f/n,a[l-1]=2*h/n}return{halfPeriod:s,center:o,a0:u,a:i,b:a}}function Nr(e,t,r=e.a.length){let n=Math.min(r,e.a.length),s=Math.PI/e.halfPeriod,o=e.a0/2;for(let i=1;i<=n;i++){let a=i*s*(t-e.center);o+=e.a[i-1]*Math.cos(a)+e.b[i-1]*Math.sin(a)}return o}var T=class e extends Array{static Empty=new e;constructor(...t){t.length===1&&typeof t[0]=="number"?super(t[0]):super(...t)}static get[Symbol.species](){return Array}static fromArray(t){let r=new e;for(let n of t)r.push(n);return r}static fromXML(t){let r=new e;for(let n of t.matchAll(/<coordinate>(.*?)<\/coordinate>/g)){let s=n[1],o=Number(s);r.push(s!==""&&!Number.isNaN(o)?o:s)}return r}static fromString(t,r=",",n="[",s="]"){let o=t.trim();o.startsWith(n)&&(o=o.slice(n.length)),o.endsWith(s)&&(o=o.slice(0,o.length-s.length));let i=new e;if(o==="")return i;for(let a of o.split(r)){let c=a.trim(),u=Number(c);i.push(c!==""&&!Number.isNaN(u)?u:c)}return i}toString(t=",",r="[",n="]"){let s=r;for(let o=0;o<this.length;o++)s+=this[o]!=null?String(this[o]):String(null),o!==this.length-1&&(s+=t);return s+n}toXML(){let t=[];for(let r=0;r<this.length;r++)t.push(`<coordinate>${this[r]}</coordinate>`);return`<vector>${t.join("")}</vector>`}getElement(t=0){return this[t]}removeElement(t=0){return this.splice(t,1)[0]}setElement(t,r=0,n=null){for(;this.length<r;)this.push(n);let s=this[r];return this[r]=t,s}addElement(t=null,r=-1,n=null){if(r<0)return this.push(t);for(;r>this.length;)this.push(n);return this.splice(r,0,t),this.length}coord(t){return t<this.length&&this[t]!=null?this[t]:0}get x(){return this.coord(0)}get y(){return this.coord(1)}get z(){return this.coord(2)}get t(){return this.coord(3)}set x(t){this.setElement(t,0)}set y(t){this.setElement(t,1)}set z(t){this.setElement(t,2)}set t(t){this.setElement(t,3)}clone(t=!0){let r=new e;for(let n=0;n<this.length;n++){let s=this[n];r[n]=t&&s instanceof e?s.clone():s}return r}reversed(){let t=new e;for(let r=0;r<this.length;r++)t[r]=this[this.length-1-r];return t}};var D=class e{static isVector(t){return t instanceof T}static isNotVector(t){return!(t instanceof T)}static isMultiDimensional(t,r=e.isVector){for(let n of t)if(r(n))return!0;return!1}static contains(t,r,n){if(!n)return t.lastIndexOf(r)!==-1;for(let s of t)if(n(r,s))return!0;return!1}static longer(t,r){return t.length>=r.length?t:r}static shorter(t,r){return t.length>=r.length?r:t}static isNotMultiDimensional(t,r){return!e.isMultiDimensional(t,r??e.isVector)}static isFlat(t,r){return e.isNotMultiDimensional(t,r)}static arithmeticSequence(t=0,r=100,n=1){let s=new T,o=t;if(n>0)for(r<o&&(r=o);o<=r;)s.push(o),o+=n;else if(n<0)for(r>o&&(r=o);o>=r;)s.push(o),o+=n;else s.push(o);return s}static arithmeticBounds(t,r,n){return e.arithmeticSequence(t,r,(r-t)/n)}static geometricSequence(t=1,r=1e3,n=2){let s=new T,o=t;if(Math.abs(n)>1)for(Math.abs(r)<Math.abs(o)&&(r=o);o<=Math.abs(r);)s.push(o),o*=n;else if(Math.abs(n)<1&&n!==0)for(Math.abs(r)<Math.abs(o)&&(r=o);o>=Math.abs(r);)s.push(o),o*=n;else s.push(o);return s}static constantVector(t=1,r){let n=new T;for(let s=0;s<t;s++)n.push(r);return n}static fromArray(t){return T.fromArray(t)}static merge(t=null,r=null){if(t instanceof T&&r instanceof T)return T.fromArray([...t,...r]);if(t instanceof T){let n=t.clone();return n.push(r),n}if(r instanceof T){let n=r.clone();return n.addElement(t,0),n}return T.fromArray([t,r])}static recursiveSequence(t,r,n,s=!1){let o=T.fromArray(t);if(s)for(;!n(o);)o.push(r(o));else{let i=[...t];for(;!n(i);)o.push(r(i)),i.shift(),i.push(o[o.length-1])}return o}static wrap(t,r=1){if(r===0)return t;let n=new T;return n.push(t),e.wrap(n,r-1)}static fromOEIS(t=1){let r;switch(t){case 1:r="1,2,3";break;case 2:r="4,5,6";break;case 3:r="7,8,9";break;default:r="0,0,0"}return e.transform(T.fromArray(r.split(",")),n=>parseInt(n,10))}static fillByIndex(t,r){let n=new T(t.length);for(let s=0;s<n.length;s++)n[s]=r(s);return n}static transform(t,r){let n=new T;for(let s of t)n.push(r(s));return n}static replace(t,r){let n=new T;for(let s=0;s<t.length;s++)n.push(r);return n}static transformEndNodes(t,r,n=e.isNotVector){let s=t.clone();for(let o=0;o<s.length;o++){let i=s[o];n(i)||!(i instanceof T)?s[o]=r(i):s[o]=e.transformEndNodes(i,r,n)}return s}static replaceEndNodes(t,r,n=e.isNotVector){let s=t.clone();for(let o=0;o<s.length;o++){let i=s[o];n(i)||!(i instanceof T)?s[o]=r:s[o]=e.replaceEndNodes(i,r,n)}return s}static trim(t,r=0,n=0){let s=t.clone();return s.splice(t.length-n,n),s.splice(0,r),s}static removeElements(t,...r){let n=t.clone();for(let s=0;s<n.length;s++)r.includes(n[s])&&(n.removeElement(s),s--);return n}static filter(t,r){let n=new T;for(let s of t)r(s)&&n.push(s);return n}static modes(t){let r=new T;if(t.length===0)return r;let n=new Map,s=[];for(let i of t){let a=n.get(i);a===void 0?(n.set(i,1),s.push(i)):n.set(i,a+1)}let o=0;for(let i of s){let a=n.get(i);a>o&&(o=a)}for(let i of s)n.get(i)===o&&r.push(i);return r}static flatten(t){let r=new T,n=s=>{for(let o of s)o instanceof T?n(o):r.push(o)};return n(t),r}static flattenSD(t){if(t.length===0)return new T;if(!(t[0]instanceof T))return t.clone();let r=new T;for(let n of t)if(n instanceof T)for(let s of n)r.push(s);else r.push(n);return r}static flattenSDLevels(t,r=0){let n=t.clone(),s=r>0?r:e.nestedDepthSD(t);for(let o=0;o<s;o++)n=e.flattenSD(n);return n}static fractal(t){return e.replaceEndNodes(t,t.clone())}static fractalLevels(t,r=0){let n=t.clone();for(let s=0;s<r;s++)n=e.fractal(n);return n}static insert(t,r,n=-1){n<0&&(n=t.length);let s=t.clone();for(let o=0;o<r.length;o++)s.splice(n+o,0,r[o]);return s}static combine(t,r,n,s){let o=Math.max(t.length,r.length),i=new T(o);for(let a=0;a<o;a++){let c=a<t.length,u=a<r.length;c&&u?i[a]=n(t[a],r[a]):c?i[a]=s!==void 0?s:t[a]:i[a]=s!==void 0?s:r[a]}return i}static length(t){return t.length}static collapse(t,r,n=null){let s=t.clone();if(s.length===0)return n;let o=s[0];for(let i=1;i<s.length;i++)o=r(o,s[i]);return o}static matches(t,r){let n=0;for(let s of t)r(s)&&n++;return n}static count(t,r){return e.matches(t,n=>n===r)}static consecutiveMatches(t,r){let n=[0];for(let s of t)r(s)?n[n.length-1]++:n[n.length-1]!==0&&n.push(0);return n.length>1&&n[n.length-1]===0&&n.pop(),n}static nestedDepthSD(t,r=0){return t[0]instanceof T?e.nestedDepthSD(t[0],r+1):r}static RowSeperator=",\r";static isMatrix(t){if(!(t[0]instanceof T))return!1;let r=t[0].length;for(let n of t)if(!(n instanceof T)||n.length!==r)return!1;return!0}static width(t){return t[0].length}static height(t){return t.length}static constantMatrix(t=1,r=1,n){let s=new T;for(let o=0;o<t;o++){let i=new T;for(let a=0;a<r;a++)i.push(n);s.push(i)}return s}static generateIdentity(t=1,r=1,n,s){let o=e.constantMatrix(t,r,s);return e.fillMatrixByIndex(o,(i,a)=>i===a?n:s)}static vectorToMatrixRow(t){let r=new T;return r.push(t),r}static vectorToMatrixColumn(t){return e.transpose(e.vectorToMatrixRow(t))}static fillMatrixByIndex(t,r){let n=t.clone();for(let s=0;s<e.height(n);s++)for(let o=0;o<e.width(n);o++)n[s][o]=r(s,o);return n}static replaceMatrix(t,r){let n=t.clone();for(let s=0;s<e.height(n);s++)for(let o=0;o<e.width(n);o++)n[s][o]=r;return n}static transpose(t){let r=new T;for(let n=0;n<e.width(t);n++)r.push(new T(e.height(t)));for(let n=0;n<e.height(t);n++)for(let s=0;s<e.width(t);s++)r[s][n]=t[n][s];return r}static getRow(t,r=0){return e.wrap(t[r])}static getColumn(t,r=0){return e.transpose(e.getRow(e.transpose(t),r))}static rowRemoved(t,r=0){let n=t.clone();return n.removeElement(r),n}static columnRemoved(t,r=0){return e.transpose(e.rowRemoved(e.transpose(t),r))}static rowInserted(t,r,n=-1){return e.insert(t,e.wrap(r),n)}static columnInserted(t,r,n=-1){return e.transpose(e.rowInserted(e.transpose(t),r,n))}static mergeRows(t,r){return e.merge(t,r)}static mergeColumns(t,r){return e.transpose(e.mergeRows(e.transpose(t),e.transpose(r)))}static rowSet(t,r,n=0){let s=t.clone();return s.setElement(r,n),s}static columnSet(t,r,n=0){return e.transpose(e.rowSet(e.transpose(t),r,n))}static placeBlock(t,r,n,s){let o=t.clone();for(let i=0;i<e.height(r);i++)for(let a=0;a<e.width(r);a++){let c=o[n+i];c&&c.length>s+a&&(c[s+a]=r[i][a])}return o}static breakBlock(t){let r=0,n=0,s=e.height(t),o=e.width(t);for(let l=0;l<s;l++)r+=e.height(t[l][0]);for(let l=0;l<o;l++)n+=e.width(t[0][l]);let i=e.constantMatrix(r,n,null),a=0,c=0,u=t[0][0];for(;a<r;)for(let l=0;l<s;l++){for(let f=0;f<o;f++){u=t[l][f];for(let h=0;h<e.height(u);h++)for(let m=0;m<e.width(u);m++)i[a+h][c+m]=u[h][m];c+=e.width(u)}c=0,a+=e.height(u)}return i}static pad(t,r=null,n=!0,s=!0,o=!0,i=!0,a=!0,c=!0){let u=t.clone(),l;if(n){let f=1;for(;f<e.height(u);)l=e.constantVector(e.width(u),r),u=e.rowInserted(u,l,f),f+=2}if(s){let f=1;for(;f<e.width(u);)l=e.constantVector(e.height(u),r),u=e.columnInserted(u,l,f),f+=2}return o&&(u=e.rowInserted(u,e.constantVector(e.width(u),r),0)),i&&(u=e.rowInserted(u,e.constantVector(e.width(u),r),-1)),a&&(u=e.columnInserted(u,e.constantVector(e.height(u),r),0)),c&&(u=e.columnInserted(u,e.constantVector(e.height(u),r),-1)),u}static diagonal(t,r=0){let n=new T;if(r>=0)for(let s=0;s<e.width(t)-r;s++)n.push(t[s][s+r]);else{let s=-r;for(let o=0;o<e.height(t)-s;o++)n.push(t[o+s][o])}return n}static minorDiagonal(t,r=0){let n=new T;if(r>=0)for(let s=0;s<e.width(t)-r;s++)n.push(t[s][e.width(t)-s-1-r]);else{let s=-r;for(let o=0;o<e.height(t)-s;o++)n.push(t[o+s][e.width(t)-o-1])}return n}static matrixString(t,r=0,n=0,s=",",o="[",i="]",a=",",c="[",u="]"){let l=[],f=r;for(let p=0;p<e.height(t);p++){let y=[];for(let d=0;d<e.width(t);d++){let w=t[p][d],g=w==null?"null":String(w);y.push(g),r>0&&f<g.length&&(f=g.length)}l.push(y)}if(r>0)for(let p of l)for(let y=0;y<p.length;y++){let d=p[y];if(n!==0){let w=Math.ceil((f-d.length)/2),g=Math.floor((f-d.length)/2);n<0&&([w,g]=[g,w]),p[y]=" ".repeat(w)+d+" ".repeat(g)}else p[y]=" ".repeat(f-d.length)+d}let h=l.map(p=>o+p.join(s)+i),m=`${a}\r${" ".repeat(c.length)}`;return c+h.join(m)+u}};function ls(e=1){return Yt(e)}function nr(e){return ls(.5*(Math.exp(e)-Math.exp(-e)))}function sr(e){return ls(.5*(Math.exp(e)+Math.exp(-e)))}function Yt(e,t=10){if(!Number.isFinite(e))return e;let r=10**t;return Math.round(e*r)/r}function xe(e){return e instanceof Tt?e:new Tt(e)}function bn(e,t=10){return new Tt(Yt(e.value,t),Yt(e.iValue,t))}var Tt=class e{value;iValue;static NaCN=new e(NaN,NaN);static PositiveInfinity=new e(1/0,0);static InfinityQ1=new e(1/0,1/0);static PositiveInfinityI=new e(0,1/0);static InfinityQ2=new e(-1/0,1/0);static NegativeInfinity=new e(-1/0,0);static InfinityQ3=new e(-1/0,-1/0);static NegativeInfinityI=new e(0,-1/0);static InfinityQ4=new e(1/0,-1/0);static Zero=new e(0,0);static One=new e(1,0);static I=new e(0,1);static E=new e(Math.E,0);static PI=new e(Math.PI,0);static PHI=new e((1+Math.sqrt(5))/2,0);constructor(t=0,r=0){if(t instanceof e)this.value=t.value,this.iValue=t.iValue;else if(typeof t=="string"){let n=e.parse(t);this.value=n.value,this.iValue=n.iValue}else this.value=t,this.iValue=r}get re(){return this.value}set re(t){this.value=t}get im(){return this.iValue}set im(t){this.iValue=t}static from(t){return t instanceof e?new e(t):typeof t=="number"?new e(t,0):typeof t=="string"?e.parse(t):new e(NaN,NaN)}static isNotComplex(t){let r=e.from(t);return Number.isNaN(r.value)||Number.isNaN(r.iValue)}static isComplex(t){let r=e.from(t);return!Number.isNaN(r.value)&&!Number.isNaN(r.iValue)}static wrap(...t){return t.length===1?e.from(t[0]):t.length===2?new e(Number(t[0]),Number(t[1])):new e(NaN,NaN)}static fromNumber(t){return new e(t,0)}static fromPolar(t,r){return new e(t*Math.cos(r),t*Math.sin(r))}static fromVector(t){return new e(t[0]??0,t[1]??0)}static fromXML(t){let r=/<value>(.*?)<\/value>/.exec(t),n=/<iValue>(.*?)<\/iValue>/.exec(t);return new e(r?Number(r[1]):NaN,n?Number(n[1]):NaN)}static parse(t){let r=t.replace(/\s+/g,"").replace(/\*i/g,"i");if(r.length===0)return new e(NaN,NaN);if(!r.includes("i")){let u=Number(r);return Number.isNaN(u)?new e(NaN,NaN):new e(u,0)}if(!r.endsWith("i"))return new e(NaN,NaN);let n=r.slice(0,-1),s=-1;for(let u=1;u<n.length;u++){let l=n[u],f=n[u-1];(l==="+"||l==="-")&&f!=="e"&&f!=="E"&&(s=u)}let o,i;s===-1?(o="",i=n):(o=n.slice(0,s),i=n.slice(s));let a=o===""?0:Number(o),c;return i===""||i==="+"?c=1:i==="-"?c=-1:c=Number(i),Number.isNaN(a)||Number.isNaN(c)?new e(NaN,NaN):new e(a,c)}static random(t=1,r=0,n=1,s=0,o=!0){let i=Math.min(t,r),a=Math.max(t,r),c=Math.min(n,s),u=Math.max(n,s);return new e(i+Math.random()*(a-i),c+Math.random()*(u-c))}toXML(){return`<complexNumber><value>${this.value}</value><iValue>${this.iValue}</iValue></complexNumber>`}toVector(){return T.fromArray([this.value,this.iValue])}toString(t=!1){if(t)return`${this.value}+${this.iValue}i`;if(this.value===0&&this.iValue===0)return"0";if(this.iValue===0)return String(this.value);let r=Math.abs(this.iValue),n=r===1?"i":`${r}*i`;return this.value===0?this.iValue<0?`-${n}`:n:`${this.value}${this.iValue<0?"-":"+"}${n}`}neg(){return new e(-this.value,-this.iValue)}reciprocal(){let{value:t,iValue:r}=this;if(t===0&&r===0)return new e(NaN,NaN);let n=t*t+r*r;return new e(t/n,-r/n)}conjugate(){return new e(this.value,-this.iValue)}flip(){return new e(this.iValue,this.value)}equals(t){return this.value===t.value&&this.iValue===t.iValue}lexCompare(t){let r=xe(t);return this.value>r.value?1:this.value<r.value?-1:this.iValue>r.iValue?1:this.iValue<r.iValue?-1:0}magCompare(t){let r=this.magnitude(),n=xe(t).magnitude();return r>n?1:r<n?-1:0}add(t=0){let r=xe(t);return new e(this.value+r.value,this.iValue+r.iValue)}subtract(t=0){let r=xe(t);return new e(this.value-r.value,this.iValue-r.iValue)}multiply(t=1){let r=xe(t);return new e(this.value*r.value-this.iValue*r.iValue,this.value*r.iValue+this.iValue*r.value)}divide(t=1){let r=xe(t);return r.value===0&&r.iValue===0?this.value>0?this.iValue===0?e.PositiveInfinity:this.iValue>0?e.InfinityQ1:e.InfinityQ4:this.value<0?this.iValue===0?e.NegativeInfinity:this.iValue>0?e.InfinityQ2:e.InfinityQ3:this.iValue===0?e.NaCN:this.iValue>0?e.PositiveInfinityI:e.NegativeInfinityI:this.multiply(r.reciprocal())}magnitude(){return Math.hypot(this.value,this.iValue)}angle(){return Math.atan2(this.iValue,this.value)}static power2(t,r){if(t.value===0&&t.iValue===0&&!(r.value===0&&r.iValue===0))return new e(0,0);let n=t.magnitude(),s=t.angle(),o=r.value,i=r.iValue,a=n**o/Math.E**(i*s),c=a*Math.cos(i*Math.log(n)+o*s),u=a*Math.sin(i*Math.log(n)+o*s);return bn(new e(c,u))}selectedNaturalLogarithm(t=0){let r=this.magnitude(),n=this.angle();return bn(new e(Math.log(r),n+2*Math.PI*t))}power(t=1,r=0){let n=xe(t);if(this.value===0&&this.iValue===0)return n.value===0&&n.iValue===0?new e(1,0):n.value>0?new e(0,0):e.NaCN;let s=n.multiply(this.selectedNaturalLogarithm(r));return e.power2(e.E,s)}square(){return this.power(2)}squareRoot(){return this.power(.5)}logarithm(t=Math.E,r=0,n=0){let s=xe(t);return bn(this.selectedNaturalLogarithm(r).divide(s.selectedNaturalLogarithm(n)))}sine(){return new e(Yt(Math.sin(this.value)*sr(this.iValue)),Yt(Math.cos(this.value)*nr(this.iValue)))}cosine(){return new e(Yt(Math.cos(this.value)*sr(this.iValue)),Yt(-Math.sin(this.value)*nr(this.iValue)))}tangent(){return this.sine().divide(this.cosine())}hyperbolicSine(){return new e(Yt(nr(this.value)*Math.cos(this.iValue)),Yt(sr(this.value)*Math.sin(this.iValue)))}hyperbolicCosine(){return new e(Yt(sr(this.value)*Math.cos(this.iValue)),Yt(nr(this.value)*Math.sin(this.iValue)))}hyperbolicTangent(){return this.hyperbolicSine().divide(this.hyperbolicCosine())}arcSine(){let t=e.I.multiply(this).add(new e(1,0).subtract(this.square()).squareRoot());return e.I.neg().multiply(t.logarithm())}arcCosine(){let t=this.add(this.square().subtract(1).squareRoot());return e.I.neg().multiply(t.logarithm())}arcTangent(){let t=e.I.multiply(this),r=new e(1,0).subtract(t).logarithm(),n=new e(1,0).add(t).logarithm();return e.I.divide(2).multiply(r.subtract(n))}arcHyperbolicSine(){return this.add(this.square().add(1).squareRoot()).logarithm()}arcHyperbolicCosine(){return this.add(this.add(1).squareRoot().multiply(this.subtract(1).squareRoot())).logarithm()}arcHyperbolicTangent(){let t=new e(1,0).add(this),r=new e(1,0).subtract(this);return t.divide(r).logarithm().divide(2)}valueOf(){if(this.iValue!==0)throw new TypeError(`Cannot implicitly convert a non-real ComplexNumber (${this.toString()}) to a Number -- use .value/.re for the real part, .magnitude() for the modulus, or an explicit .toString().`);return this.value}};var fs=e=>(e<0n?-e:e).toString().length;function ki(e,t){let r=e/t,n=e%t;if(n===0n)return r;let s=(n<0n?-n:n)*2n,o=t<0n?-t:t;return s>=o?e<0n==t<0n?r+1n:r-1n:r}var be=class e{static DEFAULT_PRECISION=20;digits;exponent;static Zero=new e(0n,0);static One=new e(1n,0);constructor(t=0n,r=0){this.digits=t,this.exponent=r}static fromString(t){let r=/^\s*([+-]?)(\d+)(?:\.(\d+))?(?:[eE]([+-]?\d+))?\s*$/.exec(t);if(!r)throw new Error(`Invalid Decimal string: ${t}`);let[,n,s,o="",i]=r,a=BigInt((n==="-"?"-":"")+s+o),c=-o.length+(i?Number(i):0);return new e(a,c)}static from(t){if(t instanceof e)return t;if(typeof t=="bigint")return new e(t,0);if(typeof t=="number"){if(!Number.isFinite(t))throw new Error("Cannot make a Decimal from a non-finite number.");return e.fromString(t.toString())}return e.fromString(t)}static align(t,r){let n=Math.min(t.exponent,r.exponent),s=t.digits*10n**BigInt(t.exponent-n),o=r.digits*10n**BigInt(r.exponent-n);return{ad:s,bd:o,exponent:n}}add(t){let{ad:r,bd:n,exponent:s}=e.align(this,t);return new e(r+n,s)}subtract(t){let{ad:r,bd:n,exponent:s}=e.align(this,t);return new e(r-n,s)}multiply(t){return new e(this.digits*t.digits,this.exponent+t.exponent)}divide(t,r=e.DEFAULT_PRECISION){if(t.digits===0n)throw new Error("Division by zero Decimal.");if(this.digits===0n)return e.Zero;let n=Math.max(0,r-fs(this.digits)+fs(t.digits)),s=this.digits*10n**BigInt(n),o=ki(s,t.digits);return new e(o,this.exponent-t.exponent-n)}negate(){return new e(-this.digits,this.exponent)}abs(){return this.digits<0n?this.negate():this}equals(t){let{ad:r,bd:n}=e.align(this,t);return r===n}compare(t){let{ad:r,bd:n}=e.align(this,t);return r<n?-1:r>n?1:0}lessThan(t){return this.compare(t)<0}isZero(){return this.digits===0n}toNumber(){return Number(this.digits)*10**this.exponent}toString(){if(this.digits===0n)return"0";let t=this.digits<0n,r=(t?-this.digits:this.digits).toString();if(this.exponent>=0)r=r+"0".repeat(this.exponent);else{let n=r.length+this.exponent;r=n<=0?`0.${"0".repeat(-n)}${r}`:`${r.slice(0,n)}.${r.slice(n)}`,r.includes(".")&&(r=r.replace(/0+$/,"").replace(/\.$/,""))}return t?`-${r}`:r}};var qe=[.9999999999998099,676.5203681218851,-1259.1392167224028,771.3234287776531,-176.6150291621406,12.507343278686905,-.13857109526572012,9984369578019572e-21,15056327351493116e-23],Ie=class e{static gamma(t){if(t<.5)return Math.PI/(Math.sin(Math.PI*t)*e.gamma(1-t));let r=t-1,n=qe[0],s=r+7+.5;for(let o=1;o<qe.length;o++)n+=qe[o]/(r+o);return Math.sqrt(2*Math.PI)*s**(r+.5)*Math.exp(-s)*n}static lnGamma(t){if(t<.5)return Math.log(Math.abs(Math.PI/Math.sin(Math.PI*t)))-e.lnGamma(1-t);let r=t-1,n=qe[0],s=r+7+.5;for(let o=1;o<qe.length;o++)n+=qe[o]/(r+o);return .5*Math.log(2*Math.PI)+(r+.5)*Math.log(s)-s+Math.log(n)}static beta(t,r){return Math.exp(e.lnGamma(t)+e.lnGamma(r)-e.lnGamma(t+r))}static erf(t){if(t===0||Number.isNaN(t))return t;let r=e.regularizedGammaP(.5,t*t);return t<0?-r:r}static erfc(t){return Number.isNaN(t)?t:t<0?2-e.regularizedGammaQ(.5,t*t):e.regularizedGammaQ(.5,t*t)}static regularizedGammaP(t,r){return r<0||t<=0?Number.NaN:r===0?0:r===Number.POSITIVE_INFINITY?1:r<t+1?ms(t,r):1-ps(t,r)}static regularizedGammaQ(t,r){return r<0||t<=0?Number.NaN:r===0?1:r===Number.POSITIVE_INFINITY?0:r<t+1?1-ms(t,r):ps(t,r)}static regularizedIncompleteBeta(t,r,n){if(t<=0)return 0;if(t>=1)return 1;let s=e.lnGamma(r+n)-e.lnGamma(r)-e.lnGamma(n),o=Math.exp(s+r*Math.log(t)+n*Math.log(1-t));return t<(r+1)/(r+n+2)?o*hs(r,n,t)/r:1-o*hs(n,r,1-t)/n}};function hs(e,t,r){let s=e+t,o=e+1,i=e-1,a=1,c=1-s*r/o;Math.abs(c)<1e-300&&(c=1e-300),c=1/c;let u=c;for(let l=1;l<1e3;l++){let f=2*l,h=l*(t-l)*r/((i+f)*(e+f));c=1+h*c,Math.abs(c)<1e-300&&(c=1e-300),a=1+h/a,Math.abs(a)<1e-300&&(a=1e-300),c=1/c,u*=c*a,h=-(e+l)*(s+l)*r/((e+f)*(o+f)),c=1+h*c,Math.abs(c)<1e-300&&(c=1e-300),a=1+h/a,Math.abs(a)<1e-300&&(a=1e-300),c=1/c;let m=c*a;if(u*=m,Math.abs(m-1)<1e-15)break}return u}function ms(e,t){let r=e,n=1/e,s=n;for(let o=0;o<1e3&&(r++,s*=t/r,n+=s,!(Math.abs(s)<Math.abs(n)*1e-16));o++);return n*Math.exp(-t+e*Math.log(t)-Ie.lnGamma(e))}function ps(e,t){let n=t+1-e,s=1/1e-300,o=1/n,i=o;for(let a=1;a<1e3;a++){let c=-a*(a-e);n+=2,o=c*o+n,Math.abs(o)<1e-300&&(o=1e-300),s=n+c/s,Math.abs(s)<1e-300&&(s=1e-300),o=1/o;let u=o*s;if(i*=u,Math.abs(u-1)<1e-16)break}return Math.exp(-t+e*Math.log(t)-Ie.lnGamma(e))*i}var ue=class e{value;deriv;constructor(t=0,r=0){this.value=t,this.deriv=r}static constant(t){return new e(t,0)}static variable(t){return new e(t,1)}static domain(t,r){return new e(t,Number.isNaN(t)?Number.NaN:r)}static lift(t){return t instanceof e?t:new e(t,0)}add(t){let r=e.lift(t);return new e(this.value+r.value,this.deriv+r.deriv)}subtract(t){let r=e.lift(t);return new e(this.value-r.value,this.deriv-r.deriv)}multiply(t){let r=e.lift(t);return new e(this.value*r.value,this.value*r.deriv+this.deriv*r.value)}divide(t){let r=e.lift(t);return new e(this.value/r.value,(this.deriv*r.value-this.value*r.deriv)/(r.value*r.value))}negate(){return new e(-this.value,-this.deriv)}pow(t){return t===0?new e(1,0):e.domain(this.value**t,t*this.value**(t-1)*this.deriv)}static sin(t){return new e(Math.sin(t.value),Math.cos(t.value)*t.deriv)}static cos(t){return new e(Math.cos(t.value),-Math.sin(t.value)*t.deriv)}static tan(t){let r=Math.cos(t.value);return new e(Math.tan(t.value),t.deriv/(r*r))}static exp(t){let r=Math.exp(t.value);return new e(r,r*t.deriv)}static log(t){return e.domain(Math.log(t.value),t.deriv/t.value)}static sqrt(t){let r=Math.sqrt(t.value);return e.domain(r,t.deriv/(2*r))}static derivative(t,r){return t(e.variable(r)).deriv}static valueAndDerivative(t,r){let n=t(e.variable(r));return{value:n.value,derivative:n.deriv}}static gradient(t,r){return r.map((n,s)=>{let o=r.map((i,a)=>new e(i,s===a?1:0));return t(o).deriv})}toString(){return`${this.value} + ${this.deriv}\u03B5`}};var Z=e=>({type:"const",value:e}),Te=(e,t)=>({type:"add",left:e,right:t}),le=(e,t)=>({type:"sub",left:e,right:t}),rt=(e,t)=>({type:"mul",left:e,right:t}),gt=(e,t)=>({type:"div",left:e,right:t}),$t=(e,t)=>({type:"pow",base:e,exp:t}),Qt=e=>({type:"neg",arg:e}),Y=(e,t)=>({type:"func",name:e,arg:t}),wn={sin:(e,t)=>rt(Y("cos",e),t),cos:(e,t)=>Qt(rt(Y("sin",e),t)),tan:(e,t)=>gt(t,$t(Y("cos",e),Z(2))),exp:(e,t)=>rt(Y("exp",e),t),ln:(e,t)=>gt(t,e),sqrt:(e,t)=>gt(t,rt(Z(2),Y("sqrt",e))),asin:(e,t)=>gt(t,Y("sqrt",le(Z(1),$t(e,Z(2))))),acos:(e,t)=>Qt(gt(t,Y("sqrt",le(Z(1),$t(e,Z(2)))))),atan:(e,t)=>gt(t,Te(Z(1),$t(e,Z(2)))),sinh:(e,t)=>rt(Y("cosh",e),t),cosh:(e,t)=>rt(Y("sinh",e),t),tanh:(e,t)=>gt(t,$t(Y("cosh",e),Z(2))),cot:(e,t)=>Qt(rt($t(Y("csc",e),Z(2)),t)),sec:(e,t)=>rt(rt(Y("sec",e),Y("tan",e)),t),csc:(e,t)=>Qt(rt(rt(Y("csc",e),Y("cot",e)),t)),asinh:(e,t)=>gt(t,Y("sqrt",Te($t(e,Z(2)),Z(1)))),acosh:(e,t)=>gt(t,Y("sqrt",le($t(e,Z(2)),Z(1)))),atanh:(e,t)=>gt(t,le(Z(1),$t(e,Z(2)))),coth:(e,t)=>Qt(rt($t(Y("csch",e),Z(2)),t)),sech:(e,t)=>Qt(rt(rt(Y("sech",e),Y("tanh",e)),t)),csch:(e,t)=>Qt(rt(rt(Y("csch",e),Y("coth",e)),t)),acot:(e,t)=>Qt(gt(t,Te(Z(1),$t(e,Z(2))))),asec:(e,t)=>gt(t,rt(Y("abs",e),Y("sqrt",le($t(e,Z(2)),Z(1))))),acsc:(e,t)=>Qt(gt(t,rt(Y("abs",e),Y("sqrt",le($t(e,Z(2)),Z(1)))))),acoth:(e,t)=>gt(t,le(Z(1),$t(e,Z(2)))),asech:(e,t)=>Qt(gt(t,rt(e,Y("sqrt",le(Z(1),$t(e,Z(2))))))),acsch:(e,t)=>Qt(gt(t,rt(Y("abs",e),Y("sqrt",Te(Z(1),$t(e,Z(2))))))),abs:(e,t)=>rt(Y("sign",e),t),log10:(e,t)=>gt(t,rt(e,Y("ln",Z(10)))),log2:(e,t)=>gt(t,rt(e,Y("ln",Z(2)))),cbrt:(e,t)=>gt(t,rt(Z(3),$t(Y("cbrt",e),Z(2)))),floor:()=>Z(0),ceil:()=>Z(0),round:()=>Z(0),sign:()=>Z(0),trunc:()=>Z(0),expm1:(e,t)=>rt(Y("exp",e),t),log1p:(e,t)=>gt(t,Te(Z(1),e)),sigmoid:(e,t)=>rt(rt(Y("sigmoid",e),le(Z(1),Y("sigmoid",e))),t),erf:(e,t)=>rt(rt(gt(Z(2),Y("sqrt",Z(Math.PI))),Y("exp",Qt($t(e,Z(2))))),t),relu:(e,t)=>rt(gt(Te(Z(1),Y("sign",e)),Z(2)),t)};function zi(e,t){let r=e<0n?-e:e,n=t<0n?-t:t;for(;n;)[r,n]=[n,r%n];return r}var ds=e=>{if(typeof e=="bigint")return e;if(!Number.isInteger(e))throw new Error(`Rational requires integer inputs; got ${e}`);return BigInt(e)},st=class e{numerator;denominator;static Zero=new e(0n,1n);static One=new e(1n,1n);constructor(t,r=1n){let n=ds(t),s=ds(r);if(s===0n)throw new Error("Rational denominator must be non-zero.");s<0n&&(n=-n,s=-s);let o=zi(n,s)||1n;this.numerator=n/o,this.denominator=s/o}static from(t){return t instanceof e?t:typeof t=="bigint"?new e(t,1n):e.fromNumber(t)}static fromNumber(t,r=1e6){if(Number.isInteger(t))return new e(BigInt(t),1n);if(!Number.isFinite(t))throw new Error("Cannot make a Rational from a non-finite number.");let[n,s]=[0n,1n],[o,i]=[1n,0n],a=t,c=BigInt(r);for(let u=0;u<64;u++){let l=Math.floor(a),f=BigInt(l);if([n,s]=[s,f*s+n],[o,i]=[i,f*i+o],i>c)return new e(n,o);let h=a-l;if(h<1e-15)break;a=1/h}return new e(s,i)}add(t){return new e(this.numerator*t.denominator+t.numerator*this.denominator,this.denominator*t.denominator)}subtract(t){return new e(this.numerator*t.denominator-t.numerator*this.denominator,this.denominator*t.denominator)}multiply(t){return new e(this.numerator*t.numerator,this.denominator*t.denominator)}divide(t){if(t.numerator===0n)throw new Error("Division by zero Rational.");return new e(this.numerator*t.denominator,this.denominator*t.numerator)}negate(){return new e(-this.numerator,this.denominator)}reciprocal(){if(this.numerator===0n)throw new Error("Zero has no reciprocal.");return new e(this.denominator,this.numerator)}abs(){return this.numerator<0n?this.negate():this}pow(t){if(!Number.isInteger(t))throw new Error("Rational.pow requires an integer exponent.");if(t<0)return this.reciprocal().pow(-t);let r=e.One,n=this,s=t;for(;s>0;)s&1&&(r=r.multiply(n)),n=n.multiply(n),s>>=1;return r}equals(t){return this.numerator===t.numerator&&this.denominator===t.denominator}compare(t){let r=this.numerator*t.denominator-t.numerator*this.denominator;return r<0n?-1:r>0n?1:0}lessThan(t){return this.compare(t)<0}get sign(){return this.numerator<0n?-1:this.numerator>0n?1:0}isZero(){return this.numerator===0n}toNumber(){return Number(this.numerator)/Number(this.denominator)}toString(){return this.denominator===1n?`${this.numerator}`:`${this.numerator}/${this.denominator}`}};var vn=new Float64Array(1),gs=new BigUint64Array(vn.buffer);function ys(e){return Number.isNaN(e)||e===1/0?e:e===0?Number.MIN_VALUE:(vn[0]=e,gs[0]=gs[0]+(e>0?1n:-1n),vn[0])}function Pi(e){return-ys(-e)}function se(e){return new _t(Pi(e.lo),ys(e.hi))}var _t=class e{lo;hi;constructor(t,r=t){if(t>r)throw new Error(`Invalid interval: [${t}, ${r}]`);this.lo=t,this.hi=r}static of(t,r){return new e(t,r)}static point(t){return new e(t,t)}get width(){return this.hi-this.lo}get midpoint(){return(this.lo+this.hi)/2}get radius(){return this.width/2}contains(t){return this.lo<=t&&t<=this.hi}overlaps(t){return this.lo<=t.hi&&t.lo<=this.hi}add(t){return se(new e(this.lo+t.lo,this.hi+t.hi))}subtract(t){return se(new e(this.lo-t.hi,this.hi-t.lo))}negate(){return new e(-this.hi,-this.lo)}multiply(t){let r=[this.lo*t.lo,this.lo*t.hi,this.hi*t.lo,this.hi*t.hi];return se(new e(Math.min(...r),Math.max(...r)))}divide(t){if(t.contains(0))throw new Error("Interval division by an interval containing zero.");let r=se(new e(1/t.hi,1/t.lo));return this.multiply(r)}hull(t){return new e(Math.min(this.lo,t.lo),Math.max(this.hi,t.hi))}intersect(t){let r=Math.max(this.lo,t.lo),n=Math.min(this.hi,t.hi);return r<=n?new e(r,n):null}abs(){return this.lo>=0?this:this.hi<=0?this.negate():new e(0,Math.max(-this.lo,this.hi))}sqrt(){if(this.lo<0)throw new Error("sqrt of an interval with negative values.");return se(new e(Math.sqrt(this.lo),Math.sqrt(this.hi)))}exp(){return se(new e(Math.exp(this.lo),Math.exp(this.hi)))}log(){if(this.lo<=0)throw new Error("log of an interval with non-positive values.");return se(new e(Math.log(this.lo),Math.log(this.hi)))}pow(t){if(!Number.isInteger(t)||t<0)throw new Error("Interval.pow requires a non-negative integer.");if(t===0)return e.point(1);let r=this.lo**t,n=this.hi**t;return t%2===0&&this.contains(0)?se(new e(0,Math.max(r,n))):se(new e(Math.min(r,n),Math.max(r,n)))}extrema(t,r,n){let s=[t(this.lo),t(this.hi)],o=Math.ceil((this.lo-r)/n),i=Math.floor((this.hi-r)/n);for(let a=o;a<=i;a++)s.push(t(r+a*n));return se(new e(Math.min(...s),Math.max(...s)))}sin(){return this.width>=2*Math.PI?new e(-1,1):this.extrema(Math.sin,Math.PI/2,Math.PI)}cos(){return this.width>=2*Math.PI?new e(-1,1):this.extrema(Math.cos,0,Math.PI)}equals(t){return this.lo===t.lo&&this.hi===t.hi}toString(){return`[${this.lo}, ${this.hi}]`}};var $r=e=>Array.from({length:e},()=>new Array(e).fill(0));function xs(e,t=60){let r=e.length;if(r===0)return{values:[],vectors:[]};let n={re:$r(r),im:$r(r)};for(let f=0;f<r;f++){if(e[f].length!==r)throw new Error("eigen requires a square matrix.");for(let h=0;h<r;h++){let m=e[f][h];if(typeof m=="number"?n.re[f][h]=m:(n.re[f][h]=m.re,n.im[f][h]=m.im),!Number.isFinite(n.re[f][h])||!Number.isFinite(n.im[f][h]))throw new Error("eigen requires finite matrix entries.")}}let s={re:$r(r),im:$r(r)};for(let f=0;f<r;f++)s.re[f][f]=1;let o=0;for(let f=0;f<r;f++)for(let h=0;h<r;h++)o=Math.max(o,Math.hypot(n.re[f][h],n.im[f][h]));o===0&&(o=1),Oi(n,s,r),Ri(n,s,r,o,t);let i=o*r,a=[];for(let f=0;f<r;f++)a.push([n.re[f][f],n.im[f][f]]);let c=1e-12*o,u=e.every(f=>f.every(h=>typeof h=="number"||h.im===0)),l=[];for(let f=0;f<r;f++){let h=new Array(r).fill(0),m=new Array(r).fill(0);h[f]=1;for(let b=f-1;b>=0;b--){let x=0,S=0;for(let k=b+1;k<=f;k++)x+=n.re[b][k]*h[k]-n.im[b][k]*m[k],S+=n.re[b][k]*m[k]+n.im[b][k]*h[k];let O=n.re[b][b]-a[f][0],A=n.im[b][b]-a[f][1];Math.hypot(O,A)<Number.EPSILON*i&&(O=Number.EPSILON*i,A=0);let F=O*O+A*A;h[b]=-(x*O+S*A)/F,m[b]=-(S*O-x*A)/F}let p=new Array(r).fill(0),y=new Array(r).fill(0);for(let b=0;b<r;b++)for(let x=0;x<=f;x++)p[b]+=s.re[b][x]*h[x]-s.im[b][x]*m[x],y[b]+=s.re[b][x]*m[x]+s.im[b][x]*h[x];let d=0,w=0,g=0;for(let b=0;b<r;b++){let x=Math.hypot(p[b],y[b]);d+=x*x,x>w*(1+1e-12)&&(w=x,g=b)}d=Math.sqrt(d);let M=p[g]/w,v=-y[g]/w;for(let b=0;b<r;b++){let x=(p[b]*M-y[b]*v)/d,S=(p[b]*v+y[b]*M)/d;p[b]=x,y[b]=S}let N=a[f][0],$=a[f][1];if(Math.abs($)<=c&&u){$=0;for(let b=0;b<r;b++)Math.abs(y[b])<=1e-10&&(y[b]=0)}N===0&&(N=0),l.push({lre:N,lim:$,vre:p,vim:y})}return l.sort((f,h)=>Math.abs(f.lre-h.lre)<=c?h.lim-f.lim:h.lre-f.lre),{values:l.map(f=>new Tt(f.lre,f.lim)),vectors:Array.from({length:r},(f,h)=>l.map(m=>new Tt(m.vre[h],m.vim[h])))}}function Oi(e,t,r){for(let n=0;n<r-2;n++){let s=0;for(let f=n+1;f<r;f++)s+=e.re[f][n]**2+e.im[f][n]**2;if(s=Math.sqrt(s),s===0)continue;let o=Math.hypot(e.re[n+1][n],e.im[n+1][n]),i=o===0?1:e.re[n+1][n]/o,a=o===0?0:e.im[n+1][n]/o,c=new Array(r).fill(0),u=new Array(r).fill(0);for(let f=n+1;f<r;f++)c[f]=e.re[f][n],u[f]=e.im[f][n];c[n+1]+=i*s,u[n+1]+=a*s;let l=0;for(let f=n+1;f<r;f++)l+=c[f]**2+u[f]**2;if(l!==0){for(let f=0;f<r;f++){let h=0,m=0;for(let p=n+1;p<r;p++)h+=c[p]*e.re[p][f]+u[p]*e.im[p][f],m+=c[p]*e.im[p][f]-u[p]*e.re[p][f];h=2*h/l,m=2*m/l;for(let p=n+1;p<r;p++)e.re[p][f]-=c[p]*h-u[p]*m,e.im[p][f]-=c[p]*m+u[p]*h}for(let f of[e,t])for(let h=0;h<r;h++){let m=0,p=0;for(let y=n+1;y<r;y++)m+=f.re[h][y]*c[y]-f.im[h][y]*u[y],p+=f.re[h][y]*u[y]+f.im[h][y]*c[y];m=2*m/l,p=2*p/l;for(let y=n+1;y<r;y++)f.re[h][y]-=m*c[y]+p*u[y],f.im[h][y]-=p*c[y]-m*u[y]}for(let f=n+2;f<r;f++)e.re[f][n]=0,e.im[f][n]=0}}}function Ri(e,t,r,n,s){let o=r-1,i=0,a=0;for(;o>0;){let c=o;for(;c>0;){let h=Math.hypot(e.re[c-1][c-1],e.im[c-1][c-1])+Math.hypot(e.re[c][c],e.im[c][c]);if(Math.hypot(e.re[c][c-1],e.im[c][c-1])<=Number.EPSILON*(h===0?n:h)){e.re[c][c-1]=0,e.im[c][c-1]=0;break}c--}if(c===o){o--,i=0;continue}if(++i>s)throw new Error("eigen: QR iteration failed to converge.");if(++a>1e3*r)throw new Error("eigen: QR iteration failed to converge.");let u,l;if(i%10===0)u=e.re[o][o]+Math.hypot(e.re[o][o-1],e.im[o][o-1]),l=e.im[o][o];else{let h=e.re[o-1][o-1],m=e.im[o-1][o-1],p=e.re[o-1][o],y=e.im[o-1][o],d=e.re[o][o-1],w=e.im[o][o-1],g=e.re[o][o],M=e.im[o][o],v=(h-g)/2,N=(m-M)/2,$=v*v-N*N+(p*d-y*w),b=2*v*N+(p*w+y*d),x=Math.hypot($,b),S=Math.sqrt((x+$)/2),O=(b<0?-1:1)*Math.sqrt(Math.max(0,(x-$)/2)),A=(h+g)/2,F=(m+M)/2,k=A+S,I=F+O,E=A-S,P=F-O;Math.hypot(k-g,I-M)<=Math.hypot(E-g,P-M)?(u=k,l=I):(u=E,l=P)}for(let h=c;h<=o;h++)e.re[h][h]-=u,e.im[h][h]-=l;let f=[];for(let h=c;h<o;h++){let m=e.re[h][h],p=e.im[h][h],y=e.re[h+1][h],d=e.im[h+1][h],w=Math.hypot(m,p),g=Math.hypot(w,Math.hypot(y,d)),M,v,N;if(g===0)M=1,v=0,N=0;else if(w===0){M=0;let $=Math.hypot(y,d);v=y/$,N=-d/$}else{M=w/g;let $=m/w,b=p/w;v=($*y+b*d)/g,N=(b*y-$*d)/g}f.push([M,v,N]);for(let $=h;$<r;$++){let b=e.re[h][$],x=e.im[h][$],S=e.re[h+1][$],O=e.im[h+1][$];e.re[h][$]=M*b+(v*S-N*O),e.im[h][$]=M*x+(v*O+N*S),e.re[h+1][$]=-(v*b+N*x)+M*S,e.im[h+1][$]=-(v*x-N*b)+M*O}e.re[h+1][h]=0,e.im[h+1][h]=0}for(let h=0;h<f.length;h++){let m=c+h,[p,y,d]=f[h],w=Math.min(o,m+1);for(let[g,M]of[[e,w],[t,r-1]])for(let v=0;v<=M;v++){let N=g.re[v][m],$=g.im[v][m],b=g.re[v][m+1],x=g.im[v][m+1];g.re[v][m]=p*N+(b*y+x*d),g.im[v][m]=p*$+(x*y-b*d),g.re[v][m+1]=-(N*y-$*d)+p*b,g.im[v][m+1]=-(N*d+$*y)+p*x}}for(let h=c;h<=o;h++)e.re[h][h]+=u,e.im[h][h]+=l}for(let c=1;c<r;c++)for(let u=0;u<c;u++)e.re[c][u]=0,e.im[c][u]=0}var we=1e-12,At=e=>[...e].map(t=>[...t]),Vt=e=>T.fromArray(e.map(t=>T.fromArray(t))),Mn=e=>T.fromArray(e),Nn=e=>Array.from({length:e},(t,r)=>Array.from({length:e},(n,s)=>r===s?1:0)),Ve=(e,t)=>Array.from({length:e},()=>new Array(t).fill(0)),or=e=>e[0].map((t,r)=>e.map(n=>n[r])),Sr=(e,t)=>{let r=e.length,n=t[0].length,s=t.length,o=Ve(r,n);for(let i=0;i<r;i++)for(let a=0;a<s;a++)for(let c=0;c<n;c++)o[i][c]+=e[i][a]*t[a][c];return o},oe=class e{static lu(t){let r=At(t),n=r.length,s=Nn(n),o=Nn(n),i=1;for(let a=0;a<n;a++){let c=a;for(let u=a+1;u<n;u++)Math.abs(r[u][a])>Math.abs(r[c][a])&&(c=u);if(c!==a){[r[a],r[c]]=[r[c],r[a]],[o[a],o[c]]=[o[c],o[a]];for(let u=0;u<a;u++)[s[a][u],s[c][u]]=[s[c][u],s[a][u]];i=-i}if(!(Math.abs(r[a][a])<we))for(let u=a+1;u<n;u++){let l=r[u][a]/r[a][a];s[u][a]=l;for(let f=a;f<n;f++)r[u][f]-=l*r[a][f]}}return{L:Vt(s),U:Vt(r),P:Vt(o),sign:i}}static solve(t,r){let n=At(t),s=n.length,o=[...r],{L:i,U:a,P:c}=e.lu(n),u=At(i),l=At(a),h=At(c).map(y=>y.reduce((d,w,g)=>d+w*o[g],0)),m=new Array(s).fill(0);for(let y=0;y<s;y++){let d=h[y];for(let w=0;w<y;w++)d-=u[y][w]*m[w];m[y]=d}let p=new Array(s).fill(0);for(let y=s-1;y>=0;y--){let d=m[y];for(let w=y+1;w<s;w++)d-=l[y][w]*p[w];p[y]=Math.abs(l[y][y])<we?0:d/l[y][y]}return Mn(p)}static rref(t){let r=At(t),n=r.length,s=r[0].length,o=0;for(let i=0;i<n&&o<s;i++,o++){let a=i;for(;o<s&&Math.abs(r[a][o])<we;)if(a++,a===n&&(a=i,o++,o===s))return Vt(r);[r[a],r[i]]=[r[i],r[a]];let c=r[i][o];for(let u=0;u<s;u++)r[i][u]/=c;for(let u=0;u<n;u++){if(u===i)continue;let l=r[u][o];for(let f=0;f<s;f++)r[u][f]-=l*r[i][f]}}return Vt(r)}static rank(t){return At(e.rref(t)).filter(n=>n.some(s=>Math.abs(s)>1e-9)).length}static nullSpace(t){let r=At(e.rref(t)),n=r.length,s=r[0].length,o=[];for(let c=0;c<n;c++){let u=r[c].findIndex(l=>Math.abs(l)>1e-9);u!==-1&&o.push(u)}let i=[];for(let c=0;c<s;c++)o.includes(c)||i.push(c);let a=[];for(let c of i){let u=new Array(s).fill(0);u[c]=1;for(let l=0;l<o.length;l++)u[o[l]]=-r[l][c];a.push(u)}return Vt(a.length?a:[new Array(s).fill(0)])}static qr(t){let r=At(t),n=r.length,s=r[0].length,o=Ve(n,s),i=Ve(s,s),a=or(r);for(let c=0;c<s;c++){let u=[...a[c]];for(let f=0;f<c;f++){let h=0;for(let m=0;m<n;m++)h+=o[m][f]*u[m];i[f][c]=h;for(let m=0;m<n;m++)u[m]-=h*o[m][f]}let l=Math.hypot(...u);i[c][c]=l,l<we&&(l=1);for(let f=0;f<n;f++)o[f][c]=u[f]/l}return{Q:Vt(o),R:Vt(i)}}static cholesky(t){let r=At(t),n=r.length,s=Ve(n,n);for(let o=0;o<n;o++){let i=r[o][o];for(let a=0;a<o;a++)i-=s[o][a]*s[o][a];if(i<=0)throw new Error("Matrix is not positive-definite.");s[o][o]=Math.sqrt(i);for(let a=o+1;a<n;a++){let c=r[a][o];for(let u=0;u<o;u++)c-=s[a][u]*s[o][u];s[a][o]=c/s[o][o]}}return Vt(s)}static eigenSymmetric(t,r=100){let n=At(t),s=n.length,o=Nn(s);for(let a=0;a<r;a++){let c=0;for(let u=0;u<s;u++)for(let l=u+1;l<s;l++)c+=n[u][l]*n[u][l];if(c<we)break;for(let u=0;u<s;u++)for(let l=u+1;l<s;l++){if(Math.abs(n[u][l])<we)continue;let f=(n[l][l]-n[u][u])/(2*n[u][l]),h=Math.sign(f||1)/(Math.abs(f)+Math.sqrt(f*f+1)),m=1/Math.sqrt(h*h+1),p=h*m;for(let y=0;y<s;y++){let d=n[y][u],w=n[y][l];n[y][u]=m*d-p*w,n[y][l]=p*d+m*w}for(let y=0;y<s;y++){let d=n[u][y],w=n[l][y];n[u][y]=m*d-p*w,n[l][y]=p*d+m*w}for(let y=0;y<s;y++){let d=o[y][u],w=o[y][l];o[y][u]=m*d-p*w,o[y][l]=p*d+m*w}}}let i=n.map((a,c)=>({value:a[c],vec:o.map(u=>u[c])}));return i.sort((a,c)=>c.value-a.value),{values:Mn(i.map(a=>a.value)),vectors:Vt(or(i.map(a=>a.vec)))}}static eigen(t){return xs([...t].map(r=>[...r]))}static svd(t){let r=At(t),n=r.length,s=r[0].length,o=or(r),i=Sr(o,r),{values:a,vectors:c}=e.eigenSymmetric(i),u=At(c),l=[...a].map(h=>Math.sqrt(Math.max(h,0))),f=Ve(n,s);for(let h=0;h<s;h++){let m=u.map(d=>d[h]),p=r.map(d=>d.reduce((w,g,M)=>w+g*m[M],0)),y=l[h];for(let d=0;d<n;d++)f[d][h]=y>we?p[d]/y:0}return{U:Vt(f),S:Mn(l),V:Vt(u)}}static leastSquares(t,r){let n=At(t),s=or(n),o=Sr(s,n),i=[...r],a=s.map(c=>c.reduce((u,l,f)=>u+l*i[f],0));return e.solve(Vt(o),a)}static pseudoInverse(t){let{U:r,S:n,V:s}=e.svd(t),o=At(r),i=At(s),a=[...n],c=a.length,u=a.map(f=>f>1e-9?1/f:0),l=Ve(c,c);for(let f=0;f<c;f++)l[f][f]=u[f];return Vt(Sr(Sr(i,l),or(o)))}static frobeniusNorm(t){return Math.hypot(...At(t).flat())}static spectralNorm(t){return Math.max(...e.svd(t).S)}static conditionNumber(t){let r=[...e.svd(t).S],n=Math.min(...r);return n<we?Number.POSITIVE_INFINITY:Math.max(...r)/n}};var bs=[0,-.5384693101056831,.5384693101056831,-.906179845938664,.906179845938664],Ci=[.5688888888888889,.4786286704993665,.4786286704993665,.2369268850561891,.2369268850561891],ir=class{static bisection(t,r,n,s=1e-12,o=200){let i=r,a=n,c=t(i);if(c*t(a)>0)throw new Error("bisection requires f(a) and f(b) to have opposite signs.");for(let u=0;u<o;u++){let l=(i+a)/2,f=t(l);if(Math.abs(f)<s||(a-i)/2<s)return l;c*f<0?a=l:(i=l,c=f)}return(i+a)/2}static secant(t,r,n,s=1e-12,o=200){let i=r,a=n,c=t(i),u=t(a);for(let l=0;l<o;l++){if(Math.abs(u)<s)return a;let f=u-c;if(f===0)break;let h=a-u*(a-i)/f;i=a,c=u,a=h,u=t(a)}return a}static newton(t,r,n,s=1e-12,o=200){let i=r,a=n??(c=>(t(c+1e-7)-t(c-1e-7))/2e-7);for(let c=0;c<o;c++){let u=t(i);if(Math.abs(u)<s)return i;let l=a(i);if(l===0)break;i-=u/l}return i}static brent(t,r,n,s=1e-12,o=200){let i=t(r),a=t(n);if(i*a>0)throw new Error("brent requires f(a) and f(b) to have opposite signs.");Math.abs(i)<Math.abs(a)&&([r,n]=[n,r],[i,a]=[a,i]);let c=r,u=i,l=n-r,f=!0;for(let h=0;h<o;h++){if(Math.abs(a)<s||Math.abs(n-r)<s)return n;let m;i!==u&&a!==u?m=r*a*u/((i-a)*(i-u))+n*i*u/((a-i)*(a-u))+c*i*a/((u-i)*(u-a)):m=n-a*(n-r)/(a-i),m<(3*r+n)/4||m>n||f&&Math.abs(m-n)>=Math.abs(n-c)/2||!f&&Math.abs(m-n)>=Math.abs(c-l)/2?(m=(r+n)/2,f=!0):f=!1;let y=t(m);l=c,c=n,u=a,i*y<0?(n=m,a=y):(r=m,i=y),Math.abs(i)<Math.abs(a)&&([r,n]=[n,r],[i,a]=[a,i])}return n}static trapezoid(t,r,n,s=1e3){let o=(n-r)/s,i=(t(r)+t(n))/2;for(let a=1;a<s;a++)i+=t(r+a*o);return i*o}static simpson(t,r,n,s=1e3){let o=s%2===0?s:s+1,i=(n-r)/o,a=t(r)+t(n);for(let c=1;c<o;c++)a+=(c%2===0?2:4)*t(r+c*i);return a*i/3}static adaptiveSimpson(t,r,n,s=1e-10,o=50){let i=(h,m,p,y,d)=>(m-h)/6*(p+4*y+d),a=(h,m,p,y,d,w,g,M)=>{let v=(h+m)/2,N=(h+v)/2,$=(v+m)/2,b=t(N),x=t($),S=i(h,v,p,b,y),O=i(v,m,y,x,d);return M<=0||Math.abs(S+O-w)<=15*g?S+O+(S+O-w)/15:a(h,v,p,b,y,S,g/2,M-1)+a(v,m,y,x,d,O,g/2,M-1)},c=(r+n)/2,u=t(r),l=t(c),f=t(n);return a(r,n,u,l,f,i(r,n,u,l,f),s,o)}static gaussLegendre(t,r,n){let s=(n-r)/2,o=(r+n)/2,i=0;for(let a=0;a<bs.length;a++)i+=Ci[a]*t(o+s*bs[a]);return i*s}static euler(t,r,n,s,o=.01){let i=[{t:n,y:[...r]}],a=n,c=[...r];for(;a<s-1e-12;){let u=Math.min(o,s-a),l=t(a,c);c=c.map((f,h)=>f+u*l[h]),a+=u,i.push({t:a,y:[...c]})}return i}static rk4(t,r,n,s,o=.01){let i=[{t:n,y:[...r]}],a=n,c=[...r];for(;a<s-1e-12;){let u=Math.min(o,s-a),l=t(a,c),f=t(a+u/2,c.map((p,y)=>p+u/2*l[y])),h=t(a+u/2,c.map((p,y)=>p+u/2*f[y])),m=t(a+u,c.map((p,y)=>p+u*h[y]));c=c.map((p,y)=>p+u/6*(l[y]+2*f[y]+2*h[y]+m[y])),a+=u,i.push({t:a,y:[...c]})}return i}static levenbergMarquardt(t,r,n,s,o={}){let{lambda0:i=.01,tolerance:a=1e-10,maxIterations:c=200}=o,u=r.length,l=n.length,f=[...r],h=i;function m(v){return n.map((N,$)=>t(N,v)-s[$])}function p(v){return v.reduce((N,$)=>N+$*$,0)}function y(v){let N=Array.from({length:l},()=>new Array(u).fill(0));for(let $=0;$<u;$++){let b=1e-6*(Math.abs(v[$])+1e-6),x=[...v],S=[...v];x[$]+=b,S[$]-=b;let O=m(x),A=m(S);for(let F=0;F<l;F++)N[F][$]=(O[F]-A[F])/(2*b)}return N}let d=m(f),w=p(d),g=0,M=!1;for(;g<c&&!(w<a);g++){let v=y(f),N=Array.from({length:u},()=>new Array(u).fill(0)),$=new Array(u).fill(0);for(let O=0;O<u;O++){for(let F=0;F<u;F++){let k=0;for(let I=0;I<l;I++)k+=v[I][O]*v[I][F];N[O][F]=k}let A=0;for(let F=0;F<l;F++)A+=v[F][O]*d[F];$[O]=A}let b=w,x=!1;for(let O=0;O<30&&!x;O++){let A=N.map((P,j)=>P.map((L,U)=>L+(j===U?h*N[j][j]:0))),F;try{F=[...oe.solve(A,$.map(P=>-P))]}catch{h*=10;continue}let k=f.map((P,j)=>P+F[j]),I=m(k),E=p(I);Number.isFinite(E)&&E<w?(f=k,d=I,w=E,h=Math.max(h/10,1e-12),x=!0,M=!0):h*=10}if(!x||(b-w)/Math.max(1,b)<1e-12)break}return{params:f,residualNorm:Math.sqrt(w),iterations:g,converged:M||w<a}}};var Me=class extends Error{constructor(t){super(t),this.name="ShaderUnsupportedError"}},Ns=new Set(["NULL","Self","abs","abstract","acos","acosh","active","alias","alignas","alignof","all","any","array","arrayLength","as","asin","asinh","asm","asm_fragment","async","atan","atan2","atanh","atomic","attribute","auto","await","become","binding_array","bitcast","bool","break","buffer","bvec2","bvec3","bvec4","case","cast","catch","ceil","centroid","clamp","class","co_await","co_return","co_yield","coherent","column_major","common","compile","compile_fragment","concept","const","const_assert","const_cast","consteval","constexpr","constinit","continue","continuing","cos","cosh","countOneBits","crate","cross","dFdx","dFdy","debugger","decltype","default","degrees","delete","demote","demote_to_helper","determinant","diagnostic","discard","distance","do","dot","dvec2","dvec3","dvec4","dynamic_cast","else","enable","enum","equal","exp","exp2","explicit","export","extends","extern","external","f16","f32","faceforward","fallthrough","false","filter","final","finally","fixed","flat","float","floatBitsToInt","floatBitsToUint","floor","fma","fn","for","fract","friend","from","fvec2","fvec3","fvec4","fwidth","fxgroup","get","goto","greaterThan","greaterThanEqual","groupshared","half","highp","hvec2","hvec3","hvec4","i32","if","impl","implements","import","in","inline","inout","input","instanceof","int","intBitsToFloat","interface","invariant","inverse","inverseSqrt","inversesqrt","isampler1D","isampler1DArray","isampler2D","isampler2DArray","isampler2DMS","isampler2DMSArray","isampler2DRect","isampler3D","isamplerBuffer","isamplerCube","isinf","isnan","ivec2","ivec3","ivec4","layout","length","lessThan","lessThanEqual","let","log","log2","long","loop","lowp","macro","macro_rules","main","mat2","mat2x2","mat2x2f","mat2x3","mat2x4","mat3","mat3x2","mat3x3","mat3x3f","mat3x4","mat4","mat4x2","mat4x3","mat4x4","mat4x4f","match","matrixCompMult","max","mediump","meta","min","mix","mod","modf","module","move","mut","mutable","namespace","new","nil","noexcept","noinline","nointerpolation","noperspective","normalize","not","notEqual","null","nullptr","of","operator","out","outerProduct","output","override","packHalf2x16","packSnorm2x16","packUnorm2x16","package","packoffset","partition","pass","patch","pixelfragment","pow","precise","precision","premerge","priv","protected","ptr","pub","public","radians","readonly","ref","reflect","refract","regardless","register","reinterpret_cast","require","requires","resource","restrict","return","reverseBits","round","roundEven","sample","sampler","sampler1D","sampler1DArray","sampler1DArrayShadow","sampler1DShadow","sampler2D","sampler2DArray","sampler2DArrayShadow","sampler2DMS","sampler2DMSArray","sampler2DRect","sampler2DRectShadow","sampler2DShadow","sampler3D","samplerBuffer","samplerCube","samplerCubeShadow","sampler_comparison","saturate","select","self","set","shared","short","sign","sin","sinh","sizeof","smooth","smoothstep","snorm","sqrt","static","static_assert","static_cast","std","step","struct","subroutine","super","superp","switch","tan","tanh","target","template","texelFetch","texelFetchOffset","texture","textureGrad","textureGradOffset","textureLod","textureLodOffset","textureOffset","textureProj","textureProjGrad","textureProjGradOffset","textureProjLod","textureProjLodOffset","textureProjOffset","textureSize","texture_1d","texture_2d","texture_2d_array","texture_3d","texture_cube","texture_cube_array","texture_depth_2d","texture_multisampled_2d","texture_storage_1d","texture_storage_2d","texture_storage_2d_array","texture_storage_3d","this","thread_local","throw","trait","transpose","true","trunc","try","type","typedef","typeid","typename","typeof","u32","uint","uintBitsToFloat","uniform","union","unless","unorm","unpackHalf2x16","unpackSnorm2x16","unpackUnorm2x16","unsafe","unsigned","unsized","usampler1D","usampler1DArray","usampler2D","usampler2DArray","usampler2DMS","usampler2DMSArray","usampler2DRect","usampler3D","usamplerBuffer","usamplerCube","use","using","uvec2","uvec3","uvec4","var","varying","vec2","vec2f","vec2h","vec2i","vec2u","vec3","vec3f","vec3h","vec3i","vec3u","vec4","vec4f","vec4h","vec4i","vec4u","virtual","void","volatile","wgsl","where","while","with","writeonly","yield"]),ji="2.302585092994046";function $n(e,t){if(!Number.isFinite(e))throw new Me(`constant ${e} has no shader literal`);let r=String(e);return/[.e]/i.test(r)?/^-?\d+e/i.test(r)&&(r=r.replace(/e/i,".0e")):r+=".0",e<0||Object.is(e,-0)?`(${r})`:r}function ws(e,t,r){return r.d==="glsl"?`vec2(${e}, ${t})`:`vec2<f32>(${e}, ${t})`}function ar(e,t){return e.helpers.add(t),`mx_${t}`}function $s(e){if(e.type==="const")return e.value;if(e.type==="neg"&&e.arg.type==="const")return-e.arg.value}var vs={lt:"<",le:"<=",gt:">",ge:">=",eq:"==",ne:"!="};function Li(e){if(!Object.hasOwn(vs,e))throw new Me(`unknown comparison operator "${e}"`);return vs[e]}function Ms(e,t){if(e.type==="cmp"){let r=Li(e.op);return`${it(e.left,t)} ${r} ${it(e.right,t)}`}return`${it(e,t)} != 0.0`}function ve(e){throw new Me(`${e} is not supported by the shader compiler`)}function it(e,t){switch(e.type){case"const":return t.complex?ws($n(e.value,t),"0.0",t):$n(e.value,t);case"var":{if(t.complex&&e.name==="i"&&!t.vars.has("i"))return ws("0.0","1.0",t);if(!t.vars.has(e.name))throw new Me(`variable "${e.name}" is not in the variables list`);return t.used.add(e.name),e.name}case"neg":return`(-${it(e.arg,t)})`;case"add":return`(${it(e.left,t)} + ${it(e.right,t)})`;case"sub":return`(${it(e.left,t)} - ${it(e.right,t)})`;case"mul":return t.complex?`${ar(t,"cmul")}(${it(e.left,t)}, ${it(e.right,t)})`:`(${it(e.left,t)} * ${it(e.right,t)})`;case"div":return t.complex?`${ar(t,"cdiv")}(${it(e.left,t)}, ${it(e.right,t)})`:`(${it(e.left,t)} / ${it(e.right,t)})`;case"pow":return t.complex?Vi(e.base,e.exp,t):qi(e.base,e.exp,t);case"func":return t.complex?Ui(e.name,it(e.arg,t),t):Ti(e.name,it(e.arg,t),t);case"call2":{t.complex&&ve(`${e.name} over complex numbers`);let r=it(e.left,t),n=it(e.right,t);switch(e.name){case"atan2":return t.d==="glsl"?`atan(${r}, ${n})`:`atan2(${r}, ${n})`;case"hypot":return t.d==="glsl"?`length(vec2(${r}, ${n}))`:`length(vec2<f32>(${r}, ${n}))`;case"min":case"max":return`${e.name}(${r}, ${n})`;default:return ve(`${e.name}`)}}case"cmp":{t.complex&&ve("comparison over complex numbers");let r=Ms(e,t);return t.d==="glsl"?`(${r} ? 1.0 : 0.0)`:`select(0.0, 1.0, ${r})`}case"piecewise":{t.complex&&ve("piecewise over complex numbers");let r=it(e.otherwise,t);for(let n=e.branches.length-1;n>=0;n--){let s=e.branches[n],o=Ms(s.cond,t),i=it(s.expr,t);r=t.d==="glsl"?`(${o} ? ${i} : ${r})`:`select(${r}, ${i}, ${o})`}return r}case"sum":return ve("sum");case"product":return ve("product")}}function qi(e,t,r){let n=it(e,r),s=$s(t);if(s!==void 0&&Number.isInteger(s)&&Math.abs(s)<=4){let o=s;if(o===0)return"1.0";if(o===1)return n;let i=Array.from({length:Math.abs(o)},()=>n).join(" * ");return o>0?`(${i})`:`(1.0 / (${i}))`}if(s!==void 0&&Number.isInteger(s)){let o=s,i=Math.abs(o)%2===1,a=`pow(abs(${n}), ${$n(o,r)})`;return i?`(sign(${n}) * ${a})`:a}return`pow(${n}, ${it(t,r)})`}function Ti(e,t,r){let n=r.d==="glsl";switch(e){case"sin":case"cos":case"tan":case"exp":case"sqrt":case"asin":case"acos":case"atan":case"sinh":case"cosh":case"tanh":case"asinh":case"acosh":case"atanh":case"abs":case"sign":case"floor":case"ceil":case"round":case"trunc":case"log2":return`${e}(${t})`;case"ln":return`log(${t})`;case"log10":return`(log(${t}) / ${ji})`;case"cot":return`(1.0 / tan(${t}))`;case"sec":return`(1.0 / cos(${t}))`;case"csc":return`(1.0 / sin(${t}))`;case"coth":return`(1.0 / tanh(${t}))`;case"sech":return`(1.0 / cosh(${t}))`;case"csch":return`(1.0 / sinh(${t}))`;case"acot":return`atan(1.0 / ${t})`;case"asec":return`acos(1.0 / ${t})`;case"acsc":return`asin(1.0 / ${t})`;case"acoth":return`atanh(1.0 / ${t})`;case"asech":return`acosh(1.0 / ${t})`;case"acsch":return`asinh(1.0 / ${t})`;case"cbrt":return`(sign(${t}) * pow(abs(${t}), 0.3333333333333333))`;case"expm1":return`(exp(${t}) - 1.0)`;case"log1p":return`log(1.0 + ${t})`;case"sigmoid":return`(1.0 / (1.0 + exp(-${t})))`;case"relu":return n?`max(${t}, 0.0)`:`max(${t}, 0.0)`;default:return ve(`function ${e}`)}}function Vi(e,t,r){let n=it(e,r),s=$s(t);return s!==void 0&&Number.isInteger(s)&&Math.abs(s)<=64?`${ar(r,"cpowi")}(${n}, ${s})`:`${ar(r,"cpow")}(${n}, ${it(t,r)})`}function Ui(e,t,r){switch(e){case"exp":case"ln":case"sqrt":case"sin":case"cos":case"tan":case"sinh":case"cosh":case"tanh":case"abs":return`${ar(r,`c${e}`)}(${t})`;default:return ve(`function ${e} over complex numbers`)}}var Bi=["cmul","cdiv","cexp","cln","cpow","cpowi","csqrt","csin","ccos","ctan","csinh","ccosh","ctanh","cabs"],Gi={cpow:["cmul","cexp","cln"],cpowi:["cmul","cdiv"],ctan:["cdiv","csin","ccos"],ctanh:["cdiv","csinh","ccosh"]};function Di(e,t){let r=t==="glsl"?"vec2":"vec2<f32>",n=(a,c,u)=>t==="glsl"?`${r} mx_${a}(${c.replace(/(\w+): vec2|(\w+): int/g,(l,f,h)=>f?`vec2 ${f}`:`int ${h}`)}) {
3
+ ${u}
4
+ }`:`fn mx_${a}(${c.replace(/: vec2/g,": vec2<f32>")}) -> ${r} {
5
+ ${u}
6
+ }`,s=(a,c,u)=>t==="glsl"?` ${a} ${c} = ${u};`:` let ${c}: ${a==="float"?"f32":a} = ${u};`,o=a=>` return ${a};`,i=(a,c)=>`${r}(${a}, ${c})`;switch(e){case"cmul":return n("cmul","a: vec2, b: vec2",o(i("a.x * b.x - a.y * b.y","a.x * b.y + a.y * b.x")));case"cdiv":return n("cdiv","a: vec2, b: vec2",[s("float","m","b.x * b.x + b.y * b.y"),o(i("(a.x * b.x + a.y * b.y) / m","(a.y * b.x - a.x * b.y) / m"))].join(`
7
+ `));case"cexp":return n("cexp","z: vec2",o(`exp(z.x) * ${i("cos(z.y)","sin(z.y)")}`));case"cln":return n("cln","z: vec2",o(i("log(length(z))",t==="glsl"?"atan(z.y, z.x)":"atan2(z.y, z.x)")));case"cpow":return n("cpow","a: vec2, b: vec2",o("mx_cexp(mx_cmul(b, mx_cln(a)))"));case"cpowi":return t==="glsl"?`vec2 mx_cpowi(vec2 z, int n) {
8
+ int k = n < 0 ? -n : n;
9
+ vec2 r = vec2(1.0, 0.0);
10
+ vec2 s = z;
11
+ for (int j = 0; j < 7; j++) {
12
+ if ((k & 1) == 1) r = mx_cmul(r, s);
13
+ s = mx_cmul(s, s);
14
+ k = k >> 1;
15
+ }
16
+ return n < 0 ? mx_cdiv(vec2(1.0, 0.0), r) : r;
17
+ }`:`fn mx_cpowi(z: vec2<f32>, n: i32) -> vec2<f32> {
18
+ var k: i32 = abs(n);
19
+ var r: vec2<f32> = vec2<f32>(1.0, 0.0);
20
+ var s: vec2<f32> = z;
21
+ for (var j: i32 = 0; j < 7; j = j + 1) {
22
+ if ((k & 1) == 1) { r = mx_cmul(r, s); }
23
+ s = mx_cmul(s, s);
24
+ k = k >> 1u;
25
+ }
26
+ if (n < 0) { return mx_cdiv(vec2<f32>(1.0, 0.0), r); }
27
+ return r;
28
+ }`;case"csqrt":return n("csqrt","z: vec2",[s("float","r","length(z)"),o(i("sqrt(max(0.5 * (r + z.x), 0.0))",t==="glsl"?"(z.y < 0.0 ? -1.0 : 1.0) * sqrt(max(0.5 * (r - z.x), 0.0))":"select(1.0, -1.0, z.y < 0.0) * sqrt(max(0.5 * (r - z.x), 0.0))"))].join(`
29
+ `));case"csin":return n("csin","z: vec2",o(i("sin(z.x) * cosh(z.y)","cos(z.x) * sinh(z.y)")));case"ccos":return n("ccos","z: vec2",o(i("cos(z.x) * cosh(z.y)","-sin(z.x) * sinh(z.y)")));case"ctan":return n("ctan","z: vec2",o("mx_cdiv(mx_csin(z), mx_ccos(z))"));case"csinh":return n("csinh","z: vec2",o(i("sinh(z.x) * cos(z.y)","cosh(z.x) * sin(z.y)")));case"ccosh":return n("ccosh","z: vec2",o(i("cosh(z.x) * cos(z.y)","sinh(z.x) * sin(z.y)")));case"ctanh":return n("ctanh","z: vec2",o("mx_cdiv(mx_csinh(z), mx_ccosh(z))"));case"cabs":return n("cabs","z: vec2",o(i("length(z)","0.0")));default:throw new Error(`unknown helper ${e}`)}}function Zi(e){return/^[A-Za-z][A-Za-z0-9_]*$/.test(e)&&!Ns.has(e)&&!e.includes("__")&&!e.startsWith("mx_")&&!e.startsWith("gl_")}function Sn(e,t,r={}){let n=r.complex===!0,s=r.variables??[n?"z":"x"];for(let f of s)if(!/^[A-Za-z][A-Za-z0-9_]*$/.test(f)||Ns.has(f)||f.includes("__")||f.startsWith("mx_")||f.startsWith("gl_"))throw new Me(`variable name "${f}" is not a safe shader identifier`);let o=r.functionName;if(o!==void 0&&(!Zi(o)||o==="main"))throw new Me(`function name "${o}" is not a safe shader identifier`);let i={d:t,complex:n,vars:new Set(s),used:new Set,helpers:new Set},a=it(e,i),c=new Set(i.helpers);for(let f=!0;f;){f=!1;for(let h of[...c])for(let m of Gi[h]??[])c.has(m)||(c.add(m),f=!0)}let u=Bi.filter(f=>c.has(f)).map(f=>Di(f,t)).join(`
30
+
31
+ `),l=u;if(r.functionName!==void 0){let f=n?t==="glsl"?"vec2":"vec2<f32>":t==="glsl"?"float":"f32",h=s.map(p=>t==="glsl"?`${f} ${p}`:`${p}: ${f}`).join(", "),m=t==="glsl"?`${f} ${r.functionName}(${h}) {
32
+ return ${a};
33
+ }`:`fn ${r.functionName}(${h}) -> ${f} {
34
+ return ${a};
35
+ }`;l=u?`${u}
36
+
37
+ ${m}`:m}return{expression:a,helpers:u,source:l,variables:[...i.used].sort()}}var js=["sin","cos","tan","exp","ln","sqrt","asin","acos","atan","sinh","cosh","tanh","cot","sec","csc","asinh","acosh","atanh","coth","sech","csch","acot","asec","acsc","acoth","asech","acsch","abs","log10","log2","cbrt","floor","ceil","round","sign","trunc","expm1","log1p","sigmoid","erf","relu"],Ls=["atan2","hypot","min","max","gcd","lcm"],qs={arcsin:"asin",arccos:"acos",arctan:"atan",arcsinh:"asinh",arccosh:"acosh",arctanh:"atanh",arccot:"acot",arcsec:"asec",arccsc:"acsc",arccoth:"acoth",arcsech:"asech",arccsch:"acsch",sgn:"sign",logistic:"sigmoid"},Ts=[...js,...Object.keys(qs),...Ls,"log","clamp","piecewise","sum","product"],z=e=>({type:"const",value:e}),et=e=>({type:"var",name:e}),Q=(e,t)=>({type:"add",left:e,right:t}),W=(e,t)=>({type:"sub",left:e,right:t}),R=(e,t)=>({type:"mul",left:e,right:t}),X=(e,t)=>({type:"div",left:e,right:t}),ot=(e,t)=>({type:"pow",base:e,exp:t}),xt=e=>({type:"neg",arg:e}),q=(e,t)=>({type:"func",name:e,arg:t}),ee=(e,t,r)=>({type:"call2",name:e,left:t,right:r}),De=(e,t,r)=>({type:"cmp",op:e,left:t,right:r}),de=(e,t)=>({type:"piecewise",branches:e,otherwise:t}),ce=(e,t,r,n)=>({type:"sum",variable:e,from:t,to:r,body:n}),Se=(e,t,r,n)=>({type:"product",variable:e,from:t,to:r,body:n}),kt=(e,t)=>e.type==="const"&&(t===void 0||e.value===t),K=(e,t)=>{switch(e.type){case"const":return!1;case"var":return e.name===t;case"neg":return K(e.arg,t);case"func":return K(e.arg,t);case"pow":return K(e.base,t)||K(e.exp,t);case"piecewise":return e.branches.some(r=>K(r.cond,t)||K(r.expr,t))||K(e.otherwise,t);case"sum":case"product":return K(e.from,t)||K(e.to,t)||e.variable!==t&&K(e.body,t);default:return K(e.left,t)||K(e.right,t)}},jt=(e,t=new Set)=>{switch(e.type){case"const":return t;case"var":return t.add(e.name),t;case"neg":case"func":return jt(e.arg,t),t;case"pow":return jt(e.base,t),jt(e.exp,t),t;case"piecewise":for(let r of e.branches)jt(r.cond,t),jt(r.expr,t);return jt(e.otherwise,t),t;case"sum":case"product":{jt(e.from,t),jt(e.to,t);let r=jt(e.body,new Set);for(let n of r)n!==e.variable&&t.add(n);return t}default:return jt(e.left,t),jt(e.right,t),t}};function Xi(e,t){let r=o=>t[o]==="positive"||t[o]==="nonnegative",n=o=>t[o]==="negative"||t[o]==="nonpositive";function s(o){switch(o.type){case"const":case"var":return o;case"neg":return{type:"neg",arg:s(o.arg)};case"func":{let i=s(o.arg);if(o.name==="sqrt"&&i.type==="pow"&&kt(i.exp,2)&&i.base.type==="var"){if(r(i.base.name))return i.base;if(n(i.base.name))return{type:"neg",arg:i.base}}if(o.name==="abs"&&i.type==="var"){if(r(i.name))return i;if(n(i.name))return{type:"neg",arg:i}}return{type:"func",name:o.name,arg:i}}case"pow":return{type:"pow",base:s(o.base),exp:s(o.exp)};case"piecewise":return{type:"piecewise",branches:o.branches.map(i=>({cond:s(i.cond),expr:s(i.expr)})),otherwise:s(o.otherwise)};case"sum":case"product":return{...o,from:s(o.from),to:s(o.to),body:s(o.body)};default:return{...o,left:s(o.left),right:s(o.right)}}}return s(e)}var Lt=class extends Error{constructor(t="This expression cannot be integrated by the elementary rules implemented."){super(t),this.name="NotIntegrableError"}},Ar=class extends Error{constructor(t="solveSystem only supports systems that are linear in the given variables."){super(t),this.name="NonLinearSystemError"}},Ir=class extends Error{constructor(t="solveSystem: the system is singular (rank < number of variables) and has no unique solution."){super(t),this.name="SingularSystemError"}},Ge=class extends Error{constructor(t="sumSeries: the series does not appear to converge (or converges too slowly to sum numerically)."){super(t),this.name="SeriesDivergesError"}},Fr=class extends Error{names;constructor(t){super(`Expression references variable${t.length===1?"":"s"} not in the declared set: ${t.join(", ")}`),this.name="UndeclaredVariableError",this.names=t}},Fe=class extends Error{constructor(t="solveSystemNumeric: Newton's method did not converge from the given initial guess."){super(t),this.name="SystemDidNotConvergeError"}},kr=class extends Error{constructor(t="integrateDefinite: the integrand appears to have a singularity strictly inside the integration bounds."){super(t),this.name="IntegrationSingularityError"}};var zr=class extends Error{constructor(t="solveOdeClosedForm: dy/dx matches none of the five recognized closed-form methods (separable, linear first-order, homogeneous, Bernoulli, exact)."){super(t),this.name="NotSeparableError"}},fe=class extends Error{constructor(t="solveOdeClosedForm: the equation matches a recognized closed-form method, but the antiderivative(s) it requires aren't in this engine's elementary-rule coverage."){super(t),this.name="NoClosedFormError"}},Pr=class extends Error{constructor(t="solveOde2ndOrderConstCoeff: a === 0 -- this isn't actually a second-order equation (it's first-order, or not an ODE at all in the caller's intended sense)."){super(t),this.name="DegenerateOdeError"}},Or=class extends Error{constructor(t="solve: the expression is identically zero -- every real number is a solution (infinitely many), not none."){super(t),this.name="InfiniteSolutionsError"}},C=class e{static parse(t,r={}){return new On(t,r??{}).parse()}static differentiate(t,r="x"){let n=typeof t=="string"?e.parse(t):t;return B(tt(n,r))}static differentiateSteps(t,r="x"){let n=typeof t=="string"?e.parse(t):t,s=[],o=vt(n,r,s);return{steps:s,result:B(o)}}static simplify(t){return Ft(B(t))}static simplifyAssuming(t,r){let n=B(t),s=Xi(n,r);return B(s)}static integrate(t,r="x"){let n=typeof t=="string"?e.parse(t):t;return B(St(n,r))}static integrateDefinite(t,r,n,s="x",o={}){let i=B(typeof t=="string"?e.parse(t):t),a=ft(i);if(ta(c=>a({...o,[s]:c}),r,n))throw new kr;try{let c=B(St(i,s)),u=l=>G(c,{...o,[s]:l});return u(n)-u(r)}catch(c){if(!(c instanceof Lt))throw c;return ir.adaptiveSimpson(u=>a({...o,[s]:u}),r,n)}}static solveOdeClosedForm(t,r,n,s="x",o="y"){let i=B(typeof t=="string"?e.parse(t):t),a=ea(i,s,o);if(a)return Bs(a,s,o,r,n);let c=ra(i,s,o);if(c)return Gs(c,s,o,r,n);let u=sa(i,s,o);if(u)return oa(u,s,o,r,n);let l=ia(i,s,o);if(l)return aa(l,s,o,r,n);let f=ca(i,s,o);if(f)return ua(f,s,o,r,n);throw new zr}static solveOde2ndOrderConstCoeff(t,r,n,s,o,i){if(t===0)throw new Pr;let a=r*r-4*t*n,c=et("x");if(Math.abs(a)<1e-9){let d=-r/(2*t),w=Math.exp(-d*s),g=(i-d*o)*w,M=o*w-g*s;return R(Q(z(M),R(z(g),c)),q("exp",R(z(d),c)))}if(a>0){let d=Math.sqrt(a),w=(-r+d)/(2*t),g=(-r-d)/(2*t),M=Math.exp(w*s),v=Math.exp(g*s),[N,$]=oe.solve([[M,v],[w*M,g*v]],[o,i]);return Q(R(z(N),q("exp",R(z(w),c))),R(z($),q("exp",R(z(g),c))))}let u=-r/(2*t),l=Math.sqrt(4*t*n-r*r)/(2*t),f=Math.exp(u*s),h=Math.cos(l*s),m=Math.sin(l*s),[p,y]=oe.solve([[f*h,f*m],[-f*l*m,f*l*h]],[o,i-u*o]);return R(q("exp",R(z(u),c)),Q(R(z(p),q("cos",R(z(l),c))),R(z(y),q("sin",R(z(l),c)))))}static taylor(t,r="x",n=0,s=4){let o=typeof t=="string"?e.parse(t):t,i=z(0),a=1;for(let c=0;c<=s;c++){c>0&&(a*=c);let u=e.evaluate(o,{[r]:n});if(u!==0){let l=ot(W(et(r),z(n)),z(c));i=Q(i,R(z(u/a),l))}o=tt(o,r)}return B(i)}static substitute(t,r,n){let s=typeof t=="string"?e.parse(t):t,o=typeof n=="string"?e.parse(n):n;return B(at(s,r,o))}static expand(t){let n=typeof t=="string"?e.parse(t):t;for(let s=0;s<30;s++){let o=B(ct(n));if(ht(o,n))return o;n=o}return n}static freeVariables(t){let r=typeof t=="string"?e.parse(t):t;return[...jt(r)].sort()}static assertVariables(t,r){let n=typeof t=="string"?e.parse(t):t,s=new Set(r),o=e.freeVariables(n).filter(i=>!s.has(i));if(o.length>0)throw new Fr(o)}static evaluate(t,r={},n){let s=typeof t=="string"?e.parse(t):t;return n?.declaredVariables&&e.assertVariables(s,n.declaredVariables),G(s,r)}static compile(t,r){let n=typeof t=="string"?e.parse(t):t;return r?.declaredVariables&&e.assertVariables(n,r.declaredVariables),ft(n)}static evaluateExact(t,r={}){let n=typeof t=="string"?e.parse(t):t;return It(n,r)}static evaluateOverStructure(t,r,n={}){let s=typeof t=="string"?e.parse(t):t;return Ot(s,r,n)}static toString(t){return nt(typeof t=="string"?e.parse(t):t,0)}static toGLSL(t,r={}){return Sn(typeof t=="string"?e.parse(t):t,"glsl",r)}static toWGSL(t,r={}){return Sn(typeof t=="string"?e.parse(t):t,"wgsl",r)}static toLatex(t){return H(typeof t=="string"?e.parse(t):t,0)}static fromLatex(t,r={}){return e.parse(Aa(t,r),r)}static solve(t,r="x"){let n=typeof t=="string"?e.parse(t):t,s=Os(B(n),r,6);if(!s)throw new Error(`solve: expression is not a polynomial in "${r}" of degree \u2264 6.`);return Pn(s).map(o=>B(o))}static solveSystem(t,r){let n=t.map(u=>B(typeof u=="string"?e.parse(u):u));if(n.length!==r.length)throw new Error(`solveSystem: expected ${r.length} equations for ${r.length} variables, got ${n.length}.`);let s=[],o=[];n.forEach((u,l)=>{let f=Va(u,r);if(!f)throw new Ar(`solveSystem: equation ${l} ("${e.toString(u)}") is not linear in [${r.join(", ")}].`);s.push(f.slice(0,r.length)),o.push(-f[r.length])});let i=oe.rank(s);if(i<r.length)throw new Ir(`solveSystem: the system is singular (rank ${i} < ${r.length} variables) and has no unique solution.`);let a=oe.solve(s,o),c={};return r.forEach((u,l)=>{c[u]=a[l]}),c}static solveSystemNumeric(t,r,n){let s=t.map(h=>typeof h=="string"?e.parse(h):h);if(s.length!==r.length)throw new Error(`solveSystemNumeric: expected ${r.length} equations for ${r.length} variables, got ${s.length}.`);let o=r.length,i=s.map(h=>e.compile(h)),a=h=>{let m={};return r.forEach((p,y)=>{m[p]=h[y]}),i.map(p=>p(m))},c=n?[...n]:new Array(o).fill(1),u=1e-6,l=100,f=1e-10;for(let h=0;h<l;h++){let m=a(c);if(!m.every(Number.isFinite))throw new Fe("solveSystemNumeric: evaluation produced a non-finite value.");let p=Math.sqrt(m.reduce((M,v)=>M+v*v,0));if(p<f){let M={};return r.forEach((v,N)=>{M[v]=c[N]}),M}let y=Array.from({length:o},()=>new Array(o).fill(0));for(let M=0;M<o;M++){let v=[...c];v[M]=v[M]+u;let N=a(v);for(let $=0;$<o;$++)y[$][M]=(N[$]-m[$])/u}let d;try{d=oe.solve(y,m.map(M=>-M))}catch{throw new Fe("solveSystemNumeric: the Jacobian became singular during iteration.")}let w=1,g=!1;for(let M=0;M<20&&!g;M++){let v=c.map(($,b)=>$+w*d[b]),N=a(v);if(N.every(Number.isFinite)&&Math.sqrt(N.reduce((b,x)=>b+x*x,0))<p){c=v,g=!0;break}w/=2}if(!g)throw new Fe("solveSystemNumeric: no damped step improved the residual from the current iterate.")}throw new Fe(`solveSystemNumeric: did not converge within ${l} iterations from the given initial guess.`)}static verifySolution(t,r,n,s={},o=1e-6){let i=e.evaluate(t,{...s,[r]:n});return Number.isFinite(i)&&Math.abs(i)<o}static verifySystemSolution(t,r,n=1e-6){return t.every(s=>{let o=e.evaluate(s,r);return Number.isFinite(o)&&Math.abs(o)<n})}static sumSeries(t,r,n,s="n",o={}){let i=typeof t=="string"?e.parse(t):t;if(Number.isFinite(n)){if(r>n)return 0;let c=ft(i),u=0;for(let l=r;l<=n;l++)u+=c({...o,[s]:l});return u}let a=la(i,s,r,o);return a!==null?a:fa(i,s,r,o)}static factor(t,r="x"){let n=typeof t=="string"?e.parse(t):t,s=B(n),o=Os(s,r,6);return o?Ba(o,r):s}static limit(t,r="x",n=0,s="both"){let o=typeof t=="string"?e.parse(t):t;return po(o,r,n,s,0)}};function vt(e,t,r){let n,s;switch(e.type){case"const":n="Constant Rule",s=z(0);break;case"var":n=e.name===t?"Variable Rule":"Constant Rule",s=z(e.name===t?1:0);break;case"add":n="Sum Rule",s=Q(vt(e.left,t,r),vt(e.right,t,r));break;case"sub":n="Difference Rule",s=W(vt(e.left,t,r),vt(e.right,t,r));break;case"mul":n="Product Rule",s=Q(R(vt(e.left,t,r),e.right),R(e.left,vt(e.right,t,r)));break;case"div":n="Quotient Rule",s=X(W(R(vt(e.left,t,r),e.right),R(e.left,vt(e.right,t,r))),ot(e.right,z(2)));break;case"neg":n="Negation Rule",s=xt(vt(e.arg,t,r));break;case"pow":e.exp.type==="const"?(n="Power Rule",s=R(R(e.exp,ot(e.base,z(e.exp.value-1))),vt(e.base,t,r))):(n="Generalized Power Rule",s=R(e,Q(R(vt(e.exp,t,r),q("ln",e.base)),R(e.exp,X(vt(e.base,t,r),e.base)))));break;case"func":{n=`Chain Rule (${e.name})`;let o=e.arg,i=vt(o,t,r);s=wn[e.name](o,i);break}case"call2":{n=`Multivariable Chain Rule (${e.name})`;let o=e.left,i=e.right,a=vt(o,t,r),c=vt(i,t,r);switch(e.name){case"atan2":s=X(W(R(i,a),R(o,c)),Q(ot(o,z(2)),ot(i,z(2))));break;case"hypot":s=X(Q(R(o,a),R(i,c)),ee("hypot",o,i));break;case"min":s=W(X(Q(a,c),z(2)),R(q("sign",W(o,i)),X(W(a,c),z(2))));break;case"max":s=Q(X(Q(a,c),z(2)),R(q("sign",W(o,i)),X(W(a,c),z(2))));break;case"gcd":case"lcm":s=z(0);break}break}case"cmp":n="Comparison Rule (locally constant)",s=z(0);break;case"piecewise":n="Piecewise Rule (branch-wise)",s=de(e.branches.map(o=>({cond:o.cond,expr:vt(o.expr,t,r)})),vt(e.otherwise,t,r));break;case"sum":n="Sum Rule (\u03A3, term-wise by linearity)",s=ce(e.variable,e.from,e.to,vt(e.body,t,r));break;case"product":n="Product Rule (\u03A0, via the logarithmic-derivative identity: d(ln P)/dx = \u03A3 (dbody/dx)/body)",s=R(Se(e.variable,e.from,e.to,e.body),ce(e.variable,e.from,e.to,X(vt(e.body,t,r),e.body)));break}return r.push({rule:n,input:e,output:s}),s}function tt(e,t){switch(e.type){case"const":return z(0);case"var":return z(e.name===t?1:0);case"add":return Q(tt(e.left,t),tt(e.right,t));case"sub":return W(tt(e.left,t),tt(e.right,t));case"mul":return Q(R(tt(e.left,t),e.right),R(e.left,tt(e.right,t)));case"div":return X(W(R(tt(e.left,t),e.right),R(e.left,tt(e.right,t))),ot(e.right,z(2)));case"neg":return xt(tt(e.arg,t));case"pow":return e.exp.type==="const"?R(R(e.exp,ot(e.base,z(e.exp.value-1))),tt(e.base,t)):R(e,Q(R(tt(e.exp,t),q("ln",e.base)),R(e.exp,X(tt(e.base,t),e.base))));case"func":{let r=e.arg,n=tt(r,t);return wn[e.name](r,n)}case"call2":{let r=e.left,n=e.right,s=tt(r,t),o=tt(n,t),i=e.name;switch(i){case"atan2":return X(W(R(n,s),R(r,o)),Q(ot(r,z(2)),ot(n,z(2))));case"hypot":return X(Q(R(r,s),R(n,o)),ee("hypot",r,n));case"min":return W(X(Q(s,o),z(2)),R(q("sign",W(r,n)),X(W(s,o),z(2))));case"max":return Q(X(Q(s,o),z(2)),R(q("sign",W(r,n)),X(W(s,o),z(2))));case"gcd":case"lcm":return z(0)}throw new Error(`Unhandled binary function: ${i}`)}case"cmp":return z(0);case"piecewise":return de(e.branches.map(r=>({cond:r.cond,expr:tt(r.expr,t)})),tt(e.otherwise,t));case"sum":return ce(e.variable,e.from,e.to,tt(e.body,t));case"product":return R(Se(e.variable,e.from,e.to,e.body),ce(e.variable,e.from,e.to,X(tt(e.body,t),e.body)))}}function B(e){let t=typeof e=="string"?C.parse(e):e;for(let r=0;r<30;r++){let n=yt(Mt(t));if(ht(n,t))return n;t=n}return t}function Mt(e){if(e.type==="const"||e.type==="var")return e;if(e.type==="neg"){let n=Mt(e.arg);return n.type==="const"?z(-n.value):n.type==="neg"?n.arg:xt(n)}if(e.type==="func")return q(e.name,Mt(e.arg));if(e.type==="call2"){let n=Mt(e.left),s=Mt(e.right);return n.type==="const"&&s.type==="const"?z(Rn[e.name](n.value,s.value)):ee(e.name,n,s)}if(e.type==="pow"){let n=Mt(e.base),s=Mt(e.exp);return kt(s,0)?z(1):kt(s,1)?n:kt(n,0)?z(0):kt(n,1)?z(1):n.type==="const"&&s.type==="const"?z(n.value**s.value):ot(n,s)}if(e.type==="cmp"){let n=Mt(e.left),s=Mt(e.right);return n.type==="const"&&s.type==="const"?z(Cn[e.op](n.value,s.value)?1:0):De(e.op,n,s)}if(e.type==="piecewise")return de(e.branches.map(n=>({cond:Mt(n.cond),expr:Mt(n.expr)})),Mt(e.otherwise));if(e.type==="sum")return ce(e.variable,Mt(e.from),Mt(e.to),Mt(e.body));if(e.type==="product")return Se(e.variable,Mt(e.from),Mt(e.to),Mt(e.body));let t=Mt(e.left),r=Mt(e.right);if(t.type==="const"&&r.type==="const"){if(e.type==="add")return z(t.value+r.value);if(e.type==="sub")return z(t.value-r.value);if(e.type==="mul")return z(t.value*r.value);if(e.type==="div"&&r.value!==0)return z(t.value/r.value)}switch(e.type){case"add":return kt(t,0)?r:kt(r,0)?t:Q(t,r);case"sub":return kt(r,0)?t:kt(t,0)?xt(r):ht(t,r)?z(0):W(t,r);case"mul":return kt(t,0)||kt(r,0)?z(0):kt(t,1)?r:kt(r,1)?t:R(t,r);case"div":return kt(r,0)?X(t,r):kt(t,0)?z(0):kt(r,1)?t:X(t,r)}return e}function ht(e,t){if(e.type!==t.type)return!1;switch(e.type){case"const":return e.value===t.value;case"var":return e.name===t.name;case"neg":return ht(e.arg,t.arg);case"func":return e.name===t.name&&ht(e.arg,t.arg);case"call2":return e.name===t.name&&ht(e.left,t.left)&&ht(e.right,t.right);case"pow":return ht(e.base,t.base)&&ht(e.exp,t.exp);case"cmp":{let r=t;return e.op===r.op&&ht(e.left,r.left)&&ht(e.right,r.right)}case"piecewise":{let r=t;return e.branches.length===r.branches.length&&e.branches.every((n,s)=>ht(n.cond,r.branches[s].cond)&&ht(n.expr,r.branches[s].expr))&&ht(e.otherwise,r.otherwise)}case"sum":case"product":{let r=t;return e.variable===r.variable&&ht(e.from,r.from)&&ht(e.to,r.to)&&ht(e.body,r.body)}default:return ht(e.left,t.left)&&ht(e.right,t.right)}}function at(e,t,r){switch(e.type){case"const":return e;case"var":return e.name===t?r:e;case"neg":return xt(at(e.arg,t,r));case"func":return q(e.name,at(e.arg,t,r));case"call2":return ee(e.name,at(e.left,t,r),at(e.right,t,r));case"pow":return ot(at(e.base,t,r),at(e.exp,t,r));case"add":return Q(at(e.left,t,r),at(e.right,t,r));case"sub":return W(at(e.left,t,r),at(e.right,t,r));case"mul":return R(at(e.left,t,r),at(e.right,t,r));case"div":return X(at(e.left,t,r),at(e.right,t,r));case"cmp":return De(e.op,at(e.left,t,r),at(e.right,t,r));case"piecewise":return de(e.branches.map(n=>({cond:at(n.cond,t,r),expr:at(n.expr,t,r)})),at(e.otherwise,t,r));case"sum":case"product":{let n=at(e.from,t,r),s=at(e.to,t,r),o=e.variable===t?e.body:at(e.body,t,r);return e.type==="sum"?ce(e.variable,n,s,o):Se(e.variable,n,s,o)}}}var Wi=8;function ct(e){switch(e.type){case"const":case"var":return e;case"neg":return xt(ct(e.arg));case"func":return q(e.name,ct(e.arg));case"call2":return ee(e.name,ct(e.left),ct(e.right));case"add":return Q(ct(e.left),ct(e.right));case"sub":return W(ct(e.left),ct(e.right));case"div":return X(ct(e.left),ct(e.right));case"pow":{let t=ct(e.base);if(e.exp.type==="const"&&Number.isInteger(e.exp.value)&&e.exp.value>=2&&e.exp.value<=Wi&&(t.type==="add"||t.type==="sub")){let r=t;for(let n=1;n<e.exp.value;n++)r=ae(r,t);return r}return ot(t,ct(e.exp))}case"mul":return ae(ct(e.left),ct(e.right));case"cmp":return De(e.op,ct(e.left),ct(e.right));case"piecewise":return de(e.branches.map(t=>({cond:ct(t.cond),expr:ct(t.expr)})),ct(e.otherwise));case"sum":return ce(e.variable,ct(e.from),ct(e.to),ct(e.body));case"product":return Se(e.variable,ct(e.from),ct(e.to),ct(e.body))}}function ae(e,t){return e.type==="add"?Q(ae(e.left,t),ae(e.right,t)):e.type==="sub"?W(ae(e.left,t),ae(e.right,t)):t.type==="add"?Q(ae(e,t.left),ae(e,t.right)):t.type==="sub"?W(ae(e,t.left),ae(e,t.right)):R(e,t)}function yt(e){switch(e.type){case"const":case"var":return e;case"func":return q(e.name,yt(e.arg));case"call2":return ee(e.name,yt(e.left),yt(e.right));case"div":{let t=yt(e.left),r=yt(e.right);return r.type==="const"&&r.value!==0&&t.type!=="add"&&t.type!=="sub"?Es(Ss([Be(X(t,r))])):X(t,r)}case"pow":return ot(yt(e.base),yt(e.exp));case"neg":case"add":case"sub":case"mul":{let t=[];return Ue(e,1,t),Es(Ss(t))}case"cmp":return De(e.op,yt(e.left),yt(e.right));case"piecewise":return de(e.branches.map(t=>({cond:yt(t.cond),expr:yt(t.expr)})),yt(e.otherwise));case"sum":return ce(e.variable,yt(e.from),yt(e.to),yt(e.body));case"product":return Se(e.variable,yt(e.from),yt(e.to),yt(e.body))}}function Ue(e,t,r){if(e.type==="add"){Ue(e.left,t,r),Ue(e.right,t,r);return}if(e.type==="sub"){Ue(e.left,t,r),Ue(e.right,-t,r);return}if(e.type==="neg"){Ue(e.arg,-t,r);return}let n=Be(e);r.push({coeff:n.coeff*t,factors:n.factors})}function Be(e){if(e.type==="const")return{coeff:e.value,factors:[]};if(e.type==="neg"){let t=Be(e.arg);return{coeff:-t.coeff,factors:t.factors}}if(e.type==="mul"){let t=Be(e.left),r=Be(e.right);return En(t.coeff*r.coeff,[...t.factors,...r.factors])}if(e.type==="div"&&e.right.type==="const"&&e.right.value!==0){let t=Be(e.left);return{coeff:t.coeff/e.right.value,factors:t.factors}}return e.type==="pow"&&e.exp.type==="const"?En(1,[{base:yt(e.base),exp:e.exp.value}]):En(1,[{base:yt(e),exp:1}])}function En(e,t){let r=[];for(let n of t){let s=r.find(o=>ht(o.base,n.base));s?s.exp+=n.exp:r.push({...n})}return{coeff:e,factors:r.filter(n=>n.exp!==0)}}function Ss(e){let t=new Map,r=[];for(let n of e){let s=[...n.factors].sort((a,c)=>nt(a.base,0).localeCompare(nt(c.base,0))),o=s.map(a=>`${nt(a.base,0)}^${a.exp}`).join("*"),i=t.get(o);i?i.coeff+=n.coeff:(t.set(o,{coeff:n.coeff,factors:s}),r.push(o))}return r.map(n=>t.get(n)).filter(n=>n.coeff!==0)}function Yi(e){let t=null;for(let r of e){let n=r.exp===1?r.base:ot(r.base,z(r.exp));t=t===null?n:R(t,n)}return t}function Es(e){let t=null;for(let r of e){let n=Yi(r.factors),s=Math.abs(r.coeff),o=s!==0?1/s:0,i=s<1&&Math.abs(Math.round(o)-o)<1e-12,a=n===null?z(s):s===1?n:i?X(n,z(Math.round(o))):R(z(s),n);t===null?t=r.coeff<0?xt(a):a:t=r.coeff<0?W(t,a):Q(t,a)}return t??z(0)}function Vs(e,t){if(!K(e,t))return R(e,et(t));switch(e.type){case"var":return X(ot(et(t),z(2)),z(2));case"add":return Q(St(e.left,t),St(e.right,t));case"sub":return W(St(e.left,t),St(e.right,t));case"neg":return xt(St(e.arg,t));case"mul":{if(!K(e.left,t))return R(e.left,St(e.right,t));if(!K(e.right,t))return R(e.right,St(e.left,t));for(let[r,n]of[[e.left,e.right],[e.right,e.left]]){let s=ma(r,t);if(s!==null&&n.type==="func"&&da(n.name)&&Fn(n.arg,t))return Ds(s,n,t)}throw new Lt}case"div":{if(!K(e.right,t))return X(St(e.left,t),e.right);if(!K(e.left,t)&&e.right.type==="var"&&e.right.name===t)return R(e.left,q("ln",q("abs",et(t))));if(!K(e.left,t)){let r=G(e.left,{}),n=An(e.right,t);if(n&&Math.abs(n.a-1)<1e-9&&Math.abs(n.b)<1e-9&&n.c>0){let o=Math.sqrt(n.c);return R(z(r/o),q("atan",X(et(t),z(o))))}if(e.right.type==="func"&&e.right.name==="sqrt"){let o=An(e.right.arg,t);if(o&&Math.abs(o.a+1)<1e-9&&Math.abs(o.b)<1e-9&&o.c>0){let i=Math.sqrt(o.c);return R(z(r),q("asin",X(et(t),z(i))))}}let s=An(e.right,t);if(s){let o=s.b*s.b-4*s.a*s.c;if(o>1e-9){let i=Math.sqrt(o),a=(-s.b+i)/(2*s.a),c=(-s.b-i)/(2*s.a),u=r/(s.a*(a-c)),l=-u;return Q(R(z(u),q("ln",q("abs",W(et(t),z(a))))),R(z(l),q("ln",q("abs",W(et(t),z(c))))))}}}throw new Lt}case"pow":{if(e.base.type==="var"&&e.base.name===t&&e.exp.type==="const")return e.exp.value===-1?q("ln",q("abs",et(t))):X(ot(et(t),z(e.exp.value+1)),z(e.exp.value+1));throw new Lt}case"func":{let r=Fn(e.arg,t);if(!r)throw new Lt;let n=e.arg,s=o=>X(o,z(r.a));switch(e.name){case"sin":return s(xt(q("cos",n)));case"cos":return s(q("sin",n));case"exp":return s(q("exp",n));case"ln":return s(W(R(n,q("ln",n)),n));case"sqrt":return s(R(z(2/3),ot(n,z(1.5))));case"tan":return s(xt(q("ln",q("abs",q("cos",n)))));case"cot":return s(q("ln",q("abs",q("sin",n))));case"sec":return s(q("ln",q("abs",Q(q("sec",n),q("tan",n)))));case"csc":return s(xt(q("ln",q("abs",Q(q("csc",n),q("cot",n))))));case"sinh":return s(q("cosh",n));case"cosh":return s(q("sinh",n));case"tanh":return s(q("ln",q("cosh",n)));case"asin":return s(Q(R(n,q("asin",n)),q("sqrt",W(z(1),ot(n,z(2))))));case"acos":return s(W(R(n,q("acos",n)),q("sqrt",W(z(1),ot(n,z(2))))));case"atan":return s(W(R(n,q("atan",n)),R(z(.5),q("ln",Q(z(1),ot(n,z(2)))))));default:throw new Lt}}default:throw new Lt}}function ie(e,t){if(ht(e,t))return!0;switch(e.type){case"const":case"var":return!1;case"neg":return ie(e.arg,t);case"func":return ie(e.arg,t);case"pow":return ie(e.base,t)||ie(e.exp,t);case"piecewise":return e.branches.some(r=>ie(r.cond,t)||ie(r.expr,t))||ie(e.otherwise,t);case"sum":case"product":return!1;default:return ie(e.left,t)||ie(e.right,t)}}function te(e,t,r){if(ht(e,t))return r;switch(e.type){case"const":case"var":return e;case"neg":return xt(te(e.arg,t,r));case"func":return q(e.name,te(e.arg,t,r));case"pow":return ot(te(e.base,t,r),te(e.exp,t,r));case"piecewise":return de(e.branches.map(n=>({cond:te(n.cond,t,r),expr:te(n.expr,t,r)})),te(e.otherwise,t,r));case"sum":case"product":return e;default:return{...e,left:te(e.left,t,r),right:te(e.right,t,r)}}}function Rr(e){return e.type==="mul"?[...Rr(e.left),...Rr(e.right)]:[e]}function Qi(e,t){let r=e.type==="div"?e.right:null,n=e.type==="div"?e.left:e,s=1,o=[];for(let f of Rr(n))f.type==="const"?s*=f.value:o.push(f);let i=1,a=[];for(let f of Rr(t))f.type==="const"?i*=f.value:a.push(f);if(i===0)return null;for(let f of a){let h=o.findIndex(m=>ht(m,f));if(h===-1)return null;o.splice(h,1)}let c=s/i,u=c===1?o:[z(c),...o],l=u.length===0?z(c):u.reduce((f,h)=>f?R(f,h):h);return r?X(l,r):l}function _i(e,t){let r=[],n=o=>{switch(o.type){case"const":case"var":return;case"neg":n(o.arg);return;case"func":K(o.arg,t)&&r.push(o.arg),n(o.arg);return;case"pow":K(o.base,t)&&r.push(o.base),K(o.exp,t)&&r.push(o.exp),n(o.base),n(o.exp);return;case"call2":K(o.left,t)&&r.push(o.left),K(o.right,t)&&r.push(o.right),n(o.left),n(o.right);return;case"piecewise":for(let i of o.branches)n(i.cond),n(i.expr);n(o.otherwise);return;case"sum":case"product":return;case"div":K(o.right,t)&&r.push(o.right),n(o.left),n(o.right);return;default:n(o.left),n(o.right);return}};n(e);let s=[];for(let o of r)o.type==="var"&&o.name===t||s.some(i=>ht(i,o))||s.push(o);return s}function Ki(e,t){let r="u",n=2;for(;r===t||K(e,r);)r=`u${n++}`;return r}function Ji(e,t,r){let n=B(tt(e,r)),s=0;for(let o of[.7,1.3,-.9]){let i=G(t,{[r]:o}),a=G(n,{[r]:o});if(!(!Number.isFinite(i)||!Number.isFinite(a))){if(Math.abs(a-i)>1e-6*Math.max(1,Math.abs(i)))return!1;s++}}return s>=2}function Hi(e,t){for(let r of _i(e,t)){let n=B(tt(r,t));if(kt(n,0))continue;let s=B(Qi(e,n)??X(e,n));if(!ie(s,r))continue;let o=Ki(s,t),i=te(s,r,et(o));if(!K(i,t))try{let a=Vs(i,o),c=B(te(a,et(o),r));if(Ji(c,e,t))return c}catch(a){if(!(a instanceof Lt))throw a}}return null}function ta(e,t,r){let n=Math.min(t,r),s=Math.max(t,r),o=(s-n)*.01,i=n+o,a=s-o,c=64,u=-1/0;for(let l=0;l<6;l++){let f=-1/0,h=(i+a)/2;for(let p=1;p<c;p++){let y=i+p/c*(a-i),d=e(y);if(!Number.isFinite(d))return!0;let w=Math.abs(d);w>f&&(f=w,h=y)}if(l>0&&f>u*4)return!0;u=f;let m=(a-i)/c;if(i=Math.max(n+o,h-m*2),a=Math.min(s-o,h+m*2),a-i<1e-9)return!0}return!1}function St(e,t){try{return Vs(e,t)}catch(r){if(!(r instanceof Lt))throw r;let n=Hi(e,t);if(n)return n;throw r}}var he=(e,t)=>[...jt(e)].every(r=>t.has(r));function ea(e,t,r){let n=jt(e);if(![...n].every(c=>c===t||c===r))return null;let s=n.has(t);if(!n.has(r))return{g:e,h:z(1)};if(!s)return{g:z(1),h:e};if(e.type!=="mul")return null;let i=new Set([t]),a=new Set([r]);return he(e.left,i)&&he(e.right,a)?{g:e.left,h:e.right}:he(e.left,a)&&he(e.right,i)?{g:e.right,h:e.left}:null}function ra(e,t,r){if(!K(e,r))return null;let n=B(tt(e,r));if(K(n,r))return null;let s=B(W(e,R(n,et(r))));if(K(s,r))return null;let o=B(xt(n)),i=new Set([t]);return!he(o,i)||!he(s,i)?null:{p:o,q:s}}function Us(e,t,r,n){if(e.type==="var"&&e.name===t)return r;if(e.type==="func"&&e.name==="ln"&&e.arg.type==="var"&&e.arg.name===t)return q("exp",r);if(e.type==="func"&&e.name==="ln"&&e.arg.type==="func"&&e.arg.name==="abs"&&e.arg.arg.type==="var"&&e.arg.arg.name===t){let s=Math.sign(n);return s===0?null:s===1?q("exp",r):xt(q("exp",r))}if(e.type==="div"&&e.right.type==="const"&&e.left.type==="pow"&&e.left.base.type==="var"&&e.left.base.name===t&&e.left.exp.type==="const"&&e.left.exp.value===e.right.value){let s=e.right.value;return s===0?null:ot(R(z(s),r),z(1/s))}return null}function Bs(e,t,r,n,s){let o=B(X(z(1),e.h)),i,a;try{i=B(St(o,r)),a=B(St(e.g,t))}catch(f){throw f instanceof Lt?new fe:f}let c=G(i,{[r]:s})-G(a,{[t]:n}),u=B(Q(a,z(c))),l=Us(i,r,u,s);return l?{explicit:!0,y:B(l)}:{explicit:!1,implicitRelation:B(W(i,u))}}function Gs(e,t,r,n,s){let o,i,a;try{o=B(St(e.p,t)),i=B(q("exp",o)),a=B(St(B(R(i,e.q)),t))}catch(h){throw h instanceof Lt?new fe:h}let c=G(i,{[t]:n}),u=G(a,{[t]:n}),l=s*c-u;return{explicit:!0,y:B(X(Q(a,z(l)),i))}}function na(e,t){let r="v",n=2;for(;t.includes(r)||K(e,r);)r=`v${n++}`;return r}function sa(e,t,r){let n=na(e,[t,r]),s=at(e,r,R(et(n),et(t))),o=0,i=0;for(let c of[.6,1.4,-.8]){let u=null;for(let l of[1,2.3,-1.7]){i++;let f=G(s,{[t]:l,[n]:c});if(Number.isFinite(f))if(u===null)u=f,o++;else{if(Math.abs(f-u)>1e-6*Math.max(1,Math.abs(u)))return null;o++}}}if(i===0||o<4)return null;let a=B(at(s,t,z(1)));return{vName:n,F:a}}function oa(e,t,r,n,s){let{vName:o,F:i}=e,a=s/n,c=B(W(i,et(o)));if(c.type==="const"&&c.value===0)return{explicit:!0,y:B(R(z(a),et(t)))};let u=Bs({g:X(z(1),et(t)),h:c},t,o,n,a);return u.explicit&&u.y?{explicit:!0,y:B(R(u.y,et(t)))}:{explicit:!1,implicitRelation:B(at(u.implicitRelation,o,X(et(r),et(t))))}}function As(e,t,r){let n=i=>i.type==="var"&&i.name===r,s=i=>n(i)?1:i.type==="pow"&&n(i.base)&&i.exp.type==="const"?i.exp.value:null,o=new Set([t]);if(e.type!=="mul"){let i=s(e);return i===null?null:{coef:z(1),n:i}}for(let[i,a]of[[e.left,e.right],[e.right,e.left]]){if(!he(i,o))continue;let c=s(a);if(c!==null)return{coef:i,n:c}}return null}function ia(e,t,r){let n,s,o;if(e.type==="sub")n=e.left,s=e.right,o=-1;else if(e.type==="add")n=e.left,s=e.right,o=1;else return null;let i=As(n,t,r),a=As(s,t,r);if(!i||!a)return null;let c,u,l,f;if(i.n!==1&&a.n===1)c=i,u=1,l=a,f=o;else if(a.n!==1&&i.n===1)c=a,u=o,l=i,f=1;else return null;if(c.n===0)return null;let h=u===1?c.coef:B(xt(c.coef));return{p:f===1?B(xt(l.coef)):l.coef,q:h,n:c.n}}function aa(e,t,r,n,s){let o=1-e.n,i=s**o,a=B(R(z(o),e.p)),c=B(R(z(o),e.q)),u=Gs({p:a,q:c},t,r,n,i);return{explicit:!0,y:B(ot(u.y,z(1/o)))}}function ca(e,t,r){if(e.type!=="div"||![...jt(e)].every(u=>u===t||u===r))return null;let s=e.left,o=B(xt(e.right)),i=tt(s,r),a=tt(o,t),c=0;for(let u of[.7,1.3,-.9])for(let l of[.8,-1.2,1.7]){let f=G(i,{[t]:u,[r]:l}),h=G(a,{[t]:u,[r]:l});if(!(!Number.isFinite(f)||!Number.isFinite(h))){if(Math.abs(f-h)>1e-6*Math.max(1,Math.abs(f),Math.abs(h)))return null;c++}}return c<4?null:{M:s,N:o}}function ua(e,t,r,n,s){let{M:o,N:i}=e,a,c,u;try{if(a=B(St(o,t)),u=B(W(i,tt(a,r))),K(u,t)){let h=null;for(let m of[1,2.3,-1.7]){let p=G(u,{[t]:m,[r]:.8}),y=G(u,{[t]:m===1?2.3:1,[r]:.8});if(!(!Number.isFinite(p)||!Number.isFinite(y))){if(Math.abs(p-y)>1e-6*Math.max(1,Math.abs(p)))throw new fe;h=B(at(u,t,z(m)));break}}if(!h)throw new fe;u=h}c=B(St(u,r))}catch(h){throw h instanceof Lt?new fe:h}let l=B(Q(a,c)),f=G(l,{[t]:n,[r]:s});if(!Number.isFinite(f))throw new fe;if(l.type==="add"||l.type==="sub"){let h=new Set([t]),m=new Set([r]),[p,y]=[l.left,l.right];for(let[d,w]of[[p,l.type==="sub"?xt(y):y],[y,l.type==="sub"?xt(p):p]]){if(!he(d,m)||!he(w,h)||l.type==="sub"&&d===y)continue;let g=B(W(z(f),w)),M=Us(d,r,g,s);if(M)return{explicit:!0,y:B(M)}}}return{explicit:!1,implicitRelation:B(W(l,z(f)))}}function Fn(e,t){try{let r=G(e,{[t]:0}),s=G(e,{[t]:1})-r,o=r,i=G(e,{[t]:2});return Math.abs(i-(2*s+o))>1e-9||!Number.isFinite(s)||!Number.isFinite(o)?null:{a:s,b:o}}catch{return null}}function la(e,t,r,n){let s=1,o=e;if(e.type==="mul")if(!K(e.left,t)&&e.right.type==="pow")s=G(e.left,n),o=e.right;else if(!K(e.right,t)&&e.left.type==="pow")s=G(e.right,n),o=e.left;else return null;else if(e.type!=="pow")return null;if(o.type!=="pow"||K(o.base,t))return null;let i=Fn(o.exp,t);if(!i)return null;let a=G(o.base,n),c=a**i.a;if(!Number.isFinite(c)||Math.abs(c)>=1)return null;let u=i.a*r+i.b;return s*a**u/(1-c)}function fa(e,t,r,n){let s=ft(e),o=1e-12,i=2e5,a=0,c=0,u=0;for(let f=0;f<i;f++){let h=r+f,m=s({...n,[t]:h});if(!Number.isFinite(m))throw new Ge(`sumSeries: term at index ${h} is not finite.`);if(f===0&&(u=Math.abs(m)||1),a+=m,Math.abs(m)<o*Math.max(1,Math.abs(a))){if(c++,c>=5)return a}else c=0;if(f>100&&Math.abs(m)>u*10)throw new Ge("sumSeries: terms are growing (not shrinking toward 0) -- the series appears to diverge.")}let l=ha(f=>s({...n,[t]:f}),r+i);if(l!==null)return a+l;throw new Ge(`sumSeries: did not converge to within tolerance after ${i} terms -- the series may converge too slowly to sum numerically, or may not converge at all.`)}function ha(e,t){let r=t,n=Math.max(1,t),s=0,o=Number.POSITIVE_INFINITY,i=40;for(let a=0;a<i;a++){let c=r+n,u=ir.adaptiveSimpson(e,r,c);if(!Number.isFinite(u)||(s+=u,a>5&&Math.abs(u)>Math.abs(o)*1.5))return null;if(Math.abs(u)<1e-13*Math.max(1,Math.abs(s))&&a>2)return s;o=u,r=c,n*=2}return null}function An(e,t){try{let r=G(e,{[t]:0}),n=G(e,{[t]:1}),s=G(e,{[t]:-1}),o=r,i=(n+s)/2-o,a=(n-s)/2,c=G(e,{[t]:2});return Math.abs(c-(4*i+2*a+o))>1e-9||![i,a,o].every(Number.isFinite)?null:{a:i,b:a,c:o}}catch{return null}}function ma(e,t){return e.type==="var"&&e.name===t?1:e.type==="pow"&&e.base.type==="var"&&e.base.name===t&&e.exp.type==="const"&&Number.isInteger(e.exp.value)&&e.exp.value>=1?e.exp.value:null}var pa=new Set(["sin","cos","exp"]);function da(e){return pa.has(e)}function Ds(e,t,r){if(e===0)return St(t,r);let n=St(t,r),s=e===1?et(r):ot(et(r),z(e)),o=R(s,n),i=Ds(e-1,n,r);return W(o,R(z(e),i))}function G(e,t){switch(e.type){case"const":return e.value;case"var":return t[e.name]??Number.NaN;case"add":return G(e.left,t)+G(e.right,t);case"sub":return G(e.left,t)-G(e.right,t);case"mul":return G(e.left,t)*G(e.right,t);case"div":return G(e.left,t)/G(e.right,t);case"pow":return G(e.base,t)**G(e.exp,t);case"neg":return-G(e.arg,t);case"func":{let r=G(e.arg,t),n=e.name;switch(n){case"sin":return Math.sin(r);case"cos":return Math.cos(r);case"tan":return Math.tan(r);case"exp":return Math.exp(r);case"ln":return Math.log(r);case"sqrt":return Math.sqrt(r);case"asin":return Math.asin(r);case"acos":return Math.acos(r);case"atan":return Math.atan(r);case"sinh":return Math.sinh(r);case"cosh":return Math.cosh(r);case"tanh":return Math.tanh(r);case"cot":return Ws(r);case"sec":return Ys(r);case"csc":return Qs(r);case"asinh":return Math.asinh(r);case"acosh":return Math.acosh(r);case"atanh":return Math.atanh(r);case"coth":return _s(r);case"sech":return Ks(r);case"csch":return Js(r);case"acot":return Hs(r);case"asec":return to(r);case"acsc":return eo(r);case"acoth":return ro(r);case"asech":return no(r);case"acsch":return so(r);case"abs":return Math.abs(r);case"log10":return Math.log10(r);case"log2":return Math.log2(r);case"cbrt":return Math.cbrt(r);case"floor":return Math.floor(r);case"ceil":return Math.ceil(r);case"round":return Math.round(r);case"sign":return Math.sign(r);case"trunc":return Math.trunc(r);case"expm1":return Math.expm1(r);case"log1p":return Math.log1p(r);case"sigmoid":return oo(r);case"erf":return Ie.erf(r);case"relu":return Math.max(r,0)}throw new Error(`Unhandled function: ${n}`)}case"call2":return Rn[e.name](G(e.left,t),G(e.right,t));case"cmp":return Cn[e.op](G(e.left,t),G(e.right,t))?1:0;case"piecewise":{for(let r of e.branches)if(G(r.cond,t)!==0)return G(r.expr,t);return G(e.otherwise,t)}case"sum":return Zs(e,t);case"product":return Xs(e,t)}}function Zs(e,t){let r=Math.round(G(e.from,t)),n=G(e.to,t);return C.sumSeries(e.body,r,Number.isFinite(n)?Math.round(n):n,e.variable,t)}function Xs(e,t){let r=Math.round(G(e.from,t)),n=G(e.to,t);if(!Number.isFinite(n))throw new Error("product (\u03A0): only finite upper bounds are supported.");let s=Math.round(n);if(r>s)return 1;let o=ft(e.body),i=1;for(let a=r;a<=s;a++)i*=o({...t,[e.variable]:a});return i}var Ws=e=>1/Math.tan(e),Ys=e=>1/Math.cos(e),Qs=e=>1/Math.sin(e),_s=e=>1/Math.tanh(e),Ks=e=>1/Math.cosh(e),Js=e=>1/Math.sinh(e),Hs=e=>Math.PI/2-Math.atan(e),to=e=>Math.acos(1/e),eo=e=>Math.asin(1/e),ro=e=>Math.atanh(1/e),no=e=>Math.acosh(1/e),so=e=>Math.asinh(1/e),oo=e=>1/(1+Math.exp(-e)),ga={sin:Math.sin,cos:Math.cos,tan:Math.tan,exp:Math.exp,ln:Math.log,sqrt:Math.sqrt,asin:Math.asin,acos:Math.acos,atan:Math.atan,sinh:Math.sinh,cosh:Math.cosh,tanh:Math.tanh,cot:Ws,sec:Ys,csc:Qs,asinh:Math.asinh,acosh:Math.acosh,atanh:Math.atanh,coth:_s,sech:Ks,csch:Js,acot:Hs,asec:to,acsc:eo,acoth:ro,asech:no,acsch:so,abs:Math.abs,log10:Math.log10,log2:Math.log2,cbrt:Math.cbrt,floor:Math.floor,ceil:Math.ceil,round:Math.round,sign:Math.sign,trunc:Math.trunc,expm1:Math.expm1,log1p:Math.log1p,sigmoid:oo,erf:Ie.erf,relu:e=>Math.max(e,0)},Rn={atan2:Math.atan2,hypot:Math.hypot,min:Math.min,max:Math.max,gcd:zn,lcm:(e,t)=>Math.abs(e*t)/zn(e,t)},Cn={lt:(e,t)=>e<t,le:(e,t)=>e<=t,gt:(e,t)=>e>t,ge:(e,t)=>e>=t,eq:(e,t)=>e===t,ne:(e,t)=>e!==t};function ft(e){switch(e.type){case"const":{let t=e.value;return()=>t}case"var":{let t=e.name;return r=>r[t]??Number.NaN}case"add":{let t=ft(e.left),r=ft(e.right);return n=>t(n)+r(n)}case"sub":{let t=ft(e.left),r=ft(e.right);return n=>t(n)-r(n)}case"mul":{let t=ft(e.left),r=ft(e.right);return n=>t(n)*r(n)}case"div":{let t=ft(e.left),r=ft(e.right);return n=>t(n)/r(n)}case"pow":{let t=ft(e.base),r=ft(e.exp);return n=>t(n)**r(n)}case"neg":{let t=ft(e.arg);return r=>-t(r)}case"func":{let t=ft(e.arg),r=ga[e.name];return n=>r(t(n))}case"call2":{let t=ft(e.left),r=ft(e.right),n=Rn[e.name];return s=>n(t(s),r(s))}case"cmp":{let t=ft(e.left),r=ft(e.right),n=Cn[e.op];return s=>n(t(s),r(s))?1:0}case"piecewise":{let t=e.branches.map(n=>({cond:ft(n.cond),expr:ft(n.expr)})),r=ft(e.otherwise);return n=>{for(let s of t)if(s.cond(n)!==0)return s.expr(n);return r(n)}}case"sum":return t=>Zs(e,t);case"product":return t=>Xs(e,t)}}var ya={lt:e=>e<0,le:e=>e<=0,gt:e=>e>0,ge:e=>e>=0,eq:e=>e===0,ne:e=>e!==0};function It(e,t){switch(e.type){case"const":return st.fromNumber(e.value);case"var":{let r=t[e.name];if(!r)throw new Error(`No exact value bound for "${e.name}"`);return r}case"add":return It(e.left,t).add(It(e.right,t));case"sub":return It(e.left,t).subtract(It(e.right,t));case"mul":return It(e.left,t).multiply(It(e.right,t));case"div":return It(e.left,t).divide(It(e.right,t));case"pow":{let r=It(e.exp,t);if(r.denominator!==1n)throw new Error("Exact pow requires an integer exponent");return It(e.base,t).pow(Number(r.numerator))}case"neg":return It(e.arg,t).negate();case"func":throw new Error(`"${e.name}" is not exactly representable as a Rational`);case"call2":throw new Error(`"${e.name}" is not exactly representable as a Rational`);case"cmp":{let r=It(e.left,t),n=It(e.right,t);return ya[e.op](r.compare(n))?st.One:st.Zero}case"piecewise":{for(let r of e.branches)if(!It(r.cond,t).isZero())return It(r.expr,t);return It(e.otherwise,t)}case"sum":throw new Error("sum (\u03A3) is not exactly representable as a Rational");case"product":throw new Error("product (\u03A0) is not exactly representable as a Rational")}}var xa=new Set(["lt","le","gt","ge"]);function Ot(e,t,r){switch(e.type){case"const":return t.wrap(e.value);case"var":{let n=r[e.name];if(n===void 0)throw new Error(`No value bound for "${e.name}"`);return t.wrap(n)}case"add":return t.add(Ot(e.left,t,r),Ot(e.right,t,r));case"sub":return t.subtract(Ot(e.left,t,r),Ot(e.right,t,r));case"mul":return t.multiply(Ot(e.left,t,r),Ot(e.right,t,r));case"div":return t.divide(Ot(e.left,t,r),Ot(e.right,t,r));case"pow":{if(e.exp.type!=="const"||!Number.isInteger(e.exp.value))throw new Error("Structure-aware pow requires a literal integer exponent");return t.multiplyPower(Ot(e.base,t,r),e.exp.value)}case"neg":return t.negative(Ot(e.arg,t,r));case"func":throw new Error(`"${e.name}" has no meaning over this structure`);case"call2":throw new Error(`"${e.name}" has no meaning over this structure`);case"cmp":{if(xa.has(e.op))throw new Error(`Ordering comparisons ("${e.op}") have no general meaning over this structure`);let n=Ot(e.left,t,r),s=Ot(e.right,t,r),o=t.equality(n,s);return(e.op==="eq"?o:!o)?t.one:t.zero}case"piecewise":{for(let n of e.branches){let s=Ot(n.cond,t,r);if(!t.equality(s,t.zero))return Ot(n.expr,t,r)}return Ot(e.otherwise,t,r)}case"sum":throw new Error("sum (\u03A3) has no general meaning over this structure");case"product":throw new Error("product (\u03A0) has no general meaning over this structure")}}var _={add:1,sub:1,mul:2,div:2,neg:3,pow:4,cmp:0};function nt(e,t){switch(e.type){case"const":return`${e.value}`;case"var":return e.name;case"func":return`${e.name}(${nt(e.arg,0)})`;case"call2":return`${e.name}(${nt(e.left,0)}, ${nt(e.right,0)})`;case"neg":return Zt(`-${nt(e.arg,_.neg)}`,_.neg,t);case"pow":return Zt(`${nt(e.base,_.pow+1)}^${nt(e.exp,_.pow)}`,_.pow,t);case"add":return Zt(`${nt(e.left,_.add)} + ${nt(e.right,_.add)}`,_.add,t);case"sub":return Zt(`${nt(e.left,_.sub)} - ${nt(e.right,_.sub+1)}`,_.sub,t);case"mul":return Zt(`${nt(e.left,_.mul)}*${nt(e.right,_.mul+1)}`,_.mul,t);case"div":return Zt(`${nt(e.left,_.div)}/${nt(e.right,_.div+1)}`,_.div,t);case"cmp":{let r=ba[e.op];return Zt(`${nt(e.left,_.cmp+1)}${r}${nt(e.right,_.cmp+1)}`,_.cmp,t)}case"piecewise":return`piecewise(${e.branches.map(n=>`${nt(n.cond,0)}, ${nt(n.expr,0)}`).join(", ")}, ${nt(e.otherwise,0)})`;case"sum":return`sum(${e.variable}, ${nt(e.from,0)}, ${nt(e.to,0)}, ${nt(e.body,0)})`;case"product":return`product(${e.variable}, ${nt(e.from,0)}, ${nt(e.to,0)}, ${nt(e.body,0)})`}}var Zt=(e,t,r)=>t<r?`(${e})`:e,ba={lt:"<",le:"<=",gt:">",ge:">=",eq:"==",ne:"!="},jn={sin:"\\sin",cos:"\\cos",tan:"\\tan",exp:"\\exp",ln:"\\ln",asin:"\\arcsin",acos:"\\arccos",atan:"\\arctan",sinh:"\\sinh",cosh:"\\cosh",tanh:"\\tanh",cot:"\\cot",sec:"\\sec",csc:"\\csc",coth:"\\coth",sech:"\\operatorname{sech}",csch:"\\operatorname{csch}",asinh:"\\operatorname{arcsinh}",acosh:"\\operatorname{arccosh}",atanh:"\\operatorname{arctanh}",acot:"\\operatorname{arccot}",asec:"\\operatorname{arcsec}",acsc:"\\operatorname{arccsc}",acoth:"\\operatorname{arccoth}",asech:"\\operatorname{arcsech}",acsch:"\\operatorname{arccsch}",round:"\\operatorname{round}",sign:"\\operatorname{sgn}",trunc:"\\operatorname{trunc}",expm1:"\\operatorname{expm1}",log1p:"\\operatorname{log1p}",sigmoid:"\\operatorname{sigmoid}",erf:"\\operatorname{erf}",relu:"\\operatorname{relu}"},Ln={atan2:"\\operatorname{atan2}",hypot:"\\operatorname{hypot}",min:"\\min",max:"\\max",gcd:"\\gcd",lcm:"\\operatorname{lcm}"};function H(e,t){switch(e.type){case"const":return Math.abs(e.value-Math.PI)<1e-12?"\\pi":Math.abs(e.value-Math.E)<1e-12?"e":`${e.value}`;case"var":return e.name;case"func":return e.name==="sqrt"?`\\sqrt{${H(e.arg,0)}}`:e.name==="cbrt"?`\\sqrt[3]{${H(e.arg,0)}}`:e.name==="abs"?`\\left|${H(e.arg,0)}\\right|`:e.name==="floor"?`\\left\\lfloor ${H(e.arg,0)}\\right\\rfloor`:e.name==="ceil"?`\\left\\lceil ${H(e.arg,0)}\\right\\rceil`:e.name==="log10"?`\\log_{10}\\left(${H(e.arg,0)}\\right)`:e.name==="log2"?`\\log_{2}\\left(${H(e.arg,0)}\\right)`:`${jn[e.name]}\\left(${H(e.arg,0)}\\right)`;case"call2":return`${Ln[e.name]}\\left(${H(e.left,0)}, ${H(e.right,0)}\\right)`;case"neg":return Zt(`-${H(e.arg,_.neg)}`,_.neg,t);case"pow":return Zt(`${H(e.base,_.pow+1)}^{${H(e.exp,0)}}`,_.pow,t);case"add":return Zt(`${H(e.left,_.add)} + ${H(e.right,_.add)}`,_.add,t);case"sub":return Zt(`${H(e.left,_.sub)} - ${H(e.right,_.sub+1)}`,_.sub,t);case"mul":return Zt(`${H(e.left,_.mul)} \\cdot ${H(e.right,_.mul+1)}`,_.mul,t);case"div":return`\\frac{${H(e.left,0)}}{${H(e.right,0)}}`;case"cmp":{let r=wa[e.op];return Zt(`${H(e.left,_.cmp+1)} ${r} ${H(e.right,_.cmp+1)}`,_.cmp,t)}case"piecewise":{let r=e.branches.map(n=>`${H(n.expr,0)} & ${H(n.cond,0)}`);return r.push(`${H(e.otherwise,0)} & \\text{otherwise}`),`\\begin{cases}${r.join("\\\\")}\\end{cases}`}case"sum":return`\\sum_{${e.variable}=${H(e.from,0)}}^{${H(e.to,0)}} ${H(e.body,0)}`;case"product":return`\\prod_{${e.variable}=${H(e.from,0)}}^{${H(e.to,0)}} ${H(e.body,0)}`}}var wa={lt:"<",le:"\\leq",gt:">",ge:"\\geq",eq:"=",ne:"\\neq"},va=Object.fromEntries(Object.entries(jn).filter(([,e])=>!e.startsWith("\\operatorname")).map(([e,t])=>[t,e])),Ma=Object.fromEntries(Object.entries(jn).filter(e=>e[1].startsWith("\\operatorname")).map(([e,t])=>[/\\operatorname\{(\w+)\}/.exec(t)?.[1],e])),Na=Object.fromEntries(Object.entries(Ln).filter(e=>!e[1].startsWith("\\operatorname")).map(([e,t])=>[t,e])),$a=Object.fromEntries(Object.entries(Ln).filter(e=>e[1].startsWith("\\operatorname")).map(([e,t])=>[/\\operatorname\{(\w+)\}/.exec(t)?.[1],e]));function io(e,t,r,n){let s=0;for(let o=t;o<e.length;o++)if(e[o]===r)s++;else if(e[o]===n&&(s--,s===0))return o;throw new Error(`Unmatched '${r}' in LaTeX source`)}function Ne(e,t){let r=e[t],n=r==="{"?"}":r==="("?")":r==="["?"]":void 0;if(!n)throw new Error(`Expected a group starting with '{', '(' or '[' at position ${t}`);let s=io(e,t,r,n);return{content:e.slice(t+1,s),next:s+1}}function Sa(e){let t=[],r=0,n=0;for(let s=0;s<e.length;s++){let o=e[s];o==="{"||o==="("||o==="["?r++:o==="}"||o===")"||o==="]"?r--:o===","&&r===0&&(t.push(e.slice(n,s)),n=s+1)}return t.push(e.slice(n)),t}function Is(e,t){let r=[],n=0,s=0;for(let o=0;o<e.length;o++){let i=e[o];i==="{"||i==="("||i==="["?n++:i==="}"||i===")"||i==="]"?n--:n===0&&e.startsWith(t,o)&&(r.push(e.slice(s,o)),s=o+t.length,o+=t.length-1)}return r.push(e.slice(s)),r}var Ea={"\\leq":"<=","\\le":"<=","\\geq":">=","\\ge":">=","\\neq":"!=","\\ne":"!="};function Aa(e,t={}){let r=e.replace(/\\left|\\right/g,"").replace(/(?<!\\)\\(?:,|;|!|quad|qquad| )/g,"");return lt(r,t)}function Ia(e,t){let r=t,n=s=>{let o=e[s];return io(e,s,o,o==="{"?"}":")")+1};for(;r<e.length;){let s=e[r];if(/[A-Za-z0-9.]/.test(s))r++;else if(s==="("||s==="{")r=n(r);else if(s==="_"&&e[r+1]==="{")r=n(r+1);else if(s==="^")e[r+1]==="{"?r=n(r+1):e[r+1]==="\\"?r+=1+(/^\\[a-zA-Z]+/.exec(e.slice(r+1))?.[0].length??1):r+=2;else if(/^\\pi(?![a-zA-Z])/.test(e.slice(r)))r+=3;else if(s===" "&&/^ +(?:[A-Za-z0-9.({]|\\pi(?![a-zA-Z]))/.test(e.slice(r)))r+=e.slice(r).length-e.slice(r).trimStart().length;else break}return r}function lt(e,t={}){let r=t.implicitMultiplication===!0,n="",s=0,o=()=>{if(e[s]!=="{")throw new Error(`Expected '{' at position ${s} in LaTeX source: ${e}`);let{content:l,next:f}=Ne(e,s);return s=f,l},i=()=>{for(;e[s]===" ";)s++;if(e[s]==="{"||e[s]==="("){let{content:f,next:h}=Ne(e,s);return s=h,f}if(r){let f=Ia(e,s);if(f>s){let h=e.slice(s,f).trim();return s=f,h}}let l=/^[a-zA-Z_]\w*|^\d+\.?\d*(?:[eE][+-]?\d+)?/.exec(e.slice(s));if(l)return s+=l[0].length,l[0];throw new Error(`Expected an argument at position ${s} in LaTeX source: ${e}`)},a=()=>{for(;e[s]===" ";)s++;if(e[s]==="{")return o();let l=/^(?:\\[a-zA-Z]+|[a-zA-Z0-9])/.exec(e.slice(s));if(!l)throw new Error(`Expected an argument at position ${s} in LaTeX source: ${e}`);return s+=l[0].length,l[0]},c=()=>{if(e[s]!=="^")return null;s++;let l=a();if(/^\s*-\s*1\s*$/.test(l))throw new Error("Ambiguous LaTeX: a function with exponent -1 (e.g. \\sin^{-1}) may mean the inverse function or the reciprocal; write \\arcsin(x) for the inverse, or (\\sin x)^{-1} / 1/\\sin x for the reciprocal");return l},u=()=>{if(e[s]!=="("&&e[s]!=="{")throw new Error(`Expected '(' at position ${s} in LaTeX source: ${e}`);let{content:l,next:f}=Ne(e,s);s=f;let h=Sa(l);if(h.length!==2)throw new Error(`Expected 2 comma-separated arguments at position ${s} in LaTeX source: ${e}`);return[h[0],h[1]]};for(;s<e.length;){let l=e[s];if(l==="\\"){let f=/^\\[a-zA-Z]+/.exec(e.slice(s));if(!f)throw new Error(`Unsupported LaTeX construct at position ${s}: ${e.slice(s,s+10)}`);let h=f[0];if(s+=h.length,h==="\\cdot"||h==="\\times"){n+="*";continue}if(h==="\\pi"){n+="pi";continue}let m=Ea[h];if(m){n+=m;continue}if(h==="\\begin"){let d=o();if(d!=="cases")throw new Error(`Unsupported LaTeX environment: \\begin{${d}}`);let w="\\end{cases}",g=e.indexOf(w,s);if(g===-1)throw new Error("Unmatched \\begin{cases} in LaTeX source");let M=e.slice(s,g);s=g+w.length;let v=Is(M,"\\\\"),N=[],$=null;for(let b of v){if(b.trim()==="")continue;let x=Is(b,"&");if(x.length!==2)throw new Error(`Expected 'expr & cond' in \\begin{cases} row: ${b}`);let[S,O]=x;if(O.trim()==="\\text{otherwise}"){if($!==null)throw new Error("\\begin{cases} may have only one \\text{otherwise} row");$=lt(S,t)}else{let A=O.replace(/^\s*\\text\{\s*(?:if|when)\s*\}/,"");N.push(`${lt(A,t)}, ${lt(S,t)}`)}}if($===null)throw new Error("\\begin{cases} must have exactly one \\text{otherwise} row (as its last row)");n+=`piecewise(${N.concat($).join(", ")})`;continue}if(h==="\\frac"||h==="\\dfrac"||h==="\\tfrac"){let d=a(),w=a();n+=`((${lt(d,t)})/(${lt(w,t)}))`;continue}if(h==="\\sqrt"){if(e[s]==="["){let{content:d,next:w}=Ne(e,s);s=w;let g=a(),M=lt(d,t).trim();n+=M==="3"?`cbrt(${lt(g,t)})`:`((${lt(g,t)})^(1/(${M})))`}else{let d=a();n+=`sqrt(${lt(d,t)})`}continue}if(h==="\\log"){let d="10";if(e[s]==="_"&&e[s+1]==="{"){let{content:v,next:N}=Ne(e,s+1);s=N,d=v.trim()}if(d!=="10"&&d!=="2")throw new Error(`Unsupported LaTeX construct: \\log base ${d} (only base 10 and base 2 are supported)`);let w=c(),g=i(),M=`${d==="2"?"log2":"log10"}(${lt(g,t)})`;n+=w===null?M:`${M}^(${lt(w,t)})`;continue}if(h==="\\lfloor"||h==="\\lceil"){let d=h==="\\lfloor"?"\\rfloor":"\\rceil",w=e.indexOf(d,s);if(w===-1)throw new Error(`Unmatched '${h}' in LaTeX source`);let g=e.slice(s,w);s=w+d.length,n+=`${h==="\\lfloor"?"floor":"ceil"}(${lt(g,t)})`;continue}if(h==="\\operatorname"){let d=o(),w=$a[d];if(w){let[$,b]=u();n+=`${w}(${lt($,t)}, ${lt(b,t)})`;continue}let g=Ma[d];if(!g)throw new Error(`Unsupported LaTeX construct: \\operatorname{${d}}`);let M=c(),v=i(),N=`${g}(${lt(v,t)})`;n+=M===null?N:`${N}^(${lt(M,t)})`;continue}let p=Na[h];if(p){let[d,w]=u();n+=`${p}(${lt(d,t)}, ${lt(w,t)})`;continue}let y=va[h];if(y){let d=c(),w=i(),g=`${y}(${lt(w,t)})`;n+=d===null?g:`${g}^(${lt(d,t)})`;continue}throw new Error(`Unsupported LaTeX construct: ${h}`)}if(l==="|"){let f=e.indexOf("|",s+1);if(f===-1)throw new Error("Unmatched '|' in LaTeX source");let h=e.slice(s+1,f);s=f+1,n+=`abs(${lt(h,t)})`;continue}if(r&&l==="^"&&/^[a-zA-Z0-9]|^\\[a-zA-Z]/.test(e.slice(s+1))){let f=/^(?:\\[a-zA-Z]+|[a-zA-Z0-9])/.exec(e.slice(s+1));s+=1+f[0].length,n+=`^(${lt(f[0],t)})`;continue}if(l==="^"&&e[s+1]==="{"){let{content:f,next:h}=Ne(e,s+1);s=h,n+=`^(${lt(f,t)})`;continue}if(l==="_"&&e[s+1]==="{"){let{content:f,next:h}=Ne(e,s+1);s=h,n+=`_${f.replace(/\W/g,"")}`;continue}if(l==="{"){let{content:f,next:h}=Ne(e,s);s=h,n+=`(${lt(f,t)})`;continue}if(l==="="){n+="==",s++;continue}n+=l,s++}return n}var ao=400,Fa=8,pe=class extends Error{};function ka(e,t){let r=nt(t,0),n=e.keys.indexOf(r);return n<0&&(n=e.keys.length,e.keys.push(r),e.atoms.push(t)),n}function co(e,t){let r=Math.max(e.length,t.length);for(let n=0;n<r;n++){let s=(e[n]??0)-(t[n]??0);if(s!==0)return s}return 0}function Cr(e){let t=e.length;for(;t>0&&!e[t-1];)t--;return e.slice(0,t).join(",")}function jr(e){let t=new Map;for(let n of e){let s=Cr(n.exps),o=t.get(s);o?t.set(s,{exps:o.exps,c:o.c.add(n.c)}):t.set(s,{exps:n.exps,c:n.c})}let r=[...t.values()].filter(n=>!n.c.isZero());if(r.sort((n,s)=>co(s.exps,n.exps)),r.length>ao)throw new pe;return r}var me=e=>e.isZero()?[]:[{exps:[],c:e}],kn=(e,t)=>jr([...e,...t]),ur=e=>e.map(t=>({exps:t.exps,c:t.c.negate()})),za=(e,t)=>kn(e,ur(t));function $e(e,t){if(e.length*t.length>ao*20)throw new pe;let r=[];for(let n of e)for(let s of t){let o=Math.max(n.exps.length,s.exps.length),i=[];for(let a=0;a<o;a++)i.push((n.exps[a]??0)+(s.exps[a]??0));r.push({exps:i,c:n.c.multiply(s.c)})}return jr(r)}function Pa(e,t){return e.length===t.length&&e.every((r,n)=>Cr(r.exps)===Cr(t[n].exps)&&r.c.equals(t[n].c))}var Er=e=>e.length===0||e.length===1&&Cr(e[0].exps)==="";function cr(e,t){let r=t[0],n=e,s=[],o=[],i=0;for(;n.length>0;){if(++i>2e4)throw new pe;let a=n[0],c=Math.max(a.exps.length,r.exps.length),u=[],l=!0;for(let h=0;h<c;h++){let m=(a.exps[h]??0)-(r.exps[h]??0);m<0&&(l=!1),u.push(m)}if(!l){o.push(a),n=n.slice(1);continue}let f={exps:u,c:a.c.divide(r.c)};s.push(f),n=za(n,$e([f],t))}return{q:jr(s),r:jr(o)}}function Oa(...e){let t=new Set;for(let r of e)for(let n of r)for(let s=0;s<n.exps.length;s++)n.exps[s]>0&&t.add(s);return t}function Ra(e,t){if(Oa(e,t).size>1)return me(st.One);let r=e,n=t;for(;n.length>0;){let{r:o}=cr(r,n);r=n,n=o}if(r.length===0)return me(st.One);let s=r[0].c;return r.map(o=>({exps:o.exps,c:o.c.divide(s)}))}function Ca(e){if(e.length===0)return[];let t=Math.max(...e.map(n=>n.exps.length)),r=[];for(let n=0;n<t;n++)r.push(Math.min(...e.map(s=>s.exps[n]??0)));return r}function Fs(e,t){return e.map(r=>({exps:r.exps.map((n,s)=>n-(t[s]??0)),c:r.c}))}var lr=e=>({n:e,d:me(st.One)});function ks(e,t,r){let n=r?ur(t.n):t.n;return Pa(e.d,t.d)?{n:kn(e.n,n),d:e.d}:{n:kn($e(e.n,t.d),$e(n,e.d)),d:$e(e.d,t.d)}}var uo=(e,t)=>({n:$e(e.n,t.n),d:$e(e.d,t.d)});function lo(e,t){if(t.n.length===0)throw new pe;return{n:$e(e.n,t.d),d:$e(e.d,t.n)}}function ja(e,t){let r=Math.abs(t);if(r>1e3)throw new pe;let n=e.n.length===1&&e.d.length===1;if(!n&&r>Fa)throw new pe;let s;if(n){let o=i=>({exps:i.exps.map(a=>a*r),c:i.c.pow(r)});s={n:[o(e.n[0])],d:[o(e.d[0])]}}else{s=lr(me(st.One));for(let o=0;o<r;o++)s=uo(s,e)}return t<0?lo(lr(me(st.One)),s):s}function La(e){if(!Number.isFinite(e))return null;if(Number.isInteger(e))return new st(BigInt(e));let t=st.fromNumber(e,1e4);return t.toNumber()===e?t:null}function Ht(e,t){let r=n=>{let s=ka(t,n),o=new Array(s+1).fill(0);return o[s]=1,lr([{exps:o,c:st.One}])};switch(e.type){case"const":{let n=La(e.value);return n?lr(me(n)):r(e)}case"var":return r(e);case"neg":{let n=Ht(e.arg,t);return{n:ur(n.n),d:n.d}}case"add":return ks(Ht(e.left,t),Ht(e.right,t),!1);case"sub":return ks(Ht(e.left,t),Ht(e.right,t),!0);case"mul":return uo(Ht(e.left,t),Ht(e.right,t));case"div":return lo(Ht(e.left,t),Ht(e.right,t));case"pow":return e.exp.type==="const"&&Number.isInteger(e.exp.value)?ja(Ht(e.base,t),e.exp.value):r(ot(Ft(e.base),Ft(e.exp)));case"func":return r(q(e.name,Ft(e.arg)));case"call2":return r(ee(e.name,Ft(e.left),Ft(e.right)));case"cmp":return r(De(e.op,Ft(e.left),Ft(e.right)));case"piecewise":return r(de(e.branches.map(n=>({cond:Ft(n.cond),expr:Ft(n.expr)})),Ft(e.otherwise)));case"sum":return r(ce(e.variable,Ft(e.from),Ft(e.to),Ft(e.body)));case"product":return r(Se(e.variable,Ft(e.from),Ft(e.to),Ft(e.body)))}}function zs(e,t){let r=e<0n?-e:e,n=t<0n?-t:t;for(;n;)[r,n]=[n,r%n];return r}function qa(e){if(e.n.length===0)return lr([]);let{n:t,d:r}=e,n=Ca([...t,...r]);if(n.some(a=>a>0)&&(t=Fs(t,n),r=Fs(r,n)),!Er(r)){let a=Ra(t,r);if(!Er(a))t=cr(t,a).q,r=cr(r,a).q;else{let c=cr(t,r);if(c.r.length===0)t=c.q,r=me(st.One);else{let u=cr(r,t);u.r.length===0&&(r=u.q,t=me(st.One))}}}if(Er(r)){let a=r[0].c;return{n:t.map(c=>({exps:c.exps,c:c.c.divide(a)})),d:me(st.One)}}let s=1n;for(let a of[...t,...r]){let c=a.c.denominator;s=s/zs(s,c)*c}let o=new st(s);t=t.map(a=>({exps:a.exps,c:a.c.multiply(o)})),r=r.map(a=>({exps:a.exps,c:a.c.multiply(o)}));let i=0n;for(let a of[...t,...r])i=zs(i,a.c.numerator);if(i>1n){let a=new st(1n,i);t=t.map(c=>({exps:c.exps,c:c.c.multiply(a)})),r=r.map(c=>({exps:c.exps,c:c.c.multiply(a)}))}return r[0].c.sign<0&&(t=ur(t),r=ur(r)),{n:t,d:r}}function Ta(e,t){let r=null;for(let n=0;n<e.length;n++){let s=e[n]??0;if(s===0)continue;let o=s===1?t.atoms[n]:ot(t.atoms[n],z(s));r=r?R(r,o):o}return r}function Ps(e,t){if(e.length===0)return z(0);let r=[...e].sort((s,o)=>{let i=s.exps.reduce((c,u)=>c+u,0);return o.exps.reduce((c,u)=>c+u,0)-i||co(o.exps,s.exps)}),n=null;for(let s of r){let o=s.c.sign<0,i=s.c.abs(),a=Ta(s.exps,t),c=i.numerator,u;a?c===1n&&i.denominator===1n?u=a:i.denominator===1n?u=R(z(Number(c)),a):u=X(c===1n?a:R(z(Number(c)),a),z(Number(i.denominator))):u=z(i.toNumber()),n?n=o?W(n,u):Q(n,u):n=o?xt(u):u}return n}function Dt(e){switch(e.type){case"const":case"var":return 1;case"neg":case"func":return 1+Dt(e.arg);case"pow":return 1+Dt(e.base)+Dt(e.exp);case"piecewise":return 1+Dt(e.otherwise)+e.branches.reduce((t,r)=>t+Dt(r.cond)+Dt(r.expr),0);case"sum":case"product":return 1+Dt(e.from)+Dt(e.to)+Dt(e.body);default:return 1+Dt(e.left)+Dt(e.right)}}function Ft(e){if(e.type==="const"||e.type==="var")return e;try{let t={atoms:[],keys:[]},r=qa(Ht(e,t)),n=Ps(r.n,t),s=Er(r.d)?n:X(n,Ps(r.d,t));return Dt(s)<Dt(e)?s:e}catch(t){if(t instanceof pe)return e;throw t}}function Rt(e){if(Number.isInteger(e))return z(e);let t=st.fromNumber(e,1e4);return t.denominator===1n?z(Number(t.numerator)):X(z(Number(t.numerator)),z(Number(t.denominator)))}function fo(e,t){let r=0;for(let n=e.length-1;n>=0;n--)r=r*t+e[n];return r}function Va(e,t){let r={};for(let o of t)r[o]=0;let n=G(e,r);if(!Number.isFinite(n))return null;let s=[];for(let o of t){let i=B(tt(e,o));if(t.some(c=>K(i,c)))return null;let a=G(i,r);if(!Number.isFinite(a))return null;s.push(a)}return[...s,n]}function Os(e,t,r){let n=[],s=e,o=1;for(let i=0;i<=r;i++){i>0&&(o*=i);let a=G(s,{[t]:0});if(!Number.isFinite(a))return null;n.push(a/o),s=B(tt(s,t))}for(;n.length>1&&Math.abs(n[n.length-1])<1e-9;)n.pop();for(let i of[1.3,-2.1,3.7]){let a=G(e,{[t]:i});if(!Number.isFinite(a)||Math.abs(fo(n,i)-a)>1e-6*Math.max(1,Math.abs(a)))return null}return n}function zn(e,t){let r=Math.abs(e),n=Math.abs(t);for(;n;)[r,n]=[n,r%n];return r||1}function Rs(e){let t=Math.round(Math.abs(e));if(t===0)return[1];let r=[];for(let n=1;n<=t;n++)t%n===0&&r.push(n);return r}function ho(e){let t=e.length-1,r=e.map(a=>Math.round(a));if(!e.every((a,c)=>Math.abs(a-r[c])<1e-6))return null;let s=Rs(r[0]),o=Rs(r[t]),i=new Set;for(let a of s)for(let c of o)for(let u of[1,-1]){let l=u*a/c;if(!i.has(l)&&(i.add(l),Math.abs(fo(r,l))<1e-6))return l}return null}function mo(e,t){let r=[...e].reverse(),n=[r[0]];for(let s=1;s<r.length-1;s++)n.push(r[s]+t*n[s-1]);return n.reverse()}function Pn(e){let t=[...e];for(;t.length>1&&Math.abs(t[t.length-1])<1e-9;)t.pop();let r=t.length-1;if(r<=0){if(t.length===0||Math.abs(t[0])<1e-9)throw new Or;return[]}if(r===1){let[o,i]=t;return[Rt(-o/i)]}if(r===2){let[o,i,a]=t,c=i*i-4*a*o;if(c<-1e-9)return[];let u=-i,l=2*a;if(Math.abs(c)<1e-9)return[Rt(u/l)];let f=Math.sqrt(c);if(Math.abs(f-Math.round(f))<1e-9)return[Rt((u+f)/l),Rt((u-f)/l)];let h=q("sqrt",Rt(c));return[X(Q(Rt(u),h),Rt(l)),X(W(Rt(u),h),Rt(l))]}if(Math.abs(t[0])<1e-9)return[Rt(0),...Pn(t.slice(1))];let n=ho(t);if(n===null)throw new Error(`solve: no closed-form root found for a degree-${r} polynomial (only rational roots are searched for degree \u2265 3).`);let s=mo(t,n);return[Rt(n),...Pn(s)]}function Ua(e,t){let r=null;for(let n=0;n<e.length;n++){if(e[n]===0)continue;let s=n===0?Rt(e[n]):R(Rt(e[n]),n===1?et(t):ot(et(t),z(n)));r=r===null?s:Q(r,s)}return r??z(0)}function Ba(e,t){let r=[...e];for(;r.length>1&&Math.abs(r[r.length-1])<1e-9;)r.pop();if(r.every(l=>Math.abs(l)<1e-9))return z(0);let n=0;for(;r.length>1&&Math.abs(r[0])<1e-9;)r.shift(),n++;let s=r.map(l=>Math.round(l)),o=r.every((l,f)=>Math.abs(l-s[f])<1e-6),i=1;o&&(i=s.reduce((l,f)=>f===0?l:zn(l,Math.abs(f)),0)||1,r=s.map(l=>l/i));let a=[],c=r;for(;c.length-1>=3;){let l=ho(c);if(l===null)break;a.push(l),c=mo(c,l)}if(c.length-1===2){let[l,f,h]=c,m=f*f-4*h*l;if(m>=0){let p=Math.sqrt(m);Math.abs(p-Math.round(p))<1e-9&&(a.push((-f+p)/(2*h),(-f-p)/(2*h)),c=[h])}}else if(c.length-1===1){let[l,f]=c;a.push(-l/f),c=[f]}let u=Rt(i);n===1?u=R(u,et(t)):n>1&&(u=R(u,ot(et(t),z(n))));for(let l of a)u=R(u,Math.abs(l)<1e-9?et(t):W(et(t),Rt(l)));return c.length>1?u=R(u,Ua(c,t)):Math.abs(c[0]-1)>1e-9&&(u=R(u,Rt(c[0]))),B(u)}function In(e,t,r,n){if(n==="both")return G(e,{[t]:r});let s=n==="right"?1e-6:-1e-6;return G(e,{[t]:r+s})}function po(e,t,r,n,s){let o=In(e,t,r,n);if(Number.isFinite(o))return o;if(e.type==="div"&&s<12){let i=In(e.left,t,r,n),a=In(e.right,t,r,n);if(Math.abs(i)<1e-6&&Math.abs(a)<1e-6||!Number.isFinite(i)&&!Number.isFinite(a)){let u=B(tt(e.left,t)),l=B(tt(e.right,t));return po(X(u,l),t,r,n,s+1)}}return o}var Cs=[...Ts].sort((e,t)=>t.length-e.length),On=class{s;implicit;pos=0;constructor(t,r={}){this.implicit=r.implicitMultiplication===!0;let n=this.implicit?t.replace(/(\d)\s+(?=[\d.])/g,"$1*"):t;this.s=n.replace(/\s+/g,"")}parse(){let t=this.comparison();if(this.pos<this.s.length)throw new Error(`Unexpected token at ${this.pos}: ${this.s.slice(this.pos)}`);return t}peek(){return this.s[this.pos]??""}argList(){let t=[this.expr()];for(;this.peek()===",";)this.pos++,t.push(this.expr());return t}comparison(){let t=this.expr(),r=this.matchCmpOp();return r?De(r,t,this.expr()):t}matchCmpOp(){let t={"<=":"le",">=":"ge","==":"eq","!=":"ne"},r=this.s.slice(this.pos,this.pos+2),n=t[r];return n?(this.pos+=2,n):this.peek()==="<"?(this.pos++,"lt"):this.peek()===">"?(this.pos++,"gt"):null}piecewiseArgs(){let t=[this.comparison()];for(;this.peek()===",";)this.pos++,t.push(this.comparison());if(this.peek()!==")")throw new Error("Expected ')'");if(this.pos++,t.length<3||t.length%2===0)throw new Error(`piecewise() expects an odd number of arguments >= 3 (cond, expr, ..., otherwise), got ${t.length}`);let r=[];for(let n=0;n+1<t.length-1;n+=2)r.push({cond:t[n],expr:t[n+1]});return de(r,t[t.length-1])}sumOrProductArgs(t){let r=/^[a-zA-Z_]\w*/.exec(this.s.slice(this.pos));if(!r)throw new Error(`${t}() expects a bound variable name as its first argument`);let n=r[0];if(this.pos+=n.length,this.peek()!==",")throw new Error("Expected ','");this.pos++;let s=this.comparison();if(this.peek()!==",")throw new Error("Expected ','");this.pos++;let o=this.comparison();if(this.peek()!==",")throw new Error("Expected ','");this.pos++;let i=this.comparison();if(this.peek()!==")")throw new Error("Expected ')'");return this.pos++,t==="sum"?ce(n,s,o,i):Se(n,s,o,i)}expr(){let t=this.term();for(;this.peek()==="+"||this.peek()==="-";){let r=this.s[this.pos++],n=this.term();t=r==="+"?Q(t,n):W(t,n)}return t}term(){let t=this.factor();for(;;){let r=this.peek();if(r==="*"||r==="/"){this.pos++;let n=this.factor();t=r==="*"?R(t,n):X(t,n)}else if(this.implicit&&/[a-zA-Z0-9.(]/.test(r))t=R(t,this.factor());else return t}}implicitIdentifier(){let t=this.s.slice(this.pos),r=/^[a-zA-Z]+/.exec(t)?.[0]??"",n=Cs.find(i=>t.startsWith(i)&&t[i.length]==="(");if(n)return n;let s=Cs.find(i=>i.length>1&&r.startsWith(i));if(s)throw new Error(`Function ${s} needs parentheses: ${s}(...)`);if(t.startsWith("pi"))return"pi";let o=/^[a-zA-Z]_(?:\d+|[a-zA-Z])/.exec(t);return o?o[0]:t[0]}factor(){if(this.peek()==="-")return this.pos++,xt(this.factor());let t=this.base();return this.peek()==="^"?(this.pos++,ot(t,this.factor())):t}base(){if(this.peek()==="("){this.pos++;let n=this.comparison();if(this.peek()!==")")throw new Error("Expected ')'");return this.pos++,n}if(this.peek()==="|"){this.pos++;let n=this.expr();if(this.peek()!=="|")throw new Error("Expected '|'");return this.pos++,q("abs",n)}let t=/^\d+\.?\d*(?:[eE][+-]?\d+)?/.exec(this.s.slice(this.pos));if(t)return this.pos+=t[0].length,z(Number(t[0]));let r=this.implicit?/^[a-zA-Z_]/.exec(this.s.slice(this.pos)):/^[a-zA-Z_]\w*/.exec(this.s.slice(this.pos));if(r){let n=this.implicit?this.implicitIdentifier():r[0];if(this.pos+=n.length,(n==="log"||n==="clamp")&&this.peek()==="("){this.pos++;let o=this.argList();if(this.peek()!==")")throw new Error("Expected ')'");if(this.pos++,n==="log"){if(o.length!==2)throw new Error(`log() expects 2 arguments (base, x), got ${o.length}`);return X(q("ln",o[1]),q("ln",o[0]))}if(o.length!==3)throw new Error(`clamp() expects 3 arguments (x, lo, hi), got ${o.length}`);return ee("min",ee("max",o[0],o[1]),o[2])}if(n==="piecewise"&&this.peek()==="(")return this.pos++,this.piecewiseArgs();if((n==="sum"||n==="product")&&this.peek()==="(")return this.pos++,this.sumOrProductArgs(n);if(Ls.includes(n)&&this.peek()==="("){let o=n;this.pos++;let i=this.argList();if(this.peek()!==")")throw new Error("Expected ')'");if(this.pos++,o==="atan2"){if(i.length!==2)throw new Error(`atan2() expects exactly 2 arguments, got ${i.length}`);return ee("atan2",i[0],i[1])}if(i.length<2)throw new Error(`${o}() expects at least 2 arguments, got ${i.length}`);return i.reduce((a,c)=>ee(o,a,c))}let s=js.includes(n)?n:qs[n];if(s&&this.peek()==="("){this.pos++;let o=this.expr();if(this.peek()!==")")throw new Error("Expected ')'");return this.pos++,q(s,o)}return n==="pi"?z(Math.PI):n==="e"?z(Math.E):et(n)}throw new Error(`Unexpected token at ${this.pos}: ${this.s.slice(this.pos)}`)}};var Ze=class e{w;x;y;z;static Identity=new e(1,0,0,0);static Zero=new e(0,0,0,0);constructor(t=0,r=0,n=0,s=0){this.w=t,this.x=r,this.y=n,this.z=s}add(t){return new e(this.w+t.w,this.x+t.x,this.y+t.y,this.z+t.z)}subtract(t){return new e(this.w-t.w,this.x-t.x,this.y-t.y,this.z-t.z)}scale(t){return new e(this.w*t,this.x*t,this.y*t,this.z*t)}negate(){return new e(-this.w,-this.x,-this.y,-this.z)}multiply(t){return new e(this.w*t.w-this.x*t.x-this.y*t.y-this.z*t.z,this.w*t.x+this.x*t.w+this.y*t.z-this.z*t.y,this.w*t.y-this.x*t.z+this.y*t.w+this.z*t.x,this.w*t.z+this.x*t.y-this.y*t.x+this.z*t.w)}conjugate(){return new e(this.w,-this.x,-this.y,-this.z)}dot(t){return this.w*t.w+this.x*t.x+this.y*t.y+this.z*t.z}get norm(){return Math.hypot(this.w,this.x,this.y,this.z)}normalize(){let t=this.norm;if(t===0)throw new Error("Cannot normalize the zero quaternion.");return this.scale(1/t)}inverse(){let t=this.w*this.w+this.x*this.x+this.y*this.y+this.z*this.z;if(t===0)throw new Error("The zero quaternion has no inverse.");return this.conjugate().scale(1/t)}equals(t){return this.w===t.w&&this.x===t.x&&this.y===t.y&&this.z===t.z}static fromAxisAngle(t,r){let[n,s,o]=t,i=Math.hypot(n,s,o)||1,a=r/2,c=Math.sin(a)/i;return new e(Math.cos(a),n*c,s*c,o*c)}rotateVector(t){let r=this.normalize(),n=new e(0,t[0],t[1],t[2]),s=r.multiply(n).multiply(r.conjugate());return[s.x,s.y,s.z]}toRotationMatrix(){let{w:t,x:r,y:n,z:s}=this.normalize();return[[1-2*(n*n+s*s),2*(r*n-s*t),2*(r*s+n*t)],[2*(r*n+s*t),1-2*(r*r+s*s),2*(n*s-r*t)],[2*(r*s-n*t),2*(n*s+r*t),1-2*(r*r+n*n)]]}static slerp(t,r,n){let s=t.normalize(),o=r.normalize(),i=s.dot(o);if(i<0&&(o=o.scale(-1),i=-i),i>.9995)return s.add(o.subtract(s).scale(n)).normalize();let a=Math.acos(i),c=a*n,u=Math.sin(a),l=Math.sin(a-c)/u,f=Math.sin(c)/u;return s.scale(l).add(o.scale(f))}toString(){return`${this.w} + ${this.x}i + ${this.y}j + ${this.z}k`}};var Xe=class e{_criteria;_operations;_inverses;_identities;_wrapMethod;_equalityMethod;constructor(t={}){this._criteria=t.criteria??[],this._operations=t.operations??[],this._inverses=t.inverses??[],this._identities=t.identities??[],this._wrapMethod=t.wrap??(r=>r),this._equalityMethod=t.equality??((r,n)=>r===n)}criterion(t){return this._criteria[t]}isMember(t){return this._criteria.every(r=>r(t)!==!1)}operation(t){return this._operations[t]}integerPower(t,r,n=0){let s=this.identity(n),o=this.operation(n),i=t,a=r;a<0&&(a=-a,i=this.inverse(n)(t));for(let c=0;c<a;c++)s=o(s,i);return s}get add(){return this._operations[0]}addPower(t,r){return this.integerPower(t,r,0)}get multiply(){return this._operations[1]}multiplyPower(t,r){return this.integerPower(t,r,1)}inverse(t=0){return this._inverses[t]}get negative(){return this.inverse(0)}get reciprocal(){return this.inverse(1)}subtract(t,r){return this.add(t,this.negative(r))}divide(t,r){return this.multiply(t,this.reciprocal(r))}identity(t=0){return this._identities[t]}get zero(){return this._identities[0]}get one(){return this._identities[1]}get wrap(){return this._wrapMethod}get equality(){return this._equalityMethod}contains(t,r){return D.contains(t,r,this.equality)}wrapVector(t){return D.transform(t,this.wrap)}addVector(t,r){return D.combine(t,r,this.add,this.zero)}scaleVector(t,r){return D.transform(t,n=>this.multiply(r,n))}negativeVector(t){return D.transform(t,this.negative)}reciprocalVector(t){return D.transform(t,this.reciprocal)}inverseVector(t,r=0){return D.transform(t,this.inverse(r))}subtractVector(t,r){return this.addVector(t,this.negativeVector(r))}dotProduct(t,r){let n=D.combine(t,r,this.multiply,this.zero);return D.collapse(n,this.add)}crossProduct(t,r){let n=[this.zero,this.zero,this.zero],s=[this.zero,this.zero,this.zero];for(let c=0;c<3;c++)c<t.length&&t[c]!=null&&(n[c]=t[c]),c<r.length&&r[c]!=null&&(s[c]=r[c]);let o=this.subtract(this.multiply(n[1],s[2]),this.multiply(n[2],s[1])),i=this.subtract(this.multiply(n[2],s[0]),this.multiply(n[0],s[2])),a=this.subtract(this.multiply(n[0],s[1]),this.multiply(n[1],s[0]));return T.fromArray([o,i,a])}kroneckerProduct(t,r){let n=D.constantVector(t.length,null);return n=D.fillByIndex(n,s=>this.scaleVector(r,t[s])),D.flattenSDLevels(n,2)}generateIdentity(t=1,r=1){return D.generateIdentity(t,r,this.one,this.zero)}addMatrix(t,r){return D.combine(t,r,(n,s)=>this.addVector(n,s))}scaleMatrix(t,r){return D.transformEndNodes(t,n=>this.multiply(r,n))}negativeMatrix(t){return D.transformEndNodes(t,r=>this.negative(r))}subtractMatrix(t,r){return this.addMatrix(t,this.negativeMatrix(r))}scaleRow(t,r=0,n){let s=t.clone();return D.rowSet(s,this.scaleVector(s[r],n),r)}scaleColumn(t,r=0,n){return D.transpose(this.scaleRow(t,r,n))}trace(t){return D.collapse(D.diagonal(t),this.add)}kroneckerMatrixProduct(t,r){let n=D.constantMatrix(D.height(t),D.width(t),null);return n=D.fillMatrixByIndex(n,(s,o)=>this.scaleMatrix(r,t[s][o])),D.breakBlock(n)}multiplyMatrix(t,r){let n=new T;for(let s=0;s<D.width(t);s++)n.push(this.kroneckerMatrixProduct(D.getColumn(t,s),D.getRow(r,s)));return D.collapse(n,(s,o)=>this.addMatrix(s,o))}powerMatrix(t,r=1){if(r===0)return this.generateIdentity(D.height(t),D.width(t));let n=r>0?t.clone():this.invertMatrix(t),s=new T;for(let o=0;o<Math.abs(r);o++)s.push(n.clone());return D.collapse(s,(o,i)=>this.multiplyMatrix(o,i))}hasInverse(t){let r=this.reciprocal(t);return!(typeof r=="number"&&Number.isNaN(r))}noInverse(t,r){return new RangeError(`${t}: element ${String(r)} has no multiplicative inverse in this structure`)}determinantDivisionFree(t){let r=D.width(t),n=[...t].map(i=>[...i]),s=[this.one];for(let i=1;i<=r;i++){let a=i-1,c=[this.one,this.negative(n[a][a])],u=Array.from({length:a},(f,h)=>n[h][a]);for(let f=2;f<=i;f++){let h=this.zero;for(let m=0;m<a;m++)h=this.add(h,this.multiply(n[a][m],u[m]));c.push(this.negative(h)),f<i&&(u=Array.from({length:a},(m,p)=>{let y=this.zero;for(let d=0;d<a;d++)y=this.add(y,this.multiply(n[p][d],u[d]));return y}))}let l=[];for(let f=0;f<=i;f++){let h=this.zero;for(let m=0;m<i&&m<=f;m++)h=this.add(h,this.multiply(c[f-m],s[m]));l.push(h)}s=l}let o=s[r];return r%2===0?o:this.negative(o)}determinant(t){if(D.width(t)!==D.height(t))return this.zero;let r=D.width(t);if(r<2)return t[0][0];let n=[...t].map(i=>[...i]),s=this.one,o=this.one;for(let i=0;i<r;i++){if(this.equality(n[i][i],this.zero)||!this.hasInverse(n[i][i])){let u=this.equality(n[i][i],this.zero),l=-1;for(let f=i+1;f<r;f++)if(!this.equality(n[f][i],this.zero)&&this.hasInverse(n[f][i])){l=f;break}if(l===-1)return u&&n.slice(i+1).every(f=>this.equality(f[i],this.zero))?this.zero:this.determinantDivisionFree(t);[n[i],n[l]]=[n[l],n[i]],o=this.negative(o)}let a=n[i][i];s=this.multiply(s,a);let c=this.reciprocal(a);for(let u=i+1;u<r;u++){let l=this.multiply(n[u][i],c);if(!this.equality(l,this.zero))for(let f=i;f<r;f++)n[u][f]=this.subtract(n[u][f],this.multiply(l,n[i][f]))}}return this.multiply(o,s)}permanent(t){if(D.width(t)<2)return t[0][0];let r=new T;for(let n=0;n<D.width(t);n++){let s=D.columnRemoved(D.rowRemoved(t,0),n);r.push(this.multiply(t[0][n],this.permanent(s)))}return D.collapse(r,this.add)}invertMatrix(t,r=!0){let n=D.height(t),s=D.width(t);if(n!==s)throw new RangeError(`invertMatrix: matrix must be square, got ${n}x${s}`);if(r&&this.equality(this.determinant(t),this.zero))throw new RangeError("invertMatrix: matrix is singular");return this.invertByElimination(t)??this.invertByAdjugate(t)}invertByAdjugate(t){let r=D.height(t),n=[...t].map(a=>[...a]),s=this.determinant(t);if(this.equality(s,this.zero))throw new RangeError("invertMatrix: matrix is singular");if(!this.hasInverse(s))throw this.noInverse("invertMatrix",s);let o=this.reciprocal(s),i=Array.from({length:r},()=>new Array(r));for(let a=0;a<r;a++)for(let c=0;c<r;c++){let u=n.filter((h,m)=>m!==a).map(h=>T.fromArray(h.filter((m,p)=>p!==c))),l=this.determinant(T.fromArray(u)),f=(a+c)%2===0?l:this.negative(l);i[c][a]=this.multiply(o,f)}return T.fromArray(i.map(a=>T.fromArray(a)))}invertByElimination(t){let r=D.height(t),n=[...t].map(o=>[...o]),s=[...this.generateIdentity(r,r)].map(o=>[...o]);for(let o=0;o<r;o++){if(this.equality(n[o][o],this.zero)||!this.hasInverse(n[o][o])){let a=this.equality(n[o][o],this.zero),c=-1;for(let u=o+1;u<r;u++)if(!this.equality(n[u][o],this.zero)&&this.hasInverse(n[u][o])){c=u;break}if(c===-1){if(a&&n.slice(o+1).every(u=>this.equality(u[o],this.zero)))throw new RangeError("invertMatrix: matrix is singular");return null}[n[o],n[c]]=[n[c],n[o]],[s[o],s[c]]=[s[c],s[o]]}let i=this.reciprocal(n[o][o]);for(let a=0;a<r;a++)n[o][a]=this.multiply(n[o][a],i),s[o][a]=this.multiply(s[o][a],i);for(let a=0;a<r;a++){if(a===o)continue;let c=n[a][o];for(let u=0;u<r;u++)n[a][u]=this.subtract(n[a][u],this.multiply(c,n[o][u])),s[a][u]=this.subtract(s[a][u],this.multiply(c,s[o][u]))}}return T.fromArray(s.map(o=>T.fromArray(o)))}vectorSum(t){return D.collapse(t,this.add)}vectorProduct(t){return D.collapse(t,this.multiply)}vectorCollapseOperation(t,r=0){return D.collapse(t,this.operation(r))}static realField(){return new e({criteria:[t=>typeof t=="number"],operations:[(t,r)=>t+r,(t,r)=>t*r],inverses:[t=>-t,t=>1/t],identities:[0,1],equality:(t,r)=>t===r,wrap:t=>Number(t)})}static complexField(){return new e({criteria:[t=>t instanceof Tt],operations:[(t,r)=>t.add(r),(t,r)=>t.multiply(r)],inverses:[t=>t.neg(),t=>t.reciprocal()],identities:[Tt.Zero,Tt.One],equality:(t,r)=>t.equals(r),wrap:t=>t instanceof Tt?t:new Tt(t)})}static integersModulo(t){let r=s=>(s%t+t)%t,n=s=>{if(!Number.isInteger(s))return Number.NaN;let[o,i]=[r(s),t],[a,c]=[1,0];for(;i!==0;){let u=Math.floor(o/i);[o,i]=[i,o-u*i],[a,c]=[c,a-u*c]}return o!==1?NaN:r(a)};return new e({criteria:[s=>typeof s=="number"],operations:[(s,o)=>r(s+o),(s,o)=>r(s*o)],inverses:[s=>r(-s),n],identities:[0,1],equality:(s,o)=>r(s)===r(o),wrap:s=>r(Number(s))})}static booleanRing(){return e.integersModulo(2)}static rationalField(){return new e({criteria:[t=>t instanceof st],operations:[(t,r)=>t.add(r),(t,r)=>t.multiply(r)],inverses:[t=>t.negate(),t=>t.reciprocal()],identities:[st.Zero,st.One],equality:(t,r)=>t.equals(r),wrap:t=>st.from(t)})}static decimalField(){return new e({criteria:[t=>t instanceof be],operations:[(t,r)=>t.add(r),(t,r)=>t.multiply(r)],inverses:[t=>t.negate(),t=>be.One.divide(t)],identities:[be.Zero,be.One],equality:(t,r)=>t.equals(r),wrap:t=>be.from(t)})}static quaternionRing(){return new e({criteria:[t=>t instanceof Ze],operations:[(t,r)=>t.add(r),(t,r)=>t.multiply(r)],inverses:[t=>t.negate(),t=>t.inverse()],identities:[Ze.Zero,Ze.Identity],equality:(t,r)=>t.equals(r)})}static dualNumbers(){return new e({criteria:[t=>t instanceof ue],operations:[(t,r)=>t.add(r),(t,r)=>t.multiply(r)],inverses:[t=>t.negate(),t=>new ue(1,0).divide(t)],identities:[new ue(0,0),new ue(1,0)],equality:(t,r)=>t.value===r.value&&t.deriv===r.deriv,wrap:t=>t instanceof ue?t:ue.constant(t)})}};function mr(e,t={}){let r=t.variable??"x",n=typeof e=="string"?C.parse(e,{implicitMultiplication:t.implicitMultiplication===!0}):e,s=C.compile(n),o={...t.params,[r]:0};return i=>(o[r]=i,s(o))}var hr=class extends Error{};function ke(e,t){let r=e.length,n=new Float64Array(r);for(let s=0;s<r;s++){let o=e[s];if(o!==0)for(let i=0;s+i<r;i++)n[s+i]=n[s+i]+o*t[i]}return n}function fr(e,t){let r=e.length,n=new Float64Array(r);for(let s=0;s<r;s++){let o=e[s];for(let i=1;i<=s;i++)o-=t[i]*n[s-i];n[s]=o/t[0]}return n}var Ye=(e,t)=>{let r=new Float64Array(t);return r[0]=e,r};function yo(e){let t=e.length,r=new Float64Array(t);r[0]=Math.exp(e[0]);for(let n=1;n<t;n++){let s=0;for(let o=1;o<=n;o++)s+=o*e[o]*r[n-o];r[n]=s/n}return r}function xo(e){let t=e.length,r=new Float64Array(t);r[0]=Math.log(e[0]);for(let n=1;n<t;n++){let s=0;for(let o=1;o<n;o++)s+=o*r[o]*e[n-o];r[n]=(e[n]-s/n)/e[0]}return r}function We(e,t){let r=e.length,n=new Float64Array(r),s=new Float64Array(r);n[0]=t?Math.sinh(e[0]):Math.sin(e[0]),s[0]=t?Math.cosh(e[0]):Math.cos(e[0]);for(let o=1;o<r;o++){let i=0,a=0;for(let c=1;c<=o;c++)i+=c*e[c]*s[o-c],a+=c*e[c]*n[o-c];n[o]=i/o,s[o]=(t?a:-a)/o}return[n,s]}function Lr(e,t){let r=e.length,n=new Float64Array(r),s=e[0];n[0]=s**t;for(let o=1;o<r;o++){let i=0;for(let a=1;a<=o;a++)i+=(t*a-(o-a))*e[a]*n[o-a];n[o]=i/(o*s)}return n}function Ga(e,t){let r=Ye(1,e.length),n=e,s=Math.abs(t);for(;s>0;)s&1&&(r=ke(r,n)),n=ke(n,n),s=Math.floor(s/2);return t<0?fr(Ye(1,e.length),r):r}function qn(e,t){let r=e.length,n=new Float64Array(r);n[0]=t;for(let s=1;s<r;s++)n[s]=e[s-1]/s;return n}function go(e){let t=e.length,r=new Float64Array(t);for(let n=0;n+1<t;n++)r[n]=(n+1)*e[n+1];return r}function Da(e,t){let r=t.length,n=Ye(1,r);switch(e){case"exp":return yo(t);case"ln":return xo(t);case"sqrt":return Lr(t,.5);case"cbrt":return Lr(t,1/3);case"sin":return We(t,!1)[0];case"cos":return We(t,!1)[1];case"tan":{let[s,o]=We(t,!1);return fr(s,o)}case"sinh":return We(t,!0)[0];case"cosh":return We(t,!0)[1];case"tanh":{let[s,o]=We(t,!0);return fr(s,o)}case"atan":{let s=fr(go(t),qr(n,ke(t,t),1));return qn(s,Math.atan(t[0]))}case"asin":case"acos":{let s=Lr(qr(n,ke(t,t),-1),-.5),o=ke(go(t),s);return e==="asin"?qn(o,Math.asin(t[0])):qn(o.map(i=>-i),Math.acos(t[0]))}default:throw new hr(e)}}function qr(e,t,r){let n=new Float64Array(e.length);for(let s=0;s<e.length;s++)n[s]=e[s]+r*t[s];return n}function Za(e,t,r,n,s){let o=i=>{switch(i.type){case"const":return Ye(i.value,s);case"var":{if(i.name===t){let a=Ye(r,s);return s>1&&(a[1]=1),a}return Ye(n[i.name]??Number.NaN,s)}case"neg":return o(i.arg).map(a=>-a);case"add":return qr(o(i.left),o(i.right),1);case"sub":return qr(o(i.left),o(i.right),-1);case"mul":return ke(o(i.left),o(i.right));case"div":return fr(o(i.left),o(i.right));case"func":return Da(i.name,o(i.arg));case"pow":{let a=o(i.base),c=o(i.exp);if(c.every((l,f)=>f===0||l===0)){let l=c[0];return Number.isInteger(l)&&Math.abs(l)<=256?Ga(a,l):Lr(a,l)}return yo(ke(c,xo(a)))}default:throw new hr(i.type)}};return o(e)}function bo(e,t,r,n={}){if(!Number.isInteger(r)||r<0)throw new RangeError("order must be a non-negative integer");let s=n.variable??"x",o=typeof e=="string"?C.parse(e):e;try{return Za(o,s,t,n.params??{},r+1)}catch(u){if(!(u instanceof hr))throw u}let i=o,a=new Float64Array(r+1),c=1;for(let u=0;u<=r;u++)u>0&&(c*=u),a[u]=C.evaluate(i,{...n.params,[s]:t})/c,u<r&&(i=C.simplify(C.differentiate(i,s)));return a}var wo=new Set(["sin","cos","tan","cot","sec","csc"]),Xa=new Set(["asin","acos","atan","acot","asec","acsc","arcsin","arccos","arctan","arccot","arcsec","arccsc","atan2"]),Wa=2e4;function Ya(e,t){let r=0;for(let n=t;n<e.length;n++)if(e[n]==="(")r++;else if(e[n]===")"&&--r===0)return n;return-1}function vo(e){if(typeof e!="string"||e.length>Wa)return e;let t="",r=0;for(;r<e.length;){let n=/^[A-Za-z_][A-Za-z_0-9]*/.exec(e.slice(r,r+40));if(!n){t+=e[r++];continue}let s=n[0],o=r+s.length;for(;e[o]===" ";)o++;let i=s.toLowerCase();if(e[o]==="("&&(wo.has(i)||Xa.has(i))){let a=Ya(e,o);if(a<0)return e;let c=vo(e.slice(o+1,a));t+=wo.has(i)?`${s}((${c})*(pi/180))`:`((${s}(${c}))*(180/pi))`,r=a+1}else t+=s,r+=s.length}return t}var Mo=e=>{if(!e||typeof e!="object")return e;let t={...e};for(let r of["expr","expr2","expr3"])typeof t[r]=="string"&&(t[r]=vo(t[r]));return t};function No(e,t,{maxPoints:r=2e4}={}){if(typeof t!="number"||!Number.isFinite(t))throw new TypeError("the level is a finite number");let n=e?.columns,s=e?.rows;if(!e||!Number.isInteger(n)||!Number.isInteger(s)||n<2||s<2||n*s>4e6||!e.positions||!e.valid||e.positions.length<n*s*3||e.valid.length<n*s)throw new TypeError("a mesh has columns, rows, positions and valid flags for every vertex");let{positions:o,valid:i}=e,a=(g,M)=>M*n+g,c=(g,M)=>o[a(g,M)*3+2],u=g=>{let M=g>>1,v=g&1?M+n:M+1,N=o[M*3+2],$=o[v*3+2],b=$===N?.5:(t-N)/($-N);return[o[M*3]+(o[v*3]-o[M*3])*b,o[M*3+1]+(o[v*3+1]-o[M*3+1])*b]},l=[],f=Math.max(1,Math.floor(r));for(let g=0;g+1<s&&l.length<f;g++)for(let M=0;M+1<n&&l.length<f;M++){if(!(i[a(M,g)]&&i[a(M+1,g)]&&i[a(M+1,g+1)]&&i[a(M,g+1)]))continue;let v=[c(M,g),c(M+1,g),c(M+1,g+1),c(M,g+1)];if(!v.every(Number.isFinite))continue;let N=v.map(S=>S>=t);if(N.every(Boolean)||!N.some(Boolean))continue;let $=a(M,g),b={bottom:$*2,right:a(M+1,g)*2+1,top:a(M,g+1)*2,left:$*2+1},x=[N[0]!==N[1]&&"bottom",N[1]!==N[2]&&"right",N[2]!==N[3]&&"top",N[3]!==N[0]&&"left"].filter(Boolean);x.length===2?l.push([b[x[0]],b[x[1]]]):x.length===4&&((v[0]+v[1]+v[2]+v[3])/4>=t===N[0]?l.push([b.bottom,b.right],[b.top,b.left]):l.push([b.bottom,b.left],[b.right,b.top]))}let h=new Map;l.forEach(([g,M],v)=>{for(let N of[g,M])(h.get(N)??h.set(N,[]).get(N)).push(v)});let m=new Uint8Array(l.length),p=[],y=0,d=(g,M)=>{let v=[M],N=g,$=M;for(;N!==void 0&&!m[N];){m[N]=1;let[b,x]=l[N];$=b===$?x:b,v.push($),N=(h.get($)??[]).find(S=>!m[S])}return v},w=g=>{let M=f-y;if(M<2)return!1;let v=g.slice(0,M),N=new Float64Array(v.length),$=new Float64Array(v.length);return v.forEach((b,x)=>[N[x],$[x]]=u(b)),p.push({x:N,y:$}),y+=v.length,!0};for(let[g,M]of h)if(M.length===1&&!m[M[0]]&&!w(d(M[0],g)))return p;for(let g=0;g<l.length;g++)if(!m[g]&&!w(d(g,l[g][0])))return p;return p}function $o(e){let t=0;for(let o of e)t+=o.x.length+1;t=Math.max(0,t-1);let r=new Float64Array(t),n=new Float64Array(t),s=0;return e.forEach((o,i)=>{i&&(r[s]=NaN,n[s]=NaN,s++),r.set(o.x,s),n.set(o.y,s),s+=o.x.length}),{x:r,y:n}}var So=["y","param","implicit"],Eo=["x-axis","y-axis","origin"],Qa=new Set(["sin","cos","tan","asin","acos","atan","atan2","sinh","cosh","tanh","asinh","acosh","atanh","exp","ln","log","log2","log10","sqrt","cbrt","abs","floor","ceil","round","sign","min","max","pi","theta","sec","csc","cot","mod","gamma","erf"]),Ao=e=>e>="a"&&e<="z"||e>="A"&&e<="Z"||e==="_",ze=e=>e>="0"&&e<="9";function Io(e){if(e===null||typeof e!="object"||Array.isArray(e))return"transform is { of, dx?, dy?, sx?, sy?, reflect? }";for(let t of Object.keys(e))if(!["of","dx","dy","sx","sy","reflect"].includes(t))return`transform.${t.slice(0,40)} isn't a field (of, dx, dy, sx, sy, reflect)`;if(typeof e.of!="string"||!e.of)return"transform.of is the id of the curve it moves";for(let t of["dx","dy"])if(e[t]!==void 0&&(typeof e[t]!="number"||!Number.isFinite(e[t])))return`transform.${t} must be a finite number`;for(let t of["sx","sy"])if(e[t]!==void 0&&(typeof e[t]!="number"||!Number.isFinite(e[t])||e[t]===0))return`transform.${t} must be a finite number other than 0`;return e.reflect!==void 0&&!Eo.includes(e.reflect)?`transform.reflect is ${Eo.join(", ")}`:null}function _a(e){let t=e.reflect==="y-axis"||e.reflect==="origin",r=e.reflect==="x-axis"||e.reflect==="origin";return{dx:e.dx??0,dy:e.dy??0,sx:(e.sx??1)*(t?-1:1),sy:(e.sy??1)*(r?-1:1)}}var Tr=e=>e<0?`(${e})`:String(e);function Tn(e,t,r){let n="",s=0;for(;s<e.length;){let o=e[s];if(ze(o)||o==="."&&ze(e[s+1]??"")){let i=s+1;for(;i<e.length&&(ze(e[i])||e[i]===".");)i++;if((e[i]==="e"||e[i]==="E")&&(ze(e[i+1]??"")||(e[i+1]==="-"||e[i+1]==="+")&&ze(e[i+2]??"")))for(i+=2;i<e.length&&ze(e[i]);)i++;n+=e.slice(s,i),s=i}else if(Ao(o)){let i=s+1;for(;i<e.length&&(Ao(e[i])||ze(e[i]));)i++;let a=e.slice(s,i),c=i;for(;e[c]===" ";)c++;let u=e[c]==="(";if(a===t&&!u)n+=r;else{if(a.length>1&&!Qa.has(a)&&a.includes(t)&&/^[A-Za-z]+$/.test(a))throw new Error(`can't tell where ${t} is in "${a.slice(0,20)}": write it as ${t}*...`);n+=a}s=i}else n+=o,s++}return n}var Vn=e=>String(e).replace(/^\s*(?:y|r|x)\s*=(?!=)/,"").trim();function Ka(e,t){let r=Io(t);if(r)throw new Error(r);let n=e.kind??"y";if(!So.includes(n))throw new Error(`a ${n} curve can't be moved or scaled this way (only ${So.join(", ")})`);let{dx:s,dy:o,sx:i,sy:a}=_a(t),c=(l,f,h)=>`(${[f===0?l:`(${l} - ${Tr(f)})`,h===1?"":` / ${Tr(h)}`].join("")})`,u=(l,f,h)=>`${h===1?`(${l})`:`${Tr(h)} * (${l})`}${f===0?"":` + ${Tr(f)}`}`;return n==="y"?{...e,expr:u(Tn(Vn(e.expr),"x",c("x",s,i)),o,a)}:n==="implicit"?{...e,expr:Tn(Tn(String(e.expr),"x",c("x",s,i)),"y",c("y",o,a))}:{...e,expr:u(Vn(e.expr),s,i),expr2:u(Vn(e.expr2??"0"),o,a)}}function Fo(e,t=4){let r=new Map(e.map(o=>[String(o.id),o])),n=new Map,s=(o,i)=>{if(!o||o.xform===void 0)return o;let a=String(o.id);if(n.has(a))return n.get(a);if(i.includes(a))throw new Error("the transforms loop back on each other");if(i.length>=t)throw new Error(`a transform of a transform goes at most ${t} deep`);let c=r.get(String(o.xform.of));if(!c)throw new Error(`there is no curve "${String(o.xform.of).slice(0,40)}" to transform`);let u=s(c,[...i,a]),{xform:l,...f}=o,h=Ka(u,l),m={...f,xform:l,kind:u.kind??"y",expr:h.expr,...h.expr2!==void 0?{expr2:h.expr2}:{},...u.min!==void 0?{min:u.min}:{},...u.max!==void 0?{max:u.max}:{}};return n.set(a,m),m};return e.map(o=>{if(o?.xform===void 0)return o;try{return s(o,[])}catch(i){let{xform:a,...c}=o;return{...c,expr:c.expr||"0",error:i?.message??String(i),xform:a}}})}var Ll=Object.freeze({xMin:-10,xMax:10,yMin:-6,yMax:6}),ql=Object.freeze({value:1,min:-10,max:10,step:.1}),Tl=Object.freeze({grid:256,curve:4e3,field:16}),Vl=Object.freeze({ivps:16,field:60,taylor:24,fourier:100}),Ja=Object.freeze({raster:400,conformal:24,unity:360,curves:16,expression:2e3,label:80,sliders:32,overlays:16,points:16,annotations:16,text:200,levels:24,grid:400,modulus:4096}),Ul=Object.freeze(["#3b82d6","#d9622b","#2e9a62","#9a52c9","#c79a1e","#d1498a","#3aa7a3","#7a8a99"]);function Ha(e,t){let r=e?.x;if(!r?.length||!(t>=r[0])||t>r[r.length-1])return null;let n=0,s=r.length-1;for(;s-n>1;){let a=n+s>>1;r[a]<=t?n=a:s=a}let[o,i]=[e.y[n],e.y[s]];return Number.isNaN(o)||Number.isNaN(i)?null:r[s]===r[n]?o:o+(i-o)*(t-r[n])/(r[s]-r[n])}function tc(e,t,r){if(e.point!==void 0){let n=(t?.pins??[]).find(s=>s.id===e.point&&!s.error);return n&&Number.isFinite(n.x)&&Number.isFinite(n.y)?{x:n.x,y:n.y}:null}if(e.curve!==void 0){let n=Ha((t?.items??[]).find(s=>s.id===e.curve),e.x);return n===null||!Number.isFinite(n)?null:{x:e.x,y:n}}return{x:e.x,y:e.y}}function ko(e,t){return Array.isArray(e)?e.slice(0,Ja.annotations).map(r=>{let n=tc(r,t),s=r.point!==void 0?{point:r.point}:r.curve!==void 0?{curve:r.curve}:{};return n?{id:r.id,text:r.text,x:n.x,y:n.y,...s}:{id:r.id,text:r.text,x:null,y:null,...s,error:"its anchor is not on the plot"}}):[]}var Pe=Object.freeze(["slope","ode2","phase","taylor","limit","series","fourier"]),Ut=Object.freeze({ivps:16,field:60,taylor:24,fourier:100,terms:5e3,closed:4,nullGrid:100,solutionSteps:4e3}),Ro=Object.freeze({slope:["x","y"],ode2:["x","y","v"],phase:["x","y"],taylor:["x"],limit:["x"],series:["n"],fourier:["x"]}),Co=Object.freeze({slope:"x",ode2:"x",phase:"x",taylor:"x",limit:"x",series:"n",fourier:"x"}),ec=/^\s*(?:d\s*y\s*\/\s*d\s*x|d\s*x\s*\/\s*d\s*t|d\s*y\s*\/\s*d\s*t|y''|y'|x'|v')\s*=(?!=)/,Oe=e=>String(e).replace(ec,""),Dr=(e,t,r,n)=>{let s=Number(e);return Number.isFinite(s)?Math.min(r,Math.max(t,Math.round(s))):n},jo=e=>Math.max(1,(e.deadline??Date.now()+2e3)-Date.now()),Vr=e=>Float64Array.from(e);function Ur(e,t,r,n,s){let o=Oe(s.sourceText(e,r)),i=C.parse(s.spelled(o,n.aliases),s.IMPLICIT);if(i?.type==="cmp")throw new Error(`${r} is a comparison, not a formula`);let a=C.compile(i),c={...n.aliasedParams};for(let l of t)c[l]=0;let u=(...l)=>{n.spend();for(let f=0;f<t.length;f++)c[t[f]]=l[f];return a(c)};return u.expr=i,u}function Lo(e,t,r){let n=e;for(let s of C.freeVariables(e)){if(t.includes(s))continue;let o=r.aliasedParams[s];if(typeof o!="number")throw new Error(`${s} has no value`);n=C.substitute(n,s,{type:"const",value:o})}return n}var Br=e=>{try{return C.simplify(e)}catch{return e}};function Qe(e){if(!Number.isFinite(e))return e>0?"\\infty":e<0?"-\\infty":"\\text{undefined}";let t=String(Number(e.toPrecision(5))),r=/^(-?[\d.]+)e([+-]?\d+)$/.exec(t);return r?`${r[1]}\\times 10^{${Number(r[2])}}`:t}function rc(e,t=1e4){if(!Number.isFinite(e))return null;let r=Math.abs(e);if(Math.abs(r-Math.round(r))<1e-11*Math.max(1,r))return[Math.sign(e)*Math.round(r),1];let[n,s,o,i]=[0,1,1,0],a=r;for(let c=0;c<40;c++){let u=Math.floor(a),[l,f]=[u*s+n,u*i+o];if(f>t)return null;if([n,s,o,i]=[s,l,i,f],Math.abs(r-s/i)<1e-11*Math.max(1,r))return[Math.sign(e)*s,i];let h=a-u;if(h<1e-14)return null;a=1/h}return null}function qo(e,t,r=8){let n=e.filter(o=>o.coefficient!==0&&Number.isFinite(o.coefficient));if(!n.length)return`${t}0`;let s=n.slice(0,r).map((o,i)=>{let a=rc(o.coefficient),c=Math.abs(o.coefficient),u=a?a[1]===1?String(Math.abs(a[0])):`\\frac{${Math.abs(a[0])}}{${a[1]}}`:Qe(c),l=o.basis?u==="1"?o.basis:a&&a[1]!==1?`${u}${o.basis}`:`${u}\\,${o.basis}`:u,f=o.coefficient<0;return i===0?`${f?"-":""}${l}`:` ${f?"-":"+"} ${l}`});return`${t}${s.join("")}${n.length>r?" + \\cdots":""}`}function Un(e){let t=[],r=[];for(let n of e)if(n.x.length){t.length&&(t.push(Number.NaN),r.push(Number.NaN));for(let s=0;s<n.x.length;s++)t.push(n.x[s]),r.push(n.y[s])}return{x:Vr(t),y:Vr(r)}}var Zr=e=>String(e?.message??e).replace(/^Error:\s*/,"");function To(e){let t=e.viewport,r=t.xMax-t.xMin,n=Math.min(.25,e.pad);return{min:t.xMin-n*r,max:t.xMax+n*r}}var nc={NotSeparableError:"no closed form found: the equation is not separable, linear, homogeneous, Bernoulli or exact",NoClosedFormError:"no closed form found: an integral it needs is not elementary"};function sc(e){let t=e(.3,0),r=e(.3,1)-t;if(![t,r].every(Number.isFinite)||Gr(r,0))return null;for(let[n,s]of[[.7,1.3],[-1.9,.2],[2.6,-1.1]])if(!Gr(e(n,s),r*s+t))return null;return{a:r,b:t}}function oc(e,t){let n=`${t.y+e.b/e.a} * exp(${e.a} * (x - ${t.x})) - ${e.b/e.a}`;return`y(x) = ${C.toLatex(Br(C.parse(n)))}`}function ic(e,t,r,n){let s=[],o=sc(n);for(let i of e.slice(0,Ut.closed)){let a={x0:i.x,y0:i.y,explicit:!1};try{let c,u=!1;if(o)c=oc(o,i);else{let l=C.solveOdeClosedForm(Lo(t,["x","y"],r),i.x,i.y,"x","y");if(u=!l.explicit,c=l.explicit?`y(x) = ${C.toLatex(Br(l.y))}`:`${C.toLatex(Br(l.implicitRelation))} = 0`,/NaN|Infinity/.test(c))throw Object.assign(new Error("no closed form found"),{name:"NoClosedFormError"})}Object.assign(a,{explicit:!u,latex:c},u?{implicit:!0}:{})}catch(c){a.error=nc[c?.name]??Zr(c)}s.push(a)}return s}function ac(e,t,r){let n=Ur(e.expr,["x","y"],"f(x, y)",t,r),s=t.viewport,o=Dr(e.grid,4,Ut.field,22),i={},a=h=>h&&(i.limit=i.limit?`${i.limit}; ${h}`:h),c=mn(n,{min:s.xMin,max:s.xMax},{min:s.yMin,max:s.yMax},{columns:o,rows:o,maxMillis:jo(t),isCancelled:t.stop});i.field={columns:o,rows:c.rows??o,x:c.x,y:c.y,dirX:c.dirX,dirY:c.dirY,complete:c.progress.complete},c.progress.complete||a(`slope field stopped at row ${c.progress.rows} of ${c.progress.of}: the ${c.progress.reason==="time"?"time limit":"cell budget"}`);let u=Array.isArray(e.ivps)?e.ivps.slice(0,Ut.ivps):[],l=To(t),f=[];i.solutions=[];for(let h of u)try{let m=pn(n,h.x,h.y,l,{isCancelled:t.stop,maxSteps:Ut.solutionSteps,yLimit:1e5,hMax:(l.max-l.min)/300});f.push({x:m.x,y:m.y}),i.solutions.push({x0:h.x,y0:h.y,reasonBefore:m.reasonBefore,reasonAfter:m.reasonAfter})}catch(m){if(m?.name==="SampleCancelledError"||m?.name==="PlotLimitError")throw m;i.solutions.push({x0:h.x,y0:h.y,error:Zr(m)})}return Object.assign(i,Un(f)),i.closed=ic(u,n.expr,t,n),i}function cc(e,t,r,n,s,o=0){let i={isCancelled:s.stop,maxSteps:Ut.solutionSteps,blowup:1e6,hMax:(n.max-n.min)/300},a={t:new Float64Array(0),y:new Float64Array(0),dim:r.length,steps:0,reason:"end"},c=t<n.max?Ae(e,t,r,n.max,i):{...a,t:Float64Array.of(t),y:Float64Array.from(r),steps:1},u=t>n.min?Ae(e,t,r,n.min,i):{...a,t:Float64Array.of(t),y:Float64Array.from(r),steps:1},l=[],f=[];for(let h=u.steps-1;h>=1;h--)l.push(u.t[h]),f.push(u.y[h*r.length+o]);for(let h=0;h<c.steps;h++)l.push(c.t[h]),f.push(c.y[h*r.length+o]);return{x:Vr(l),y:Vr(f),reasonBefore:u.reason,reasonAfter:c.reason}}var Gr=(e,t)=>Math.abs(e-t)<=1e-9*Math.max(1,Math.abs(e),Math.abs(t));function uc(e){let t=[[.7,1.3,-.4],[-1.9,.2,2.1],[2.6,-1.1,.9]],r=(i,a,c)=>e(i,a,c),n=r(.3,0,0),s=r(.3,1,0)-n,o=r(.3,0,1)-n;if(![n,s,o].every(Number.isFinite)||!Gr(n,0))return null;for(let[i,a,c]of t)if(!Gr(r(i,a,c),s*a+o*c))return null;return{b:-o,c:-s}}function lc(e,t,r){let n=uc(t);return e.slice(0,Ut.closed).map(s=>{let o={x0:s.x,y0:s.y,v0:s.v??0,explicit:!1};if(!n)return{...o,error:"a closed form is found only for y'' = -b y' - c y with constant coefficients (no forcing term)"};try{let i=Br(C.solveOde2ndOrderConstCoeff(1,n.b,n.c,s.x,s.y,s.v??0)),a=n.b*n.b-4*n.c,c=Math.abs(a)<1e-9?"critically damped":a>0?"overdamped":"underdamped";return{...o,explicit:!0,regime:c,latex:`y(x) = ${C.toLatex(i)}`,equation:`y'' ${n.b<0?"-":"+"} ${Math.abs(n.b)}y' ${n.c<0?"-":"+"} ${Math.abs(n.c)}y = 0`,characteristic:`r^2 ${n.b<0?"-":"+"} ${Qe(Math.abs(n.b))}r ${n.c<0?"-":"+"} ${Qe(Math.abs(n.c))} = 0`}}catch(i){return{...o,error:Zr(i)}}})}function fc(e,t,r){let n=Ur(e.expr,["x","y","v"],"f(x, y, y')",t,r),s=Array.isArray(e.ivps)?e.ivps.slice(0,Ut.ivps):[],o=To(t),i=(u,l)=>[l[1],n(u,l[0],l[1])],a={solutions:[]},c=[];for(let u of s){if(t.timeUp()){a.limit=`stopped after ${c.length} of ${s.length} curves: the time limit`;break}let l=cc(i,u.x,[u.y,u.v??0],o,t);c.push(l),a.solutions.push({x0:u.x,y0:u.y,v0:u.v??0,reasonBefore:l.reasonBefore,reasonAfter:l.reasonAfter})}return Object.assign(a,Un(c)),a.closed=lc(s,n,t),a}function zo(e,t,r,n,s){let o=t.viewport,i=Ut.nullGrid,a=r.fillGrid(e,o,i,t);a.limit&&(n.limit=n.limit?`${n.limit}; ${s}: ${a.limit}`:`${s}: ${a.limit}`);let c=new r.Segments(6e4);r.traceLevel(a,o,0,c);let{x:u,y:l}=c.arrays();return{x:u,y:l}}function hc(e,t,r){let n=Ur(e.expr,["x","y"],"x'",t,r),s=Ur(e.expr2,["x","y"],"y'",t,r),o=t.viewport,i=Dr(e.grid,4,Ut.field,15),a={},c=Math.min(1e3,Math.max(.1,r.bound(e.max,"max",10,t.params,t.aliases))),u=Array.isArray(e.ivps)?e.ivps.slice(0,Ut.ivps):[],l=dn((h,m)=>[n(h,m),s(h,m)],{min:o.xMin,max:o.xMax},{min:o.yMin,max:o.yMax},{grid:i,seeds:u.map(h=>[h.x,h.y]),tMax:c,fixedPointStarts:8,maxMillis:jo(t),isCancelled:t.stop}),f=0;for(let h=0;h<l.field.magnitude.length;h++)Number.isFinite(l.field.magnitude[h])&&(f=Math.max(f,l.field.magnitude[h]));return a.field={grid:i,x:l.field.x,y:l.field.y,u:l.field.u,v:l.field.v,max:f,complete:l.progress.complete},l.progress.complete||(a.limit=`phase portrait stopped at row ${l.progress.rows} of ${l.progress.of}: the ${l.progress.reason==="time"?"time limit":"cell budget"}`),a.solutions=l.trajectories.map(h=>({x0:h.seed[0],y0:h.seed[1],reasonBefore:h.reasonBefore,reasonAfter:h.reasonAfter})),a.trajectories=l.trajectories.length,Object.assign(a,Un(l.trajectories)),a.fixedPoints=l.fixedPoints.map(({x:h,y:m,type:p,trace:y,determinant:d,eigenvalues:w})=>({x:h,y:m,type:p,trace:y,determinant:d,eigenvalues:w.map(g=>[...g])})),a.nullclines={a:zo(n,t,r,a,"x' = 0"),b:zo(s,t,r,a,"y' = 0")},a}function mc(e,t,r){let n=r.bound(e.center,"center",0,t.params,t.aliases),s=Dr(e.order,0,Ut.taylor,3),o=Oe(r.sourceText(e.expr,"f(x)")).replace(/^\s*(?:f\s*\(x\)|y)\s*=(?!=)/,""),i=C.parse(r.spelled(o,t.aliases),r.IMPLICIT),a=t.compile(e.expr,"f(x)","x"),c=bo(i,n,s+1,{variable:"x",params:t.aliasedParams}),u=t.viewport,l=u.xMax-u.xMin,f={min:u.xMin-t.pad*l,max:u.xMax+t.pad*l},h=Math.min(2e3,Math.max(200,t.points)),m=b=>gn(c,n,b,s),p=new Float64Array(h),y=new Float64Array(h),d=new Float64Array(h),w=new Float64Array(h);for(let b=0;b<h;b++){let x=f.min+(f.max-f.min)*b/(h-1),S=m(x),O=a(x);p[b]=x,w[b]=Number.isFinite(S)?S:Number.NaN,y[b]=Number.isFinite(S)&&Number.isFinite(O)?Math.min(S,O):Number.NaN,d[b]=Number.isFinite(S)&&Number.isFinite(O)?Math.max(S,O):Number.NaN}let g=ye(a,f,Math.min(h,800),{visibleYRange:{min:u.yMin,max:u.yMax},isCancelled:t.stop}),M=Math.abs(c[s+1]),v=[.1,.25,.5,1,2].map(b=>{let x=0;for(let O=-20;O<=20;O++){let A=Math.abs(a(n+b*O/20)-m(n+b*O/20));Number.isFinite(A)&&(x=Math.max(x,A))}let S=Math.abs(a(n+b)-m(n+b));return{h:b,error:S,worst:x,estimate:M*b**(s+1)}}),N=n===0?"x":`(x ${n<0?"+":"-"} ${Qe(Math.abs(n))})`,$=Array.from({length:s+1},(b,x)=>({coefficient:c[x],basis:x===0?"":x===1?N:`${N}^{${x}}`}));return{x:p,y:w,base:{x:g.x,y:g.y},band:{x:p,lo:y,hi:d},coefficients:Array.from(c.slice(0,s+1)),center:n,order:s,polynomial:qo($,`T_{${s}}(x) = `,9),table:v}}var pc=[1,.1,.01,.001,1e-4,1e-5,1e-6];function Po(e){let t=e.slice(-3);return t.length<3||!t.every(Number.isFinite)?0:Math.abs(t[1])>5*Math.abs(t[0])&&Math.abs(t[2])>5*Math.abs(t[1])&&Math.abs(t[2])>1e3?Math.sign(t[2]):0}function Oo(e){let t=e.slice(-2);return t.length===2&&t.every(Number.isFinite)&&Math.abs(t[1]-t[0])<=1e-4*Math.max(1,Math.abs(t[1]))}function dc(e,t,r){let n=r.bound(e.center,"center",0,t.params,t.aliases),s=t.compile(e.expr,"f(x)","x"),o=t.viewport,i=o.xMax-o.xMin,a={min:o.xMin-t.pad*i,max:o.xMax+t.pad*i},c=ye(s,a,Math.min(t.points,1200),{visibleYRange:{min:o.yMin,max:o.yMax},isCancelled:t.stop}),u=pc.map(g=>({h:g,left:s(n-g),right:s(n+g)})),l=u.map(g=>g.left),f=u.map(g=>g.right),h=Po(l),m=Po(f),p=l.at(-1),y=f.at(-1),d={left:h?h*(1/0):p,right:m?m*(1/0):y},w=g=>g===1/0?"+\u221E":g===-1/0?"\u2212\u221E":String(Number(g.toPrecision(6)));h&&m?h===m?Object.assign(d,{kind:"infinite",value:h*(1/0),message:`f grows without bound to ${w(h*(1/0))} from both sides`}):Object.assign(d,{kind:"none",message:`from the left f \u2192 ${w(d.left)}, from the right f \u2192 ${w(d.right)}: no two-sided limit`}):h||m?Object.assign(d,{kind:"none",message:`from the left f \u2192 ${w(d.left)}, from the right f \u2192 ${w(d.right)}: no two-sided limit`}):Oo(l)&&Oo(f)?Math.abs(p-y)<=1e-5*Math.max(1,Math.abs(p),Math.abs(y))?Object.assign(d,{kind:"finite",value:(p+y)/2,message:`f \u2192 ${w((p+y)/2)} from both sides`}):Object.assign(d,{kind:"jump",message:`from the left f \u2192 ${w(p)}, from the right f \u2192 ${w(y)}: a jump, no two-sided limit`}):Object.assign(d,{kind:"none",message:"f does not settle as x closes in on the point (it oscillates or is undefined there)"});try{let g=Lo(C.parse(r.spelled(Oe(r.sourceText(e.expr,"f(x)")).replace(/^\s*y\s*=(?!=)/,""),t.aliases),r.IMPLICIT),["x"],t),M=C.limit(g,"x",n,"both");Number.isFinite(M)&&(d.symbolic=M)}catch{}return{x:c.x,y:c.y,base:{x:c.x,y:c.y},center:n,atPoint:s(n),limit:d,table:u}}function gc(e,t,r){let n=Math.round(r.bound(e.min,"min",1,t.params,t.aliases)),s=e.max===void 0||e.max===""?n+49:Math.round(r.bound(e.max,"max",n+49,t.params,t.aliases));if(!(s>=n))throw new RangeError("max must be at least min");let o=Math.min(s,n+Ut.terms-1),i=t.compile(e.expr,"a(n)","n"),a=yn(i,n,o),c=new Float64Array(a.partial.length);for(let f=0;f<c.length;f++)c[f]=n+f;let u={x:c,y:Float64Array.from(a.partial,f=>Number.isFinite(f)?f:Number.NaN),from:n,to:o};s>o&&(u.limit=`terms cut from ${s-n+1} to ${Ut.terms}`);let l={converges:!1,aitken:a.limitEstimate,last:u.y[u.y.length-1]};try{let f=C.parse(r.spelled(Oe(r.sourceText(e.expr,"a(n)")).replace(/^\s*(?:a|y)\s*=(?!=)/,""),t.aliases),r.IMPLICIT),{n:h,...m}=t.aliasedParams,p=C.sumSeries(f,n,1/0,"n",m);Object.assign(l,{converges:!0,sum:p,message:`converges to ${Number(p.toPrecision(8))}`})}catch(f){l.message=f?.name==="SeriesDivergesError"?"diverges, or converges too slowly to confirm: the partial sums do not settle":Zr(f)}return u.verdict=l,u}function yc(e,t,r){let s=r-t,o=Array.from({length:2e3},(c,u)=>e(t+s*(u+.5)/2e3));if(!o.every(Number.isFinite))return null;let i=Math.max(...o)-Math.min(...o);if(!(i>0))return null;let a=null;for(let c=0;c<2e3;c++){let u=(c+1)%2e3,l=Math.abs(o[u]-o[c]);l>.2*i&&(!a||l>a.jump)&&(a={x:u===0?r:t+s*(c+1)/2e3,jump:l,from:o[c],to:o[u]})}return a}function xc(e,t,r){let n=r.bound(e.min,"min",-Math.PI,t.params,t.aliases),s=r.bound(e.max,"max",Math.PI,t.params,t.aliases);if(!(n<s))throw new RangeError("min must be less than max");let o=s-n,i=Dr(e.order,1,Ut.fourier,5),a=t.compile(e.expr,"f(x)","x"),c=x=>n+((x-n)%o+o)%o,u=xn(a,{min:n,max:s},i,4096),l=t.viewport,f=l.xMax-l.xMin,h={min:l.xMin-t.pad*f,max:l.xMax+t.pad*f},m=Math.min(4e3,Math.max(600,Math.ceil(24*i*(h.max-h.min)/o))),p=new Float64Array(m),y=new Float64Array(m);for(let x=0;x<m;x++)p[x]=h.min+(h.max-h.min)*x/(m-1),y[x]=Nr(u,p[x],i);let d=ye(x=>a(c(x)),h,800,{visibleYRange:{min:l.yMin,max:l.yMax},isCancelled:t.stop}),w={x:p,y,base:{x:d.x,y:d.y},order:i},g=(x,S)=>Array.from(x.slice(0,S));w.coefficients={a0:u.a0,a:g(u.a,Math.min(i,24)),b:g(u.b,Math.min(i,24)),halfPeriod:u.halfPeriod,center:u.center};let M=Math.PI/u.halfPeriod,v=x=>`${x===1?"":x}${M===1?"":"\\omega"}${u.center===0?"x":`(x ${u.center<0?"+":"-"} ${Qe(Math.abs(u.center))})`}`,N=Math.max(Math.abs(u.a0)/2,...u.a.map(Math.abs),...u.b.map(Math.abs),1e-300),$=[{coefficient:Math.abs(u.a0)>1e-9*N?u.a0/2:0,basis:""}];for(let x=1;x<=i;x++)Math.abs(u.a[x-1])>1e-4*N&&$.push({coefficient:u.a[x-1],basis:`\\cos(${v(x)})`}),Math.abs(u.b[x-1])>1e-4*N&&$.push({coefficient:u.b[x-1],basis:`\\sin(${v(x)})`});w.polynomial=`${qo($,`S_{${i}}(x) = `,6)}${M===1?"":`,; \\omega = ${Qe(M)}`}`;let b=yc(a,n,s);if(b){let x=Math.max(b.from,b.to),S=Math.min(b.from,b.to),O=1.5*o/(2*i),A=x,F=S;for(let E=0;E<=600;E++){let P=Nr(u,b.x-O+2*O*E/600,i);A=Math.max(A,P),F=Math.min(F,P)}let k=Math.max(A-x,S-F),I=A-x>=S-F;w.gibbs={x:b.x,jump:b.jump,overshoot:k,ratio:k/b.jump,level:I?x:S,peak:I?A:F}}return w}function Vo(e,t,r,n){switch(e){case"slope":return ac(t,r,n);case"ode2":return fc(t,r,n);case"phase":return hc(t,r,n);case"taylor":return mc(t,r,n);case"limit":return dc(t,r,n);case"series":return gc(t,r,n);case"fourier":return xc(t,r,n);default:throw new Error(`unknown calculus kind "${e}"`)}}function Uo(e){let t=e.field,r=e.nullclines;return[t?.x,t?.y,t?.u,t?.v,t?.dirX,t?.dirY,r?.a?.x,r?.a?.y,r?.b?.x,r?.b?.y,e.base?.x,e.base?.y,e.band?.x,e.band?.lo,e.band?.hi]}var Bo=Object.freeze(["exp","ln","sqrt","sin","cos","tan","sinh","cosh","tanh","abs","asin","acos","atan","asinh","acosh","atanh","sec","csc","cot","sech","csch","coth","cbrt","log10","log2"]),Ct=(e,t)=>[e[0]*t[0]-e[1]*t[1],e[0]*t[1]+e[1]*t[0]],dr=(e,t)=>{let r=t[0]*t[0]+t[1]*t[1];return[(e[0]*t[0]+e[1]*t[1])/r,(e[1]*t[0]-e[0]*t[1])/r]},Bn=e=>[Math.exp(e[0])*Math.cos(e[1]),Math.exp(e[0])*Math.sin(e[1])],Kt=e=>[Math.log(Math.hypot(e[0],e[1])),Math.atan2(e[1],e[0])],pr=e=>{let t=Math.hypot(e[0],e[1]);return[Math.sqrt(Math.max(.5*(t+e[0]),0)),(e[1]<0?-1:1)*Math.sqrt(Math.max(.5*(t-e[0]),0))]},Gn=e=>[Math.sin(e[0])*Math.cosh(e[1]),Math.cos(e[0])*Math.sinh(e[1])],Dn=e=>[Math.cos(e[0])*Math.cosh(e[1]),-Math.sin(e[0])*Math.sinh(e[1])],Zn=e=>[Math.sinh(e[0])*Math.cos(e[1]),Math.cosh(e[0])*Math.sin(e[1])],Xn=e=>[Math.cosh(e[0])*Math.cos(e[1]),Math.sinh(e[0])*Math.sin(e[1])],Xr=[0,1],bc=e=>[-e[0],-e[1]],Ce=(e,t)=>[e[0]+t[0],e[1]+t[1]],Re=(e,t)=>[e[0]-t[0],e[1]-t[1]],_e=e=>dr([1,0],e),Go=e=>Ct(bc(Xr),Kt(Ce(Ct(Xr,e),pr(Re([1,0],Ct(e,e)))))),wc=e=>Kt(Ce(e,pr(Ce(Ct(e,e),[1,0])))),vc=e=>Ct([.5,0],Re(Kt(Ce([1,0],e)),Kt(Re([1,0],e)))),Do=e=>dr(Gn(e),Dn(e)),Zo=e=>dr(Zn(e),Xn(e)),Mc={exp:Bn,ln:Kt,sqrt:pr,sin:Gn,cos:Dn,sinh:Zn,cosh:Xn,tan:Do,tanh:Zo,abs:e=>[Math.hypot(e[0],e[1]),0],asin:Go,acos:e=>Re([Math.PI/2,0],Go(e)),atan:e=>Ct([0,.5],Re(Kt(Re([1,0],Ct(Xr,e))),Kt(Ce([1,0],Ct(Xr,e))))),asinh:wc,acosh:e=>Kt(Ce(e,Ct(pr(Ce(e,[1,0])),pr(Re(e,[1,0]))))),atanh:vc,sec:e=>_e(Dn(e)),csc:e=>_e(Gn(e)),cot:e=>_e(Do(e)),sech:e=>_e(Xn(e)),csch:e=>_e(Zn(e)),coth:e=>_e(Zo(e)),cbrt:e=>e[0]===0&&e[1]===0?[0,0]:Bn(Ct([1/3,0],Kt(e))),log10:e=>Ct([1/Math.LN10,0],Kt(e)),log2:e=>Ct([1/Math.LN2,0],Kt(e))};function Nc(e,t){let r=Math.abs(t),n=[1,0],s=e;for(;r>0;)r&1&&(n=Ct(n,s)),s=Ct(s,s),r=Math.floor(r/2);return t<0?dr([1,0],n):n}function $c(e,t){return t[1]===0&&Number.isInteger(t[0])&&Math.abs(t[0])<=64?Nc(e,t[0]):e[0]===0&&e[1]===0?t[0]>0?[0,0]:[NaN,NaN]:Bn(Ct(t,Kt(e)))}function Sc(e,t=["z"]){let r=n=>{switch(n?.type){case"const":return Number.isFinite(n.value)?null:"a constant that is not a finite number";case"var":return n.name==="i"||t.includes(n.name)||/^[A-Za-z_][A-Za-z0-9_]*$/.test(n.name)?null:`the name "${String(n.name).slice(0,20)}"`;case"neg":return r(n.arg);case"add":case"sub":case"mul":case"div":return r(n.left)??r(n.right);case"pow":return r(n.base)??r(n.exp);case"func":return Bo.includes(n.name)?r(n.arg):`${String(n.name).slice(0,20)}() (the complex functions are ${Bo.join(", ")})`;default:return`${String(n?.type).slice(0,20)} (a comparison, a piecewise formula, a sum or a product has no complex form here)`}};return r(e)}function Wn(e,t={}){let r=Sc(e);if(r)throw new Error(`f(z) can't use ${r}`);let n=o=>{switch(o.type){case"const":{let i=[o.value,0];return()=>i}case"var":{if(o.name==="z")return a=>a;if(o.name==="i"&&!(o.name in t))return()=>[0,1];let i=[Number.isFinite(t[o.name])?t[o.name]:NaN,0];return()=>i}case"neg":{let i=n(o.arg);return a=>{let c=i(a);return[-c[0],-c[1]]}}case"add":{let[i,a]=[n(o.left),n(o.right)];return c=>{let[u,l]=[i(c),a(c)];return[u[0]+l[0],u[1]+l[1]]}}case"sub":{let[i,a]=[n(o.left),n(o.right)];return c=>{let[u,l]=[i(c),a(c)];return[u[0]-l[0],u[1]-l[1]]}}case"mul":{let[i,a]=[n(o.left),n(o.right)];return c=>Ct(i(c),a(c))}case"div":{let[i,a]=[n(o.left),n(o.right)];return c=>dr(i(c),a(c))}case"pow":{let[i,a]=[n(o.base),n(o.exp)];return c=>$c(i(c),a(c))}default:{let i=Mc[o.name],a=n(o.arg);return c=>i(a(c))}}},s=n(e);return(o,i)=>s([o,i])}function Wo(e){if(!Number.isInteger(e)||e<1||e>360)throw new RangeError("the order of the roots of unity is a whole number from 1 to 360");return Array.from({length:e},(t,r)=>({k:r,re:Xo(Math.cos(2*Math.PI*r/e)),im:Xo(Math.sin(2*Math.PI*r/e))}))}var Xo=e=>Math.abs(e)<1e-15?0:e;var Ec=new WeakSet,Ac=/^(vf_|u_|v_)/;function Yo(e,t=[]){let r=[...new Set(t)].filter(n=>n!=="z"&&n!=="i").sort();for(let n of r)if(Ac.test(n))return{ok:!1,reason:`the variable name ${n.slice(0,20)} is reserved by the shader`};try{let n=C.toGLSL(e,{complex:!0,variables:["z",...r]}),s={ok:!0,expression:n.expression,helpers:n.helpers,uniforms:r.filter(o=>n.variables.includes(o))};return Ec.add(s),s}catch(n){return{ok:!1,reason:String(n?.message??n).replace(/^Error:\s*/,"").slice(0,200)}}}var bt=Object.freeze({cells:9e4,outputs:2,params:16,workgroup:64,timeoutMs:4e3,checks:64,repair:4096,pipelines:8,backoffMs:3e4}),Qo=Object.freeze({rel:.001,abs:.001});function Ic(e,t){return!Number.isFinite(e)||!Number.isFinite(t)?Object.is(e,t)||Number.isNaN(e)&&Number.isNaN(t):Math.abs(e-t)<=Qo.abs+Qo.rel*Math.max(Math.abs(t),1)}var Fc=new Set(["sin","cos","tan","atan","sinh","cosh","tanh","exp","abs"]),kc=new Set(["min","max","atan2","hypot"]),zc=8;function Pc(e){let t=n=>({ok:!1,reason:n}),r=n=>{switch(n?.type){case"const":return Number.isFinite(n.value)?null:t("a constant that is not finite");case"var":return null;case"add":case"sub":case"mul":case"div":return r(n.left)??r(n.right);case"neg":return r(n.arg);case"func":return Fc.has(n.name)?r(n.arg):t(`${String(n.name).slice(0,20)} is not the same on the GPU for every input`);case"call2":return kc.has(n.name)?r(n.left)??r(n.right):t(`${String(n.name).slice(0,20)} is not taken by the GPU path`);case"pow":{let s=n.exp?.type==="neg"?n.exp.arg:n.exp;return s?.type!=="const"||!Number.isInteger(s.value)||s.value<0||s.value>zc?t("a power that is not a whole number from -8 to 8"):r(n.base)}default:return t(`${String(n?.type).slice(0,20)} is not taken by the GPU path`)}};return r(e)??{ok:!0}}function Oc(e,t){let r=!1,n=o=>{if(o.type==="var"){let a=t.get(o.name);return a===void 0&&(r=!0),{type:"var",name:a??o.name}}let i={...o};for(let a of["left","right","arg","base","exp"])o[a]&&typeof o[a]=="object"&&(i[a]=n(o[a]));return i},s=n(e);return r?null:s}function Rc(e,t=[]){let r=h=>({ok:!1,reason:h});if(!Array.isArray(e)||e.length<1||e.length>bt.outputs)return r(`a grid has 1 to ${bt.outputs} outputs`);if(t.length>bt.params)return r(`at most ${bt.params} parameters`);let n=new Map([["x","x"],["y","y"]]),s=[...new Set(t)].filter(h=>h!=="x"&&h!=="y");s.forEach((h,m)=>n.set(h,`vp${m}`));let o=new Set,i=[],a=new Set;for(let h of e){let m=Pc(h);if(!m.ok)return r(m.reason);let p=Oc(h,n);if(!p)return r("the formula names a variable that is neither x, y nor a parameter");try{let y=C.toWGSL(p,{variables:["x","y",...s.map((d,w)=>`vp${w}`)]});y.helpers&&o.add(y.helpers);for(let d of y.variables)/^vp\d+$/.test(d)&&a.add(Number(d.slice(2)));i.push(y.expression)}catch(y){return r(String(y?.message??y).replace(/^Error:\s*/,"").slice(0,200))}}let c=[...a].sort((h,m)=>h-m).map(h=>` let vp${h} = vf_params.v[${h>>2}][${h&3}];`).join(`
38
+ `),u=i.map((h,m)=>`fn vf_eval${m}(x: f32, y: f32) -> f32 {
39
+ ${c}
40
+ return ${h};
41
+ }`).join(`
42
+ `),l=i.map((h,m)=>` vf_out[k * ${i.length}u + ${m}u] = vf_eval${m}(x, y);`).join(`
43
+ `);return{ok:!0,code:`struct VfGrid { x0: f32, dx: f32, y0: f32, dy: f32, cols: u32, count: u32, pad0: u32, pad1: u32 }
44
+ struct VfParams { v: array<vec4<f32>, 4> }
45
+ @group(0) @binding(0) var<uniform> vf_grid: VfGrid;
46
+ @group(0) @binding(1) var<uniform> vf_params: VfParams;
47
+ @group(0) @binding(2) var<storage, read_write> vf_out: array<f32>;
48
+ ${[...o].join(`
49
+ `)}
50
+ ${u}
51
+ @compute @workgroup_size(${bt.workgroup})
52
+ fn main(@builtin(global_invocation_id) vf_id: vec3<u32>) {
53
+ let k = vf_id.x;
54
+ if (k >= vf_grid.count) { return; }
55
+ let x = vf_grid.x0 + f32(k % vf_grid.cols) * vf_grid.dx;
56
+ let y = vf_grid.y0 + f32(k / vf_grid.cols) * vf_grid.dy;
57
+ ${l}
58
+ }
59
+ `,params:s}}function _o({count:e,outputs:t,limits:r={}}){if(!Number.isInteger(e)||e<1||e>bt.cells)throw new RangeError(`a GPU grid has 1 to ${bt.cells} cells (got ${String(e).slice(0,12)})`);if(!Number.isInteger(t)||t<1||t>bt.outputs)throw new RangeError(`a GPU grid has 1 to ${bt.outputs} outputs`);let n=e*t*4,s=Math.min(r.maxStorageBufferBindingSize??0,r.maxBufferSize??0);if(n>s)throw new RangeError(`the device cannot hold ${n} bytes in one buffer (its limit is ${s})`);return{bytes:n,groups:Math.ceil(e/bt.workgroup)}}var Cc=128,Ko=64,jc=4,Yn=8,Lc=1,je=class extends Error{constructor(t,r,n){super(`${t} took more than ${Math.round(r)} ms`),this.deadline=n}},Ke=class extends Error{},Jo=new WeakMap,Ho=(e,t,r,n=!1)=>{let s;return Promise.race([e,new Promise((o,i)=>s=setTimeout(()=>i(new je(r,t,n)),t))]).finally(()=>clearTimeout(s))};function ti({gpu:e=globalThis.navigator?.gpu,timeoutMs:t=bt.timeoutMs,now:r=Date.now}={}){let n={reason:"",available:!!e},s=e?Jo.get(e):void 0;e&&!s&&Jo.set(e,s={device:null,current:null,pipelines:new Map,disabledUntil:0,queue:Promise.resolve()});let o=()=>{s.disabledUntil=r()+bt.backoffMs};async function i(u){if(!s.device){let l=(async()=>{let f;try{f=await u(e.requestAdapter(),"the adapter")}catch(p){throw p instanceof je?p:new Ke(p.message)}if(!f)throw new Ke("no WebGPU adapter");let h=f.requestDevice(),m;try{m=await u(h,"the device")}catch(p){throw h.then(y=>y?.destroy?.(),()=>{}),p instanceof je?p:new Ke(p.message)}return m.lost?.then(()=>{s.current===m&&(s.device=null,s.current=null,s.pipelines.clear())}),s.current=m,m})();s.device=l,l.catch(()=>{s.device===l&&(s.device=null)})}return s.device}async function a(u,l,f){if(s.pipelines.has(l))return s.pipelines.get(l);let h=u.createShaderModule({code:l}),m=(await f(Promise.resolve(h.getCompilationInfo?.()),"the shader check"))?.messages??[],p=null;if(!m.some(y=>y.type==="error")){let d=u.createBindGroupLayout({entries:[{binding:0,visibility:4,buffer:{type:"uniform"}},{binding:1,visibility:4,buffer:{type:"uniform"}},{binding:2,visibility:4,buffer:{type:"storage"}}]}),w={layout:u.createPipelineLayout({bindGroupLayouts:[d]}),compute:{module:h,entryPoint:"main"}};p={layout:d,pipeline:u.createComputePipelineAsync?await f(u.createComputePipelineAsync(w),"the pipeline"):u.createComputePipeline(w)}}return s.pipelines.size>=bt.pipelines&&s.pipelines.delete(s.pipelines.keys().next().value),s.pipelines.set(l,p),p}async function c(u){let l=y=>(n.reason=y,null),f=[],h=null,m=!1,p=()=>{if(m)return m=!1,h.popErrorScope?.()};try{if(!e)return l("no navigator.gpu");if(u?.cancelled?.())return l("cancelled before its turn");if(r()<s.disabledUntil)return l("the GPU path is switched off for a while after a timeout or a failure");let{exprs:y,params:d={},x0:w,y0:g,dx:M,dy:v,cols:N,rows:$,deadline:b}=u??{};if(![w,g,M,v].every(Number.isFinite)||!Number.isInteger(N)||!Number.isInteger($)||N<1||$<1)return l("the grid is not numbers");let x=Object.keys(d);if(!x.every(ut=>Number.isFinite(d[ut])))return l("a parameter is not a finite number");let S=N*$,O=Rc(y,x);if(!O.ok)return l(O.reason);let A;try{A=_o({count:S,outputs:y.length,limits:{maxStorageBufferBindingSize:bt.cells*bt.outputs*4,maxBufferSize:bt.cells*bt.outputs*4}})}catch(ut){return l(ut.message)}let F=(ut,Nt)=>{let Ee=Number.isFinite(b)?(b-r())/2:1/0;return Ee<1?Promise.reject(new je("no time left before the deadline",0,!0)):Ho(ut,Math.min(t,Ee),Nt,Ee<t)};h=await i(F);try{_o({count:S,outputs:y.length,limits:h.limits??{}})}catch(ut){return l(`the device: ${ut.message}`)}h.pushErrorScope?.("validation"),m=!!h.pushErrorScope;let k=await a(h,O.code,F);if(!k)return await p(),l("the shader did not compile");let I=(ut,Nt)=>(f.push(h.createBuffer({size:ut,usage:Nt})),f.at(-1)),E=I(32,Ko|Yn),P=I(64,Ko|Yn),j=I(A.bytes,Cc|jc),L=I(A.bytes,Yn|Lc),U=new ArrayBuffer(32);new Float32Array(U,0,4).set([w,M,g,v].map(Math.fround)),new Uint32Array(U,16,4).set([N,S,0,0]),h.queue.writeBuffer(E,0,new Uint8Array(U));let J=new Float32Array(16);O.params.forEach((ut,Nt)=>J[Nt]=d[ut]),h.queue.writeBuffer(P,0,J);let Bt=h.createBindGroup({layout:k.layout,entries:[E,P,j].map((ut,Nt)=>({binding:Nt,resource:{buffer:ut}}))}),Pt=h.createCommandEncoder(),mt=Pt.beginComputePass();mt.setPipeline(k.pipeline),mt.setBindGroup(0,Bt),mt.dispatchWorkgroups(A.groups),mt.end(),Pt.copyBufferToBuffer(j,0,L,0,A.bytes),h.queue.submit([Pt.finish()]),await F(L.mapAsync(1),"the readback");let Xt=new Float32Array(L.getMappedRange().slice(0,A.bytes));L.unmap();let Gt=await p();if(Gt)return l(`the device reported: ${String(Gt.message).slice(0,120)}`);let Jt=y.length;return Array.from({length:Jt},(ut,Nt)=>Float32Array.from({length:S},(Ee,re)=>Xt[re*Jt+Nt]))}catch(y){let d=String(y?.message??y).slice(0,160);return(y instanceof Ke||y instanceof je&&!y.deadline)&&o(),l(d)}finally{p()?.catch?.(()=>{});for(let d of f)d.destroy?.()}}return n.values=u=>{if(n.reason="",!e)return n.reason="no navigator.gpu",Promise.resolve(null);let l=Number.isFinite(u?.deadline)?u.deadline:void 0,f=()=>Math.max(1,Math.min(t*3,l===void 0?1/0:(l-r())/2)),h=s.queue,m=(async()=>(await Promise.race([h,new Promise(y=>setTimeout(y,f()))]),c(u)))(),p=Ho(m,f(),"the GPU path",!0).catch(y=>(n.reason=String(y?.message??y).slice(0,160),null));return s.queue=m.then(()=>{},()=>{}),p},n}function ei(e,t){let r=[];for(let n=0;n<e.length;n++){let s=e[n],o=Float64Array.from(s),i=[];for(let u=0;u<o.length;u++)Number.isFinite(o[u])||i.push(u);if(i.length>bt.repair)return{ok:!1,reason:`${i.length} cells were not finite on the GPU`};let a=new Set(i);for(let u of i)o[u]=t(n,u);let c=Math.max(1,Math.floor(o.length/bt.checks));for(let u=Math.floor(c/2);u<o.length;u+=c){if(a.has(u))continue;let l=t(n,u);if(!Ic(o[u],l))return{ok:!1,reason:`cell ${u} is ${o[u]} on the GPU and ${l} on the CPU, outside the f32 tolerance`}}r.push(o)}return{ok:!0,values:r}}var qc=()=>globalThis.navigator?.gpu?ti({gpu:globalThis.navigator.gpu}):null,V=Object.freeze({expression:2e3,items:16,points:4e3,evaluations:1e6,features:64,steps:64,overlays:16,pins:16,overlayPoints:400,integration:4e3,cells:9e4,grid:400,levels:24,segments:2e5,modulus:4096,grid3:256,cells3:5e4,curve3:4e3,field3:16,raster:400,rasterCells:9e4,zeroGrid:96,zeroCells:4e4,zeros:64,conformal:24,conformalSamples:200,unity:360,deadlineMs:1e4,deadlineDefaultMs:2e3}),Qn=Object.freeze(["y","param","polar","implicit","contour","gradient","finite","surface","psurface","curve3","field3","complex","complex3",...Pe]),_n=Object.freeze(["surface","psurface","curve3","field3","complex3"]);var Qr=Object.freeze(["implicit","contour","gradient"]),ri=Object.freeze(["area","inequality","derivative","integral","difference","roots","extrema","intersections"]),ni=Object.freeze([">",">=","<","<="]),Tc=Object.freeze({y:"x",param:"t",polar:"theta",implicit:"x",contour:"x",gradient:"x",finite:"k",surface:"x",psurface:"u",curve3:"t",field3:"x",complex:"z",complex3:"z",...Co}),fi=Object.freeze({y:["x"],param:["t"],polar:["theta"],implicit:["x","y"],contour:["x","y"],gradient:["x","y"],finite:["k"],surface:["x","y"],psurface:["u","v"],curve3:["t"],field3:["x","y","z"],complex:["z","i"],complex3:["z","i"],...Ro}),He=class extends Error{constructor(t){super(t),this.name="PlotLimitError"}},Le=new Map,pf=e=>Le.get(String(e));function df(e){let t=String(e);Le.set(t,1/0),Le.delete(t)}function Je(){return typeof MessageChannel=="function"?new Promise(e=>{let t=new MessageChannel;t.port1.onmessage=()=>{t.port1.close(),t.port2.close(),e()},t.port2.postMessage(0)}):Promise.resolve()}function qt(e,t){if(typeof e!="string"||!e.trim())throw new Error(`${t} is empty: write something like sin(x)`);if(e.length>V.expression)throw new Error(`${t} has at most ${V.expression} characters`);return e}var Et=Object.freeze({implicitMultiplication:!0}),Vc=/^[A-Za-z]{2,}$/,Uc=new Set(["pi","e"]);function br(e=[]){let t={theta:"q_t"},r=0;for(let n of[...new Set(e)].sort())Vc.test(n)&&!Uc.has(n)&&!(n in t)&&(t[n]=`q_${r++}`);return t}var Bc=(e,t)=>t[e]??e,Gc=e=>br([...Object.keys(e?.wired??{}),...Object.keys(e?.sliders??{}),...Object.keys(e?.params??{})]),Hn=e=>{let t=Object.fromEntries(Object.entries(e).map(([r,n])=>[n,r]));return r=>t[r]??r};function _r(e,t){if(Array.isArray(e))return e.map(n=>_r(n,t));if(e===null||typeof e!="object")return e;let r={};for(let[n,s]of Object.entries(e))r[n]=n==="name"&&e.type==="var"?t(s):_r(s,t);return r}function tr(e,t=br()){let r=e;for(let[n,s]of Object.entries(t))r=r.replace(new RegExp(`(?<![A-Za-z_])${n}(?![A-Za-z_])(?!\\s*\\()`,"g"),s);return r}function ge(e,t=br()){return tr(e.replace(/^\s*(?:y|r|x)\s*=(?!=)/,""),t)}function ts(e){let t=String(e).replace(/^\s*z\s*=(?!=)/,"");for(let r=0;r<t.length;r++)if(t[r]==="="&&!"<>!=".includes(t[r-1]??"")&&t[r+1]!=="=")return`(${t.slice(0,r)}) - (${t.slice(r+1)})`;return t}var es=e=>String(e).replace(/^\s*(?:w|f\(z\))\s*=(?!=)/,"");function Dc(e,t=[]){let r=br(t);return C.freeVariables(C.parse(ge(qt(e,"expression"),r),Et)).map(Hn(r)).sort()}var Zc=Object.freeze({value:1,min:-10,max:10,step:.1});function Xc(e,t={},r={}){let n={},s=[],o=[];for(let i of[...e].sort()){let a=t?.[i];if(typeof a=="number"&&Number.isFinite(a)){n[i]=a,s.push(i);continue}let c=Number(r?.[i]?.value);n[i]=Number.isFinite(c)?c:Zc.value,o.push(i)}return{params:n,bound:s,unbound:o}}function Wc(e,t=[]){let r=new Set;for(let n of Array.isArray(e)?e:[]){let s=n?.kind??"y";if(!Qn.includes(s))continue;let o=s==="param"||s==="phase"?[n.expr,n.expr2]:_n.includes(s)&&s!=="surface"&&s!=="complex3"?[n.expr,n.expr2,n.expr3]:[n.expr],i=fi[s],a=Pe.includes(s)?[n.center,n.min,n.max]:s==="finite"?[n.modulus]:s==="complex"?[n.min,n.max,n.min2,n.max2,n.unity]:s==="param"||s==="polar"?[n.min,n.max]:_n.includes(s)?[n.min,n.max,n.min2,n.max2,n.zMin,n.zMax]:[];for(let c of[...o,...a.filter(u=>typeof u=="string")])if(!(typeof c!="string"||!c.trim()||c.length>V.expression))try{let u=Pe.includes(s)?Oe(c):Qr.includes(s)&&c===n.expr?ts(c):s==="complex"||s==="complex3"?c===n.expr?es(c):c:s==="surface"?c.replace(/^\s*z\s*=(?!=)/,""):c.replace(/^\s*(?:y|r|x)\s*=(?!=)/,"");for(let l of Dc(u,t))!i.includes(l)&&l!=="_"&&r.add(l)}catch{}}return[...r].sort()}var hi=(e,t)=>Object.fromEntries(Object.entries(e).map(([r,n])=>[t[r]??r,n]));function zt(e,t,r,n={},s=br()){if(e==null||e==="")return r;if(typeof e=="number"){if(!Number.isFinite(e))throw new Error(`${t} must be a finite number`);return e}let o=mr(ge(qt(String(e),t),s),{variable:"_",params:hi(n,s),...Et})(0);if(!Number.isFinite(o))throw new Error(`${t} must be a finite number`);return o}var Yc=e=>{let t={xMin:Number(e?.xMin),xMax:Number(e?.xMax),yMin:Number(e?.yMin),yMax:Number(e?.yMax)};if(![t.xMin,t.xMax,t.yMin,t.yMax].every(Number.isFinite)||!(t.xMin<t.xMax)||!(t.yMin<t.yMax))throw new RangeError("the viewport needs finite xMin < xMax and yMin < yMax");return t};function Qc(e,t,r){let n={};try{let s=Hn(r),o=fi[t]??[],i=t==="param"||t==="phase"?[e.expr,e.expr2]:[e.expr],a=new Set,c=[];for(let u of i){if(typeof u!="string"||!u.trim()||u.length>V.expression)continue;let l=Pe.includes(t)?Oe(u):Qr.includes(t)?ts(u):t==="complex"||t==="complex3"?es(u):u.replace(/^\s*(?:y|r|x)\s*=(?!=)/,""),f=C.parse(tr(l,r),Et);for(let h of C.freeVariables(f).map(s))!o.includes(h)&&h!=="_"&&a.add(h);c.push(C.toLatex(_r(f,s)))}n.vars=[...a].sort(),c.length&&(n.latex=t==="param"?`x(t) = ${c[0]},\\; y(t) = ${c[1]??""}`:t==="polar"?`r(\\theta) = ${c[0]}`:t==="implicit"||t==="contour"||t==="gradient"?`${c[0]} = 0`:t==="finite"?`f(k) = ${c[0]}`:t==="complex"||t==="complex3"?`f(z) = ${c[0]}`:t==="slope"?`y' = ${c[0]}`:t==="ode2"?`y'' = ${c[0]}`:t==="phase"?`x' = ${c[0]},\\; y' = ${c[1]??""}`:t==="series"?`a_n = ${c[0]}`:Pe.includes(t)?`f(x) = ${c[0]}`:`y = ${c[0]}`)}catch{}return n}function _c(e){let t=e.x.length,r=new Float64Array(t),n=new Float64Array(t),s=0,o=-1;for(let i=0;i<t;i++){if(r[i]=e.x[i],Number.isNaN(e.y[i])||!Number.isFinite(e.x[i])){n[i]=NaN,o=-1;continue}o>=0&&(s+=(e.y[o]+e.y[i])/2*(e.x[i]-e.x[o])),n[i]=s,o=i}return{x:r,y:n}}function Kc(e){let t=[],r=[];for(let n=1;n<e.x.length;n++){let[s,o,i,a]=[e.x[n-1],e.x[n],e.y[n-1],e.y[n]];if(Number.isNaN(i)||Number.isNaN(a)||!(o>s)){t.length&&!Number.isNaN(r.at(-1))&&(t.push(t.at(-1)),r.push(NaN));continue}t.push((s+o)/2),r.push((a-i)/(o-s))}return{x:Float64Array.from(t),y:Float64Array.from(r)}}function si(e,t){let r=[],n=[],s=!1;for(let o=0;o<e.length;o++)Number.isFinite(e[o])&&Number.isFinite(t[o])?(s&&r.length&&(r.push(r[r.length-1]),n.push(NaN)),s=!1,r.push(e[o]),n.push(t[o])):s=!0;return{x:Float64Array.from(r),y:Float64Array.from(n)}}function mi(e,t,r,n){let s=[],{x:o,y:i}=t;for(let[a,c]of rn(t))for(let u=a+1;u<c-1&&s.length<r;u++){let l=i[u]-i[u-1],f=i[u+1]-i[u],h=l>0&&f<=0||l>=0&&f<0?!0:l<0&&f>=0||l<=0&&f>0?!1:null;if(h===null)continue;let m=o[u-1],p=o[u+1],y=h?-1:1,d=S=>y*e(S),w=(Math.sqrt(5)-1)/2,g=p-w*(p-m),M=m+w*(p-m),v=d(g),N=d(M);for(let S=0;S<40&&p-m>1e-12*Math.max(1,Math.abs(p));S++)if(v<N?(p=M,M=g,N=v,g=p-w*(p-m),v=d(g)):(m=g,g=M,v=N,M=m+w*(p-m),N=d(M)),n())throw new wt;let $=(m+p)/2,b=e($),x=s.at(-1);Number.isFinite(b)&&!(x&&x.kind===(h?"max":"min")&&Math.abs(x.x-$)<=1e-6*Math.max(1,Math.abs($)))&&s.push({kind:h?"max":"min",x:$,y:b})}return s}var rs=e=>Math.round(e*1e6)/1e6;function oi(e,t,r=8){let n=Math.min(V.grid,Math.max(r,Math.round(Number(e)||t)));if((n+1)*(n+1)<=V.cells)return{n};let s=Math.floor(Math.sqrt(V.cells))-1;return{n:s,limit:`grid cut from ${n} to ${s} cells a side by the cell budget (${V.cells} evaluations)`}}function Jc(e,t,r){let n=C.parse(tr(ts(qt(e,t)),r.aliases),Et);if(n?.type==="cmp")throw new Error(`${t} is a comparison, not a curve: write F(x, y) = 0 (an inequality is shaded by an inequality overlay on a y = f(x) curve)`);let s=C.compile(n),o={...r.aliasedParams,x:0,y:0};return{expr:n,f:(i,a)=>(r.spend(),o.x=i,o.y=a,s(o))}}function pi(e,t,r,n){let s=r+1,o=new Float64Array(s*s).fill(Number.NaN),i=(t.xMax-t.xMin)/r,a=(t.yMax-t.yMin)/r,c=0,u;try{for(let l=0;l<s;l++){if(n.cancelled())throw new wt;if(n.timeUp()){u=`stopped at row ${l} of ${s}: the time limit`;break}let f=t.yMin+l*a;for(let h=0;h<s;h++){let m=e(t.xMin+h*i,f);o[l*s+h]=typeof m=="number"?m:Number.NaN}c=l+1}}catch(l){if(!(l instanceof He))throw l;u=`stopped at row ${c} of ${s}: ${l.message.replace(/^stopped /,"")}`}return{vals:o,rows:c,side:s,dx:i,dy:a,limit:u}}var Hc=[[],[[3,0]],[[0,1]],[[3,1]],[[1,2]],null,[[0,2]],[[3,2]],[[3,2]],[[0,2]],null,[[1,2]],[[3,1]],[[0,1]],[[3,0]],[]];function di(e,t,r,n,s,o,i,a){if(!(Number.isFinite(e)&&Number.isFinite(t)&&Number.isFinite(r)&&Number.isFinite(n)))return[];let c=(e>=0?1:0)|(t>=0?2:0)|(r>=0?4:0)|(n>=0?8:0),u=Hc[c];if(u===null){let f=(e+t+r+n)/4>=0;u=c===5?f?[[0,1],[3,2]]:[[3,0],[1,2]]:f?[[3,0],[1,2]]:[[0,1],[3,2]]}let l=f=>f===0?[s+e/(e-t)*i,o]:f===1?[s+i,o+t/(t-r)*a]:f===2?[s+n/(n-r)*i,o+a]:[s,o+e/(e-n)*a];return u.map(([f,h])=>[...l(f),...l(h)])}var Kr=class{constructor(t){this.x=[],this.y=[],this.z=[],this.cap=t,this.cut=!1}add(t,r){if(this.x.length>=this.cap*3)return void(this.cut=!0);this.x.push(t[0],t[2],Number.NaN),this.y.push(t[1],t[3],Number.NaN),this.z.push(r,r,Number.NaN)}dot(t,r,n){this.add([t,r,t,r],n)}arrays(){let t=Math.max(0,this.x.length-1);return{x:Float64Array.from(this.x.slice(0,t)),y:Float64Array.from(this.y.slice(0,t)),z:Float64Array.from(this.z.slice(0,t))}}};function Kn(e,t,r,n){let{vals:s,rows:o,side:i,dx:a,dy:c}=e;for(let u=0;u+1<o;u++)for(let l=0;l+1<i;l++){let f=u*i+l;for(let h of di(s[f]-r,s[f+1]-r,s[f+i+1]-r,s[f+i]-r,t.xMin+l*a,t.yMin+u*c,a,c))n.add(h,r)}}function tu(e,t){if(Array.isArray(e))return e.filter(Number.isFinite).slice(0,V.levels);let r=Math.min(V.levels,Math.max(1,Math.round(Number(e)||9))),n=1/0,s=-1/0;for(let o=0;o<t.rows*t.side;o++){let i=t.vals[o];Number.isFinite(i)&&(i<n&&(n=i),i>s&&(s=i))}return s>n?Array.from({length:r},(o,i)=>rs(n+(i+1)*(s-n)/(r+1))):[]}var eu=new Xe({operations:[(e,t)=>e.add(t),(e,t)=>e.multiply(t)],inverses:[e=>e.negate(),e=>_t.point(1).divide(e)],identities:[_t.point(0),_t.point(1)],wrap:e=>typeof e=="number"?_t.point(e):e});function ru(e,t,r,n,s,o){let i=(r.xMax-r.xMin)/n,a=(r.yMax-r.yMin)/n,c=Object.fromEntries(Object.entries(s.aliasedParams).map(([g,M])=>[g,_t.point(M)])),u=(g,M,v,N)=>C.evaluateOverStructure(e,eu,{...c,x:_t.of(r.xMin+g*i,r.xMin+M*i),y:_t.of(r.yMin+v*a,r.yMin+N*a)});try{u(0,n,0,n)}catch(g){throw new Error(`interval-robust mode reads + - * / and whole-number powers only, not this formula: ${xr(g)}`)}let l=new Map,f=(g,M)=>{let v=M*(n+1)+g;return l.has(v)||l.set(v,t(r.xMin+g*i,r.yMin+M*a)),l.get(v)},h=new Set,m=[],p=[[0,n,0,n]],y=0,d;try{for(;p.length;){if(s.cancelled())throw new wt;if(s.timeUp()){d=`stopped after ${y} cells: the time limit`;break}if(y>=V.cells){d=`stopped after ${y} cells: the cell budget (${V.cells})`;break}let[g,M,v,N]=p.pop();y++,s.spend();let $=!0;try{let F=u(g,M,v,N);$=!(F.lo>0||F.hi<0)}catch{}if(!$)continue;if(M-g>1||N-v>1){let F=M-g>1?g+M>>1:null,k=N-v>1?v+N>>1:null;for(let[I,E]of F===null?[[g,M]]:[[g,F],[F,M]])for(let[P,j]of k===null?[[v,N]]:[[v,k],[k,N]])p.push([I,E,P,j]);continue}let[b,x,S,O]=[f(g,v),f(g+1,v),f(g+1,v+1),f(g,v+1)],A=di(b,x,S,O,r.xMin+g*i,r.yMin+v*a,i,a);if(A.length){h.add(v*n+g);for(let F of A)o.add(F,0)}else m.push([g,v])}}catch(g){if(!(g instanceof He))throw g;d=`stopped after ${y} cells: ${g.message.replace(/^stopped /,"")}`}let w=0;for(let[g,M]of m){let v=!1;for(let N=-1;N<=1&&!v;N++)for(let $=-1;$<=1;$++)(N||$)&&h.has((M+$)*n+g+N)&&(v=!0);v||(o.dot(r.xMin+(g+.5)*i,r.yMin+(M+.5)*a,0),w++)}return{limit:d,dots:w}}async function ii(e,t,r,n){let s=e.gpu;if(e.gpuReason="",!s||r.cols*r.rows>bt.cells)return null;let o=new Set,i=l=>l&&typeof l=="object"?l.type==="var"?o.add(l.name):Object.values(l).forEach(i):void 0;t.forEach(i);let a={};for(let l of o)l!=="x"&&l!=="y"&&Number.isFinite(e.aliasedParams[l])&&(a[l]=e.aliasedParams[l]);let c=await s.values({exprs:t,params:a,...r,deadline:e.deadline,cancelled:e.cancelled});if(e.cancelled())throw new wt;if(!c)return e.gpuReason=s.reason,null;let u=ei(c,n);return u.ok||(e.gpuReason=u.reason),u.ok?u.values:null}async function nu(e,t,r){let{viewport:n,pad:s}=r,o=Math.min(.25,s),i=(n.xMax-n.xMin)*o,a=(n.yMax-n.yMin)*o,c=e==="implicit"?"F(x, y)":"f(x, y)",{f:u,expr:l}=Jc(t.expr,c,r),f={},h=d=>d&&(f.limit=f.limit?`${f.limit}; ${d}`:d);if(e==="gradient"){let d=n,w=oi(t.grid,18,4),g=Math.min(w.n,60);h(w.limit);let M=I=>{try{let E=C.compile(C.simplify(C.differentiate(l,I))),P={...r.aliasedParams,x:0,y:0};return(j,L)=>(r.spend(),P.x=j,P.y=L,E(P))}catch{return null}},v=M("x")??((I,E)=>(u(I+1e-6*Math.max(1,Math.abs(I)),E)-u(I-1e-6*Math.max(1,Math.abs(I)),E))/(2e-6*Math.max(1,Math.abs(I)))),N=M("y")??((I,E)=>(u(I,E+1e-6*Math.max(1,Math.abs(E)))-u(I,E-1e-6*Math.max(1,Math.abs(E))))/(2e-6*Math.max(1,Math.abs(E)))),$=[],b=[],x=[],S=[],O=0,A=I=>[d.xMin+(I%g+.5)*(d.xMax-d.xMin)/g,d.yMin+(Math.floor(I/g)+.5)*(d.yMax-d.yMin)/g],F=r.gpu&&["x","y"].map(I=>{try{return C.simplify(C.differentiate(l,I))}catch{return null}}),k=F?.every(Boolean)?await ii(r,F,{x0:d.xMin+.5*(d.xMax-d.xMin)/g,y0:d.yMin+.5*(d.yMax-d.yMin)/g,dx:(d.xMax-d.xMin)/g,dy:(d.yMax-d.yMin)/g,cols:g,rows:g},(I,E)=>(I===0?v:N)(...A(E))):null;if(k){for(let I=0;I<g*g;I++){let E=k[0][I],P=k[1][I];if(!Number.isFinite(E)||!Number.isFinite(P))continue;let[j,L]=A(I);$.push(j),b.push(L),x.push(E),S.push(P),O=Math.max(O,Math.hypot(E,P))}f.engine="gpu"}else r.gpu&&r.gpuReason&&(f.gpuReason=r.gpuReason.slice(0,200));if(!k)try{for(let I=0;I<g;I++){if(r.cancelled())throw new wt;if(r.timeUp()){h(`stopped at row ${I} of ${g}: the time limit`);break}let E=d.yMin+(I+.5)*(d.yMax-d.yMin)/g;for(let P=0;P<g;P++){let j=d.xMin+(P+.5)*(d.xMax-d.xMin)/g,L=v(j,E),U=N(j,E);!Number.isFinite(L)||!Number.isFinite(U)||($.push(j),b.push(E),x.push(L),S.push(U),O=Math.max(O,Math.hypot(L,U)))}}}catch(I){if(!(I instanceof He))throw I;h(`stopped: ${I.message.replace(/^stopped /,"")}`)}return Object.assign(f,{x:Float64Array.from($),y:Float64Array.from(b),u:Float64Array.from(x),v:Float64Array.from(S),max:O,grid:g}),f}let m={xMin:n.xMin-i,xMax:n.xMax+i,yMin:n.yMin-a,yMax:n.yMax+a},p=oi(t.grid,160);h(p.limit),f.grid=p.n;let y=new Kr(V.segments);if(e==="implicit"&&t.robust===!0){let d=ru(l,u,m,p.n,r,y);h(d.limit),f.robust=!0,d.dots&&(f.dots=d.dots)}else{let d=p.n+1,w=(m.xMax-m.xMin)/p.n,g=(m.yMax-m.yMin)/p.n,M=r.gpu?await ii(r,[l],{x0:m.xMin,y0:m.yMin,dx:w,dy:g,cols:d,rows:d},(N,$)=>u(m.xMin+$%d*w,m.yMin+Math.floor($/d)*g)):null,v=M?{vals:M[0],rows:d,side:d,dx:w,dy:g}:pi(u,m,p.n,r);if(M?f.engine="gpu":r.gpu&&r.gpuReason&&(f.gpuReason=r.gpuReason.slice(0,200)),h(v.limit),e==="implicit")Kn(v,m,0,y);else{f.levels=tu(t.levels,v);for(let N of f.levels)Kn(v,m,N,y)}}return y.cut&&h(`drawing stopped at ${V.segments} line segments`),Object.assign(f,y.arrays()),e==="implicit"&&delete f.z,f}var su={complex3:["f(z)"],surface:["f(x, y)"],psurface:["x(u, v)","y(u, v)","z(u, v)"],curve3:["x(t)","y(t)","z(t)"],field3:["Fx(x, y, z)","Fy(x, y, z)","Fz(x, y, z)"]};function Wr(e,t,r,n){let s=C.parse(tr(qt(e,r).replace(/^\s*z\s*=(?!=)/,a=>t.includes("z")?a:""),n.aliases),Et);if(s?.type==="cmp")throw new Error(`${r} is a comparison, not a formula`);let o=C.compile(s),i={...n.aliasedParams};for(let a of t)i[a]=0;return(...a)=>{for(let c=0;c<t.length;c++)i[t[c]]=a[c];return o(i)}}function gr(e,t,r,n=2){let s=e===void 0?t:Number(e);if(!Number.isInteger(s)||s<n)throw new RangeError(`grid is a whole number from ${n} to ${r}`);return s>r?{n:r,limit:`grid cut from ${s} to ${r}`}:{n:s}}function ou(e){let{positions:t,indices:r,valid:n}=e,s=0,o=0,i=0,a=0;for(let u=0;u<e.vertexCount;u++)n[u]&&(s+=t[u*3],o+=t[u*3+1],i+=t[u*3+2],a++);if(!a)return e;s/=a,o/=a,i/=a;let c=0;for(let u=0;u<r.length;u+=3){let l=r[u]*3,f=r[u+1]*3,h=r[u+2]*3,m=t[l]-s,p=t[l+1]-o,y=t[l+2]-i,d=t[f]-s,w=t[f+1]-o,g=t[f+2]-i,M=t[h]-s,v=t[h+1]-o,N=t[h+2]-i;c+=m*(w*N-g*v)-p*(d*N-g*M)+y*(d*v-w*M)}if(!(c<0))return e;for(let u=0;u<e.normals.length;u++)e.normals[u]=-e.normals[u]||0;for(let u=0;u<r.length;u+=3){let l=r[u+1];r[u+1]=r[u+2],r[u+2]=l}return e.flipped=!0,e}function gf(e=[]){return e.filter(t=>t?.mesh&&!t.hidden).map(t=>({id:t.id,kind:t.kind,...t.mesh}))}var ai=Object.freeze(["abs","re","im"]),ci=Object.freeze(["re z","im z","re f","im f","abs f"]),ui=e=>Math.abs(e)<1e-12?0:e,Yr=10;function gi(e,t){let r=C.parse(tr(es(qt(e,"f(z)")),t.aliases),Et);if(r?.type==="cmp")throw new Error("f(z) is a comparison, not a formula");return r}var iu=e=>C.freeVariables(e).filter(t=>t!=="z"&&t!=="i");function au(e,t){let{viewport:r,params:n,aliases:s}=t,o=gi(e.expr,t),i=Wn(o,t.aliasedParams),a={min:r.xMin,max:r.xMax},c={min:r.yMin,max:r.yMax},u={x:new Float64Array(0),y:new Float64Array(0)},l=[],f=()=>V.deadlineMs,h=(v,N)=>v&&!v.complete&&l.push(`${N} stopped at ${v.rows} of ${v.of}: the ${v.reason==="time"?"time":"cell"} limit`),m=()=>t.cancelled(),p=gr(e.grid,160,V.raster,8);p.limit&&l.push(p.limit);let y=p.n,d=Math.max(8,Math.round(y*.625)),w=nn(i,a,c,{width:y,height:d,maxCells:V.rasterCells,maxMillis:f(),isCancelled:m});h(w.progress,"the picture");let g={viewport:{...r},raster:{width:w.width,height:w.height,abs:w.abs,arg:w.arg,progress:w.progress}},M=Yo(o,iu(o));if(M.ok||(g.shaderReason=M.reason),e.zeros===!0){let v=on(i,a,c,{grid:Math.min(V.zeroGrid,Math.max(8,Number(e.zeroGrid)||48)),maxCells:V.zeroCells,maxMillis:f(),isCancelled:m});h(v.progress,"the search for zeros and poles"),g.zeros=v.items.slice(0,V.zeros).map(N=>({re:ui(N.re),im:ui(N.im),kind:N.kind,order:N.order,refined:N.refined})),v.items.length>V.zeros&&l.push(`${v.items.length-V.zeros} more zeros and poles than the ${V.zeros} marked`)}if(e.unity!==void 0&&e.unity!==""){let v=zt(e.unity,"unity",0,n,s);if(!Number.isInteger(v)||v<1||v>V.unity)throw new RangeError(`the order of the roots of unity is a whole number from 1 to ${V.unity}, not ${rs(v)}`);g.unity=Wo(v)}if(e.conformal!==void 0){let v=Number(e.conformal);if(!Number.isInteger(v)||v<2||v>V.conformal)throw new RangeError(`conformal is a number of grid lines from 2 to ${V.conformal}`);let N=(x,S,O,A,F)=>{let k=zt(e[x],x,O,n,s),I=zt(e[S],S,A,n,s);if(!(k<I))throw new RangeError(`${F}: ${x} must be less than ${S}`);return{min:k,max:I}},$=Math.max(r.xMax-r.xMin,r.yMax-r.yMin),b=sn(i,N("min","max",-2,2,"Re z"),N("min2","max2",-2,2,"Im z"),{reLines:v,imLines:v,samplesPerLine:V.conformalSamples,bound:1e3*$,maxStep:$});g.conformal=b.map(x=>({kind:x.kind,value:x.value,x:x.x,y:x.y}))}return u.complex=g,l.length&&(u.limit=l.join("; ")),u}function cu(e,t,r){let{params:n,aliases:s}=r,o=su[e],i=e==="surface"||e==="complex3"?[t.expr]:[t.expr,t.expr2,t.expr3];i.forEach((p,y)=>qt(p,o[y]));let a=(p,y,d,w,g)=>{let M=zt(t[p],`${p==="min"?"min":p}`,d,n,s),v=zt(t[y],`${y==="max"?"max":y}`,w,n,s);if(!(M<v))throw new RangeError(`${g}: ${p} must be less than ${y}`);return{min:M,max:v}},c=Math.max(0,r.deadline-Date.now()),u=r.budget??{},l={maxCells:Math.min(V.cells3,Number(u.maxCells)||V.cells3),maxMillis:Math.min(c,u.maxMillis??1/0),isCancelled:r.stop},f={x:new Float64Array(0),y:new Float64Array(0)},h=p=>p&&(f.limit=f.limit?`${f.limit}; ${p}`:p),m=p=>p&&!p.complete&&h(`stopped at ${p.rows} of ${p.of} rows: the ${p.reason==="time"?"time":"cell"} limit`);if(e==="complex3"){let p=gr(t.grid,64,V.grid3);h(p.limit);let y=Wn(gi(t.expr,r),r.aliasedParams),d=t.part??"abs";if(!ai.includes(d))throw new RangeError(`part is ${ai.join(", ")}`);let w=(A,F)=>{let[k,I]=y(A,F);return d==="re"?k:d==="im"?I:Math.hypot(k,I)},g=t.zMin===void 0?-Yr:zt(t.zMin,"zMin",-Yr,n,s),M=t.zMax===void 0?Yr:zt(t.zMax,"zMax",Yr,n,s),v=a("min","max",-2,2,"Re z"),N=a("min2","max2",-2,2,"Im z"),$=t.axes===void 0?null:{x:"re z",y:"im z",z:d==="re"?"re f":d==="im"?"im f":"abs f",...t.axes};if($&&(!["x","y","z"].every(A=>ci.includes($[A]))||new Set([$.x,$.y,$.z]).size!==3))throw new RangeError(`axes: x, y and z are each a different one of ${ci.join(", ")}`);let b=(A,F,k,I,E)=>A==="re z"?F:A==="im z"?k:A==="re f"?I:A==="im f"?E:Math.hypot(I,E),x=$?Mr((A,F)=>{let[k,I]=y(A,F),E=b($.z,A,F,k,I);return E>=g&&E<=M?[b($.x,A,F,k,I),b($.y,A,F,k,I),E]:[NaN,NaN,NaN]},v,N,{...l,columns:p.n,rows:p.n}):vr(w,v,N,{...l,columns:p.n,rows:p.n,zRange:{min:g,max:M}}),S=new Float32Array(x.vertexCount).fill(NaN),O=new Float32Array(x.vertexCount).fill(NaN);for(let A=0;A<x.vertexCount;A++){if(!x.valid[A])continue;let F=A%x.columns===x.columns-1?v.max:v.min+(v.max-v.min)*(A%x.columns)/(x.columns-1),k=Math.floor(A/x.columns),I=k===p.n-1?N.max:N.min+(N.max-N.min)*k/(p.n-1),[E,P]=$?y(F,I):y(x.positions[A*3],x.positions[A*3+1]);O[A]=Math.hypot(E,P),S[A]=Math.atan2(P,E)}return f.mesh={...x,arg:S,mag:O},m(x.progress),f.bounds=x.bounds,f.progress=x.progress,f}if(e==="surface"||e==="psurface"){let p=gr(t.grid,64,V.grid3);h(p.limit);let y={...l,columns:p.n,rows:p.n};if(e==="surface"){let d=Wr(t.expr,["x","y"],o[0],r),w=t.zMin===void 0?void 0:zt(t.zMin,"zMin",-1/0,n,s),g=t.zMax===void 0?void 0:zt(t.zMax,"zMax",1/0,n,s);(w!==void 0||g!==void 0)&&(y.zRange={min:w??-1/0,max:g??1/0});let M=a("min","max",-3,3,"x"),v=a("min2","max2",-3,3,"y");if(f.mesh=vr(d,M,v,y),r.slice&&r.slice.axis==="z")f.slice={axis:"z",at:r.slice.at,...$o(No(f.mesh,r.slice.at))};else if(r.slice){let{axis:N,at:$}=r.slice,b=N==="y"?M.min:v.min,x=N==="y"?M.max:v.max,S=257,O=new Float64Array(S),A=new Float64Array(S);for(let F=0;F<S;F++){let k=b+(x-b)*F/(S-1),I=N==="y"?d(k,$):d($,k);O[F]=k,A[F]=Number.isFinite(I)?I:NaN}f.slice={axis:N,at:$,x:O,y:A}}}else{let[d,w,g]=[0,1,2].map(M=>Wr(i[M],["u","v"],o[M],r));f.mesh=ou(Mr((M,v)=>[d(M,v),w(M,v),g(M,v)],a("min","max",0,2*Math.PI,"u"),a("min2","max2",0,2*Math.PI,"v"),y))}m(f.mesh.progress),f.bounds=f.mesh.bounds,f.progress=f.mesh.progress}else if(e==="curve3"){let p=gr(t.grid,512,V.curve3,2);h(p.limit);let[y,d,w]=[0,1,2].map(M=>Wr(i[M],["t"],o[M],r)),g=cn(M=>[y(M),d(M),w(M)],a("min","max",0,2*Math.PI,"t"),{...l,samples:p.n});f.curve3={positions:g.positions,t:g.t,count:g.count,runs:un(g),progress:g.progress},m(g.progress),f.bounds=uu(g.positions,g.count),f.progress=g.progress}else{let p=gr(t.grid,6,V.field3);h(p.limit);let[y,d,w]=[0,1,2].map($=>Wr(i[$],["x","y","z"],o[$],r)),g=a("min","max",-3,3,"x"),M=a("min2","max2",-3,3,"y"),v=a("zMin","zMax",-3,3,"z"),N=ln(($,b,x)=>[y($,b,x),d($,b,x),w($,b,x)],g,M,v,{...l,grid:p.n});f.field3={origins:N.origins,vectors:N.vectors,magnitudes:N.magnitudes,maxMagnitude:N.maxMagnitude,count:N.count,skipped:N.skipped,progress:N.progress,box:{min:[g.min,M.min,v.min],max:[g.max,M.max,v.max]}},m(N.progress),f.bounds={min:[g.min,M.min,v.min],max:[g.max,M.max,v.max]},f.progress=N.progress}return f}function uu(e,t){let r=[1/0,1/0,1/0],n=[-1/0,-1/0,-1/0];for(let s=0;s<t;s++)if(Number.isFinite(e[s*3]))for(let o=0;o<3;o++)r[o]=Math.min(r[o],e[s*3+o]),n[o]=Math.max(n[o],e[s*3+o]);return r[0]===1/0?{min:[NaN,NaN,NaN],max:[NaN,NaN,NaN]}:{min:r,max:n}}function lu(e,t){let r=zt(e.modulus,"modulus",7,t.params,t.aliases);if(!Number.isInteger(r))throw new RangeError(`the modulus must be a whole number, not ${rs(r)}`);if(r<2||r>V.modulus)throw new RangeError(`the modulus must be a whole number from 2 to ${V.modulus}, not ${r}`);let n=C.parse(ge(qt(e.expr,"f(k)"),t.aliases),Et),s=Xe.integersModulo(r),o=[],i=[],a=0,c;for(let u=0;u<r;u++){if(u%256===0&&t.cancelled())throw new wt;t.spend();try{let l=C.evaluateOverStructure(n,s,{...t.aliasedParams,k:u});if(typeof l!="number"||Number.isNaN(l))throw new Error("undefined");o.push(u),i.push(l)}catch(l){a++,c=l}}if(!o.length)throw new Error(c&&c.message!=="undefined"?xr(c):`f(k) is undefined at every element of Z/${r}Z`);return{x:Float64Array.from(o),y:Float64Array.from(i),modulus:r,...a?{skipped:a}:{}}}var fu={spelled:tr,sourceText:qt,bound:zt,fillGrid:pi,traceLevel:Kn,Segments:Kr,IMPLICIT:Et};async function yf(e){if(!e||typeof e!="object")throw new TypeError("a plot request is an object");let t=String(e.key??"plot"),r=Number(e.gen??0);if(!Number.isFinite(r))throw new TypeError("gen is a number");if((Le.get(t)??-1/0)>r)return{key:t,gen:r,stale:!0};Le.set(t,r);let n=()=>(Le.get(t)??-1/0)>r||!Le.has(t),s=Yc(e.viewport),o=e.formulas&&typeof e.formulas=="object"?e.formulas:{},i=Fo((Array.isArray(e.items)?e.items:[]).map(E=>E&&typeof E.source=="string"&&typeof o[E.source]=="string"&&o[E.source].trim()?{...E,expr:o[E.source],fromWire:E.source}:E));if(i.length>V.items)throw new RangeError(`a plot has at most ${V.items} curves`);let a=Math.min(V.points,Math.max(2,Math.round(Number(e.points)||600))),c=Math.min(2,Math.max(0,e.pad===void 0?.5:Number(e.pad))),u=Date.now()+Math.min(V.deadlineMs,Math.max(1,Number(e.deadlineMs)||V.deadlineDefaultMs)),l=Gc(e),f=Wc(i,Object.keys(l)),h=Xc(f,{...e.wired},e.sliders),m={...h.params};for(let[E,P]of Object.entries(e.params??{}))typeof P=="number"&&Number.isFinite(P)&&(m[E]=P);let p=hi(m,l),y=V.evaluations,d=()=>{if(--y<0)throw new He(`stopped after ${V.evaluations} evaluations`)},w=E=>P=>(d(),E(P)),g=()=>n()||Date.now()>u,M=()=>Date.now()>u,v;if(e.slice!==void 0&&e.slice!==null){let E=e.slice;if(!E||typeof E!="object"||E.axis!=="x"&&E.axis!=="y"&&E.axis!=="z"||typeof E.at!="number"||!Number.isFinite(E.at))throw new TypeError("slice is { axis: x, y or z, at: a number }");v={axis:E.axis,at:E.at}}let N={viewport:s,pad:c,params:m,aliases:l,aliasedParams:p,spend:d,cancelled:n,timeUp:M,slice:v,deadline:u,gpu:e.gpu===!1?null:qc()},$=(E,P,j)=>w(mr(ge(qt(E,P),l),{variable:Bc(j,l),params:p,...Et})),b={key:t,gen:r,viewport:s,free:f,bound:h.bound,unbound:h.unbound,params:m,items:[],features:[]},x=e.features!==!1,S=[],O=new Map,A=e.angle==="deg";for(let E of i){let P=A?Mo(E):E;if(n())return{key:t,gen:r,stale:!0};if(await Je(),n())return{key:t,gen:r,stale:!0};let j=String(P?.id??b.items.length),L=P?.kind??"y",U={id:j,kind:L,x:new Float64Array(0),y:new Float64Array(0)};b.items.push(U),P?.hidden&&(U.hidden=!0),P?.fromWire&&(U.fromWire=String(P.fromWire)),P?.xform?.of!==void 0&&(U.of=String(P.xform.of)),Object.assign(U,Qc(E,L,l));try{if(!Qn.includes(L))throw new Error(`unknown kind "${L}": use ${Qn.join(", ")}`);if(P.error)throw new Error(P.error);let J=Tc[L],Bt=L==="param"?[P.expr,P.expr2]:[P.expr];if(_n.includes(L)){if(await Je(),n())return{key:t,gen:r,stale:!0};Object.assign(U,cu(L,P,{...N,stop:g,deadline:u,budget:e.budget3}));continue}if(Pe.includes(L)){if(await Je(),n())return{key:t,gen:r,stale:!0};Object.assign(U,Vo(L,P,{...N,stop:g,deadline:u,points:a,compile:$},fu));continue}if(L==="complex"){if(await Je(),n())return{key:t,gen:r,stale:!0};Object.assign(U,au(P,{...N,deadline:u}));continue}Bt.forEach((mt,Xt)=>qt(mt,L==="param"?["x(t)","y(t)"][Xt]:L==="polar"?"r(theta)":L==="implicit"?"F(x, y)":Qr.includes(L)?"f(x, y)":L==="finite"?"f(k)":"f(x)"));let Pt=g;if(L==="y"){let mt=$(P.expr,"f(x)","x"),Xt=s.xMax-s.xMin,Gt={min:s.xMin-c*Xt,max:s.xMax+c*Xt},Jt=Math.min(V.points,Math.round(a*(1+2*c))),ut=ye(mt,Gt,Jt,{visibleYRange:{min:s.yMin,max:s.yMax},isCancelled:Pt});if(U.x=ut.x,U.y=ut.y,O.set(j,{f:mt,domain:Gt,text:P.expr,samples:ut}),x&&!P.hidden){if(await Je(),n())return{key:t,gen:r,stale:!0};for(let Nt of er(mt,Gt,{resolution:Math.min(a,1e3),isCancelled:Pt}).slice(0,V.features))b.features.push({item:j,kind:"root",x:Nt,y:0});for(let Nt of mi(mt,ut,V.features,g))b.features.push({item:j,...Nt});S.push({id:j,f:mt,domain:Gt})}}else if(Qr.includes(L))Object.assign(U,await nu(L,P,N));else if(L==="finite")Object.assign(U,lu(P,N));else{let mt=zt(P.min,"min",0,m,l),Xt=zt(P.max,"max",2*Math.PI,m,l);if(!(mt<Xt))throw new RangeError("min must be less than max");let Gt={min:mt,max:Xt},Jt=$(P.expr,L==="param"?"x(t)":"r(theta)",J),ut=wr(Jt,Gt,a,{isCancelled:Pt});if(L==="param"){let Nt=wr($(P.expr2,"y(t)",J),Gt,a,{isCancelled:Pt});Object.assign(U,si(ut.y,Nt.y))}else{let Nt=new Float64Array(a),Ee=new Float64Array(a);for(let re=0;re<a;re++)Nt[re]=ut.y[re]*Math.cos(ut.x[re]),Ee[re]=ut.y[re]*Math.sin(ut.x[re]);Object.assign(U,si(Nt,Ee))}}}catch(J){if(J instanceof wt){if(n())return{key:t,gen:r,stale:!0};U.error="stopped: it took longer than its time limit"}else U.error=J?.message??String(J);U.x=new Float64Array(0),U.y=new Float64Array(0)}}for(let E=0;E<Math.min(S.length,8)&&x;E++)for(let P=E+1;P<Math.min(S.length,8);P++){if(n())return{key:t,gen:r,stale:!0};try{for(let j of rr(S[E].f,S[P].f,S[E].domain,{resolution:Math.min(a,1e3),isCancelled:g}).slice(0,V.features))b.features.push({item:`${S[E].id},${S[P].id}`,kind:"intersection",x:j.x,y:j.y})}catch(j){if(!(j instanceof wt))throw j;if(n())return{key:t,gen:r,stale:!0}}}b.overlays=[];let F=e.exact===!0,k=Array.isArray(e.overlays)?e.overlays:[];if(k.length>V.overlays)throw new RangeError(`a plot has at most ${V.overlays} overlays`);for(let E of k){if(n())return{key:t,gen:r,stale:!0};await Je(),b.overlays.push(pu(E,{compiled:O,viewport:s,params:m,aliases:l,aliasedParams:p,metered:w,stop:g,points:a,cancelled:n,exact:F}))}b.pins=[];let I=Array.isArray(e.pins)?e.pins:[];if(I.length>V.pins)throw new RangeError(`a plot has at most ${V.pins} points on curves`);for(let E of I)b.pins.push(du(E,{compiled:O,aliases:l,aliasedParams:p,metered:w,stop:g,exact:F}));return b.annotations=ko(e.annotations,{items:b.items,pins:b.pins}),n()?{key:t,gen:r,stale:!0}:b}function Jn(e){let t=/^(-?)(\d+)(?:\.(\d+))?(?:e([+-]?\d+))?$/.exec(String(e));if(!t||!Number.isFinite(e))throw new Error("only a finite number has an exact value");let r=t[3]??"",n=BigInt(t[2]+r),s=10n**BigInt(r.length),o=Number(t[4]??0);if(Math.abs(o)>300)throw new Error("the number is too large or too small to be exact");return o>0?n*=10n**BigInt(o):s*=10n**BigInt(-o),new st(t[1]?-n:n,s)}function yr(e){if(Array.isArray(e))return void e.forEach(yr);if(!(e===null||typeof e!="object")){if(e.type==="const"){let t=Number(e.value);if(!Number.isFinite(t)||st.fromNumber(t).toNumber()!==t)throw new Error(`the constant ${String(e.value).slice(0,20)} (pi, e or a very small or long number) is not a fraction, so it has no exact value`)}for(let t of Object.values(e))yr(t)}}function Jr(e,t,r){yr(e);let n={};for(let[s,o]of Object.entries({...r.aliasedParams,...t}))n[s]=typeof o=="number"?Jn(o):o;return C.evaluateExact(e,n)}function li(e,t){let r=e.toNumber();return Number.isFinite(t)?Math.abs(r-t)<=1e-9*Math.max(1,Math.abs(t)):!1}var xr=e=>String(e?.message??e).replace(/^Error:\s*/,"");function hu(e,t,r,n,s){try{let o=ge(qt(e.text,"f(x)"),s.aliases),i=C.parse(o,Et),a=Jr(i,{x:t},s);if(!li(a,r))throw new Error("the exact value differs from the float one: a constant is not a fraction");let c={y:a.toString()};if(Number.isFinite(n)){let u=Jr(C.simplify(C.differentiate(i,"x")),{x:t},s);li(u,n)?c.slope=u.toString():c.slopeError="the exact slope differs from the float one"}return{exact:c}}catch(o){return{exactError:xr(o)}}}function mu(e,t,r,n,s){let o=(i,a,c)=>{if(i===void 0||i===""){if(c!==void 0&&!r)return Jn(c);throw new Error(`the ${a} bound is found numerically (where the curves meet): give from and to as numbers or fractions for an exact area`)}try{if(typeof i=="number")return Jn(i);let u=C.parse(ge(qt(String(i),a),s.aliases),Et);return yr(u),C.evaluateExact(u,{})}catch(u){throw new Error(`bound ${a} (${String(i).slice(0,40)}) is not exact: ${xr(u)}`)}};try{let i=o(e.from,"from",n.xMin),a=o(e.to,"to",n.xMax),c=h=>`(${ge(qt(h.text,"f(x)"),s.aliases)})`,u=C.parse(r?`${c(t)} - ${c(r)}`:c(t),Et);yr(u);let l=C.integrate(u,"x"),f=Jr(l,{x:a},s).subtract(Jr(l,{x:i},s));return{exact:{area:f.toString(),from:i.toString(),to:a.toString()},value:f.toNumber()}}catch(i){return{exactError:xr(i)}}}function pu(e,t){let{compiled:r,viewport:n,params:s,aliases:o,aliasedParams:i,metered:a,stop:c,cancelled:u}=t,l=String(e?.id??""),f=e?.kind,h={id:l,kind:f,curve:e?.curve};try{if(!ri.includes(f))throw new Error(`unknown overlay "${f}": use ${ri.join(", ")}`);let m=(y,d)=>{let w=r.get(String(y));if(!w)throw new Error(`${d} "${y}" is not a y = f(x) curve of this plot (an overlay sits on a formula that parses)`);return w},p=m(e.curve,"curve");if(f==="inequality"){if(!ni.includes(e.op))throw new Error(`op is one of ${ni.join(" ")}: y > f(x) shades above the curve`);h.op=e.op}else if(f==="roots"||f==="extrema"||f==="intersections"){let y=c;if(f==="roots")h.points=er(p.f,p.domain,{resolution:1e3,isCancelled:y}).slice(0,V.features).map(d=>({x:d,y:0,kind:"root"}));else if(f==="extrema")h.points=mi(p.f,p.samples,V.features,c);else{if(e.curve2===void 0||e.curve2==="")throw new Error("an intersections overlay needs a curve2: the curve to meet");let d=m(e.curve2,"curve2");h.curve2=String(e.curve2),h.points=rr(p.f,d.f,p.domain,{resolution:1e3,isCancelled:y}).slice(0,V.features).map(w=>({x:w.x,y:w.y,kind:"intersection"}))}}else if(f==="integral"||f==="difference"){let y=f==="integral"?_c(p.samples):Kc(p.samples);h.x=y.x,h.y=y.y}else if(f==="derivative"){let y=ge(qt(p.text,"f(x)"),o),d=C.toString(C.simplify(C.differentiate(C.parse(y,Et),"x"))),w=a(mr(d,{variable:"x",params:i,...Et})),g=ye(w,p.domain,Math.min(V.points,t.points),{visibleYRange:{min:n.yMin,max:n.yMax},isCancelled:c}),M=Hn(o);h.expr=d.replace(/\bq_[0-9t]\b/g,M);let v=N=>_r(N,M);if(h.latex=C.toLatex(v(C.simplify(C.differentiate(C.parse(y,Et),"x")))),e.steps){let{steps:N}=C.differentiateSteps(C.parse(y,Et),"x");h.steps=N.slice(0,V.steps).map($=>{let b=v($.input),x=v($.output);return{rule:String($.rule),input:C.toString(b),output:C.toString(x),inputLatex:C.toLatex(b),outputLatex:C.toLatex(x)}}),N.length>V.steps&&(h.stepsCut=!0)}h.x=g.x,h.y=g.y}else{let y=e.curve2===void 0||e.curve2===""?null:m(e.curve2,"curve2");y&&(h.curve2=String(e.curve2));let d,w;if(e.from===void 0||e.from===""||e.to===void 0||e.to===""){if(y){let x=rr(p.f,y.f,p.domain,{resolution:1e3,isCancelled:c}).map(S=>S.x).filter(S=>S>=n.xMin&&S<=n.xMax).sort((S,O)=>S-O);if(x.length<2)throw new Error("the curves meet fewer than twice in the window: give from and to, or zoom out");[d,w]=[x[0],x.at(-1)]}else[d,w]=[n.xMin,n.xMax];e.from!==void 0&&e.from!==""&&(d=zt(e.from,"from",d,s,o)),e.to!==void 0&&e.to!==""&&(w=zt(e.to,"to",w,s,o))}else d=zt(e.from,"from",0,s,o),w=zt(e.to,"to",0,s,o);if(!(d<w))throw new RangeError("from must be less than to");let g=x=>p.f(x)-(y?y.f(x):0),M=V.integration,v=(w-d)/M,N=0,$=0;for(let x=0;x<=M;x++){let S=d+x*v,O=g(S);if(!Number.isFinite(O))throw new RangeError(`the region is not finite at x = ${Math.round(S*1e6)/1e6}: choose bounds inside the curve's domain`);let A=x===0||x===M?1:x%2?4:2;if(N+=A*O,$+=A*Math.abs(O),x%256===0&&u())throw new wt}let b=Math.max(2,Math.min(V.overlayPoints,t.points));if(h.from=d,h.to=w,h.area=N*v/3,h.absolute=$*v/3,t.exact){let x=mu(e,p,y,n,t);x.exact&&Math.abs(x.value-h.area)>1e-6*Math.max(1,Math.abs(h.area))?Object.assign(h,{exactError:"the exact area differs from the numeric one: a constant is not a fraction"}):x.exact?h.exact=x.exact:h.exactError=x.exactError}h.x=new Float64Array(b),h.top=new Float64Array(b),h.bottom=new Float64Array(b);for(let x=0;x<b;x++){let S=d+(w-d)*x/(b-1);h.x[x]=S,h.top[x]=p.f(S),h.bottom[x]=y?y.f(S):0}}}catch(m){if(m instanceof wt&&u())return{id:l,kind:f,curve:h.curve,error:"stopped"};h.error=m instanceof wt?"stopped: it took longer than its time limit":m?.message??String(m);for(let p of["x","y","top","bottom"])delete h[p]}return h}function du(e,t){let n={id:String(e?.id??""),curve:e?.curve,x:Number(e?.x)};try{if(!Number.isFinite(n.x))throw new Error("x must be a finite number");let s=t.compiled.get(String(e.curve));if(!s)throw new Error(`curve "${e.curve}" is not a y = f(x) curve of this plot (a point sits on a formula that parses)`);let o=s.f(n.x);if(!Number.isFinite(o))throw new Error(`the curve is not finite at x = ${Math.round(n.x*1e6)/1e6}: move the point`);n.y=o,n.slope=gu(s,n.x,t),t.exact&&Object.assign(n,hu(s,n.x,n.y,n.slope,t))}catch(s){n.error=s?.message??String(s),delete n.y,delete n.slope}return n}function gu(e,t,r){if(e.slope===void 0)try{let i=ge(qt(e.text,"f(x)"),r.aliases);e.slope=r.metered(mr(C.toString(C.simplify(C.differentiate(C.parse(i,Et),"x"))),{variable:"x",params:r.aliasedParams,...Et}))}catch{e.slope=null}let n=e.slope?e.slope(t):Number.NaN;if(Number.isFinite(n))return n;let s=1e-6*Math.max(1,Math.abs(t)),o=(e.f(t+s)-e.f(t-s))/(2*s);return Number.isFinite(o)?o:Number.NaN}function xf(e){let t=new Set;for(let r of[...e?.items??[],...e?.overlays??[]]){let n=r.mesh,s=r.curve3,o=r.field3,i=r.complex;for(let a of[r.x,r.y,r.z,r.u,r.v,r.top,r.bottom,r.slice?.x,r.slice?.y,n?.arg,n?.mag,i?.raster?.abs,i?.raster?.arg,...(i?.conformal??[]).flatMap(c=>[c.x,c.y]),n?.positions,n?.normals,n?.indices,n?.valid,s?.positions,s?.t,o?.origins,o?.vectors,o?.magnitudes,...Uo(r)])a?.buffer instanceof ArrayBuffer&&a.byteLength&&t.add(a.buffer)}return[...t]}export{Zc as DEFAULT_SLIDER,Qr as GRID_KINDS,Et as IMPLICIT,ni as INEQUALITIES,Qn as KINDS,_n as KINDS_3D,Pe as KINDS_CALC,V as LIMITS,ri as OVERLAY_KINDS,fi as OWN_VARIABLES,He as PlotLimitError,Tc as VARIABLE,br as aliasesFor,Xc as bindVariables,df as cancel,es as complexText,Wc as freeOf,Dc as freeVariables,ts as gridText,pf as latestGeneration,gf as meshesOf,ou as orientOutward,Jn as rationalOf,_r as renameVariables,yf as run,tr as spelled,xf as transferList,Hn as unalias};