@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,45 @@
1
+ /*! mallory exact math: src/exact/source.js with @johnhenry/math@0.3.0 (MIT), bundled into one ES module by scripts/build-exact-vendor.mjs. Do not edit. */
2
+ var R=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 n=new e;for(let r of t)n.push(r);return n}static fromXML(t){let n=new e;for(let r of t.matchAll(/<coordinate>(.*?)<\/coordinate>/g)){let s=r[1],o=Number(s);n.push(s!==""&&!Number.isNaN(o)?o:s)}return n}static fromString(t,n=",",r="[",s="]"){let o=t.trim();o.startsWith(r)&&(o=o.slice(r.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(n)){let c=a.trim(),l=Number(c);i.push(c!==""&&!Number.isNaN(l)?l:c)}return i}toString(t=",",n="[",r="]"){let s=n;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+r}toXML(){let t=[];for(let n=0;n<this.length;n++)t.push(`<coordinate>${this[n]}</coordinate>`);return`<vector>${t.join("")}</vector>`}getElement(t=0){return this[t]}removeElement(t=0){return this.splice(t,1)[0]}setElement(t,n=0,r=null){for(;this.length<n;)this.push(r);let s=this[n];return this[n]=t,s}addElement(t=null,n=-1,r=null){if(n<0)return this.push(t);for(;n>this.length;)this.push(r);return this.splice(n,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 n=new e;for(let r=0;r<this.length;r++){let s=this[r];n[r]=t&&s instanceof e?s.clone():s}return n}reversed(){let t=new e;for(let n=0;n<this.length;n++)t[n]=this[this.length-1-n];return t}};var z=class e{static isVector(t){return t instanceof R}static isNotVector(t){return!(t instanceof R)}static isMultiDimensional(t,n=e.isVector){for(let r of t)if(n(r))return!0;return!1}static contains(t,n,r){if(!r)return t.lastIndexOf(n)!==-1;for(let s of t)if(r(n,s))return!0;return!1}static longer(t,n){return t.length>=n.length?t:n}static shorter(t,n){return t.length>=n.length?n:t}static isNotMultiDimensional(t,n){return!e.isMultiDimensional(t,n??e.isVector)}static isFlat(t,n){return e.isNotMultiDimensional(t,n)}static arithmeticSequence(t=0,n=100,r=1){let s=new R,o=t;if(r>0)for(n<o&&(n=o);o<=n;)s.push(o),o+=r;else if(r<0)for(n>o&&(n=o);o>=n;)s.push(o),o+=r;else s.push(o);return s}static arithmeticBounds(t,n,r){return e.arithmeticSequence(t,n,(n-t)/r)}static geometricSequence(t=1,n=1e3,r=2){let s=new R,o=t;if(Math.abs(r)>1)for(Math.abs(n)<Math.abs(o)&&(n=o);o<=Math.abs(n);)s.push(o),o*=r;else if(Math.abs(r)<1&&r!==0)for(Math.abs(n)<Math.abs(o)&&(n=o);o>=Math.abs(n);)s.push(o),o*=r;else s.push(o);return s}static constantVector(t=1,n){let r=new R;for(let s=0;s<t;s++)r.push(n);return r}static fromArray(t){return R.fromArray(t)}static merge(t=null,n=null){if(t instanceof R&&n instanceof R)return R.fromArray([...t,...n]);if(t instanceof R){let r=t.clone();return r.push(n),r}if(n instanceof R){let r=n.clone();return r.addElement(t,0),r}return R.fromArray([t,n])}static recursiveSequence(t,n,r,s=!1){let o=R.fromArray(t);if(s)for(;!r(o);)o.push(n(o));else{let i=[...t];for(;!r(i);)o.push(n(i)),i.shift(),i.push(o[o.length-1])}return o}static wrap(t,n=1){if(n===0)return t;let r=new R;return r.push(t),e.wrap(r,n-1)}static fromOEIS(t=1){let n;switch(t){case 1:n="1,2,3";break;case 2:n="4,5,6";break;case 3:n="7,8,9";break;default:n="0,0,0"}return e.transform(R.fromArray(n.split(",")),r=>parseInt(r,10))}static fillByIndex(t,n){let r=new R(t.length);for(let s=0;s<r.length;s++)r[s]=n(s);return r}static transform(t,n){let r=new R;for(let s of t)r.push(n(s));return r}static replace(t,n){let r=new R;for(let s=0;s<t.length;s++)r.push(n);return r}static transformEndNodes(t,n,r=e.isNotVector){let s=t.clone();for(let o=0;o<s.length;o++){let i=s[o];r(i)||!(i instanceof R)?s[o]=n(i):s[o]=e.transformEndNodes(i,n,r)}return s}static replaceEndNodes(t,n,r=e.isNotVector){let s=t.clone();for(let o=0;o<s.length;o++){let i=s[o];r(i)||!(i instanceof R)?s[o]=n:s[o]=e.replaceEndNodes(i,n,r)}return s}static trim(t,n=0,r=0){let s=t.clone();return s.splice(t.length-r,r),s.splice(0,n),s}static removeElements(t,...n){let r=t.clone();for(let s=0;s<r.length;s++)n.includes(r[s])&&(r.removeElement(s),s--);return r}static filter(t,n){let r=new R;for(let s of t)n(s)&&r.push(s);return r}static modes(t){let n=new R;if(t.length===0)return n;let r=new Map,s=[];for(let i of t){let a=r.get(i);a===void 0?(r.set(i,1),s.push(i)):r.set(i,a+1)}let o=0;for(let i of s){let a=r.get(i);a>o&&(o=a)}for(let i of s)r.get(i)===o&&n.push(i);return n}static flatten(t){let n=new R,r=s=>{for(let o of s)o instanceof R?r(o):n.push(o)};return r(t),n}static flattenSD(t){if(t.length===0)return new R;if(!(t[0]instanceof R))return t.clone();let n=new R;for(let r of t)if(r instanceof R)for(let s of r)n.push(s);else n.push(r);return n}static flattenSDLevels(t,n=0){let r=t.clone(),s=n>0?n:e.nestedDepthSD(t);for(let o=0;o<s;o++)r=e.flattenSD(r);return r}static fractal(t){return e.replaceEndNodes(t,t.clone())}static fractalLevels(t,n=0){let r=t.clone();for(let s=0;s<n;s++)r=e.fractal(r);return r}static insert(t,n,r=-1){r<0&&(r=t.length);let s=t.clone();for(let o=0;o<n.length;o++)s.splice(r+o,0,n[o]);return s}static combine(t,n,r,s){let o=Math.max(t.length,n.length),i=new R(o);for(let a=0;a<o;a++){let c=a<t.length,l=a<n.length;c&&l?i[a]=r(t[a],n[a]):c?i[a]=s!==void 0?s:t[a]:i[a]=s!==void 0?s:n[a]}return i}static length(t){return t.length}static collapse(t,n,r=null){let s=t.clone();if(s.length===0)return r;let o=s[0];for(let i=1;i<s.length;i++)o=n(o,s[i]);return o}static matches(t,n){let r=0;for(let s of t)n(s)&&r++;return r}static count(t,n){return e.matches(t,r=>r===n)}static consecutiveMatches(t,n){let r=[0];for(let s of t)n(s)?r[r.length-1]++:r[r.length-1]!==0&&r.push(0);return r.length>1&&r[r.length-1]===0&&r.pop(),r}static nestedDepthSD(t,n=0){return t[0]instanceof R?e.nestedDepthSD(t[0],n+1):n}static RowSeperator=",\r";static isMatrix(t){if(!(t[0]instanceof R))return!1;let n=t[0].length;for(let r of t)if(!(r instanceof R)||r.length!==n)return!1;return!0}static width(t){return t[0].length}static height(t){return t.length}static constantMatrix(t=1,n=1,r){let s=new R;for(let o=0;o<t;o++){let i=new R;for(let a=0;a<n;a++)i.push(r);s.push(i)}return s}static generateIdentity(t=1,n=1,r,s){let o=e.constantMatrix(t,n,s);return e.fillMatrixByIndex(o,(i,a)=>i===a?r:s)}static vectorToMatrixRow(t){let n=new R;return n.push(t),n}static vectorToMatrixColumn(t){return e.transpose(e.vectorToMatrixRow(t))}static fillMatrixByIndex(t,n){let r=t.clone();for(let s=0;s<e.height(r);s++)for(let o=0;o<e.width(r);o++)r[s][o]=n(s,o);return r}static replaceMatrix(t,n){let r=t.clone();for(let s=0;s<e.height(r);s++)for(let o=0;o<e.width(r);o++)r[s][o]=n;return r}static transpose(t){let n=new R;for(let r=0;r<e.width(t);r++)n.push(new R(e.height(t)));for(let r=0;r<e.height(t);r++)for(let s=0;s<e.width(t);s++)n[s][r]=t[r][s];return n}static getRow(t,n=0){return e.wrap(t[n])}static getColumn(t,n=0){return e.transpose(e.getRow(e.transpose(t),n))}static rowRemoved(t,n=0){let r=t.clone();return r.removeElement(n),r}static columnRemoved(t,n=0){return e.transpose(e.rowRemoved(e.transpose(t),n))}static rowInserted(t,n,r=-1){return e.insert(t,e.wrap(n),r)}static columnInserted(t,n,r=-1){return e.transpose(e.rowInserted(e.transpose(t),n,r))}static mergeRows(t,n){return e.merge(t,n)}static mergeColumns(t,n){return e.transpose(e.mergeRows(e.transpose(t),e.transpose(n)))}static rowSet(t,n,r=0){let s=t.clone();return s.setElement(n,r),s}static columnSet(t,n,r=0){return e.transpose(e.rowSet(e.transpose(t),n,r))}static placeBlock(t,n,r,s){let o=t.clone();for(let i=0;i<e.height(n);i++)for(let a=0;a<e.width(n);a++){let c=o[r+i];c&&c.length>s+a&&(c[s+a]=n[i][a])}return o}static breakBlock(t){let n=0,r=0,s=e.height(t),o=e.width(t);for(let u=0;u<s;u++)n+=e.height(t[u][0]);for(let u=0;u<o;u++)r+=e.width(t[0][u]);let i=e.constantMatrix(n,r,null),a=0,c=0,l=t[0][0];for(;a<n;)for(let u=0;u<s;u++){for(let h=0;h<o;h++){l=t[u][h];for(let f=0;f<e.height(l);f++)for(let m=0;m<e.width(l);m++)i[a+f][c+m]=l[f][m];c+=e.width(l)}c=0,a+=e.height(l)}return i}static pad(t,n=null,r=!0,s=!0,o=!0,i=!0,a=!0,c=!0){let l=t.clone(),u;if(r){let h=1;for(;h<e.height(l);)u=e.constantVector(e.width(l),n),l=e.rowInserted(l,u,h),h+=2}if(s){let h=1;for(;h<e.width(l);)u=e.constantVector(e.height(l),n),l=e.columnInserted(l,u,h),h+=2}return o&&(l=e.rowInserted(l,e.constantVector(e.width(l),n),0)),i&&(l=e.rowInserted(l,e.constantVector(e.width(l),n),-1)),a&&(l=e.columnInserted(l,e.constantVector(e.height(l),n),0)),c&&(l=e.columnInserted(l,e.constantVector(e.height(l),n),-1)),l}static diagonal(t,n=0){let r=new R;if(n>=0)for(let s=0;s<e.width(t)-n;s++)r.push(t[s][s+n]);else{let s=-n;for(let o=0;o<e.height(t)-s;o++)r.push(t[o+s][o])}return r}static minorDiagonal(t,n=0){let r=new R;if(n>=0)for(let s=0;s<e.width(t)-n;s++)r.push(t[s][e.width(t)-s-1-n]);else{let s=-n;for(let o=0;o<e.height(t)-s;o++)r.push(t[o+s][e.width(t)-o-1])}return r}static matrixString(t,n=0,r=0,s=",",o="[",i="]",a=",",c="[",l="]"){let u=[],h=n;for(let p=0;p<e.height(t);p++){let d=[];for(let x=0;x<e.width(t);x++){let g=t[p][x],w=g==null?"null":String(g);d.push(w),n>0&&h<w.length&&(h=w.length)}u.push(d)}if(n>0)for(let p of u)for(let d=0;d<p.length;d++){let x=p[d];if(r!==0){let g=Math.ceil((h-x.length)/2),w=Math.floor((h-x.length)/2);r<0&&([g,w]=[w,g]),p[d]=" ".repeat(g)+x+" ".repeat(w)}else p[d]=" ".repeat(h-x.length)+x}let f=u.map(p=>o+p.join(s)+i),m=`${a}\r${" ".repeat(c.length)}`;return c+f.join(m)+l}};function ls(e=1){return _t(e)}function fn(e){return ls(.5*(Math.exp(e)-Math.exp(-e)))}function mn(e){return ls(.5*(Math.exp(e)+Math.exp(-e)))}function _t(e,t=10){if(!Number.isFinite(e))return e;let n=10**t;return Math.round(e*n)/n}function ve(e){return e instanceof ht?e:new ht(e)}function ur(e,t=10){return new ht(_t(e.value,t),_t(e.iValue,t))}var ht=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,n=0){if(t instanceof e)this.value=t.value,this.iValue=t.iValue;else if(typeof t=="string"){let r=e.parse(t);this.value=r.value,this.iValue=r.iValue}else this.value=t,this.iValue=n}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 n=e.from(t);return Number.isNaN(n.value)||Number.isNaN(n.iValue)}static isComplex(t){let n=e.from(t);return!Number.isNaN(n.value)&&!Number.isNaN(n.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,n){return new e(t*Math.cos(n),t*Math.sin(n))}static fromVector(t){return new e(t[0]??0,t[1]??0)}static fromXML(t){let n=/<value>(.*?)<\/value>/.exec(t),r=/<iValue>(.*?)<\/iValue>/.exec(t);return new e(n?Number(n[1]):NaN,r?Number(r[1]):NaN)}static parse(t){let n=t.replace(/\s+/g,"").replace(/\*i/g,"i");if(n.length===0)return new e(NaN,NaN);if(!n.includes("i")){let l=Number(n);return Number.isNaN(l)?new e(NaN,NaN):new e(l,0)}if(!n.endsWith("i"))return new e(NaN,NaN);let r=n.slice(0,-1),s=-1;for(let l=1;l<r.length;l++){let u=r[l],h=r[l-1];(u==="+"||u==="-")&&h!=="e"&&h!=="E"&&(s=l)}let o,i;s===-1?(o="",i=r):(o=r.slice(0,s),i=r.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,n=0,r=1,s=0,o=!0){let i=Math.min(t,n),a=Math.max(t,n),c=Math.min(r,s),l=Math.max(r,s);return new e(i+Math.random()*(a-i),c+Math.random()*(l-c))}toXML(){return`<complexNumber><value>${this.value}</value><iValue>${this.iValue}</iValue></complexNumber>`}toVector(){return R.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 n=Math.abs(this.iValue),r=n===1?"i":`${n}*i`;return this.value===0?this.iValue<0?`-${r}`:r:`${this.value}${this.iValue<0?"-":"+"}${r}`}neg(){return new e(-this.value,-this.iValue)}reciprocal(){let{value:t,iValue:n}=this;if(t===0&&n===0)return new e(NaN,NaN);let r=t*t+n*n;return new e(t/r,-n/r)}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 n=ve(t);return this.value>n.value?1:this.value<n.value?-1:this.iValue>n.iValue?1:this.iValue<n.iValue?-1:0}magCompare(t){let n=this.magnitude(),r=ve(t).magnitude();return n>r?1:n<r?-1:0}add(t=0){let n=ve(t);return new e(this.value+n.value,this.iValue+n.iValue)}subtract(t=0){let n=ve(t);return new e(this.value-n.value,this.iValue-n.iValue)}multiply(t=1){let n=ve(t);return new e(this.value*n.value-this.iValue*n.iValue,this.value*n.iValue+this.iValue*n.value)}divide(t=1){let n=ve(t);return n.value===0&&n.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(n.reciprocal())}magnitude(){return Math.hypot(this.value,this.iValue)}angle(){return Math.atan2(this.iValue,this.value)}static power2(t,n){if(t.value===0&&t.iValue===0&&!(n.value===0&&n.iValue===0))return new e(0,0);let r=t.magnitude(),s=t.angle(),o=n.value,i=n.iValue,a=r**o/Math.E**(i*s),c=a*Math.cos(i*Math.log(r)+o*s),l=a*Math.sin(i*Math.log(r)+o*s);return ur(new e(c,l))}selectedNaturalLogarithm(t=0){let n=this.magnitude(),r=this.angle();return ur(new e(Math.log(n),r+2*Math.PI*t))}power(t=1,n=0){let r=ve(t);if(this.value===0&&this.iValue===0)return r.value===0&&r.iValue===0?new e(1,0):r.value>0?new e(0,0):e.NaCN;let s=r.multiply(this.selectedNaturalLogarithm(n));return e.power2(e.E,s)}square(){return this.power(2)}squareRoot(){return this.power(.5)}logarithm(t=Math.E,n=0,r=0){let s=ve(t);return ur(this.selectedNaturalLogarithm(n).divide(s.selectedNaturalLogarithm(r)))}sine(){return new e(_t(Math.sin(this.value)*mn(this.iValue)),_t(Math.cos(this.value)*fn(this.iValue)))}cosine(){return new e(_t(Math.cos(this.value)*mn(this.iValue)),_t(-Math.sin(this.value)*fn(this.iValue)))}tangent(){return this.sine().divide(this.cosine())}hyperbolicSine(){return new e(_t(fn(this.value)*Math.cos(this.iValue)),_t(mn(this.value)*Math.sin(this.iValue)))}hyperbolicCosine(){return new e(_t(mn(this.value)*Math.cos(this.iValue)),_t(fn(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),n=new e(1,0).subtract(t).logarithm(),r=new e(1,0).add(t).logarithm();return e.I.divide(2).multiply(n.subtract(r))}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),n=new e(1,0).subtract(this);return t.divide(n).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 rt=e=>typeof e=="bigint"?e:BigInt(e),Ze=e=>e<0n?-e:e;function hr(e,t){let n=Ze(e),r=Ze(t);for(;r;)[n,r]=[r,n%r];return n}var Di=[2n,3n,5n,7n,11n,13n,17n,19n,23n,29n,31n,37n],Ft=class e{static modPow(t,n,r){let s=rt(r);if(s===1n)return 0n;let o=(rt(t)%s+s)%s,i=rt(n),a=1n;for(;i>0n;)i&1n&&(a=a*o%s),o=o*o%s,i>>=1n;return a}static extendedGcd(t,n){let[r,s]=[rt(t),rt(n)],[o,i]=[1n,0n],[a,c]=[0n,1n];for(;s!==0n;){let l=r/s;[r,s]=[s,r-l*s],[o,i]=[i,o-l*i],[a,c]=[c,a-l*c]}return r<0n?{g:-r,x:-o,y:-a}:{g:r,x:o,y:a}}static modInverse(t,n){let r=rt(n),{g:s,x:o}=e.extendedGcd((rt(t)%r+r)%r,r);return s!==1n?null:(o%r+r)%r}static mod(t,n){let r=rt(n);if(r===0n)throw new RangeError("NumberTheory.mod: modulus must be non-zero");return(rt(t)%r+r)%r}static gcd(t,n){return hr(rt(t),rt(n))}static lcm(t,n){let r=rt(t),s=rt(n);return r===0n||s===0n?0n:Ze(r*s)/hr(r,s)}static lcmList(t){return t.reduce((n,r)=>e.lcm(n,rt(r)),1n)}static crt(t,n){let r=0n,s=1n;for(let o=0;o<t.length;o++){let i=(rt(t[o])%rt(n[o])+rt(n[o]))%rt(n[o]),a=rt(n[o]),c=e.modInverse(s,a);if(c===null)return null;let l=((i-r)*c%a+a)%a;r+=s*l,s*=a,r=(r%s+s)%s}return{x:r,modulus:s}}static isProbablePrime(t){let n=rt(t);if(n<2n)return!1;for(let o of[2n,3n,5n,7n,11n,13n,17n,19n,23n,29n,31n,37n]){if(n===o)return!0;if(n%o===0n)return!1}let r=n-1n,s=0n;for(;(r&1n)===0n;)r>>=1n,s++;t:for(let o of Di){if(o>=n)continue;let i=e.modPow(o,r,n);if(!(i===1n||i===n-1n)){for(let a=0n;a<s-1n;a++)if(i=i*i%n,i===n-1n)continue t;return!1}}return!0}static nextPrime(t){let n=rt(t)+1n;for(;!e.isProbablePrime(n);)n++;return n}static pollardRho(t){let n=rt(t);if(n<=1n)throw new RangeError("NumberTheory.pollardRho: n must be greater than 1");if(n%2n===0n)return 2n;for(let r=1n;;r++){let s=2n,o=2n,i=1n,a=c=>(c*c+r)%n;for(;i===1n;)s=a(s),o=a(a(o)),i=hr(Ze(s-o),n);if(i!==n)return i}}static factorize(t){let n=Ze(rt(t));if(n===0n)throw new RangeError("NumberTheory.factorize: n must be non-zero");let r=new Map,s=i=>r.set(i,(r.get(i)??0)+1);for(let i of[2n,3n,5n,7n,11n,13n])for(;n%i===0n;)s(i),n/=i;let o=n>1n?[n]:[];for(;o.length;){let i=o.pop();if(i===1n)continue;if(e.isProbablePrime(i)){s(i);continue}let a=e.pollardRho(i);o.push(a,i/a)}return[...r.entries()].sort((i,a)=>i[0]<a[0]?-1:i[0]>a[0]?1:0)}static eulerPhi(t){let n=Ze(rt(t));for(let[r]of e.factorize(t))n=n/r*(r-1n);return n}static legendreSymbol(t,n){let r=rt(n),s=e.modPow(t,(r-1n)/2n,r);return s===r-1n?-1:Number(s)}static jacobiSymbol(t,n){let r=(rt(t)%rt(n)+rt(n))%rt(n),s=rt(n),o=1;for(;r!==0n;){for(;r%2n===0n;){r/=2n;let i=s%8n;(i===3n||i===5n)&&(o=-o)}[r,s]=[s,r],r%4n===3n&&s%4n===3n&&(o=-o),r%=s}return s===1n?o:0}};var te=class e{_domain;_coDomain;_lookup=null;constructor(t,n){if(t.length!==n.length)throw new Error("Permutation domain and codomain must have equal length.");this._domain=[...t],this._coDomain=[...n]}get domain(){return[...this._domain]}get coDomain(){return[...this._coDomain]}get lookup(){return this._lookup===null&&(this._lookup=new Map(this._domain.map((t,n)=>[t,this._coDomain[n]]))),this._lookup}apply(t){let n=this.lookup;return n.has(t)?n.get(t):t}inverse(){return new e(this.coDomain,this.domain)}power(t){if(t===0)return e.Identity;if(t===1)return this;if(t===-1)return this.inverse();let n=this,r=t;t<-1&&(n=this.inverse(),r=-t);let s;for(;r>0;)r%2===1&&(s=s===void 0?n:e.compose(s,n)),r=Math.floor(r/2),r>0&&(n=e.compose(n,n));return s}toString(){return`(${this._domain.map((n,r)=>`${n} -> ${this._coDomain[r]}`).join(",")})`}cycles(){let t=[...this._domain],n=[...this._coDomain],r=[];for(;t.length>0;){let s=t[0],o=s,i=[];do{i.push(o),o=this.apply(o);for(let a=0;a<n.length;a++)if(o===n[a]){t.splice(a,1),n.splice(a,1);break}}while(o!==s);r.push(new kn(i))}return r}order(){let t=this.cycles().map(n=>n.length);return t.length===0?1:Number(Ft.lcmList(t))}static Identity=new e([],[]);static compose(t,n){let r=Array.from(new Set(t.domain.concat(n.domain))),s=r.map(o=>t.apply(n.apply(o)));return new e(r,s)}static composeList(t){return t.length===0?e.Identity:t.length===1?t[0]:t.reduce((n,r)=>e.compose(n,r))}static equal(t,n){for(let r of t.domain)if(t.apply(r)!==n.apply(r))return!1;for(let r of n.domain)if(n.apply(r)!==t.apply(r))return!1;return!0}static commute(t,n){return e.equal(e.compose(t,n),e.compose(n,t))}};var kn=class e{_elements;constructor(t){for(let n=0;n<t.length;n++)if(t.lastIndexOf(t[n])!==n)throw new Error("Cycle elements must be distinct (no repeats).");this._elements=[...t]}get elements(){return[...this._elements]}get length(){return this._elements.length<2?1:this._elements.length}apply(t){let n=this._elements;if(t===n[n.length-1])return n[0];for(let r=0;r<n.length;r++)if(t===n[r])return n[r+1];return t}inverse(){return new e([...this._elements].reverse())}shiftedLeft(){return new e(this._elements.map(t=>this.apply(t)))}shiftedRight(){let t=this.inverse();return new e(this._elements.map(n=>t.apply(n)))}toPermutation(){return new te(this.elements,this.shiftedLeft().elements)}toString(){return`(${this._elements.join(",")})`}contains(t){return this._elements.includes(t)}transpositions(){if(this.length<2)return[];let t=[];for(let n=0;n<this.length-1;n++)t.push(new e([this._elements[n],this._elements[n+1]]));return t}transpositionsAlt(){if(this.length<2)return[];let t=[];for(let n=0;n<this.length-1;n++)t.push(new e([this._elements[this.length-2-n],this._elements[this.length-1]]));return t}even(){return this.length%2===1}odd(){return!this.even()}static equal(t,n){if(t.length!==n.length)return!1;let r=t;for(let s=0;s<t.length;s++){let o=r.elements,i=n.elements,a=0;for(let c=0;c<o.length;c++)o[c]===i[c]&&a++;if(a===t.length)return!0;r=r.shiftedLeft()}return!1}static disjoint(t,n){for(let r of t.elements)for(let s of n.elements)if(r===s)return!1;return!0}};var us=e=>(e<0n?-e:e).toString().length;function Li(e,t){let n=e/t,r=e%t;if(r===0n)return n;let s=(r<0n?-r:r)*2n,o=t<0n?-t:t;return s>=o?e<0n==t<0n?n+1n:n-1n:n}var Me=class e{static DEFAULT_PRECISION=20;digits;exponent;static Zero=new e(0n,0);static One=new e(1n,0);constructor(t=0n,n=0){this.digits=t,this.exponent=n}static fromString(t){let n=/^\s*([+-]?)(\d+)(?:\.(\d+))?(?:[eE]([+-]?\d+))?\s*$/.exec(t);if(!n)throw new Error(`Invalid Decimal string: ${t}`);let[,r,s,o="",i]=n,a=BigInt((r==="-"?"-":"")+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,n){let r=Math.min(t.exponent,n.exponent),s=t.digits*10n**BigInt(t.exponent-r),o=n.digits*10n**BigInt(n.exponent-r);return{ad:s,bd:o,exponent:r}}add(t){let{ad:n,bd:r,exponent:s}=e.align(this,t);return new e(n+r,s)}subtract(t){let{ad:n,bd:r,exponent:s}=e.align(this,t);return new e(n-r,s)}multiply(t){return new e(this.digits*t.digits,this.exponent+t.exponent)}divide(t,n=e.DEFAULT_PRECISION){if(t.digits===0n)throw new Error("Division by zero Decimal.");if(this.digits===0n)return e.Zero;let r=Math.max(0,n-us(this.digits)+us(t.digits)),s=this.digits*10n**BigInt(r),o=Li(s,t.digits);return new e(o,this.exponent-t.exponent-r)}negate(){return new e(-this.digits,this.exponent)}abs(){return this.digits<0n?this.negate():this}equals(t){let{ad:n,bd:r}=e.align(this,t);return n===r}compare(t){let{ad:n,bd:r}=e.align(this,t);return n<r?-1:n>r?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,n=(t?-this.digits:this.digits).toString();if(this.exponent>=0)n=n+"0".repeat(this.exponent);else{let r=n.length+this.exponent;n=r<=0?`0.${"0".repeat(-r)}${n}`:`${n.slice(0,r)}.${n.slice(r)}`,n.includes(".")&&(n=n.replace(/0+$/,"").replace(/\.$/,""))}return t?`-${n}`:n}};var Xe=[.9999999999998099,676.5203681218851,-1259.1392167224028,771.3234287776531,-176.6150291621406,12.507343278686905,-.13857109526572012,9984369578019572e-21,15056327351493116e-23],st=class e{static gamma(t){if(t<.5)return Math.PI/(Math.sin(Math.PI*t)*e.gamma(1-t));let n=t-1,r=Xe[0],s=n+7+.5;for(let o=1;o<Xe.length;o++)r+=Xe[o]/(n+o);return Math.sqrt(2*Math.PI)*s**(n+.5)*Math.exp(-s)*r}static lnGamma(t){if(t<.5)return Math.log(Math.abs(Math.PI/Math.sin(Math.PI*t)))-e.lnGamma(1-t);let n=t-1,r=Xe[0],s=n+7+.5;for(let o=1;o<Xe.length;o++)r+=Xe[o]/(n+o);return .5*Math.log(2*Math.PI)+(n+.5)*Math.log(s)-s+Math.log(r)}static beta(t,n){return Math.exp(e.lnGamma(t)+e.lnGamma(n)-e.lnGamma(t+n))}static erf(t){if(t===0||Number.isNaN(t))return t;let n=e.regularizedGammaP(.5,t*t);return t<0?-n:n}static erfc(t){return Number.isNaN(t)?t:t<0?2-e.regularizedGammaQ(.5,t*t):e.regularizedGammaQ(.5,t*t)}static regularizedGammaP(t,n){return n<0||t<=0?Number.NaN:n===0?0:n===Number.POSITIVE_INFINITY?1:n<t+1?fs(t,n):1-ms(t,n)}static regularizedGammaQ(t,n){return n<0||t<=0?Number.NaN:n===0?1:n===Number.POSITIVE_INFINITY?0:n<t+1?1-fs(t,n):ms(t,n)}static regularizedIncompleteBeta(t,n,r){if(t<=0)return 0;if(t>=1)return 1;let s=e.lnGamma(n+r)-e.lnGamma(n)-e.lnGamma(r),o=Math.exp(s+n*Math.log(t)+r*Math.log(1-t));return t<(n+1)/(n+r+2)?o*hs(n,r,t)/n:1-o*hs(r,n,1-t)/r}};function hs(e,t,n){let s=e+t,o=e+1,i=e-1,a=1,c=1-s*n/o;Math.abs(c)<1e-300&&(c=1e-300),c=1/c;let l=c;for(let u=1;u<1e3;u++){let h=2*u,f=u*(t-u)*n/((i+h)*(e+h));c=1+f*c,Math.abs(c)<1e-300&&(c=1e-300),a=1+f/a,Math.abs(a)<1e-300&&(a=1e-300),c=1/c,l*=c*a,f=-(e+u)*(s+u)*n/((e+h)*(o+h)),c=1+f*c,Math.abs(c)<1e-300&&(c=1e-300),a=1+f/a,Math.abs(a)<1e-300&&(a=1e-300),c=1/c;let m=c*a;if(l*=m,Math.abs(m-1)<1e-15)break}return l}function fs(e,t){let n=e,r=1/e,s=r;for(let o=0;o<1e3&&(n++,s*=t/n,r+=s,!(Math.abs(s)<Math.abs(r)*1e-16));o++);return r*Math.exp(-t+e*Math.log(t)-st.lnGamma(e))}function ms(e,t){let r=t+1-e,s=1/1e-300,o=1/r,i=o;for(let a=1;a<1e3;a++){let c=-a*(a-e);r+=2,o=c*o+r,Math.abs(o)<1e-300&&(o=1e-300),s=r+c/s,Math.abs(s)<1e-300&&(s=1e-300),o=1/o;let l=o*s;if(i*=l,Math.abs(l-1)<1e-16)break}return Math.exp(-t+e*Math.log(t)-st.lnGamma(e))*i}function We(e){let t=e.ppf??(n=>Vi(e.cdf,e.sf,n,e.lower??Number.NEGATIVE_INFINITY,e.upper??Number.POSITIVE_INFINITY));return{pdf:e.pdf,cdf:e.cdf,sf:e.sf,ppf:t,quantile:t,mean:e.mean,variance:e.variance,std:()=>Math.sqrt(e.variance()),sample:e.sample,rvs:n=>Array.from({length:n},()=>e.sample())}}function ps(e){let t=n=>{if(Number.isNaN(n)||n<0||n>1)return Number.NaN;if(n===0)return-1;let r=e.max??Number.POSITIVE_INFINITY;if(n===1)return r;let s=Math.max(1,Math.ceil(e.mean()+4*Math.sqrt(e.variance())));for(;s<r&&e.cdf(s)<n;)s*=2;s=Math.min(s,r);let o=-1;for(;s-o>1;){let i=Math.floor((o+s)/2);e.cdf(i)>=n?s=i:o=i}return s};return{pmf:e.pmf,cdf:e.cdf,sf:e.sf,ppf:t,quantile:t,mean:e.mean,variance:e.variance,std:()=>Math.sqrt(e.variance()),sample:e.sample,rvs:n=>Array.from({length:n},()=>e.sample())}}function Vi(e,t,n,r,s){if(Number.isNaN(n)||n<0||n>1)return Number.NaN;if(n===0)return r;if(n===1)return s;let o=n<=.5?c=>e(c)<n:c=>t(c)>1-n,i=r;if(!Number.isFinite(i)){i=-1;for(let c=1;!o(i);c*=2)i-=c}let a=Number.isFinite(s)?s:i+1;if(!Number.isFinite(s))for(let c=1;o(a);c*=2)i=a,a+=c;for(let c=0;c<400;c++){let l=i+(a-i)/2;if(l===i||l===a)break;o(l)?i=l:a=l}return a}function Bi(e){if(e<=0)return Number.NEGATIVE_INFINITY;if(e>=1)return Number.POSITIVE_INFINITY;let t=[-39.69683028665376,220.9460984245205,-275.9285104469687,138.357751867269,-30.66479806614716,2.506628277459239],n=[-54.47609879822406,161.5858368580409,-155.6989798598866,66.80131188771972,-13.28068155288572],r=[-.007784894002430293,-.3223964580411365,-2.400758277161838,-2.549732539343734,4.374664141464968,2.938163982698783],s=[.007784695709041462,.3224671290700398,2.445134137142996,3.754408661907416],o=.02425,i=1-o;if(e<o){let c=Math.sqrt(-2*Math.log(e));return(((((r[0]*c+r[1])*c+r[2])*c+r[3])*c+r[4])*c+r[5])/((((s[0]*c+s[1])*c+s[2])*c+s[3])*c+1)}if(e<=i){let c=e-.5,l=c*c;return(((((t[0]*l+t[1])*l+t[2])*l+t[3])*l+t[4])*l+t[5])*c/(((((n[0]*l+n[1])*l+n[2])*l+n[3])*l+n[4])*l+1)}let a=Math.sqrt(-2*Math.log(1-e));return-(((((r[0]*a+r[1])*a+r[2])*a+r[3])*a+r[4])*a+r[5])/((((s[0]*a+s[1])*a+s[2])*a+s[3])*a+1)}var ds=Math.sqrt(2*Math.PI),vt=class e{static normalQuantile(t,n=0,r=1){if(Number.isNaN(t)||t<0||t>1)return Number.NaN;let s=Bi(t);if(Number.isFinite(s)){let i=(.5*st.erfc(-s/Math.SQRT2)-t)*ds*Math.exp(s*s/2);s-=i/(1+s*i/2)}return n+r*s}static normal(t=0,n=1,r=Math.random){return We({pdf:s=>Math.exp(-.5*((s-t)/n)**2)/(n*ds),cdf:s=>.5*st.erfc(-(s-t)/(n*Math.SQRT2)),sf:s=>.5*st.erfc((s-t)/(n*Math.SQRT2)),ppf:s=>e.normalQuantile(s,t,n),mean:()=>t,variance:()=>n*n,sample:()=>t+n*Math.sqrt(-2*Math.log(1-r()))*Math.cos(2*Math.PI*r())})}static exponential(t=1,n=Math.random){return We({pdf:r=>r<0?0:t*Math.exp(-t*r),cdf:r=>r<0?0:-Math.expm1(-t*r),sf:r=>r<0?1:Math.exp(-t*r),ppf:r=>r<0||r>1?Number.NaN:-Math.log1p(-r)/t,mean:()=>1/t,variance:()=>1/(t*t),sample:()=>-Math.log(1-n())/t})}static uniform(t=0,n=1,r=Math.random){return We({pdf:s=>s>=t&&s<=n?1/(n-t):0,cdf:s=>s<t?0:s>n?1:(s-t)/(n-t),sf:s=>s<t?1:s>n?0:(n-s)/(n-t),ppf:s=>s<0||s>1?Number.NaN:t+s*(n-t),mean:()=>(t+n)/2,variance:()=>(n-t)**2/12,sample:()=>t+r()*(n-t)})}static gamma(t,n=1,r=Math.random){return We({pdf:s=>s<0?0:s===0?t<1?Number.POSITIVE_INFINITY:t===1?1/n:0:Math.exp((t-1)*Math.log(s)-s/n-st.lnGamma(t)-t*Math.log(n)),cdf:s=>s<=0?0:st.regularizedGammaP(t,s/n),sf:s=>s<=0?1:st.regularizedGammaQ(t,s/n),lower:0,mean:()=>t*n,variance:()=>t*n*n,sample:()=>e.sampleGamma(t,r)*n})}static chiSquare(t,n=Math.random){return{...e.gamma(t/2,2,n),mean:()=>t,variance:()=>2*t,std:()=>Math.sqrt(2*t)}}static studentT(t,n=Math.random){let r=st.lnGamma((t+1)/2)-st.lnGamma(t/2)-.5*Math.log(t*Math.PI),s=o=>{if(o===Number.POSITIVE_INFINITY)return 1;if(o===Number.NEGATIVE_INFINITY)return 0;let i=st.regularizedIncompleteBeta(t/(t+o*o),t/2,.5);return o>=0?1-.5*i:.5*i};return We({pdf:o=>Math.exp(r-(t+1)/2*Math.log1p(o*o/t)),cdf:s,sf:o=>s(-o),mean:()=>t>1?0:Number.NaN,variance:()=>t>2?t/(t-2):t>1?Number.POSITIVE_INFINITY:Number.NaN,sample:()=>{let o=e.normal(0,1,n).sample(),i=e.chiSquare(t,n).sample();return o/Math.sqrt(i/t)}})}static fisherF(t,n,r=Math.random){let s=st.lnGamma(t/2)+st.lnGamma(n/2)-st.lnGamma((t+n)/2);return We({pdf:o=>o<0?0:o===0?t<2?Number.POSITIVE_INFINITY:t===2?1:0:Math.exp(.5*t*Math.log(t)+.5*n*Math.log(n)+(t/2-1)*Math.log(o)-(t+n)/2*Math.log(n+t*o)-s),cdf:o=>o<=0?0:st.regularizedIncompleteBeta(t*o/(t*o+n),t/2,n/2),sf:o=>o<=0?1:st.regularizedIncompleteBeta(n/(n+t*o),n/2,t/2),lower:0,mean:()=>n>2?n/(n-2):Number.NaN,variance:()=>n>4?2*n*n*(t+n-2)/(t*(n-2)**2*(n-4)):n>2?Number.POSITIVE_INFINITY:Number.NaN,sample:()=>e.sampleGamma(t/2,r)*2/t/(e.sampleGamma(n/2,r)*2/n)})}static binomial(t,n,r=Math.random){let s=i=>st.lnGamma(t+1)-st.lnGamma(i+1)-st.lnGamma(t-i+1);return ps({pmf:i=>i<0||i>t||!Number.isInteger(i)?0:n===0?i===0?1:0:n===1?i===t?1:0:Math.exp(s(i)+i*Math.log(n)+(t-i)*Math.log1p(-n)),cdf:i=>{if(i<0)return 0;let a=Math.floor(i);return a>=t?1:st.regularizedIncompleteBeta(1-n,t-a,a+1)},sf:i=>{if(i<0)return 1;let a=Math.floor(i);return a>=t?0:st.regularizedIncompleteBeta(n,a+1,t-a)},max:t,mean:()=>t*n,variance:()=>t*n*(1-n),sample:()=>{let i=0;for(let a=0;a<t;a++)r()<n&&i++;return i}})}static poisson(t,n=Math.random){return ps({pmf:r=>r<0||!Number.isInteger(r)?0:Math.exp(r*Math.log(t)-t-st.lnGamma(r+1)),cdf:r=>r<0?0:st.regularizedGammaQ(Math.floor(r)+1,t),sf:r=>r<0?1:st.regularizedGammaP(Math.floor(r)+1,t),mean:()=>t,variance:()=>t,sample:()=>{let r=t,s=0;for(;r>0;){let o=Math.min(r,500);r-=o;let i=Math.exp(-o),a=0,c=1;do a++,c*=n();while(c>i);s+=a-1}return s}})}static sampleGamma(t,n=Math.random){if(t<1)return e.sampleGamma(t+1,n)*n()**(1/t);let r=t-1/3,s=1/Math.sqrt(9*r);for(;;){let o,i;do o=e.normal(0,1,n).sample(),i=1+s*o;while(i<=0);i=i*i*i;let a=n();if(a<1-.0331*o**4||Math.log(a)<.5*o*o+r*(1-i+Math.log(i)))return r*i}}},Te=e=>e.reduce((t,n)=>t+n,0),le=e=>Te(e)/e.length,Ye=e=>{let t=le(e);return e.reduce((n,r)=>n+(r-t)**2,0)/(e.length-1)};function gs(e,t,n="two-sided"){let r=vt.studentT(t);return n==="less"?r.cdf(e):n==="greater"?r.sf(e):Math.min(1,2*r.sf(Math.abs(e)))}var ue=class e{static tTestOneSample(t,n=0,r={}){let s=t.length,o=Math.sqrt(Ye(t)/s),i=(le(t)-n)/o,a=s-1;return{statistic:i,df:a,pValue:gs(i,a,r.alternative)}}static tTestTwoSample(t,n,r={}){return e.tTestIndependent(t,n,{...r,equalVar:!1})}static welch(t,n,r={}){return e.tTestTwoSample(t,n,r)}static tTestIndependent(t,n,r={}){let{equalVar:s=!0,alternative:o}=r,i=t.length,a=n.length,c=Ye(t),l=Ye(n),u,h;if(s){h=i+a-2;let f=((i-1)*c+(a-1)*l)/h;u=(le(t)-le(n))/Math.sqrt(f*(1/i+1/a))}else{let f=c/i,m=l/a;u=(le(t)-le(n))/Math.sqrt(f+m),h=(f+m)**2/(f**2/(i-1)+m**2/(a-1))}return{statistic:u,df:h,pValue:gs(u,h,o)}}static tTestPaired(t,n,r={}){if(t.length!==n.length)throw new Error("tTestPaired requires samples of equal length.");return e.tTestOneSample(t.map((s,o)=>s-n[o]),0,r)}static chiSquareGoodnessOfFit(t,n,r=0){let s=t.length,o=n??new Array(s).fill(Te(t)/s);if(o.length!==s)throw new Error("observed and expected must have the same length.");let i=Te(t),a=Te(o);if(Math.abs(i-a)>1e-8*Math.max(Math.abs(i),Math.abs(a)))throw new Error(`observed (${i}) and expected (${a}) frequencies must sum to the same total.`);let c=t.reduce((u,h,f)=>u+(h-o[f])**2/o[f],0),l=s-1-r;return{statistic:c,df:l,pValue:vt.chiSquare(l).sf(c)}}static chiSquareIndependence(t,n={}){let{correction:r=!0}=n,s=t.length,o=t[0].length,i=t.map(Te),a=Array.from({length:o},(f,m)=>Te(t.map(p=>p[m]))),c=Te(i),l=t.map((f,m)=>a.map(p=>i[m]*p/c)),u=(s-1)*(o-1),h=0;for(let f=0;f<s;f++)for(let m=0;m<o;m++){let p=Math.abs(t[f][m]-l[f][m]);r&&u===1&&(p=Math.max(0,p-.5)),h+=p**2/l[f][m]}return{statistic:h,df:u,pValue:u===0?1:vt.chiSquare(u).sf(h),expected:l}}static confidenceIntervalMean(t,n=.95){let r=t.length,s=le(t),o=Math.sqrt(Ye(t)/r),i=vt.studentT(r-1).ppf(1-(1-n)/2);return[s-i*o,s+i*o]}static confidenceIntervalDifference(t,n,r=.95){let s=Ye(t)/t.length,o=Ye(n)/n.length,i=(s+o)**2/(s**2/(t.length-1)+o**2/(n.length-1)),a=le(t)-le(n),c=vt.studentT(i).ppf(1-(1-r)/2)*Math.sqrt(s+o);return[a-c,a+c]}static confidenceIntervalProportion(t,n,r=.95){let s=vt.normalQuantile(1-(1-r)/2),o=t/n,i=1+s*s/n,a=(o+s*s/(2*n))/i,c=s*Math.sqrt(o*(1-o)/n+s*s/(4*n*n))/i;return[Math.max(0,a-c),Math.min(1,a+c)]}};var he=class e{value;deriv;constructor(t=0,n=0){this.value=t,this.deriv=n}static constant(t){return new e(t,0)}static variable(t){return new e(t,1)}static domain(t,n){return new e(t,Number.isNaN(t)?Number.NaN:n)}static lift(t){return t instanceof e?t:new e(t,0)}add(t){let n=e.lift(t);return new e(this.value+n.value,this.deriv+n.deriv)}subtract(t){let n=e.lift(t);return new e(this.value-n.value,this.deriv-n.deriv)}multiply(t){let n=e.lift(t);return new e(this.value*n.value,this.value*n.deriv+this.deriv*n.value)}divide(t){let n=e.lift(t);return new e(this.value/n.value,(this.deriv*n.value-this.value*n.deriv)/(n.value*n.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 n=Math.cos(t.value);return new e(Math.tan(t.value),t.deriv/(n*n))}static exp(t){let n=Math.exp(t.value);return new e(n,n*t.deriv)}static log(t){return e.domain(Math.log(t.value),t.deriv/t.value)}static sqrt(t){let n=Math.sqrt(t.value);return e.domain(n,t.deriv/(2*n))}static derivative(t,n){return t(e.variable(n)).deriv}static valueAndDerivative(t,n){let r=t(e.variable(n));return{value:r.value,derivative:r.deriv}}static gradient(t,n){return n.map((r,s)=>{let o=n.map((i,a)=>new e(i,s===a?1:0));return t(o).deriv})}toString(){return`${this.value} + ${this.deriv}\u03B5`}};var V=e=>({type:"const",value:e}),Qe=(e,t)=>({type:"add",left:e,right:t}),fe=(e,t)=>({type:"sub",left:e,right:t}),ot=(e,t)=>({type:"mul",left:e,right:t}),bt=(e,t)=>({type:"div",left:e,right:t}),At=(e,t)=>({type:"pow",base:e,exp:t}),Kt=e=>({type:"neg",arg:e}),X=(e,t)=>({type:"func",name:e,arg:t}),fr={sin:(e,t)=>ot(X("cos",e),t),cos:(e,t)=>Kt(ot(X("sin",e),t)),tan:(e,t)=>bt(t,At(X("cos",e),V(2))),exp:(e,t)=>ot(X("exp",e),t),ln:(e,t)=>bt(t,e),sqrt:(e,t)=>bt(t,ot(V(2),X("sqrt",e))),asin:(e,t)=>bt(t,X("sqrt",fe(V(1),At(e,V(2))))),acos:(e,t)=>Kt(bt(t,X("sqrt",fe(V(1),At(e,V(2)))))),atan:(e,t)=>bt(t,Qe(V(1),At(e,V(2)))),sinh:(e,t)=>ot(X("cosh",e),t),cosh:(e,t)=>ot(X("sinh",e),t),tanh:(e,t)=>bt(t,At(X("cosh",e),V(2))),cot:(e,t)=>Kt(ot(At(X("csc",e),V(2)),t)),sec:(e,t)=>ot(ot(X("sec",e),X("tan",e)),t),csc:(e,t)=>Kt(ot(ot(X("csc",e),X("cot",e)),t)),asinh:(e,t)=>bt(t,X("sqrt",Qe(At(e,V(2)),V(1)))),acosh:(e,t)=>bt(t,X("sqrt",fe(At(e,V(2)),V(1)))),atanh:(e,t)=>bt(t,fe(V(1),At(e,V(2)))),coth:(e,t)=>Kt(ot(At(X("csch",e),V(2)),t)),sech:(e,t)=>Kt(ot(ot(X("sech",e),X("tanh",e)),t)),csch:(e,t)=>Kt(ot(ot(X("csch",e),X("coth",e)),t)),acot:(e,t)=>Kt(bt(t,Qe(V(1),At(e,V(2))))),asec:(e,t)=>bt(t,ot(X("abs",e),X("sqrt",fe(At(e,V(2)),V(1))))),acsc:(e,t)=>Kt(bt(t,ot(X("abs",e),X("sqrt",fe(At(e,V(2)),V(1)))))),acoth:(e,t)=>bt(t,fe(V(1),At(e,V(2)))),asech:(e,t)=>Kt(bt(t,ot(e,X("sqrt",fe(V(1),At(e,V(2))))))),acsch:(e,t)=>Kt(bt(t,ot(X("abs",e),X("sqrt",Qe(V(1),At(e,V(2))))))),abs:(e,t)=>ot(X("sign",e),t),log10:(e,t)=>bt(t,ot(e,X("ln",V(10)))),log2:(e,t)=>bt(t,ot(e,X("ln",V(2)))),cbrt:(e,t)=>bt(t,ot(V(3),At(X("cbrt",e),V(2)))),floor:()=>V(0),ceil:()=>V(0),round:()=>V(0),sign:()=>V(0),trunc:()=>V(0),expm1:(e,t)=>ot(X("exp",e),t),log1p:(e,t)=>bt(t,Qe(V(1),e)),sigmoid:(e,t)=>ot(ot(X("sigmoid",e),fe(V(1),X("sigmoid",e))),t),erf:(e,t)=>ot(ot(bt(V(2),X("sqrt",V(Math.PI))),X("exp",Kt(At(e,V(2))))),t),relu:(e,t)=>ot(bt(Qe(V(1),X("sign",e)),V(2)),t)};var On=class{items=[];get size(){return this.items.length}push(t,n){this.items.push({priority:n,value:t});let r=this.items.length-1;for(;r>0;){let s=r-1>>1;if(this.items[s].priority<=this.items[r].priority)break;[this.items[s],this.items[r]]=[this.items[r],this.items[s]],r=s}}pop(){let t=this.items[0];if(t===void 0)return;let n=this.items.pop();if(this.items.length){this.items[0]=n;let r=0,s=this.items.length;for(;;){let o=2*r+1,i=2*r+2,a=r;if(o<s&&this.items[o].priority<this.items[a].priority&&(a=o),i<s&&this.items[i].priority<this.items[a].priority&&(a=i),a===r)break;[this.items[a],this.items[r]]=[this.items[r],this.items[a]],r=a}}return t}},Pe=class e{directed;adjacency=new Map;constructor(t=!1){this.directed=t}addVertex(t){return this.adjacency.has(t)||this.adjacency.set(t,new Map),this}addEdge(t,n,r=1){return this.addVertex(t).addVertex(n),this.adjacency.get(t).set(n,r),this.directed||this.adjacency.get(n).set(t,r),this}vertices(){return[...this.adjacency.keys()]}neighbors(t){return[...this.adjacency.get(t)?.keys()??[]]}edges(){let t=[],n=new Set;for(let[r,s]of this.adjacency)for(let[o,i]of s){if(!this.directed){let a=JSON.stringify([r,o].map(String).sort());if(n.has(a))continue;n.add(a)}t.push({from:r,to:o,weight:i})}return t}bfs(t){let n=new Set([t]),r=[],s=[t];for(;s.length;){let o=s.shift();r.push(o);for(let i of this.neighbors(o))n.has(i)||(n.add(i),s.push(i))}return r}dfs(t){let n=new Set,r=[],s=o=>{n.add(o),r.push(o);for(let i of this.neighbors(o))n.has(i)||s(i)};return s(t),r}runDijkstra(t){let n=new Map,r=new Map;for(let i of this.vertices())n.set(i,Number.POSITIVE_INFINITY);n.set(t,0);let s=new Set,o=new On;for(o.push(t,0);o.size;){let i=o.pop(),a=i.value;if(!s.has(a)&&!(i.priority>n.get(a))){s.add(a);for(let[c,l]of this.adjacency.get(a)??[]){if(s.has(c))continue;let u=n.get(a)+l;u<n.get(c)&&(n.set(c,u),r.set(c,a),o.push(c,u))}}}return{dist:n,prev:r}}dijkstra(t){return this.runDijkstra(t).dist}shortestPath(t,n){let{dist:r,prev:s}=this.runDijkstra(t);if(r.get(n)===Number.POSITIVE_INFINITY)return{distance:Number.POSITIVE_INFINITY,path:[]};let o=[],i=n;for(;i!==void 0;)o.unshift(i),i=i===t?void 0:s.get(i);return{distance:r.get(n),path:o}}connectedComponents(){let t=new Set,n=[];for(let r of this.vertices()){if(t.has(r))continue;let s=this.bfs(r);for(let o of s)t.add(o);n.push(s)}return n}topologicalSort(){let t=new Map;for(let s of this.vertices())t.set(s,0);for(let[,s]of this.adjacency)for(let[o]of s)t.set(o,t.get(o)+1);let n=this.vertices().filter(s=>t.get(s)===0),r=[];for(;n.length;){let s=n.shift();r.push(s);for(let o of this.neighbors(s))t.set(o,t.get(o)-1),t.get(o)===0&&n.push(o)}return r.length===this.vertices().length?r:null}hasCycle(){if(this.directed)return this.topologicalSort()===null;let t=new Set,n=(r,s)=>{t.add(r);for(let o of this.neighbors(r))if(t.has(o)){if(o!==s)return!0}else if(n(o,r))return!0;return!1};for(let r of this.vertices())if(!t.has(r)&&n(r,null))return!0;return!1}minimumSpanningTree(){let t=new Map,n=s=>{for(;t.get(s)!==s;)t.set(s,t.get(t.get(s))),s=t.get(s);return s};for(let s of this.vertices())t.set(s,s);let r=[];for(let s of this.edges().sort((o,i)=>o.weight-i.weight)){let o=n(s.from),i=n(s.to);o!==i&&(t.set(o,i),r.push(s))}return r}mst(t="kruskal"){let n=this.vertices().length,r;if(t==="kruskal")r=this.minimumSpanningTree();else{r=[];let s=new Map;for(let i of this.vertices())s.set(i,[]);for(let i of this.edges())s.get(i.from).push(i),s.get(i.to).push(i);let o=new Set;for(let i of this.vertices()){if(o.has(i))continue;o.add(i);let a=new On;for(let c of s.get(i))a.push(c,c.weight);for(let c=a.pop();c;c=a.pop()){let l=c.value,u=o.has(l.from)?l.to:l.from;if(!o.has(u)){o.add(u),r.push(l);for(let h of s.get(u))(!o.has(h.from)||!o.has(h.to))&&a.push(h,h.weight)}}}}return{edges:r,totalWeight:r.reduce((s,o)=>s+o.weight,0),components:n-r.length}}scc(){return this.stronglyConnectedComponents()}condensation(){let t=this.scc(),n=new Map;t.forEach((s,o)=>{for(let i of s)n.set(i,o)});let r=new e(!0);for(let s=0;s<t.length;s++)r.addVertex(s);for(let s of this.edges()){let o=n.get(s.from),i=n.get(s.to);o!==i&&r.addEdge(o,i,1),!this.directed&&o!==i&&r.addEdge(i,o,1)}return{graph:r,components:t,componentOf:n}}toAdjacencyMatrix(){let t=this.vertices(),n=new Map(t.map((o,i)=>[o,i])),r=t.length,s=Array.from({length:r},(o,i)=>Array.from({length:r},(a,c)=>i===c?0:Number.POSITIVE_INFINITY));for(let[o,i]of this.adjacency)for(let[a,c]of i)s[n.get(o)][n.get(a)]=c;return{matrix:s,order:t}}stronglyConnectedComponents(){let t=0,n=new Map,r=new Map,s=new Set,o=[],i=[],a=c=>{n.set(c,t),r.set(c,t),t++,o.push(c),s.add(c);for(let l of this.neighbors(c))n.has(l)?s.has(l)&&r.set(c,Math.min(r.get(c),n.get(l))):(a(l),r.set(c,Math.min(r.get(c),r.get(l))));if(r.get(c)===n.get(c)){let l=[],u;do u=o.pop(),s.delete(u),l.push(u);while(u!==c);i.push(l)}};for(let c of this.vertices())n.has(c)||a(c);return i}floydWarshall(){let{matrix:t,order:n}=this.toAdjacencyMatrix(),r=n.length,s=t.map(o=>[...o]);for(let o=0;o<r;o++)for(let i=0;i<r;i++)for(let a=0;a<r;a++)s[i][o]+s[o][a]<s[i][a]&&(s[i][a]=s[i][o]+s[o][a]);return{distances:s,order:n}}};function Gi(e,t){let n=e<0n?-e:e,r=t<0n?-t:t;for(;r;)[n,r]=[r,n%r];return n}var xs=e=>{if(typeof e=="bigint")return e;if(!Number.isInteger(e))throw new Error(`Rational requires integer inputs; got ${e}`);return BigInt(e)},tt=class e{numerator;denominator;static Zero=new e(0n,1n);static One=new e(1n,1n);constructor(t,n=1n){let r=xs(t),s=xs(n);if(s===0n)throw new Error("Rational denominator must be non-zero.");s<0n&&(r=-r,s=-s);let o=Gi(r,s)||1n;this.numerator=r/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,n=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[r,s]=[0n,1n],[o,i]=[1n,0n],a=t,c=BigInt(n);for(let l=0;l<64;l++){let u=Math.floor(a),h=BigInt(u);if([r,s]=[s,h*s+r],[o,i]=[i,h*i+o],i>c)return new e(r,o);let f=a-u;if(f<1e-15)break;a=1/f}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 n=e.One,r=this,s=t;for(;s>0;)s&1&&(n=n.multiply(r)),r=r.multiply(r),s>>=1;return n}equals(t){return this.numerator===t.numerator&&this.denominator===t.denominator}compare(t){let n=this.numerator*t.denominator-t.numerator*this.denominator;return n<0n?-1:n>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}`}};function mr(e){let t=e.length;for(let u of e)if(u.length!==t)throw new Error(`frobeniusNormalForm requires a square matrix (got a ${t}-row matrix with a ${u.length}-entry row).`);let n=new Pe(!0);for(let u=0;u<t;u++)n.addVertex(u);for(let u=0;u<t;u++)for(let h=0;h<t;h++)e[u][h]!==0&&n.addEdge(u,h,e[u][h]);let{graph:r,components:s}=n.condensation(),o=r.topologicalSort();if(!o)throw new Error("frobeniusNormalForm: condensation unexpectedly has a cycle.");let i=[],a=[];for(let u of o){let h=[...s[u]].sort((m,p)=>m-p),f=i.length;i.push(...h),a.push({component:h,start:f,end:i.length})}let c=i.map(u=>i.map(h=>e[u][h])),l=Array.from({length:t},()=>new Array(t).fill(0));for(let u=0;u<t;u++)l[i[u]][u]=1;return{order:i,P:l,permuted:c,blocks:a,irreducible:s.length===1}}var je=(e,t,n)=>e.some(r=>n(t,r)),pn=class e{static cayleyTable(t,n){return t.map(r=>t.map(s=>n(r,s)))}static isClosed(t,n,r){for(let s of t)for(let o of t)if(!je(t,n(s,o),r))return!1;return!0}static findIdentity(t,n,r){for(let s of t)if(t.every(o=>r(n(s,o),o)&&r(n(o,s),o)))return s;return null}static isAssociative(t,n,r){for(let s of t)for(let o of t)for(let i of t)if(!r(n(n(s,o),i),n(s,n(o,i))))return!1;return!0}static hasInverses(t,n,r,s){return t.every(o=>t.some(i=>r(n(o,i),s)&&r(n(i,o),s)))}static isGroup(t,n,r){if(!e.isClosed(t,n,r))return!1;let s=e.findIdentity(t,n,r);return s===null?!1:e.isAssociative(t,n,r)&&e.hasInverses(t,n,r,s)}static isAbelian(t,n,r){for(let s of t)for(let o of t)if(!r(n(s,o),n(o,s)))return!1;return!0}static elementOrder(t,n,r,s,o=1e5){let i=t;for(let a=1;a<=o;a++){if(r(i,s))return a;i=n(i,t)}throw new Error("Element order exceeded the search bound (is the group finite?).")}static closure(t,n,r,s,o=1e5){let i=[];s!==void 0&&i.push(s);for(let c of t)je(i,c,r)||i.push(c);let a=!0;for(;a;){a=!1;for(let c=0;c<i.length;c++)for(let l of t){let u=n(i[c],l);if(!je(i,u,r)&&(i.push(u),a=!0,i.length>o))throw new Error("Closure exceeded the size cap.")}}return i}static isSubgroup(t,n,r,s){return t.every(o=>je(n,o,s))?e.isGroup(t,r,s):!1}static leftCosets(t,n,r,s){let o=[],i=[];for(let a of n){if(je(i,a,s))continue;let c=t.map(l=>r(a,l));o.push(c);for(let l of c)je(i,l,s)||i.push(l)}return o}static index(t,n){return t.length/n.length}static orbit(t,n,r,s,o=1e5){let i=[t],a=!0;for(;a;){a=!1;for(let c=0;c<i.length;c++)for(let l of n){let u=r(l,i[c]);if(!je(i,u,s)&&(i.push(u),a=!0,i.length>o))throw new Error("Orbit exceeded the size cap.")}}return i}static cyclicGroup(t){return{elements:Array.from({length:t},(n,r)=>r),op:(n,r)=>(n+r)%t,identity:0}}static dihedralGroup(t){let n=Array.from({length:t},(i,a)=>a),r=i=>(i%t+t)%t,s=Array.from({length:t},(i,a)=>new te(n,n.map(c=>r(c+a)))),o=Array.from({length:t},(i,a)=>new te(n,n.map(c=>r(a-c))));return[...s,...o]}static stabilizer(t,n,r,s){return n.filter(o=>s(r(o,t),t))}static symmetricGroup(t){let n=Array.from({length:t},(o,i)=>i),r=[],s=(o,i)=>{if(i===o.length){r.push(new te(n,[...o]));return}for(let a=i;a<o.length;a++)[o[i],o[a]]=[o[a],o[i]],s(o,i+1),[o[i],o[a]]=[o[a],o[i]]};return s([...n],0),r}};var pr=new Float64Array(1),ws=new BigUint64Array(pr.buffer);function bs(e){return Number.isNaN(e)||e===1/0?e:e===0?Number.MIN_VALUE:(pr[0]=e,ws[0]=ws[0]+(e>0?1n:-1n),pr[0])}function Ui(e){return-bs(-e)}function oe(e){return new me(Ui(e.lo),bs(e.hi))}var me=class e{lo;hi;constructor(t,n=t){if(t>n)throw new Error(`Invalid interval: [${t}, ${n}]`);this.lo=t,this.hi=n}static of(t,n){return new e(t,n)}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 oe(new e(this.lo+t.lo,this.hi+t.hi))}subtract(t){return oe(new e(this.lo-t.hi,this.hi-t.lo))}negate(){return new e(-this.hi,-this.lo)}multiply(t){let n=[this.lo*t.lo,this.lo*t.hi,this.hi*t.lo,this.hi*t.hi];return oe(new e(Math.min(...n),Math.max(...n)))}divide(t){if(t.contains(0))throw new Error("Interval division by an interval containing zero.");let n=oe(new e(1/t.hi,1/t.lo));return this.multiply(n)}hull(t){return new e(Math.min(this.lo,t.lo),Math.max(this.hi,t.hi))}intersect(t){let n=Math.max(this.lo,t.lo),r=Math.min(this.hi,t.hi);return n<=r?new e(n,r):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 oe(new e(Math.sqrt(this.lo),Math.sqrt(this.hi)))}exp(){return oe(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 oe(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 n=this.lo**t,r=this.hi**t;return t%2===0&&this.contains(0)?oe(new e(0,Math.max(n,r))):oe(new e(Math.min(n,r),Math.max(n,r)))}extrema(t,n,r){let s=[t(this.lo),t(this.hi)],o=Math.ceil((this.lo-n)/r),i=Math.floor((this.hi-n)/r);for(let a=o;a<=i;a++)s.push(t(n+a*r));return oe(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 Tn=e=>Array.from({length:e},()=>new Array(e).fill(0));function ys(e,t=60){let n=e.length;if(n===0)return{values:[],vectors:[]};let r={re:Tn(n),im:Tn(n)};for(let h=0;h<n;h++){if(e[h].length!==n)throw new Error("eigen requires a square matrix.");for(let f=0;f<n;f++){let m=e[h][f];if(typeof m=="number"?r.re[h][f]=m:(r.re[h][f]=m.re,r.im[h][f]=m.im),!Number.isFinite(r.re[h][f])||!Number.isFinite(r.im[h][f]))throw new Error("eigen requires finite matrix entries.")}}let s={re:Tn(n),im:Tn(n)};for(let h=0;h<n;h++)s.re[h][h]=1;let o=0;for(let h=0;h<n;h++)for(let f=0;f<n;f++)o=Math.max(o,Math.hypot(r.re[h][f],r.im[h][f]));o===0&&(o=1),Zi(r,s,n),Xi(r,s,n,o,t);let i=o*n,a=[];for(let h=0;h<n;h++)a.push([r.re[h][h],r.im[h][h]]);let c=1e-12*o,l=e.every(h=>h.every(f=>typeof f=="number"||f.im===0)),u=[];for(let h=0;h<n;h++){let f=new Array(n).fill(0),m=new Array(n).fill(0);f[h]=1;for(let $=h-1;$>=0;$--){let O=0,L=0;for(let D=$+1;D<=h;D++)O+=r.re[$][D]*f[D]-r.im[$][D]*m[D],L+=r.re[$][D]*m[D]+r.im[$][D]*f[D];let k=r.re[$][$]-a[h][0],Y=r.im[$][$]-a[h][1];Math.hypot(k,Y)<Number.EPSILON*i&&(k=Number.EPSILON*i,Y=0);let P=k*k+Y*Y;f[$]=-(O*k+L*Y)/P,m[$]=-(L*k-O*Y)/P}let p=new Array(n).fill(0),d=new Array(n).fill(0);for(let $=0;$<n;$++)for(let O=0;O<=h;O++)p[$]+=s.re[$][O]*f[O]-s.im[$][O]*m[O],d[$]+=s.re[$][O]*m[O]+s.im[$][O]*f[O];let x=0,g=0,w=0;for(let $=0;$<n;$++){let O=Math.hypot(p[$],d[$]);x+=O*O,O>g*(1+1e-12)&&(g=O,w=$)}x=Math.sqrt(x);let b=p[w]/g,y=-d[w]/g;for(let $=0;$<n;$++){let O=(p[$]*b-d[$]*y)/x,L=(p[$]*y+d[$]*b)/x;p[$]=O,d[$]=L}let E=a[h][0],N=a[h][1];if(Math.abs(N)<=c&&l){N=0;for(let $=0;$<n;$++)Math.abs(d[$])<=1e-10&&(d[$]=0)}E===0&&(E=0),u.push({lre:E,lim:N,vre:p,vim:d})}return u.sort((h,f)=>Math.abs(h.lre-f.lre)<=c?f.lim-h.lim:f.lre-h.lre),{values:u.map(h=>new ht(h.lre,h.lim)),vectors:Array.from({length:n},(h,f)=>u.map(m=>new ht(m.vre[f],m.vim[f])))}}function Zi(e,t,n){for(let r=0;r<n-2;r++){let s=0;for(let h=r+1;h<n;h++)s+=e.re[h][r]**2+e.im[h][r]**2;if(s=Math.sqrt(s),s===0)continue;let o=Math.hypot(e.re[r+1][r],e.im[r+1][r]),i=o===0?1:e.re[r+1][r]/o,a=o===0?0:e.im[r+1][r]/o,c=new Array(n).fill(0),l=new Array(n).fill(0);for(let h=r+1;h<n;h++)c[h]=e.re[h][r],l[h]=e.im[h][r];c[r+1]+=i*s,l[r+1]+=a*s;let u=0;for(let h=r+1;h<n;h++)u+=c[h]**2+l[h]**2;if(u!==0){for(let h=0;h<n;h++){let f=0,m=0;for(let p=r+1;p<n;p++)f+=c[p]*e.re[p][h]+l[p]*e.im[p][h],m+=c[p]*e.im[p][h]-l[p]*e.re[p][h];f=2*f/u,m=2*m/u;for(let p=r+1;p<n;p++)e.re[p][h]-=c[p]*f-l[p]*m,e.im[p][h]-=c[p]*m+l[p]*f}for(let h of[e,t])for(let f=0;f<n;f++){let m=0,p=0;for(let d=r+1;d<n;d++)m+=h.re[f][d]*c[d]-h.im[f][d]*l[d],p+=h.re[f][d]*l[d]+h.im[f][d]*c[d];m=2*m/u,p=2*p/u;for(let d=r+1;d<n;d++)h.re[f][d]-=m*c[d]+p*l[d],h.im[f][d]-=p*c[d]-m*l[d]}for(let h=r+2;h<n;h++)e.re[h][r]=0,e.im[h][r]=0}}}function Xi(e,t,n,r,s){let o=n-1,i=0,a=0;for(;o>0;){let c=o;for(;c>0;){let f=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*(f===0?r:f)){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*n)throw new Error("eigen: QR iteration failed to converge.");let l,u;if(i%10===0)l=e.re[o][o]+Math.hypot(e.re[o][o-1],e.im[o][o-1]),u=e.im[o][o];else{let f=e.re[o-1][o-1],m=e.im[o-1][o-1],p=e.re[o-1][o],d=e.im[o-1][o],x=e.re[o][o-1],g=e.im[o][o-1],w=e.re[o][o],b=e.im[o][o],y=(f-w)/2,E=(m-b)/2,N=y*y-E*E+(p*x-d*g),$=2*y*E+(p*g+d*x),O=Math.hypot(N,$),L=Math.sqrt((O+N)/2),k=($<0?-1:1)*Math.sqrt(Math.max(0,(O-N)/2)),Y=(f+w)/2,P=(m+b)/2,D=Y+L,G=P+k,Z=Y-L,pt=P-k;Math.hypot(D-w,G-b)<=Math.hypot(Z-w,pt-b)?(l=D,u=G):(l=Z,u=pt)}for(let f=c;f<=o;f++)e.re[f][f]-=l,e.im[f][f]-=u;let h=[];for(let f=c;f<o;f++){let m=e.re[f][f],p=e.im[f][f],d=e.re[f+1][f],x=e.im[f+1][f],g=Math.hypot(m,p),w=Math.hypot(g,Math.hypot(d,x)),b,y,E;if(w===0)b=1,y=0,E=0;else if(g===0){b=0;let N=Math.hypot(d,x);y=d/N,E=-x/N}else{b=g/w;let N=m/g,$=p/g;y=(N*d+$*x)/w,E=($*d-N*x)/w}h.push([b,y,E]);for(let N=f;N<n;N++){let $=e.re[f][N],O=e.im[f][N],L=e.re[f+1][N],k=e.im[f+1][N];e.re[f][N]=b*$+(y*L-E*k),e.im[f][N]=b*O+(y*k+E*L),e.re[f+1][N]=-(y*$+E*O)+b*L,e.im[f+1][N]=-(y*O-E*$)+b*k}e.re[f+1][f]=0,e.im[f+1][f]=0}for(let f=0;f<h.length;f++){let m=c+f,[p,d,x]=h[f],g=Math.min(o,m+1);for(let[w,b]of[[e,g],[t,n-1]])for(let y=0;y<=b;y++){let E=w.re[y][m],N=w.im[y][m],$=w.re[y][m+1],O=w.im[y][m+1];w.re[y][m]=p*E+($*d+O*x),w.im[y][m]=p*N+(O*d-$*x),w.re[y][m+1]=-(E*d-N*x)+p*$,w.im[y][m+1]=-(E*x+N*d)+p*O}}for(let f=c;f<=o;f++)e.re[f][f]+=l,e.im[f][f]+=u}for(let c=1;c<n;c++)for(let l=0;l<c;l++)e.re[c][l]=0,e.im[c][l]=0}var Ee=1e-12,Tt=e=>[...e].map(t=>[...t]),Zt=e=>R.fromArray(e.map(t=>R.fromArray(t))),dr=e=>R.fromArray(e),gr=e=>Array.from({length:e},(t,n)=>Array.from({length:e},(r,s)=>n===s?1:0)),Je=(e,t)=>Array.from({length:e},()=>new Array(t).fill(0)),dn=e=>e[0].map((t,n)=>e.map(r=>r[n])),Pn=(e,t)=>{let n=e.length,r=t[0].length,s=t.length,o=Je(n,r);for(let i=0;i<n;i++)for(let a=0;a<s;a++)for(let c=0;c<r;c++)o[i][c]+=e[i][a]*t[a][c];return o},at=class e{static lu(t){let n=Tt(t),r=n.length,s=gr(r),o=gr(r),i=1;for(let a=0;a<r;a++){let c=a;for(let l=a+1;l<r;l++)Math.abs(n[l][a])>Math.abs(n[c][a])&&(c=l);if(c!==a){[n[a],n[c]]=[n[c],n[a]],[o[a],o[c]]=[o[c],o[a]];for(let l=0;l<a;l++)[s[a][l],s[c][l]]=[s[c][l],s[a][l]];i=-i}if(!(Math.abs(n[a][a])<Ee))for(let l=a+1;l<r;l++){let u=n[l][a]/n[a][a];s[l][a]=u;for(let h=a;h<r;h++)n[l][h]-=u*n[a][h]}}return{L:Zt(s),U:Zt(n),P:Zt(o),sign:i}}static solve(t,n){let r=Tt(t),s=r.length,o=[...n],{L:i,U:a,P:c}=e.lu(r),l=Tt(i),u=Tt(a),f=Tt(c).map(d=>d.reduce((x,g,w)=>x+g*o[w],0)),m=new Array(s).fill(0);for(let d=0;d<s;d++){let x=f[d];for(let g=0;g<d;g++)x-=l[d][g]*m[g];m[d]=x}let p=new Array(s).fill(0);for(let d=s-1;d>=0;d--){let x=m[d];for(let g=d+1;g<s;g++)x-=u[d][g]*p[g];p[d]=Math.abs(u[d][d])<Ee?0:x/u[d][d]}return dr(p)}static rref(t){let n=Tt(t),r=n.length,s=n[0].length,o=0;for(let i=0;i<r&&o<s;i++,o++){let a=i;for(;o<s&&Math.abs(n[a][o])<Ee;)if(a++,a===r&&(a=i,o++,o===s))return Zt(n);[n[a],n[i]]=[n[i],n[a]];let c=n[i][o];for(let l=0;l<s;l++)n[i][l]/=c;for(let l=0;l<r;l++){if(l===i)continue;let u=n[l][o];for(let h=0;h<s;h++)n[l][h]-=u*n[i][h]}}return Zt(n)}static rank(t){return Tt(e.rref(t)).filter(r=>r.some(s=>Math.abs(s)>1e-9)).length}static nullSpace(t){let n=Tt(e.rref(t)),r=n.length,s=n[0].length,o=[];for(let c=0;c<r;c++){let l=n[c].findIndex(u=>Math.abs(u)>1e-9);l!==-1&&o.push(l)}let i=[];for(let c=0;c<s;c++)o.includes(c)||i.push(c);let a=[];for(let c of i){let l=new Array(s).fill(0);l[c]=1;for(let u=0;u<o.length;u++)l[o[u]]=-n[u][c];a.push(l)}return Zt(a.length?a:[new Array(s).fill(0)])}static qr(t){let n=Tt(t),r=n.length,s=n[0].length,o=Je(r,s),i=Je(s,s),a=dn(n);for(let c=0;c<s;c++){let l=[...a[c]];for(let h=0;h<c;h++){let f=0;for(let m=0;m<r;m++)f+=o[m][h]*l[m];i[h][c]=f;for(let m=0;m<r;m++)l[m]-=f*o[m][h]}let u=Math.hypot(...l);i[c][c]=u,u<Ee&&(u=1);for(let h=0;h<r;h++)o[h][c]=l[h]/u}return{Q:Zt(o),R:Zt(i)}}static cholesky(t){let n=Tt(t),r=n.length,s=Je(r,r);for(let o=0;o<r;o++){let i=n[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<r;a++){let c=n[a][o];for(let l=0;l<o;l++)c-=s[a][l]*s[o][l];s[a][o]=c/s[o][o]}}return Zt(s)}static eigenSymmetric(t,n=100){let r=Tt(t),s=r.length,o=gr(s);for(let a=0;a<n;a++){let c=0;for(let l=0;l<s;l++)for(let u=l+1;u<s;u++)c+=r[l][u]*r[l][u];if(c<Ee)break;for(let l=0;l<s;l++)for(let u=l+1;u<s;u++){if(Math.abs(r[l][u])<Ee)continue;let h=(r[u][u]-r[l][l])/(2*r[l][u]),f=Math.sign(h||1)/(Math.abs(h)+Math.sqrt(h*h+1)),m=1/Math.sqrt(f*f+1),p=f*m;for(let d=0;d<s;d++){let x=r[d][l],g=r[d][u];r[d][l]=m*x-p*g,r[d][u]=p*x+m*g}for(let d=0;d<s;d++){let x=r[l][d],g=r[u][d];r[l][d]=m*x-p*g,r[u][d]=p*x+m*g}for(let d=0;d<s;d++){let x=o[d][l],g=o[d][u];o[d][l]=m*x-p*g,o[d][u]=p*x+m*g}}}let i=r.map((a,c)=>({value:a[c],vec:o.map(l=>l[c])}));return i.sort((a,c)=>c.value-a.value),{values:dr(i.map(a=>a.value)),vectors:Zt(dn(i.map(a=>a.vec)))}}static eigen(t){return ys([...t].map(n=>[...n]))}static svd(t){let n=Tt(t),r=n.length,s=n[0].length,o=dn(n),i=Pn(o,n),{values:a,vectors:c}=e.eigenSymmetric(i),l=Tt(c),u=[...a].map(f=>Math.sqrt(Math.max(f,0))),h=Je(r,s);for(let f=0;f<s;f++){let m=l.map(x=>x[f]),p=n.map(x=>x.reduce((g,w,b)=>g+w*m[b],0)),d=u[f];for(let x=0;x<r;x++)h[x][f]=d>Ee?p[x]/d:0}return{U:Zt(h),S:dr(u),V:Zt(l)}}static leastSquares(t,n){let r=Tt(t),s=dn(r),o=Pn(s,r),i=[...n],a=s.map(c=>c.reduce((l,u,h)=>l+u*i[h],0));return e.solve(Zt(o),a)}static pseudoInverse(t){let{U:n,S:r,V:s}=e.svd(t),o=Tt(n),i=Tt(s),a=[...r],c=a.length,l=a.map(h=>h>1e-9?1/h:0),u=Je(c,c);for(let h=0;h<c;h++)u[h][h]=l[h];return Zt(Pn(Pn(i,u),dn(o)))}static frobeniusNorm(t){return Math.hypot(...Tt(t).flat())}static spectralNorm(t){return Math.max(...e.svd(t).S)}static conditionNumber(t){let n=[...e.svd(t).S],r=Math.min(...n);return r<Ee?Number.POSITIVE_INFINITY:Math.max(...n)/r}};var vs=[0,-.5384693101056831,.5384693101056831,-.906179845938664,.906179845938664],Wi=[.5688888888888889,.4786286704993665,.4786286704993665,.2369268850561891,.2369268850561891],pe=class{static bisection(t,n,r,s=1e-12,o=200){let i=n,a=r,c=t(i);if(c*t(a)>0)throw new Error("bisection requires f(a) and f(b) to have opposite signs.");for(let l=0;l<o;l++){let u=(i+a)/2,h=t(u);if(Math.abs(h)<s||(a-i)/2<s)return u;c*h<0?a=u:(i=u,c=h)}return(i+a)/2}static secant(t,n,r,s=1e-12,o=200){let i=n,a=r,c=t(i),l=t(a);for(let u=0;u<o;u++){if(Math.abs(l)<s)return a;let h=l-c;if(h===0)break;let f=a-l*(a-i)/h;i=a,c=l,a=f,l=t(a)}return a}static newton(t,n,r,s=1e-12,o=200){let i=n,a=r??(c=>(t(c+1e-7)-t(c-1e-7))/2e-7);for(let c=0;c<o;c++){let l=t(i);if(Math.abs(l)<s)return i;let u=a(i);if(u===0)break;i-=l/u}return i}static brent(t,n,r,s=1e-12,o=200){let i=t(n),a=t(r);if(i*a>0)throw new Error("brent requires f(a) and f(b) to have opposite signs.");Math.abs(i)<Math.abs(a)&&([n,r]=[r,n],[i,a]=[a,i]);let c=n,l=i,u=r-n,h=!0;for(let f=0;f<o;f++){if(Math.abs(a)<s||Math.abs(r-n)<s)return r;let m;i!==l&&a!==l?m=n*a*l/((i-a)*(i-l))+r*i*l/((a-i)*(a-l))+c*i*a/((l-i)*(l-a)):m=r-a*(r-n)/(a-i),m<(3*n+r)/4||m>r||h&&Math.abs(m-r)>=Math.abs(r-c)/2||!h&&Math.abs(m-r)>=Math.abs(c-u)/2?(m=(n+r)/2,h=!0):h=!1;let d=t(m);u=c,c=r,l=a,i*d<0?(r=m,a=d):(n=m,i=d),Math.abs(i)<Math.abs(a)&&([n,r]=[r,n],[i,a]=[a,i])}return r}static trapezoid(t,n,r,s=1e3){let o=(r-n)/s,i=(t(n)+t(r))/2;for(let a=1;a<s;a++)i+=t(n+a*o);return i*o}static simpson(t,n,r,s=1e3){let o=s%2===0?s:s+1,i=(r-n)/o,a=t(n)+t(r);for(let c=1;c<o;c++)a+=(c%2===0?2:4)*t(n+c*i);return a*i/3}static adaptiveSimpson(t,n,r,s=1e-10,o=50){let i=(f,m,p,d,x)=>(m-f)/6*(p+4*d+x),a=(f,m,p,d,x,g,w,b)=>{let y=(f+m)/2,E=(f+y)/2,N=(y+m)/2,$=t(E),O=t(N),L=i(f,y,p,$,d),k=i(y,m,d,O,x);return b<=0||Math.abs(L+k-g)<=15*w?L+k+(L+k-g)/15:a(f,y,p,$,d,L,w/2,b-1)+a(y,m,d,O,x,k,w/2,b-1)},c=(n+r)/2,l=t(n),u=t(c),h=t(r);return a(n,r,l,u,h,i(n,r,l,u,h),s,o)}static gaussLegendre(t,n,r){let s=(r-n)/2,o=(n+r)/2,i=0;for(let a=0;a<vs.length;a++)i+=Wi[a]*t(o+s*vs[a]);return i*s}static euler(t,n,r,s,o=.01){let i=[{t:r,y:[...n]}],a=r,c=[...n];for(;a<s-1e-12;){let l=Math.min(o,s-a),u=t(a,c);c=c.map((h,f)=>h+l*u[f]),a+=l,i.push({t:a,y:[...c]})}return i}static rk4(t,n,r,s,o=.01){let i=[{t:r,y:[...n]}],a=r,c=[...n];for(;a<s-1e-12;){let l=Math.min(o,s-a),u=t(a,c),h=t(a+l/2,c.map((p,d)=>p+l/2*u[d])),f=t(a+l/2,c.map((p,d)=>p+l/2*h[d])),m=t(a+l,c.map((p,d)=>p+l*f[d]));c=c.map((p,d)=>p+l/6*(u[d]+2*h[d]+2*f[d]+m[d])),a+=l,i.push({t:a,y:[...c]})}return i}static levenbergMarquardt(t,n,r,s,o={}){let{lambda0:i=.01,tolerance:a=1e-10,maxIterations:c=200}=o,l=n.length,u=r.length,h=[...n],f=i;function m(y){return r.map((E,N)=>t(E,y)-s[N])}function p(y){return y.reduce((E,N)=>E+N*N,0)}function d(y){let E=Array.from({length:u},()=>new Array(l).fill(0));for(let N=0;N<l;N++){let $=1e-6*(Math.abs(y[N])+1e-6),O=[...y],L=[...y];O[N]+=$,L[N]-=$;let k=m(O),Y=m(L);for(let P=0;P<u;P++)E[P][N]=(k[P]-Y[P])/(2*$)}return E}let x=m(h),g=p(x),w=0,b=!1;for(;w<c&&!(g<a);w++){let y=d(h),E=Array.from({length:l},()=>new Array(l).fill(0)),N=new Array(l).fill(0);for(let k=0;k<l;k++){for(let P=0;P<l;P++){let D=0;for(let G=0;G<u;G++)D+=y[G][k]*y[G][P];E[k][P]=D}let Y=0;for(let P=0;P<u;P++)Y+=y[P][k]*x[P];N[k]=Y}let $=g,O=!1;for(let k=0;k<30&&!O;k++){let Y=E.map((pt,v)=>pt.map((A,j)=>A+(v===j?f*E[v][v]:0))),P;try{P=[...at.solve(Y,N.map(pt=>-pt))]}catch{f*=10;continue}let D=h.map((pt,v)=>pt+P[v]),G=m(D),Z=p(G);Number.isFinite(Z)&&Z<g?(h=D,x=G,g=Z,f=Math.max(f/10,1e-12),O=!0,b=!0):f*=10}if(!O||($-g)/Math.max(1,$)<1e-12)break}return{params:h,residualNorm:Math.sqrt(g),iterations:w,converged:b||g<a}}};var Ne=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"]),Yi="2.302585092994046";function xr(e,t){if(!Number.isFinite(e))throw new Ne(`constant ${e} has no shader literal`);let n=String(e);return/[.e]/i.test(n)?/^-?\d+e/i.test(n)&&(n=n.replace(/e/i,".0e")):n+=".0",e<0||Object.is(e,-0)?`(${n})`:n}function Ms(e,t,n){return n.d==="glsl"?`vec2(${e}, ${t})`:`vec2<f32>(${e}, ${t})`}function gn(e,t){return e.helpers.add(t),`mx_${t}`}function Ss(e){if(e.type==="const")return e.value;if(e.type==="neg"&&e.arg.type==="const")return-e.arg.value}var Es={lt:"<",le:"<=",gt:">",ge:">=",eq:"==",ne:"!="};function Qi(e){if(!Object.hasOwn(Es,e))throw new Ne(`unknown comparison operator "${e}"`);return Es[e]}function $s(e,t){if(e.type==="cmp"){let n=Qi(e.op);return`${lt(e.left,t)} ${n} ${lt(e.right,t)}`}return`${lt(e,t)} != 0.0`}function $e(e){throw new Ne(`${e} is not supported by the shader compiler`)}function lt(e,t){switch(e.type){case"const":return t.complex?Ms(xr(e.value,t),"0.0",t):xr(e.value,t);case"var":{if(t.complex&&e.name==="i"&&!t.vars.has("i"))return Ms("0.0","1.0",t);if(!t.vars.has(e.name))throw new Ne(`variable "${e.name}" is not in the variables list`);return t.used.add(e.name),e.name}case"neg":return`(-${lt(e.arg,t)})`;case"add":return`(${lt(e.left,t)} + ${lt(e.right,t)})`;case"sub":return`(${lt(e.left,t)} - ${lt(e.right,t)})`;case"mul":return t.complex?`${gn(t,"cmul")}(${lt(e.left,t)}, ${lt(e.right,t)})`:`(${lt(e.left,t)} * ${lt(e.right,t)})`;case"div":return t.complex?`${gn(t,"cdiv")}(${lt(e.left,t)}, ${lt(e.right,t)})`:`(${lt(e.left,t)} / ${lt(e.right,t)})`;case"pow":return t.complex?Ki(e.base,e.exp,t):Ji(e.base,e.exp,t);case"func":return t.complex?Hi(e.name,lt(e.arg,t),t):_i(e.name,lt(e.arg,t),t);case"call2":{t.complex&&$e(`${e.name} over complex numbers`);let n=lt(e.left,t),r=lt(e.right,t);switch(e.name){case"atan2":return t.d==="glsl"?`atan(${n}, ${r})`:`atan2(${n}, ${r})`;case"hypot":return t.d==="glsl"?`length(vec2(${n}, ${r}))`:`length(vec2<f32>(${n}, ${r}))`;case"min":case"max":return`${e.name}(${n}, ${r})`;default:return $e(`${e.name}`)}}case"cmp":{t.complex&&$e("comparison over complex numbers");let n=$s(e,t);return t.d==="glsl"?`(${n} ? 1.0 : 0.0)`:`select(0.0, 1.0, ${n})`}case"piecewise":{t.complex&&$e("piecewise over complex numbers");let n=lt(e.otherwise,t);for(let r=e.branches.length-1;r>=0;r--){let s=e.branches[r],o=$s(s.cond,t),i=lt(s.expr,t);n=t.d==="glsl"?`(${o} ? ${i} : ${n})`:`select(${n}, ${i}, ${o})`}return n}case"sum":return $e("sum");case"product":return $e("product")}}function Ji(e,t,n){let r=lt(e,n),s=Ss(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 r;let i=Array.from({length:Math.abs(o)},()=>r).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(${r}), ${xr(o,n)})`;return i?`(sign(${r}) * ${a})`:a}return`pow(${r}, ${lt(t,n)})`}function _i(e,t,n){let r=n.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}) / ${Yi})`;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 r?`max(${t}, 0.0)`:`max(${t}, 0.0)`;default:return $e(`function ${e}`)}}function Ki(e,t,n){let r=lt(e,n),s=Ss(t);return s!==void 0&&Number.isInteger(s)&&Math.abs(s)<=64?`${gn(n,"cpowi")}(${r}, ${s})`:`${gn(n,"cpow")}(${r}, ${lt(t,n)})`}function Hi(e,t,n){switch(e){case"exp":case"ln":case"sqrt":case"sin":case"cos":case"tan":case"sinh":case"cosh":case"tanh":case"abs":return`${gn(n,`c${e}`)}(${t})`;default:return $e(`function ${e} over complex numbers`)}}var ta=["cmul","cdiv","cexp","cln","cpow","cpowi","csqrt","csin","ccos","ctan","csinh","ccosh","ctanh","cabs"],ea={cpow:["cmul","cexp","cln"],cpowi:["cmul","cdiv"],ctan:["cdiv","csin","ccos"],ctanh:["cdiv","csinh","ccosh"]};function na(e,t){let n=t==="glsl"?"vec2":"vec2<f32>",r=(a,c,l)=>t==="glsl"?`${n} mx_${a}(${c.replace(/(\w+): vec2|(\w+): int/g,(u,h,f)=>h?`vec2 ${h}`:`int ${f}`)}) {
3
+ ${l}
4
+ }`:`fn mx_${a}(${c.replace(/: vec2/g,": vec2<f32>")}) -> ${n} {
5
+ ${l}
6
+ }`,s=(a,c,l)=>t==="glsl"?` ${a} ${c} = ${l};`:` let ${c}: ${a==="float"?"f32":a} = ${l};`,o=a=>` return ${a};`,i=(a,c)=>`${n}(${a}, ${c})`;switch(e){case"cmul":return r("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 r("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 r("cexp","z: vec2",o(`exp(z.x) * ${i("cos(z.y)","sin(z.y)")}`));case"cln":return r("cln","z: vec2",o(i("log(length(z))",t==="glsl"?"atan(z.y, z.x)":"atan2(z.y, z.x)")));case"cpow":return r("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 r("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 r("csin","z: vec2",o(i("sin(z.x) * cosh(z.y)","cos(z.x) * sinh(z.y)")));case"ccos":return r("ccos","z: vec2",o(i("cos(z.x) * cosh(z.y)","-sin(z.x) * sinh(z.y)")));case"ctan":return r("ctan","z: vec2",o("mx_cdiv(mx_csin(z), mx_ccos(z))"));case"csinh":return r("csinh","z: vec2",o(i("sinh(z.x) * cos(z.y)","cosh(z.x) * sin(z.y)")));case"ccosh":return r("ccosh","z: vec2",o(i("cosh(z.x) * cos(z.y)","sinh(z.x) * sin(z.y)")));case"ctanh":return r("ctanh","z: vec2",o("mx_cdiv(mx_csinh(z), mx_ccosh(z))"));case"cabs":return r("cabs","z: vec2",o(i("length(z)","0.0")));default:throw new Error(`unknown helper ${e}`)}}function ra(e){return/^[A-Za-z][A-Za-z0-9_]*$/.test(e)&&!Ns.has(e)&&!e.includes("__")&&!e.startsWith("mx_")&&!e.startsWith("gl_")}function wr(e,t,n={}){let r=n.complex===!0,s=n.variables??[r?"z":"x"];for(let h of s)if(!/^[A-Za-z][A-Za-z0-9_]*$/.test(h)||Ns.has(h)||h.includes("__")||h.startsWith("mx_")||h.startsWith("gl_"))throw new Ne(`variable name "${h}" is not a safe shader identifier`);let o=n.functionName;if(o!==void 0&&(!ra(o)||o==="main"))throw new Ne(`function name "${o}" is not a safe shader identifier`);let i={d:t,complex:r,vars:new Set(s),used:new Set,helpers:new Set},a=lt(e,i),c=new Set(i.helpers);for(let h=!0;h;){h=!1;for(let f of[...c])for(let m of ea[f]??[])c.has(m)||(c.add(m),h=!0)}let l=ta.filter(h=>c.has(h)).map(h=>na(h,t)).join(`
30
+
31
+ `),u=l;if(n.functionName!==void 0){let h=r?t==="glsl"?"vec2":"vec2<f32>":t==="glsl"?"float":"f32",f=s.map(p=>t==="glsl"?`${h} ${p}`:`${p}: ${h}`).join(", "),m=t==="glsl"?`${h} ${n.functionName}(${f}) {
32
+ return ${a};
33
+ }`:`fn ${n.functionName}(${f}) -> ${h} {
34
+ return ${a};
35
+ }`;u=l?`${l}
36
+
37
+ ${m}`:m}return{expression:a,helpers:l,source:u,variables:[...i.used].sort()}}var zs=["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"],Ds=["atan2","hypot","min","max","gcd","lcm"],Ls={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"},Vs=[...zs,...Object.keys(Ls),...Ds,"log","clamp","piecewise","sum","product"],M=e=>({type:"const",value:e}),nt=e=>({type:"var",name:e}),W=(e,t)=>({type:"add",left:e,right:t}),U=(e,t)=>({type:"sub",left:e,right:t}),q=(e,t)=>({type:"mul",left:e,right:t}),B=(e,t)=>({type:"div",left:e,right:t}),ct=(e,t)=>({type:"pow",base:e,exp:t}),Et=e=>({type:"neg",arg:e}),T=(e,t)=>({type:"func",name:e,arg:t}),re=(e,t,n)=>({type:"call2",name:e,left:t,right:n}),tn=(e,t,n)=>({type:"cmp",op:e,left:t,right:n}),be=(e,t)=>({type:"piecewise",branches:e,otherwise:t}),ce=(e,t,n,r)=>({type:"sum",variable:e,from:t,to:n,body:r}),Ie=(e,t,n,r)=>({type:"product",variable:e,from:t,to:n,body:r}),Rt=(e,t)=>e.type==="const"&&(t===void 0||e.value===t),J=(e,t)=>{switch(e.type){case"const":return!1;case"var":return e.name===t;case"neg":return J(e.arg,t);case"func":return J(e.arg,t);case"pow":return J(e.base,t)||J(e.exp,t);case"piecewise":return e.branches.some(n=>J(n.cond,t)||J(n.expr,t))||J(e.otherwise,t);case"sum":case"product":return J(e.from,t)||J(e.to,t)||e.variable!==t&&J(e.body,t);default:return J(e.left,t)||J(e.right,t)}},Vt=(e,t=new Set)=>{switch(e.type){case"const":return t;case"var":return t.add(e.name),t;case"neg":case"func":return Vt(e.arg,t),t;case"pow":return Vt(e.base,t),Vt(e.exp,t),t;case"piecewise":for(let n of e.branches)Vt(n.cond,t),Vt(n.expr,t);return Vt(e.otherwise,t),t;case"sum":case"product":{Vt(e.from,t),Vt(e.to,t);let n=Vt(e.body,new Set);for(let r of n)r!==e.variable&&t.add(r);return t}default:return Vt(e.left,t),Vt(e.right,t),t}};function sa(e,t){let n=o=>t[o]==="positive"||t[o]==="nonnegative",r=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"&&Rt(i.exp,2)&&i.base.type==="var"){if(n(i.base.name))return i.base;if(r(i.base.name))return{type:"neg",arg:i.base}}if(o.name==="abs"&&i.type==="var"){if(n(i.name))return i;if(r(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 Bt=class extends Error{constructor(t="This expression cannot be integrated by the elementary rules implemented."){super(t),this.name="NotIntegrableError"}},Rn=class extends Error{constructor(t="solveSystem only supports systems that are linear in the given variables."){super(t),this.name="NonLinearSystemError"}},Fn=class extends Error{constructor(t="solveSystem: the system is singular (rank < number of variables) and has no unique solution."){super(t),this.name="SingularSystemError"}},He=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"}},Cn=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}},Re=class extends Error{constructor(t="solveSystemNumeric: Newton's method did not converge from the given initial guess."){super(t),this.name="SystemDidNotConvergeError"}},zn=class extends Error{constructor(t="integrateDefinite: the integrand appears to have a singularity strictly inside the integration bounds."){super(t),this.name="IntegrationSingularityError"}};var Dn=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"}},de=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"}},Ln=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"}},Vn=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"}},S=class e{static parse(t,n={}){return new Sr(t,n??{}).parse()}static differentiate(t,n="x"){let r=typeof t=="string"?e.parse(t):t;return F(et(r,n))}static differentiateSteps(t,n="x"){let r=typeof t=="string"?e.parse(t):t,s=[],o=St(r,n,s);return{steps:s,result:F(o)}}static simplify(t){return jt(F(t))}static simplifyAssuming(t,n){let r=F(t),s=sa(r,n);return F(s)}static integrate(t,n="x"){let r=typeof t=="string"?e.parse(t):t;return F(kt(r,n))}static integrateDefinite(t,n,r,s="x",o={}){let i=F(typeof t=="string"?e.parse(t):t),a=xt(i);if(fa(c=>a({...o,[s]:c}),n,r))throw new zn;try{let c=F(kt(i,s)),l=u=>C(c,{...o,[s]:u});return l(r)-l(n)}catch(c){if(!(c instanceof Bt))throw c;return pe.adaptiveSimpson(l=>a({...o,[s]:l}),n,r)}}static solveOdeClosedForm(t,n,r,s="x",o="y"){let i=F(typeof t=="string"?e.parse(t):t),a=ma(i,s,o);if(a)return Us(a,s,o,n,r);let c=pa(i,s,o);if(c)return Zs(c,s,o,n,r);let l=ga(i,s,o);if(l)return xa(l,s,o,n,r);let u=wa(i,s,o);if(u)return ba(u,s,o,n,r);let h=ya(i,s,o);if(h)return va(h,s,o,n,r);throw new Dn}static solveOde2ndOrderConstCoeff(t,n,r,s,o,i){if(t===0)throw new Ln;let a=n*n-4*t*r,c=nt("x");if(Math.abs(a)<1e-9){let x=-n/(2*t),g=Math.exp(-x*s),w=(i-x*o)*g,b=o*g-w*s;return q(W(M(b),q(M(w),c)),T("exp",q(M(x),c)))}if(a>0){let x=Math.sqrt(a),g=(-n+x)/(2*t),w=(-n-x)/(2*t),b=Math.exp(g*s),y=Math.exp(w*s),[E,N]=at.solve([[b,y],[g*b,w*y]],[o,i]);return W(q(M(E),T("exp",q(M(g),c))),q(M(N),T("exp",q(M(w),c))))}let l=-n/(2*t),u=Math.sqrt(4*t*r-n*n)/(2*t),h=Math.exp(l*s),f=Math.cos(u*s),m=Math.sin(u*s),[p,d]=at.solve([[h*f,h*m],[-h*u*m,h*u*f]],[o,i-l*o]);return q(T("exp",q(M(l),c)),W(q(M(p),T("cos",q(M(u),c))),q(M(d),T("sin",q(M(u),c)))))}static taylor(t,n="x",r=0,s=4){let o=typeof t=="string"?e.parse(t):t,i=M(0),a=1;for(let c=0;c<=s;c++){c>0&&(a*=c);let l=e.evaluate(o,{[n]:r});if(l!==0){let u=ct(U(nt(n),M(r)),M(c));i=W(i,q(M(l/a),u))}o=et(o,n)}return F(i)}static substitute(t,n,r){let s=typeof t=="string"?e.parse(t):t,o=typeof r=="string"?e.parse(r):r;return F(ut(s,n,o))}static expand(t){let r=typeof t=="string"?e.parse(t):t;for(let s=0;s<30;s++){let o=F(ft(r));if(wt(o,r))return o;r=o}return r}static freeVariables(t){let n=typeof t=="string"?e.parse(t):t;return[...Vt(n)].sort()}static assertVariables(t,n){let r=typeof t=="string"?e.parse(t):t,s=new Set(n),o=e.freeVariables(r).filter(i=>!s.has(i));if(o.length>0)throw new Cn(o)}static evaluate(t,n={},r){let s=typeof t=="string"?e.parse(t):t;return r?.declaredVariables&&e.assertVariables(s,r.declaredVariables),C(s,n)}static compile(t,n){let r=typeof t=="string"?e.parse(t):t;return n?.declaredVariables&&e.assertVariables(r,n.declaredVariables),xt(r)}static evaluateExact(t,n={}){let r=typeof t=="string"?e.parse(t):t;return Pt(r,n)}static evaluateOverStructure(t,n,r={}){let s=typeof t=="string"?e.parse(t):t;return Ct(s,n,r)}static toString(t){return it(typeof t=="string"?e.parse(t):t,0)}static toGLSL(t,n={}){return wr(typeof t=="string"?e.parse(t):t,"glsl",n)}static toWGSL(t,n={}){return wr(typeof t=="string"?e.parse(t):t,"wgsl",n)}static toLatex(t){return _(typeof t=="string"?e.parse(t):t,0)}static fromLatex(t,n={}){return e.parse(Da(t,n),n)}static solve(t,n="x"){let r=typeof t=="string"?e.parse(t):t,s=Rs(F(r),n,6);if(!s)throw new Error(`solve: expression is not a polynomial in "${n}" of degree \u2264 6.`);return Nr(s).map(o=>F(o))}static solveSystem(t,n){let r=t.map(l=>F(typeof l=="string"?e.parse(l):l));if(r.length!==n.length)throw new Error(`solveSystem: expected ${n.length} equations for ${n.length} variables, got ${r.length}.`);let s=[],o=[];r.forEach((l,u)=>{let h=Ka(l,n);if(!h)throw new Rn(`solveSystem: equation ${u} ("${e.toString(l)}") is not linear in [${n.join(", ")}].`);s.push(h.slice(0,n.length)),o.push(-h[n.length])});let i=at.rank(s);if(i<n.length)throw new Fn(`solveSystem: the system is singular (rank ${i} < ${n.length} variables) and has no unique solution.`);let a=at.solve(s,o),c={};return n.forEach((l,u)=>{c[l]=a[u]}),c}static solveSystemNumeric(t,n,r){let s=t.map(f=>typeof f=="string"?e.parse(f):f);if(s.length!==n.length)throw new Error(`solveSystemNumeric: expected ${n.length} equations for ${n.length} variables, got ${s.length}.`);let o=n.length,i=s.map(f=>e.compile(f)),a=f=>{let m={};return n.forEach((p,d)=>{m[p]=f[d]}),i.map(p=>p(m))},c=r?[...r]:new Array(o).fill(1),l=1e-6,u=100,h=1e-10;for(let f=0;f<u;f++){let m=a(c);if(!m.every(Number.isFinite))throw new Re("solveSystemNumeric: evaluation produced a non-finite value.");let p=Math.sqrt(m.reduce((b,y)=>b+y*y,0));if(p<h){let b={};return n.forEach((y,E)=>{b[y]=c[E]}),b}let d=Array.from({length:o},()=>new Array(o).fill(0));for(let b=0;b<o;b++){let y=[...c];y[b]=y[b]+l;let E=a(y);for(let N=0;N<o;N++)d[N][b]=(E[N]-m[N])/l}let x;try{x=at.solve(d,m.map(b=>-b))}catch{throw new Re("solveSystemNumeric: the Jacobian became singular during iteration.")}let g=1,w=!1;for(let b=0;b<20&&!w;b++){let y=c.map((N,$)=>N+g*x[$]),E=a(y);if(E.every(Number.isFinite)&&Math.sqrt(E.reduce(($,O)=>$+O*O,0))<p){c=y,w=!0;break}g/=2}if(!w)throw new Re("solveSystemNumeric: no damped step improved the residual from the current iterate.")}throw new Re(`solveSystemNumeric: did not converge within ${u} iterations from the given initial guess.`)}static verifySolution(t,n,r,s={},o=1e-6){let i=e.evaluate(t,{...s,[n]:r});return Number.isFinite(i)&&Math.abs(i)<o}static verifySystemSolution(t,n,r=1e-6){return t.every(s=>{let o=e.evaluate(s,n);return Number.isFinite(o)&&Math.abs(o)<r})}static sumSeries(t,n,r,s="n",o={}){let i=typeof t=="string"?e.parse(t):t;if(Number.isFinite(r)){if(n>r)return 0;let c=xt(i),l=0;for(let u=n;u<=r;u++)l+=c({...o,[s]:u});return l}let a=Ma(i,s,n,o);return a!==null?a:Ea(i,s,n,o)}static factor(t,n="x"){let r=typeof t=="string"?e.parse(t):t,s=F(r),o=Rs(s,n,6);return o?tc(o,n):s}static limit(t,n="x",r=0,s="both"){let o=typeof t=="string"?e.parse(t):t;return xo(o,n,r,s,0)}};function St(e,t,n){let r,s;switch(e.type){case"const":r="Constant Rule",s=M(0);break;case"var":r=e.name===t?"Variable Rule":"Constant Rule",s=M(e.name===t?1:0);break;case"add":r="Sum Rule",s=W(St(e.left,t,n),St(e.right,t,n));break;case"sub":r="Difference Rule",s=U(St(e.left,t,n),St(e.right,t,n));break;case"mul":r="Product Rule",s=W(q(St(e.left,t,n),e.right),q(e.left,St(e.right,t,n)));break;case"div":r="Quotient Rule",s=B(U(q(St(e.left,t,n),e.right),q(e.left,St(e.right,t,n))),ct(e.right,M(2)));break;case"neg":r="Negation Rule",s=Et(St(e.arg,t,n));break;case"pow":e.exp.type==="const"?(r="Power Rule",s=q(q(e.exp,ct(e.base,M(e.exp.value-1))),St(e.base,t,n))):(r="Generalized Power Rule",s=q(e,W(q(St(e.exp,t,n),T("ln",e.base)),q(e.exp,B(St(e.base,t,n),e.base)))));break;case"func":{r=`Chain Rule (${e.name})`;let o=e.arg,i=St(o,t,n);s=fr[e.name](o,i);break}case"call2":{r=`Multivariable Chain Rule (${e.name})`;let o=e.left,i=e.right,a=St(o,t,n),c=St(i,t,n);switch(e.name){case"atan2":s=B(U(q(i,a),q(o,c)),W(ct(o,M(2)),ct(i,M(2))));break;case"hypot":s=B(W(q(o,a),q(i,c)),re("hypot",o,i));break;case"min":s=U(B(W(a,c),M(2)),q(T("sign",U(o,i)),B(U(a,c),M(2))));break;case"max":s=W(B(W(a,c),M(2)),q(T("sign",U(o,i)),B(U(a,c),M(2))));break;case"gcd":case"lcm":s=M(0);break}break}case"cmp":r="Comparison Rule (locally constant)",s=M(0);break;case"piecewise":r="Piecewise Rule (branch-wise)",s=be(e.branches.map(o=>({cond:o.cond,expr:St(o.expr,t,n)})),St(e.otherwise,t,n));break;case"sum":r="Sum Rule (\u03A3, term-wise by linearity)",s=ce(e.variable,e.from,e.to,St(e.body,t,n));break;case"product":r="Product Rule (\u03A0, via the logarithmic-derivative identity: d(ln P)/dx = \u03A3 (dbody/dx)/body)",s=q(Ie(e.variable,e.from,e.to,e.body),ce(e.variable,e.from,e.to,B(St(e.body,t,n),e.body)));break}return n.push({rule:r,input:e,output:s}),s}function et(e,t){switch(e.type){case"const":return M(0);case"var":return M(e.name===t?1:0);case"add":return W(et(e.left,t),et(e.right,t));case"sub":return U(et(e.left,t),et(e.right,t));case"mul":return W(q(et(e.left,t),e.right),q(e.left,et(e.right,t)));case"div":return B(U(q(et(e.left,t),e.right),q(e.left,et(e.right,t))),ct(e.right,M(2)));case"neg":return Et(et(e.arg,t));case"pow":return e.exp.type==="const"?q(q(e.exp,ct(e.base,M(e.exp.value-1))),et(e.base,t)):q(e,W(q(et(e.exp,t),T("ln",e.base)),q(e.exp,B(et(e.base,t),e.base))));case"func":{let n=e.arg,r=et(n,t);return fr[e.name](n,r)}case"call2":{let n=e.left,r=e.right,s=et(n,t),o=et(r,t),i=e.name;switch(i){case"atan2":return B(U(q(r,s),q(n,o)),W(ct(n,M(2)),ct(r,M(2))));case"hypot":return B(W(q(n,s),q(r,o)),re("hypot",n,r));case"min":return U(B(W(s,o),M(2)),q(T("sign",U(n,r)),B(U(s,o),M(2))));case"max":return W(B(W(s,o),M(2)),q(T("sign",U(n,r)),B(U(s,o),M(2))));case"gcd":case"lcm":return M(0)}throw new Error(`Unhandled binary function: ${i}`)}case"cmp":return M(0);case"piecewise":return be(e.branches.map(n=>({cond:n.cond,expr:et(n.expr,t)})),et(e.otherwise,t));case"sum":return ce(e.variable,e.from,e.to,et(e.body,t));case"product":return q(Ie(e.variable,e.from,e.to,e.body),ce(e.variable,e.from,e.to,B(et(e.body,t),e.body)))}}function F(e){let t=typeof e=="string"?S.parse(e):e;for(let n=0;n<30;n++){let r=Mt(qt(t));if(wt(r,t))return r;t=r}return t}function qt(e){if(e.type==="const"||e.type==="var")return e;if(e.type==="neg"){let r=qt(e.arg);return r.type==="const"?M(-r.value):r.type==="neg"?r.arg:Et(r)}if(e.type==="func")return T(e.name,qt(e.arg));if(e.type==="call2"){let r=qt(e.left),s=qt(e.right);return r.type==="const"&&s.type==="const"?M(qr[e.name](r.value,s.value)):re(e.name,r,s)}if(e.type==="pow"){let r=qt(e.base),s=qt(e.exp);return Rt(s,0)?M(1):Rt(s,1)?r:Rt(r,0)?M(0):Rt(r,1)?M(1):r.type==="const"&&s.type==="const"?M(r.value**s.value):ct(r,s)}if(e.type==="cmp"){let r=qt(e.left),s=qt(e.right);return r.type==="const"&&s.type==="const"?M(Ir[e.op](r.value,s.value)?1:0):tn(e.op,r,s)}if(e.type==="piecewise")return be(e.branches.map(r=>({cond:qt(r.cond),expr:qt(r.expr)})),qt(e.otherwise));if(e.type==="sum")return ce(e.variable,qt(e.from),qt(e.to),qt(e.body));if(e.type==="product")return Ie(e.variable,qt(e.from),qt(e.to),qt(e.body));let t=qt(e.left),n=qt(e.right);if(t.type==="const"&&n.type==="const"){if(e.type==="add")return M(t.value+n.value);if(e.type==="sub")return M(t.value-n.value);if(e.type==="mul")return M(t.value*n.value);if(e.type==="div"&&n.value!==0)return M(t.value/n.value)}switch(e.type){case"add":return Rt(t,0)?n:Rt(n,0)?t:W(t,n);case"sub":return Rt(n,0)?t:Rt(t,0)?Et(n):wt(t,n)?M(0):U(t,n);case"mul":return Rt(t,0)||Rt(n,0)?M(0):Rt(t,1)?n:Rt(n,1)?t:q(t,n);case"div":return Rt(n,0)?B(t,n):Rt(t,0)?M(0):Rt(n,1)?t:B(t,n)}return e}function wt(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 wt(e.arg,t.arg);case"func":return e.name===t.name&&wt(e.arg,t.arg);case"call2":return e.name===t.name&&wt(e.left,t.left)&&wt(e.right,t.right);case"pow":return wt(e.base,t.base)&&wt(e.exp,t.exp);case"cmp":{let n=t;return e.op===n.op&&wt(e.left,n.left)&&wt(e.right,n.right)}case"piecewise":{let n=t;return e.branches.length===n.branches.length&&e.branches.every((r,s)=>wt(r.cond,n.branches[s].cond)&&wt(r.expr,n.branches[s].expr))&&wt(e.otherwise,n.otherwise)}case"sum":case"product":{let n=t;return e.variable===n.variable&&wt(e.from,n.from)&&wt(e.to,n.to)&&wt(e.body,n.body)}default:return wt(e.left,t.left)&&wt(e.right,t.right)}}function ut(e,t,n){switch(e.type){case"const":return e;case"var":return e.name===t?n:e;case"neg":return Et(ut(e.arg,t,n));case"func":return T(e.name,ut(e.arg,t,n));case"call2":return re(e.name,ut(e.left,t,n),ut(e.right,t,n));case"pow":return ct(ut(e.base,t,n),ut(e.exp,t,n));case"add":return W(ut(e.left,t,n),ut(e.right,t,n));case"sub":return U(ut(e.left,t,n),ut(e.right,t,n));case"mul":return q(ut(e.left,t,n),ut(e.right,t,n));case"div":return B(ut(e.left,t,n),ut(e.right,t,n));case"cmp":return tn(e.op,ut(e.left,t,n),ut(e.right,t,n));case"piecewise":return be(e.branches.map(r=>({cond:ut(r.cond,t,n),expr:ut(r.expr,t,n)})),ut(e.otherwise,t,n));case"sum":case"product":{let r=ut(e.from,t,n),s=ut(e.to,t,n),o=e.variable===t?e.body:ut(e.body,t,n);return e.type==="sum"?ce(e.variable,r,s,o):Ie(e.variable,r,s,o)}}}var oa=8;function ft(e){switch(e.type){case"const":case"var":return e;case"neg":return Et(ft(e.arg));case"func":return T(e.name,ft(e.arg));case"call2":return re(e.name,ft(e.left),ft(e.right));case"add":return W(ft(e.left),ft(e.right));case"sub":return U(ft(e.left),ft(e.right));case"div":return B(ft(e.left),ft(e.right));case"pow":{let t=ft(e.base);if(e.exp.type==="const"&&Number.isInteger(e.exp.value)&&e.exp.value>=2&&e.exp.value<=oa&&(t.type==="add"||t.type==="sub")){let n=t;for(let r=1;r<e.exp.value;r++)n=ae(n,t);return n}return ct(t,ft(e.exp))}case"mul":return ae(ft(e.left),ft(e.right));case"cmp":return tn(e.op,ft(e.left),ft(e.right));case"piecewise":return be(e.branches.map(t=>({cond:ft(t.cond),expr:ft(t.expr)})),ft(e.otherwise));case"sum":return ce(e.variable,ft(e.from),ft(e.to),ft(e.body));case"product":return Ie(e.variable,ft(e.from),ft(e.to),ft(e.body))}}function ae(e,t){return e.type==="add"?W(ae(e.left,t),ae(e.right,t)):e.type==="sub"?U(ae(e.left,t),ae(e.right,t)):t.type==="add"?W(ae(e,t.left),ae(e,t.right)):t.type==="sub"?U(ae(e,t.left),ae(e,t.right)):q(e,t)}function Mt(e){switch(e.type){case"const":case"var":return e;case"func":return T(e.name,Mt(e.arg));case"call2":return re(e.name,Mt(e.left),Mt(e.right));case"div":{let t=Mt(e.left),n=Mt(e.right);return n.type==="const"&&n.value!==0&&t.type!=="add"&&t.type!=="sub"?Is(qs([Ke(B(t,n))])):B(t,n)}case"pow":return ct(Mt(e.base),Mt(e.exp));case"neg":case"add":case"sub":case"mul":{let t=[];return _e(e,1,t),Is(qs(t))}case"cmp":return tn(e.op,Mt(e.left),Mt(e.right));case"piecewise":return be(e.branches.map(t=>({cond:Mt(t.cond),expr:Mt(t.expr)})),Mt(e.otherwise));case"sum":return ce(e.variable,Mt(e.from),Mt(e.to),Mt(e.body));case"product":return Ie(e.variable,Mt(e.from),Mt(e.to),Mt(e.body))}}function _e(e,t,n){if(e.type==="add"){_e(e.left,t,n),_e(e.right,t,n);return}if(e.type==="sub"){_e(e.left,t,n),_e(e.right,-t,n);return}if(e.type==="neg"){_e(e.arg,-t,n);return}let r=Ke(e);n.push({coeff:r.coeff*t,factors:r.factors})}function Ke(e){if(e.type==="const")return{coeff:e.value,factors:[]};if(e.type==="neg"){let t=Ke(e.arg);return{coeff:-t.coeff,factors:t.factors}}if(e.type==="mul"){let t=Ke(e.left),n=Ke(e.right);return br(t.coeff*n.coeff,[...t.factors,...n.factors])}if(e.type==="div"&&e.right.type==="const"&&e.right.value!==0){let t=Ke(e.left);return{coeff:t.coeff/e.right.value,factors:t.factors}}return e.type==="pow"&&e.exp.type==="const"?br(1,[{base:Mt(e.base),exp:e.exp.value}]):br(1,[{base:Mt(e),exp:1}])}function br(e,t){let n=[];for(let r of t){let s=n.find(o=>wt(o.base,r.base));s?s.exp+=r.exp:n.push({...r})}return{coeff:e,factors:n.filter(r=>r.exp!==0)}}function qs(e){let t=new Map,n=[];for(let r of e){let s=[...r.factors].sort((a,c)=>it(a.base,0).localeCompare(it(c.base,0))),o=s.map(a=>`${it(a.base,0)}^${a.exp}`).join("*"),i=t.get(o);i?i.coeff+=r.coeff:(t.set(o,{coeff:r.coeff,factors:s}),n.push(o))}return n.map(r=>t.get(r)).filter(r=>r.coeff!==0)}function ia(e){let t=null;for(let n of e){let r=n.exp===1?n.base:ct(n.base,M(n.exp));t=t===null?r:q(t,r)}return t}function Is(e){let t=null;for(let n of e){let r=ia(n.factors),s=Math.abs(n.coeff),o=s!==0?1/s:0,i=s<1&&Math.abs(Math.round(o)-o)<1e-12,a=r===null?M(s):s===1?r:i?B(r,M(Math.round(o))):q(M(s),r);t===null?t=n.coeff<0?Et(a):a:t=n.coeff<0?U(t,a):W(t,a)}return t??M(0)}function Bs(e,t){if(!J(e,t))return q(e,nt(t));switch(e.type){case"var":return B(ct(nt(t),M(2)),M(2));case"add":return W(kt(e.left,t),kt(e.right,t));case"sub":return U(kt(e.left,t),kt(e.right,t));case"neg":return Et(kt(e.arg,t));case"mul":{if(!J(e.left,t))return q(e.left,kt(e.right,t));if(!J(e.right,t))return q(e.right,kt(e.left,t));for(let[n,r]of[[e.left,e.right],[e.right,e.left]]){let s=Na(n,t);if(s!==null&&r.type==="func"&&qa(r.name)&&Mr(r.arg,t))return Xs(s,r,t)}throw new Bt}case"div":{if(!J(e.right,t))return B(kt(e.left,t),e.right);if(!J(e.left,t)&&e.right.type==="var"&&e.right.name===t)return q(e.left,T("ln",T("abs",nt(t))));if(!J(e.left,t)){let n=C(e.left,{}),r=yr(e.right,t);if(r&&Math.abs(r.a-1)<1e-9&&Math.abs(r.b)<1e-9&&r.c>0){let o=Math.sqrt(r.c);return q(M(n/o),T("atan",B(nt(t),M(o))))}if(e.right.type==="func"&&e.right.name==="sqrt"){let o=yr(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 q(M(n),T("asin",B(nt(t),M(i))))}}let s=yr(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),l=n/(s.a*(a-c)),u=-l;return W(q(M(l),T("ln",T("abs",U(nt(t),M(a))))),q(M(u),T("ln",T("abs",U(nt(t),M(c))))))}}}throw new Bt}case"pow":{if(e.base.type==="var"&&e.base.name===t&&e.exp.type==="const")return e.exp.value===-1?T("ln",T("abs",nt(t))):B(ct(nt(t),M(e.exp.value+1)),M(e.exp.value+1));throw new Bt}case"func":{let n=Mr(e.arg,t);if(!n)throw new Bt;let r=e.arg,s=o=>B(o,M(n.a));switch(e.name){case"sin":return s(Et(T("cos",r)));case"cos":return s(T("sin",r));case"exp":return s(T("exp",r));case"ln":return s(U(q(r,T("ln",r)),r));case"sqrt":return s(q(M(2/3),ct(r,M(1.5))));case"tan":return s(Et(T("ln",T("abs",T("cos",r)))));case"cot":return s(T("ln",T("abs",T("sin",r))));case"sec":return s(T("ln",T("abs",W(T("sec",r),T("tan",r)))));case"csc":return s(Et(T("ln",T("abs",W(T("csc",r),T("cot",r))))));case"sinh":return s(T("cosh",r));case"cosh":return s(T("sinh",r));case"tanh":return s(T("ln",T("cosh",r)));case"asin":return s(W(q(r,T("asin",r)),T("sqrt",U(M(1),ct(r,M(2))))));case"acos":return s(U(q(r,T("acos",r)),T("sqrt",U(M(1),ct(r,M(2))))));case"atan":return s(U(q(r,T("atan",r)),q(M(.5),T("ln",W(M(1),ct(r,M(2)))))));default:throw new Bt}}default:throw new Bt}}function ie(e,t){if(wt(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(n=>ie(n.cond,t)||ie(n.expr,t))||ie(e.otherwise,t);case"sum":case"product":return!1;default:return ie(e.left,t)||ie(e.right,t)}}function ne(e,t,n){if(wt(e,t))return n;switch(e.type){case"const":case"var":return e;case"neg":return Et(ne(e.arg,t,n));case"func":return T(e.name,ne(e.arg,t,n));case"pow":return ct(ne(e.base,t,n),ne(e.exp,t,n));case"piecewise":return be(e.branches.map(r=>({cond:ne(r.cond,t,n),expr:ne(r.expr,t,n)})),ne(e.otherwise,t,n));case"sum":case"product":return e;default:return{...e,left:ne(e.left,t,n),right:ne(e.right,t,n)}}}function Bn(e){return e.type==="mul"?[...Bn(e.left),...Bn(e.right)]:[e]}function aa(e,t){let n=e.type==="div"?e.right:null,r=e.type==="div"?e.left:e,s=1,o=[];for(let h of Bn(r))h.type==="const"?s*=h.value:o.push(h);let i=1,a=[];for(let h of Bn(t))h.type==="const"?i*=h.value:a.push(h);if(i===0)return null;for(let h of a){let f=o.findIndex(m=>wt(m,h));if(f===-1)return null;o.splice(f,1)}let c=s/i,l=c===1?o:[M(c),...o],u=l.length===0?M(c):l.reduce((h,f)=>h?q(h,f):f);return n?B(u,n):u}function ca(e,t){let n=[],r=o=>{switch(o.type){case"const":case"var":return;case"neg":r(o.arg);return;case"func":J(o.arg,t)&&n.push(o.arg),r(o.arg);return;case"pow":J(o.base,t)&&n.push(o.base),J(o.exp,t)&&n.push(o.exp),r(o.base),r(o.exp);return;case"call2":J(o.left,t)&&n.push(o.left),J(o.right,t)&&n.push(o.right),r(o.left),r(o.right);return;case"piecewise":for(let i of o.branches)r(i.cond),r(i.expr);r(o.otherwise);return;case"sum":case"product":return;case"div":J(o.right,t)&&n.push(o.right),r(o.left),r(o.right);return;default:r(o.left),r(o.right);return}};r(e);let s=[];for(let o of n)o.type==="var"&&o.name===t||s.some(i=>wt(i,o))||s.push(o);return s}function la(e,t){let n="u",r=2;for(;n===t||J(e,n);)n=`u${r++}`;return n}function ua(e,t,n){let r=F(et(e,n)),s=0;for(let o of[.7,1.3,-.9]){let i=C(t,{[n]:o}),a=C(r,{[n]: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 ha(e,t){for(let n of ca(e,t)){let r=F(et(n,t));if(Rt(r,0))continue;let s=F(aa(e,r)??B(e,r));if(!ie(s,n))continue;let o=la(s,t),i=ne(s,n,nt(o));if(!J(i,t))try{let a=Bs(i,o),c=F(ne(a,nt(o),n));if(ua(c,e,t))return c}catch(a){if(!(a instanceof Bt))throw a}}return null}function fa(e,t,n){let r=Math.min(t,n),s=Math.max(t,n),o=(s-r)*.01,i=r+o,a=s-o,c=64,l=-1/0;for(let u=0;u<6;u++){let h=-1/0,f=(i+a)/2;for(let p=1;p<c;p++){let d=i+p/c*(a-i),x=e(d);if(!Number.isFinite(x))return!0;let g=Math.abs(x);g>h&&(h=g,f=d)}if(u>0&&h>l*4)return!0;l=h;let m=(a-i)/c;if(i=Math.max(r+o,f-m*2),a=Math.min(s-o,f+m*2),a-i<1e-9)return!0}return!1}function kt(e,t){try{return Bs(e,t)}catch(n){if(!(n instanceof Bt))throw n;let r=ha(e,t);if(r)return r;throw n}}var ge=(e,t)=>[...Vt(e)].every(n=>t.has(n));function ma(e,t,n){let r=Vt(e);if(![...r].every(c=>c===t||c===n))return null;let s=r.has(t);if(!r.has(n))return{g:e,h:M(1)};if(!s)return{g:M(1),h:e};if(e.type!=="mul")return null;let i=new Set([t]),a=new Set([n]);return ge(e.left,i)&&ge(e.right,a)?{g:e.left,h:e.right}:ge(e.left,a)&&ge(e.right,i)?{g:e.right,h:e.left}:null}function pa(e,t,n){if(!J(e,n))return null;let r=F(et(e,n));if(J(r,n))return null;let s=F(U(e,q(r,nt(n))));if(J(s,n))return null;let o=F(Et(r)),i=new Set([t]);return!ge(o,i)||!ge(s,i)?null:{p:o,q:s}}function Gs(e,t,n,r){if(e.type==="var"&&e.name===t)return n;if(e.type==="func"&&e.name==="ln"&&e.arg.type==="var"&&e.arg.name===t)return T("exp",n);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(r);return s===0?null:s===1?T("exp",n):Et(T("exp",n))}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:ct(q(M(s),n),M(1/s))}return null}function Us(e,t,n,r,s){let o=F(B(M(1),e.h)),i,a;try{i=F(kt(o,n)),a=F(kt(e.g,t))}catch(h){throw h instanceof Bt?new de:h}let c=C(i,{[n]:s})-C(a,{[t]:r}),l=F(W(a,M(c))),u=Gs(i,n,l,s);return u?{explicit:!0,y:F(u)}:{explicit:!1,implicitRelation:F(U(i,l))}}function Zs(e,t,n,r,s){let o,i,a;try{o=F(kt(e.p,t)),i=F(T("exp",o)),a=F(kt(F(q(i,e.q)),t))}catch(f){throw f instanceof Bt?new de:f}let c=C(i,{[t]:r}),l=C(a,{[t]:r}),u=s*c-l;return{explicit:!0,y:F(B(W(a,M(u)),i))}}function da(e,t){let n="v",r=2;for(;t.includes(n)||J(e,n);)n=`v${r++}`;return n}function ga(e,t,n){let r=da(e,[t,n]),s=ut(e,n,q(nt(r),nt(t))),o=0,i=0;for(let c of[.6,1.4,-.8]){let l=null;for(let u of[1,2.3,-1.7]){i++;let h=C(s,{[t]:u,[r]:c});if(Number.isFinite(h))if(l===null)l=h,o++;else{if(Math.abs(h-l)>1e-6*Math.max(1,Math.abs(l)))return null;o++}}}if(i===0||o<4)return null;let a=F(ut(s,t,M(1)));return{vName:r,F:a}}function xa(e,t,n,r,s){let{vName:o,F:i}=e,a=s/r,c=F(U(i,nt(o)));if(c.type==="const"&&c.value===0)return{explicit:!0,y:F(q(M(a),nt(t)))};let l=Us({g:B(M(1),nt(t)),h:c},t,o,r,a);return l.explicit&&l.y?{explicit:!0,y:F(q(l.y,nt(t)))}:{explicit:!1,implicitRelation:F(ut(l.implicitRelation,o,B(nt(n),nt(t))))}}function As(e,t,n){let r=i=>i.type==="var"&&i.name===n,s=i=>r(i)?1:i.type==="pow"&&r(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:M(1),n:i}}for(let[i,a]of[[e.left,e.right],[e.right,e.left]]){if(!ge(i,o))continue;let c=s(a);if(c!==null)return{coef:i,n:c}}return null}function wa(e,t,n){let r,s,o;if(e.type==="sub")r=e.left,s=e.right,o=-1;else if(e.type==="add")r=e.left,s=e.right,o=1;else return null;let i=As(r,t,n),a=As(s,t,n);if(!i||!a)return null;let c,l,u,h;if(i.n!==1&&a.n===1)c=i,l=1,u=a,h=o;else if(a.n!==1&&i.n===1)c=a,l=o,u=i,h=1;else return null;if(c.n===0)return null;let f=l===1?c.coef:F(Et(c.coef));return{p:h===1?F(Et(u.coef)):u.coef,q:f,n:c.n}}function ba(e,t,n,r,s){let o=1-e.n,i=s**o,a=F(q(M(o),e.p)),c=F(q(M(o),e.q)),l=Zs({p:a,q:c},t,n,r,i);return{explicit:!0,y:F(ct(l.y,M(1/o)))}}function ya(e,t,n){if(e.type!=="div"||![...Vt(e)].every(l=>l===t||l===n))return null;let s=e.left,o=F(Et(e.right)),i=et(s,n),a=et(o,t),c=0;for(let l of[.7,1.3,-.9])for(let u of[.8,-1.2,1.7]){let h=C(i,{[t]:l,[n]:u}),f=C(a,{[t]:l,[n]:u});if(!(!Number.isFinite(h)||!Number.isFinite(f))){if(Math.abs(h-f)>1e-6*Math.max(1,Math.abs(h),Math.abs(f)))return null;c++}}return c<4?null:{M:s,N:o}}function va(e,t,n,r,s){let{M:o,N:i}=e,a,c,l;try{if(a=F(kt(o,t)),l=F(U(i,et(a,n))),J(l,t)){let f=null;for(let m of[1,2.3,-1.7]){let p=C(l,{[t]:m,[n]:.8}),d=C(l,{[t]:m===1?2.3:1,[n]:.8});if(!(!Number.isFinite(p)||!Number.isFinite(d))){if(Math.abs(p-d)>1e-6*Math.max(1,Math.abs(p)))throw new de;f=F(ut(l,t,M(m)));break}}if(!f)throw new de;l=f}c=F(kt(l,n))}catch(f){throw f instanceof Bt?new de:f}let u=F(W(a,c)),h=C(u,{[t]:r,[n]:s});if(!Number.isFinite(h))throw new de;if(u.type==="add"||u.type==="sub"){let f=new Set([t]),m=new Set([n]),[p,d]=[u.left,u.right];for(let[x,g]of[[p,u.type==="sub"?Et(d):d],[d,u.type==="sub"?Et(p):p]]){if(!ge(x,m)||!ge(g,f)||u.type==="sub"&&x===d)continue;let w=F(U(M(h),g)),b=Gs(x,n,w,s);if(b)return{explicit:!0,y:F(b)}}}return{explicit:!1,implicitRelation:F(U(u,M(h)))}}function Mr(e,t){try{let n=C(e,{[t]:0}),s=C(e,{[t]:1})-n,o=n,i=C(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 Ma(e,t,n,r){let s=1,o=e;if(e.type==="mul")if(!J(e.left,t)&&e.right.type==="pow")s=C(e.left,r),o=e.right;else if(!J(e.right,t)&&e.left.type==="pow")s=C(e.right,r),o=e.left;else return null;else if(e.type!=="pow")return null;if(o.type!=="pow"||J(o.base,t))return null;let i=Mr(o.exp,t);if(!i)return null;let a=C(o.base,r),c=a**i.a;if(!Number.isFinite(c)||Math.abs(c)>=1)return null;let l=i.a*n+i.b;return s*a**l/(1-c)}function Ea(e,t,n,r){let s=xt(e),o=1e-12,i=2e5,a=0,c=0,l=0;for(let h=0;h<i;h++){let f=n+h,m=s({...r,[t]:f});if(!Number.isFinite(m))throw new He(`sumSeries: term at index ${f} is not finite.`);if(h===0&&(l=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(h>100&&Math.abs(m)>l*10)throw new He("sumSeries: terms are growing (not shrinking toward 0) -- the series appears to diverge.")}let u=$a(h=>s({...r,[t]:h}),n+i);if(u!==null)return a+u;throw new He(`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 $a(e,t){let n=t,r=Math.max(1,t),s=0,o=Number.POSITIVE_INFINITY,i=40;for(let a=0;a<i;a++){let c=n+r,l=pe.adaptiveSimpson(e,n,c);if(!Number.isFinite(l)||(s+=l,a>5&&Math.abs(l)>Math.abs(o)*1.5))return null;if(Math.abs(l)<1e-13*Math.max(1,Math.abs(s))&&a>2)return s;o=l,n=c,r*=2}return null}function yr(e,t){try{let n=C(e,{[t]:0}),r=C(e,{[t]:1}),s=C(e,{[t]:-1}),o=n,i=(r+s)/2-o,a=(r-s)/2,c=C(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 Na(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 Sa=new Set(["sin","cos","exp"]);function qa(e){return Sa.has(e)}function Xs(e,t,n){if(e===0)return kt(t,n);let r=kt(t,n),s=e===1?nt(n):ct(nt(n),M(e)),o=q(s,r),i=Xs(e-1,r,n);return U(o,q(M(e),i))}function C(e,t){switch(e.type){case"const":return e.value;case"var":return t[e.name]??Number.NaN;case"add":return C(e.left,t)+C(e.right,t);case"sub":return C(e.left,t)-C(e.right,t);case"mul":return C(e.left,t)*C(e.right,t);case"div":return C(e.left,t)/C(e.right,t);case"pow":return C(e.base,t)**C(e.exp,t);case"neg":return-C(e.arg,t);case"func":{let n=C(e.arg,t),r=e.name;switch(r){case"sin":return Math.sin(n);case"cos":return Math.cos(n);case"tan":return Math.tan(n);case"exp":return Math.exp(n);case"ln":return Math.log(n);case"sqrt":return Math.sqrt(n);case"asin":return Math.asin(n);case"acos":return Math.acos(n);case"atan":return Math.atan(n);case"sinh":return Math.sinh(n);case"cosh":return Math.cosh(n);case"tanh":return Math.tanh(n);case"cot":return Qs(n);case"sec":return Js(n);case"csc":return _s(n);case"asinh":return Math.asinh(n);case"acosh":return Math.acosh(n);case"atanh":return Math.atanh(n);case"coth":return Ks(n);case"sech":return Hs(n);case"csch":return to(n);case"acot":return eo(n);case"asec":return no(n);case"acsc":return ro(n);case"acoth":return so(n);case"asech":return oo(n);case"acsch":return io(n);case"abs":return Math.abs(n);case"log10":return Math.log10(n);case"log2":return Math.log2(n);case"cbrt":return Math.cbrt(n);case"floor":return Math.floor(n);case"ceil":return Math.ceil(n);case"round":return Math.round(n);case"sign":return Math.sign(n);case"trunc":return Math.trunc(n);case"expm1":return Math.expm1(n);case"log1p":return Math.log1p(n);case"sigmoid":return ao(n);case"erf":return st.erf(n);case"relu":return Math.max(n,0)}throw new Error(`Unhandled function: ${r}`)}case"call2":return qr[e.name](C(e.left,t),C(e.right,t));case"cmp":return Ir[e.op](C(e.left,t),C(e.right,t))?1:0;case"piecewise":{for(let n of e.branches)if(C(n.cond,t)!==0)return C(n.expr,t);return C(e.otherwise,t)}case"sum":return Ws(e,t);case"product":return Ys(e,t)}}function Ws(e,t){let n=Math.round(C(e.from,t)),r=C(e.to,t);return S.sumSeries(e.body,n,Number.isFinite(r)?Math.round(r):r,e.variable,t)}function Ys(e,t){let n=Math.round(C(e.from,t)),r=C(e.to,t);if(!Number.isFinite(r))throw new Error("product (\u03A0): only finite upper bounds are supported.");let s=Math.round(r);if(n>s)return 1;let o=xt(e.body),i=1;for(let a=n;a<=s;a++)i*=o({...t,[e.variable]:a});return i}var Qs=e=>1/Math.tan(e),Js=e=>1/Math.cos(e),_s=e=>1/Math.sin(e),Ks=e=>1/Math.tanh(e),Hs=e=>1/Math.cosh(e),to=e=>1/Math.sinh(e),eo=e=>Math.PI/2-Math.atan(e),no=e=>Math.acos(1/e),ro=e=>Math.asin(1/e),so=e=>Math.atanh(1/e),oo=e=>Math.acosh(1/e),io=e=>Math.asinh(1/e),ao=e=>1/(1+Math.exp(-e)),Ia={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:Qs,sec:Js,csc:_s,asinh:Math.asinh,acosh:Math.acosh,atanh:Math.atanh,coth:Ks,sech:Hs,csch:to,acot:eo,asec:no,acsc:ro,acoth:so,asech:oo,acsch:io,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:ao,erf:st.erf,relu:e=>Math.max(e,0)},qr={atan2:Math.atan2,hypot:Math.hypot,min:Math.min,max:Math.max,gcd:$r,lcm:(e,t)=>Math.abs(e*t)/$r(e,t)},Ir={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 xt(e){switch(e.type){case"const":{let t=e.value;return()=>t}case"var":{let t=e.name;return n=>n[t]??Number.NaN}case"add":{let t=xt(e.left),n=xt(e.right);return r=>t(r)+n(r)}case"sub":{let t=xt(e.left),n=xt(e.right);return r=>t(r)-n(r)}case"mul":{let t=xt(e.left),n=xt(e.right);return r=>t(r)*n(r)}case"div":{let t=xt(e.left),n=xt(e.right);return r=>t(r)/n(r)}case"pow":{let t=xt(e.base),n=xt(e.exp);return r=>t(r)**n(r)}case"neg":{let t=xt(e.arg);return n=>-t(n)}case"func":{let t=xt(e.arg),n=Ia[e.name];return r=>n(t(r))}case"call2":{let t=xt(e.left),n=xt(e.right),r=qr[e.name];return s=>r(t(s),n(s))}case"cmp":{let t=xt(e.left),n=xt(e.right),r=Ir[e.op];return s=>r(t(s),n(s))?1:0}case"piecewise":{let t=e.branches.map(r=>({cond:xt(r.cond),expr:xt(r.expr)})),n=xt(e.otherwise);return r=>{for(let s of t)if(s.cond(r)!==0)return s.expr(r);return n(r)}}case"sum":return t=>Ws(e,t);case"product":return t=>Ys(e,t)}}var Aa={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 Pt(e,t){switch(e.type){case"const":return tt.fromNumber(e.value);case"var":{let n=t[e.name];if(!n)throw new Error(`No exact value bound for "${e.name}"`);return n}case"add":return Pt(e.left,t).add(Pt(e.right,t));case"sub":return Pt(e.left,t).subtract(Pt(e.right,t));case"mul":return Pt(e.left,t).multiply(Pt(e.right,t));case"div":return Pt(e.left,t).divide(Pt(e.right,t));case"pow":{let n=Pt(e.exp,t);if(n.denominator!==1n)throw new Error("Exact pow requires an integer exponent");return Pt(e.base,t).pow(Number(n.numerator))}case"neg":return Pt(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 n=Pt(e.left,t),r=Pt(e.right,t);return Aa[e.op](n.compare(r))?tt.One:tt.Zero}case"piecewise":{for(let n of e.branches)if(!Pt(n.cond,t).isZero())return Pt(n.expr,t);return Pt(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 ka=new Set(["lt","le","gt","ge"]);function Ct(e,t,n){switch(e.type){case"const":return t.wrap(e.value);case"var":{let r=n[e.name];if(r===void 0)throw new Error(`No value bound for "${e.name}"`);return t.wrap(r)}case"add":return t.add(Ct(e.left,t,n),Ct(e.right,t,n));case"sub":return t.subtract(Ct(e.left,t,n),Ct(e.right,t,n));case"mul":return t.multiply(Ct(e.left,t,n),Ct(e.right,t,n));case"div":return t.divide(Ct(e.left,t,n),Ct(e.right,t,n));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(Ct(e.base,t,n),e.exp.value)}case"neg":return t.negative(Ct(e.arg,t,n));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(ka.has(e.op))throw new Error(`Ordering comparisons ("${e.op}") have no general meaning over this structure`);let r=Ct(e.left,t,n),s=Ct(e.right,t,n),o=t.equality(r,s);return(e.op==="eq"?o:!o)?t.one:t.zero}case"piecewise":{for(let r of e.branches){let s=Ct(r.cond,t,n);if(!t.equality(s,t.zero))return Ct(r.expr,t,n)}return Ct(e.otherwise,t,n)}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 Q={add:1,sub:1,mul:2,div:2,neg:3,pow:4,cmp:0};function it(e,t){switch(e.type){case"const":return`${e.value}`;case"var":return e.name;case"func":return`${e.name}(${it(e.arg,0)})`;case"call2":return`${e.name}(${it(e.left,0)}, ${it(e.right,0)})`;case"neg":return Yt(`-${it(e.arg,Q.neg)}`,Q.neg,t);case"pow":return Yt(`${it(e.base,Q.pow+1)}^${it(e.exp,Q.pow)}`,Q.pow,t);case"add":return Yt(`${it(e.left,Q.add)} + ${it(e.right,Q.add)}`,Q.add,t);case"sub":return Yt(`${it(e.left,Q.sub)} - ${it(e.right,Q.sub+1)}`,Q.sub,t);case"mul":return Yt(`${it(e.left,Q.mul)}*${it(e.right,Q.mul+1)}`,Q.mul,t);case"div":return Yt(`${it(e.left,Q.div)}/${it(e.right,Q.div+1)}`,Q.div,t);case"cmp":{let n=Oa[e.op];return Yt(`${it(e.left,Q.cmp+1)}${n}${it(e.right,Q.cmp+1)}`,Q.cmp,t)}case"piecewise":return`piecewise(${e.branches.map(r=>`${it(r.cond,0)}, ${it(r.expr,0)}`).join(", ")}, ${it(e.otherwise,0)})`;case"sum":return`sum(${e.variable}, ${it(e.from,0)}, ${it(e.to,0)}, ${it(e.body,0)})`;case"product":return`product(${e.variable}, ${it(e.from,0)}, ${it(e.to,0)}, ${it(e.body,0)})`}}var Yt=(e,t,n)=>t<n?`(${e})`:e,Oa={lt:"<",le:"<=",gt:">",ge:">=",eq:"==",ne:"!="},Ar={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}"},kr={atan2:"\\operatorname{atan2}",hypot:"\\operatorname{hypot}",min:"\\min",max:"\\max",gcd:"\\gcd",lcm:"\\operatorname{lcm}"};function _(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{${_(e.arg,0)}}`:e.name==="cbrt"?`\\sqrt[3]{${_(e.arg,0)}}`:e.name==="abs"?`\\left|${_(e.arg,0)}\\right|`:e.name==="floor"?`\\left\\lfloor ${_(e.arg,0)}\\right\\rfloor`:e.name==="ceil"?`\\left\\lceil ${_(e.arg,0)}\\right\\rceil`:e.name==="log10"?`\\log_{10}\\left(${_(e.arg,0)}\\right)`:e.name==="log2"?`\\log_{2}\\left(${_(e.arg,0)}\\right)`:`${Ar[e.name]}\\left(${_(e.arg,0)}\\right)`;case"call2":return`${kr[e.name]}\\left(${_(e.left,0)}, ${_(e.right,0)}\\right)`;case"neg":return Yt(`-${_(e.arg,Q.neg)}`,Q.neg,t);case"pow":return Yt(`${_(e.base,Q.pow+1)}^{${_(e.exp,0)}}`,Q.pow,t);case"add":return Yt(`${_(e.left,Q.add)} + ${_(e.right,Q.add)}`,Q.add,t);case"sub":return Yt(`${_(e.left,Q.sub)} - ${_(e.right,Q.sub+1)}`,Q.sub,t);case"mul":return Yt(`${_(e.left,Q.mul)} \\cdot ${_(e.right,Q.mul+1)}`,Q.mul,t);case"div":return`\\frac{${_(e.left,0)}}{${_(e.right,0)}}`;case"cmp":{let n=Ta[e.op];return Yt(`${_(e.left,Q.cmp+1)} ${n} ${_(e.right,Q.cmp+1)}`,Q.cmp,t)}case"piecewise":{let n=e.branches.map(r=>`${_(r.expr,0)} & ${_(r.cond,0)}`);return n.push(`${_(e.otherwise,0)} & \\text{otherwise}`),`\\begin{cases}${n.join("\\\\")}\\end{cases}`}case"sum":return`\\sum_{${e.variable}=${_(e.from,0)}}^{${_(e.to,0)}} ${_(e.body,0)}`;case"product":return`\\prod_{${e.variable}=${_(e.from,0)}}^{${_(e.to,0)}} ${_(e.body,0)}`}}var Ta={lt:"<",le:"\\leq",gt:">",ge:"\\geq",eq:"=",ne:"\\neq"},Pa=Object.fromEntries(Object.entries(Ar).filter(([,e])=>!e.startsWith("\\operatorname")).map(([e,t])=>[t,e])),ja=Object.fromEntries(Object.entries(Ar).filter(e=>e[1].startsWith("\\operatorname")).map(([e,t])=>[/\\operatorname\{(\w+)\}/.exec(t)?.[1],e])),Ra=Object.fromEntries(Object.entries(kr).filter(e=>!e[1].startsWith("\\operatorname")).map(([e,t])=>[t,e])),Fa=Object.fromEntries(Object.entries(kr).filter(e=>e[1].startsWith("\\operatorname")).map(([e,t])=>[/\\operatorname\{(\w+)\}/.exec(t)?.[1],e]));function co(e,t,n,r){let s=0;for(let o=t;o<e.length;o++)if(e[o]===n)s++;else if(e[o]===r&&(s--,s===0))return o;throw new Error(`Unmatched '${n}' in LaTeX source`)}function Se(e,t){let n=e[t],r=n==="{"?"}":n==="("?")":n==="["?"]":void 0;if(!r)throw new Error(`Expected a group starting with '{', '(' or '[' at position ${t}`);let s=co(e,t,n,r);return{content:e.slice(t+1,s),next:s+1}}function Ca(e){let t=[],n=0,r=0;for(let s=0;s<e.length;s++){let o=e[s];o==="{"||o==="("||o==="["?n++:o==="}"||o===")"||o==="]"?n--:o===","&&n===0&&(t.push(e.slice(r,s)),r=s+1)}return t.push(e.slice(r)),t}function ks(e,t){let n=[],r=0,s=0;for(let o=0;o<e.length;o++){let i=e[o];i==="{"||i==="("||i==="["?r++:i==="}"||i===")"||i==="]"?r--:r===0&&e.startsWith(t,o)&&(n.push(e.slice(s,o)),s=o+t.length,o+=t.length-1)}return n.push(e.slice(s)),n}var za={"\\leq":"<=","\\le":"<=","\\geq":">=","\\ge":">=","\\neq":"!=","\\ne":"!="};function Da(e,t={}){let n=e.replace(/\\left|\\right/g,"").replace(/(?<!\\)\\(?:,|;|!|quad|qquad| )/g,"");return dt(n,t)}function La(e,t){let n=t,r=s=>{let o=e[s];return co(e,s,o,o==="{"?"}":")")+1};for(;n<e.length;){let s=e[n];if(/[A-Za-z0-9.]/.test(s))n++;else if(s==="("||s==="{")n=r(n);else if(s==="_"&&e[n+1]==="{")n=r(n+1);else if(s==="^")e[n+1]==="{"?n=r(n+1):e[n+1]==="\\"?n+=1+(/^\\[a-zA-Z]+/.exec(e.slice(n+1))?.[0].length??1):n+=2;else if(/^\\pi(?![a-zA-Z])/.test(e.slice(n)))n+=3;else if(s===" "&&/^ +(?:[A-Za-z0-9.({]|\\pi(?![a-zA-Z]))/.test(e.slice(n)))n+=e.slice(n).length-e.slice(n).trimStart().length;else break}return n}function dt(e,t={}){let n=t.implicitMultiplication===!0,r="",s=0,o=()=>{if(e[s]!=="{")throw new Error(`Expected '{' at position ${s} in LaTeX source: ${e}`);let{content:u,next:h}=Se(e,s);return s=h,u},i=()=>{for(;e[s]===" ";)s++;if(e[s]==="{"||e[s]==="("){let{content:h,next:f}=Se(e,s);return s=f,h}if(n){let h=La(e,s);if(h>s){let f=e.slice(s,h).trim();return s=h,f}}let u=/^[a-zA-Z_]\w*|^\d+\.?\d*(?:[eE][+-]?\d+)?/.exec(e.slice(s));if(u)return s+=u[0].length,u[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 u=/^(?:\\[a-zA-Z]+|[a-zA-Z0-9])/.exec(e.slice(s));if(!u)throw new Error(`Expected an argument at position ${s} in LaTeX source: ${e}`);return s+=u[0].length,u[0]},c=()=>{if(e[s]!=="^")return null;s++;let u=a();if(/^\s*-\s*1\s*$/.test(u))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 u},l=()=>{if(e[s]!=="("&&e[s]!=="{")throw new Error(`Expected '(' at position ${s} in LaTeX source: ${e}`);let{content:u,next:h}=Se(e,s);s=h;let f=Ca(u);if(f.length!==2)throw new Error(`Expected 2 comma-separated arguments at position ${s} in LaTeX source: ${e}`);return[f[0],f[1]]};for(;s<e.length;){let u=e[s];if(u==="\\"){let h=/^\\[a-zA-Z]+/.exec(e.slice(s));if(!h)throw new Error(`Unsupported LaTeX construct at position ${s}: ${e.slice(s,s+10)}`);let f=h[0];if(s+=f.length,f==="\\cdot"||f==="\\times"){r+="*";continue}if(f==="\\pi"){r+="pi";continue}let m=za[f];if(m){r+=m;continue}if(f==="\\begin"){let x=o();if(x!=="cases")throw new Error(`Unsupported LaTeX environment: \\begin{${x}}`);let g="\\end{cases}",w=e.indexOf(g,s);if(w===-1)throw new Error("Unmatched \\begin{cases} in LaTeX source");let b=e.slice(s,w);s=w+g.length;let y=ks(b,"\\\\"),E=[],N=null;for(let $ of y){if($.trim()==="")continue;let O=ks($,"&");if(O.length!==2)throw new Error(`Expected 'expr & cond' in \\begin{cases} row: ${$}`);let[L,k]=O;if(k.trim()==="\\text{otherwise}"){if(N!==null)throw new Error("\\begin{cases} may have only one \\text{otherwise} row");N=dt(L,t)}else{let Y=k.replace(/^\s*\\text\{\s*(?:if|when)\s*\}/,"");E.push(`${dt(Y,t)}, ${dt(L,t)}`)}}if(N===null)throw new Error("\\begin{cases} must have exactly one \\text{otherwise} row (as its last row)");r+=`piecewise(${E.concat(N).join(", ")})`;continue}if(f==="\\frac"||f==="\\dfrac"||f==="\\tfrac"){let x=a(),g=a();r+=`((${dt(x,t)})/(${dt(g,t)}))`;continue}if(f==="\\sqrt"){if(e[s]==="["){let{content:x,next:g}=Se(e,s);s=g;let w=a(),b=dt(x,t).trim();r+=b==="3"?`cbrt(${dt(w,t)})`:`((${dt(w,t)})^(1/(${b})))`}else{let x=a();r+=`sqrt(${dt(x,t)})`}continue}if(f==="\\log"){let x="10";if(e[s]==="_"&&e[s+1]==="{"){let{content:y,next:E}=Se(e,s+1);s=E,x=y.trim()}if(x!=="10"&&x!=="2")throw new Error(`Unsupported LaTeX construct: \\log base ${x} (only base 10 and base 2 are supported)`);let g=c(),w=i(),b=`${x==="2"?"log2":"log10"}(${dt(w,t)})`;r+=g===null?b:`${b}^(${dt(g,t)})`;continue}if(f==="\\lfloor"||f==="\\lceil"){let x=f==="\\lfloor"?"\\rfloor":"\\rceil",g=e.indexOf(x,s);if(g===-1)throw new Error(`Unmatched '${f}' in LaTeX source`);let w=e.slice(s,g);s=g+x.length,r+=`${f==="\\lfloor"?"floor":"ceil"}(${dt(w,t)})`;continue}if(f==="\\operatorname"){let x=o(),g=Fa[x];if(g){let[N,$]=l();r+=`${g}(${dt(N,t)}, ${dt($,t)})`;continue}let w=ja[x];if(!w)throw new Error(`Unsupported LaTeX construct: \\operatorname{${x}}`);let b=c(),y=i(),E=`${w}(${dt(y,t)})`;r+=b===null?E:`${E}^(${dt(b,t)})`;continue}let p=Ra[f];if(p){let[x,g]=l();r+=`${p}(${dt(x,t)}, ${dt(g,t)})`;continue}let d=Pa[f];if(d){let x=c(),g=i(),w=`${d}(${dt(g,t)})`;r+=x===null?w:`${w}^(${dt(x,t)})`;continue}throw new Error(`Unsupported LaTeX construct: ${f}`)}if(u==="|"){let h=e.indexOf("|",s+1);if(h===-1)throw new Error("Unmatched '|' in LaTeX source");let f=e.slice(s+1,h);s=h+1,r+=`abs(${dt(f,t)})`;continue}if(n&&u==="^"&&/^[a-zA-Z0-9]|^\\[a-zA-Z]/.test(e.slice(s+1))){let h=/^(?:\\[a-zA-Z]+|[a-zA-Z0-9])/.exec(e.slice(s+1));s+=1+h[0].length,r+=`^(${dt(h[0],t)})`;continue}if(u==="^"&&e[s+1]==="{"){let{content:h,next:f}=Se(e,s+1);s=f,r+=`^(${dt(h,t)})`;continue}if(u==="_"&&e[s+1]==="{"){let{content:h,next:f}=Se(e,s+1);s=f,r+=`_${h.replace(/\W/g,"")}`;continue}if(u==="{"){let{content:h,next:f}=Se(e,s);s=f,r+=`(${dt(h,t)})`;continue}if(u==="="){r+="==",s++;continue}r+=u,s++}return r}var lo=400,Va=8,we=class extends Error{};function Ba(e,t){let n=it(t,0),r=e.keys.indexOf(n);return r<0&&(r=e.keys.length,e.keys.push(n),e.atoms.push(t)),r}function uo(e,t){let n=Math.max(e.length,t.length);for(let r=0;r<n;r++){let s=(e[r]??0)-(t[r]??0);if(s!==0)return s}return 0}function Gn(e){let t=e.length;for(;t>0&&!e[t-1];)t--;return e.slice(0,t).join(",")}function Un(e){let t=new Map;for(let r of e){let s=Gn(r.exps),o=t.get(s);o?t.set(s,{exps:o.exps,c:o.c.add(r.c)}):t.set(s,{exps:r.exps,c:r.c})}let n=[...t.values()].filter(r=>!r.c.isZero());if(n.sort((r,s)=>uo(s.exps,r.exps)),n.length>lo)throw new we;return n}var xe=e=>e.isZero()?[]:[{exps:[],c:e}],Er=(e,t)=>Un([...e,...t]),wn=e=>e.map(t=>({exps:t.exps,c:t.c.negate()})),Ga=(e,t)=>Er(e,wn(t));function qe(e,t){if(e.length*t.length>lo*20)throw new we;let n=[];for(let r of e)for(let s of t){let o=Math.max(r.exps.length,s.exps.length),i=[];for(let a=0;a<o;a++)i.push((r.exps[a]??0)+(s.exps[a]??0));n.push({exps:i,c:r.c.multiply(s.c)})}return Un(n)}function Ua(e,t){return e.length===t.length&&e.every((n,r)=>Gn(n.exps)===Gn(t[r].exps)&&n.c.equals(t[r].c))}var jn=e=>e.length===0||e.length===1&&Gn(e[0].exps)==="";function xn(e,t){let n=t[0],r=e,s=[],o=[],i=0;for(;r.length>0;){if(++i>2e4)throw new we;let a=r[0],c=Math.max(a.exps.length,n.exps.length),l=[],u=!0;for(let f=0;f<c;f++){let m=(a.exps[f]??0)-(n.exps[f]??0);m<0&&(u=!1),l.push(m)}if(!u){o.push(a),r=r.slice(1);continue}let h={exps:l,c:a.c.divide(n.c)};s.push(h),r=Ga(r,qe([h],t))}return{q:Un(s),r:Un(o)}}function Za(...e){let t=new Set;for(let n of e)for(let r of n)for(let s=0;s<r.exps.length;s++)r.exps[s]>0&&t.add(s);return t}function Xa(e,t){if(Za(e,t).size>1)return xe(tt.One);let n=e,r=t;for(;r.length>0;){let{r:o}=xn(n,r);n=r,r=o}if(n.length===0)return xe(tt.One);let s=n[0].c;return n.map(o=>({exps:o.exps,c:o.c.divide(s)}))}function Wa(e){if(e.length===0)return[];let t=Math.max(...e.map(r=>r.exps.length)),n=[];for(let r=0;r<t;r++)n.push(Math.min(...e.map(s=>s.exps[r]??0)));return n}function Os(e,t){return e.map(n=>({exps:n.exps.map((r,s)=>r-(t[s]??0)),c:n.c}))}var bn=e=>({n:e,d:xe(tt.One)});function Ts(e,t,n){let r=n?wn(t.n):t.n;return Ua(e.d,t.d)?{n:Er(e.n,r),d:e.d}:{n:Er(qe(e.n,t.d),qe(r,e.d)),d:qe(e.d,t.d)}}var ho=(e,t)=>({n:qe(e.n,t.n),d:qe(e.d,t.d)});function fo(e,t){if(t.n.length===0)throw new we;return{n:qe(e.n,t.d),d:qe(e.d,t.n)}}function Ya(e,t){let n=Math.abs(t);if(n>1e3)throw new we;let r=e.n.length===1&&e.d.length===1;if(!r&&n>Va)throw new we;let s;if(r){let o=i=>({exps:i.exps.map(a=>a*n),c:i.c.pow(n)});s={n:[o(e.n[0])],d:[o(e.d[0])]}}else{s=bn(xe(tt.One));for(let o=0;o<n;o++)s=ho(s,e)}return t<0?fo(bn(xe(tt.One)),s):s}function Qa(e){if(!Number.isFinite(e))return null;if(Number.isInteger(e))return new tt(BigInt(e));let t=tt.fromNumber(e,1e4);return t.toNumber()===e?t:null}function ee(e,t){let n=r=>{let s=Ba(t,r),o=new Array(s+1).fill(0);return o[s]=1,bn([{exps:o,c:tt.One}])};switch(e.type){case"const":{let r=Qa(e.value);return r?bn(xe(r)):n(e)}case"var":return n(e);case"neg":{let r=ee(e.arg,t);return{n:wn(r.n),d:r.d}}case"add":return Ts(ee(e.left,t),ee(e.right,t),!1);case"sub":return Ts(ee(e.left,t),ee(e.right,t),!0);case"mul":return ho(ee(e.left,t),ee(e.right,t));case"div":return fo(ee(e.left,t),ee(e.right,t));case"pow":return e.exp.type==="const"&&Number.isInteger(e.exp.value)?Ya(ee(e.base,t),e.exp.value):n(ct(jt(e.base),jt(e.exp)));case"func":return n(T(e.name,jt(e.arg)));case"call2":return n(re(e.name,jt(e.left),jt(e.right)));case"cmp":return n(tn(e.op,jt(e.left),jt(e.right)));case"piecewise":return n(be(e.branches.map(r=>({cond:jt(r.cond),expr:jt(r.expr)})),jt(e.otherwise)));case"sum":return n(ce(e.variable,jt(e.from),jt(e.to),jt(e.body)));case"product":return n(Ie(e.variable,jt(e.from),jt(e.to),jt(e.body)))}}function Ps(e,t){let n=e<0n?-e:e,r=t<0n?-t:t;for(;r;)[n,r]=[r,n%r];return n}function Ja(e){if(e.n.length===0)return bn([]);let{n:t,d:n}=e,r=Wa([...t,...n]);if(r.some(a=>a>0)&&(t=Os(t,r),n=Os(n,r)),!jn(n)){let a=Xa(t,n);if(!jn(a))t=xn(t,a).q,n=xn(n,a).q;else{let c=xn(t,n);if(c.r.length===0)t=c.q,n=xe(tt.One);else{let l=xn(n,t);l.r.length===0&&(n=l.q,t=xe(tt.One))}}}if(jn(n)){let a=n[0].c;return{n:t.map(c=>({exps:c.exps,c:c.c.divide(a)})),d:xe(tt.One)}}let s=1n;for(let a of[...t,...n]){let c=a.c.denominator;s=s/Ps(s,c)*c}let o=new tt(s);t=t.map(a=>({exps:a.exps,c:a.c.multiply(o)})),n=n.map(a=>({exps:a.exps,c:a.c.multiply(o)}));let i=0n;for(let a of[...t,...n])i=Ps(i,a.c.numerator);if(i>1n){let a=new tt(1n,i);t=t.map(c=>({exps:c.exps,c:c.c.multiply(a)})),n=n.map(c=>({exps:c.exps,c:c.c.multiply(a)}))}return n[0].c.sign<0&&(t=wn(t),n=wn(n)),{n:t,d:n}}function _a(e,t){let n=null;for(let r=0;r<e.length;r++){let s=e[r]??0;if(s===0)continue;let o=s===1?t.atoms[r]:ct(t.atoms[r],M(s));n=n?q(n,o):o}return n}function js(e,t){if(e.length===0)return M(0);let n=[...e].sort((s,o)=>{let i=s.exps.reduce((c,l)=>c+l,0);return o.exps.reduce((c,l)=>c+l,0)-i||uo(o.exps,s.exps)}),r=null;for(let s of n){let o=s.c.sign<0,i=s.c.abs(),a=_a(s.exps,t),c=i.numerator,l;a?c===1n&&i.denominator===1n?l=a:i.denominator===1n?l=q(M(Number(c)),a):l=B(c===1n?a:q(M(Number(c)),a),M(Number(i.denominator))):l=M(i.toNumber()),r?r=o?U(r,l):W(r,l):r=o?Et(l):l}return r}function Wt(e){switch(e.type){case"const":case"var":return 1;case"neg":case"func":return 1+Wt(e.arg);case"pow":return 1+Wt(e.base)+Wt(e.exp);case"piecewise":return 1+Wt(e.otherwise)+e.branches.reduce((t,n)=>t+Wt(n.cond)+Wt(n.expr),0);case"sum":case"product":return 1+Wt(e.from)+Wt(e.to)+Wt(e.body);default:return 1+Wt(e.left)+Wt(e.right)}}function jt(e){if(e.type==="const"||e.type==="var")return e;try{let t={atoms:[],keys:[]},n=Ja(ee(e,t)),r=js(n.n,t),s=jn(n.d)?r:B(r,js(n.d,t));return Wt(s)<Wt(e)?s:e}catch(t){if(t instanceof we)return e;throw t}}function zt(e){if(Number.isInteger(e))return M(e);let t=tt.fromNumber(e,1e4);return t.denominator===1n?M(Number(t.numerator)):B(M(Number(t.numerator)),M(Number(t.denominator)))}function mo(e,t){let n=0;for(let r=e.length-1;r>=0;r--)n=n*t+e[r];return n}function Ka(e,t){let n={};for(let o of t)n[o]=0;let r=C(e,n);if(!Number.isFinite(r))return null;let s=[];for(let o of t){let i=F(et(e,o));if(t.some(c=>J(i,c)))return null;let a=C(i,n);if(!Number.isFinite(a))return null;s.push(a)}return[...s,r]}function Rs(e,t,n){let r=[],s=e,o=1;for(let i=0;i<=n;i++){i>0&&(o*=i);let a=C(s,{[t]:0});if(!Number.isFinite(a))return null;r.push(a/o),s=F(et(s,t))}for(;r.length>1&&Math.abs(r[r.length-1])<1e-9;)r.pop();for(let i of[1.3,-2.1,3.7]){let a=C(e,{[t]:i});if(!Number.isFinite(a)||Math.abs(mo(r,i)-a)>1e-6*Math.max(1,Math.abs(a)))return null}return r}function $r(e,t){let n=Math.abs(e),r=Math.abs(t);for(;r;)[n,r]=[r,n%r];return n||1}function Fs(e){let t=Math.round(Math.abs(e));if(t===0)return[1];let n=[];for(let r=1;r<=t;r++)t%r===0&&n.push(r);return n}function po(e){let t=e.length-1,n=e.map(a=>Math.round(a));if(!e.every((a,c)=>Math.abs(a-n[c])<1e-6))return null;let s=Fs(n[0]),o=Fs(n[t]),i=new Set;for(let a of s)for(let c of o)for(let l of[1,-1]){let u=l*a/c;if(!i.has(u)&&(i.add(u),Math.abs(mo(n,u))<1e-6))return u}return null}function go(e,t){let n=[...e].reverse(),r=[n[0]];for(let s=1;s<n.length-1;s++)r.push(n[s]+t*r[s-1]);return r.reverse()}function Nr(e){let t=[...e];for(;t.length>1&&Math.abs(t[t.length-1])<1e-9;)t.pop();let n=t.length-1;if(n<=0){if(t.length===0||Math.abs(t[0])<1e-9)throw new Vn;return[]}if(n===1){let[o,i]=t;return[zt(-o/i)]}if(n===2){let[o,i,a]=t,c=i*i-4*a*o;if(c<-1e-9)return[];let l=-i,u=2*a;if(Math.abs(c)<1e-9)return[zt(l/u)];let h=Math.sqrt(c);if(Math.abs(h-Math.round(h))<1e-9)return[zt((l+h)/u),zt((l-h)/u)];let f=T("sqrt",zt(c));return[B(W(zt(l),f),zt(u)),B(U(zt(l),f),zt(u))]}if(Math.abs(t[0])<1e-9)return[zt(0),...Nr(t.slice(1))];let r=po(t);if(r===null)throw new Error(`solve: no closed-form root found for a degree-${n} polynomial (only rational roots are searched for degree \u2265 3).`);let s=go(t,r);return[zt(r),...Nr(s)]}function Ha(e,t){let n=null;for(let r=0;r<e.length;r++){if(e[r]===0)continue;let s=r===0?zt(e[r]):q(zt(e[r]),r===1?nt(t):ct(nt(t),M(r)));n=n===null?s:W(n,s)}return n??M(0)}function tc(e,t){let n=[...e];for(;n.length>1&&Math.abs(n[n.length-1])<1e-9;)n.pop();if(n.every(u=>Math.abs(u)<1e-9))return M(0);let r=0;for(;n.length>1&&Math.abs(n[0])<1e-9;)n.shift(),r++;let s=n.map(u=>Math.round(u)),o=n.every((u,h)=>Math.abs(u-s[h])<1e-6),i=1;o&&(i=s.reduce((u,h)=>h===0?u:$r(u,Math.abs(h)),0)||1,n=s.map(u=>u/i));let a=[],c=n;for(;c.length-1>=3;){let u=po(c);if(u===null)break;a.push(u),c=go(c,u)}if(c.length-1===2){let[u,h,f]=c,m=h*h-4*f*u;if(m>=0){let p=Math.sqrt(m);Math.abs(p-Math.round(p))<1e-9&&(a.push((-h+p)/(2*f),(-h-p)/(2*f)),c=[f])}}else if(c.length-1===1){let[u,h]=c;a.push(-u/h),c=[h]}let l=zt(i);r===1?l=q(l,nt(t)):r>1&&(l=q(l,ct(nt(t),M(r))));for(let u of a)l=q(l,Math.abs(u)<1e-9?nt(t):U(nt(t),zt(u)));return c.length>1?l=q(l,Ha(c,t)):Math.abs(c[0]-1)>1e-9&&(l=q(l,zt(c[0]))),F(l)}function vr(e,t,n,r){if(r==="both")return C(e,{[t]:n});let s=r==="right"?1e-6:-1e-6;return C(e,{[t]:n+s})}function xo(e,t,n,r,s){let o=vr(e,t,n,r);if(Number.isFinite(o))return o;if(e.type==="div"&&s<12){let i=vr(e.left,t,n,r),a=vr(e.right,t,n,r);if(Math.abs(i)<1e-6&&Math.abs(a)<1e-6||!Number.isFinite(i)&&!Number.isFinite(a)){let l=F(et(e.left,t)),u=F(et(e.right,t));return xo(B(l,u),t,n,r,s+1)}}return o}var Cs=[...Vs].sort((e,t)=>t.length-e.length),Sr=class{s;implicit;pos=0;constructor(t,n={}){this.implicit=n.implicitMultiplication===!0;let r=this.implicit?t.replace(/(\d)\s+(?=[\d.])/g,"$1*"):t;this.s=r.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(),n=this.matchCmpOp();return n?tn(n,t,this.expr()):t}matchCmpOp(){let t={"<=":"le",">=":"ge","==":"eq","!=":"ne"},n=this.s.slice(this.pos,this.pos+2),r=t[n];return r?(this.pos+=2,r):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 n=[];for(let r=0;r+1<t.length-1;r+=2)n.push({cond:t[r],expr:t[r+1]});return be(n,t[t.length-1])}sumOrProductArgs(t){let n=/^[a-zA-Z_]\w*/.exec(this.s.slice(this.pos));if(!n)throw new Error(`${t}() expects a bound variable name as its first argument`);let r=n[0];if(this.pos+=r.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(r,s,o,i):Ie(r,s,o,i)}expr(){let t=this.term();for(;this.peek()==="+"||this.peek()==="-";){let n=this.s[this.pos++],r=this.term();t=n==="+"?W(t,r):U(t,r)}return t}term(){let t=this.factor();for(;;){let n=this.peek();if(n==="*"||n==="/"){this.pos++;let r=this.factor();t=n==="*"?q(t,r):B(t,r)}else if(this.implicit&&/[a-zA-Z0-9.(]/.test(n))t=q(t,this.factor());else return t}}implicitIdentifier(){let t=this.s.slice(this.pos),n=/^[a-zA-Z]+/.exec(t)?.[0]??"",r=Cs.find(i=>t.startsWith(i)&&t[i.length]==="(");if(r)return r;let s=Cs.find(i=>i.length>1&&n.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++,Et(this.factor());let t=this.base();return this.peek()==="^"?(this.pos++,ct(t,this.factor())):t}base(){if(this.peek()==="("){this.pos++;let r=this.comparison();if(this.peek()!==")")throw new Error("Expected ')'");return this.pos++,r}if(this.peek()==="|"){this.pos++;let r=this.expr();if(this.peek()!=="|")throw new Error("Expected '|'");return this.pos++,T("abs",r)}let t=/^\d+\.?\d*(?:[eE][+-]?\d+)?/.exec(this.s.slice(this.pos));if(t)return this.pos+=t[0].length,M(Number(t[0]));let n=this.implicit?/^[a-zA-Z_]/.exec(this.s.slice(this.pos)):/^[a-zA-Z_]\w*/.exec(this.s.slice(this.pos));if(n){let r=this.implicit?this.implicitIdentifier():n[0];if(this.pos+=r.length,(r==="log"||r==="clamp")&&this.peek()==="("){this.pos++;let o=this.argList();if(this.peek()!==")")throw new Error("Expected ')'");if(this.pos++,r==="log"){if(o.length!==2)throw new Error(`log() expects 2 arguments (base, x), got ${o.length}`);return B(T("ln",o[1]),T("ln",o[0]))}if(o.length!==3)throw new Error(`clamp() expects 3 arguments (x, lo, hi), got ${o.length}`);return re("min",re("max",o[0],o[1]),o[2])}if(r==="piecewise"&&this.peek()==="(")return this.pos++,this.piecewiseArgs();if((r==="sum"||r==="product")&&this.peek()==="(")return this.pos++,this.sumOrProductArgs(r);if(Ds.includes(r)&&this.peek()==="("){let o=r;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 re("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)=>re(o,a,c))}let s=zs.includes(r)?r:Ls[r];if(s&&this.peek()==="("){this.pos++;let o=this.expr();if(this.peek()!==")")throw new Error("Expected ')'");return this.pos++,T(s,o)}return r==="pi"?M(Math.PI):r==="e"?M(Math.E):nt(r)}throw new Error(`Unexpected token at ${this.pos}: ${this.s.slice(this.pos)}`)}};var ec=3e3,wo=100;function Fe(e,t){if(!Number.isInteger(e)||e<=0)throw new Error(`${t} must be a positive integer.`)}var Ce=class e{static estimatePi(t,n){Fe(t,"Sample count");let r=0,s=[],o=Math.max(1,Math.floor(t/ec)),i=Math.max(1,Math.floor(t/wo)),a=[];for(let c=0;c<t;c++){let l=n.nextFloat()*2-1,u=n.nextFloat()*2-1,h=l*l+u*u<=1;h&&r++,c%o===0&&s.push({x:l,y:u,inside:h}),(c+1)%i===0&&a.push({n:c+1,estimate:r/(c+1)*4})}return{piEstimate:r/t*4,n:t,points:s,convergence:a}}static integrate(t,n,r,s,o,i={}){if(!(r>n))throw new Error(`Upper bound must be greater than lower bound -- got [${n}, ${r}].`);Fe(s,"Sample count");let a=i.variable??"x",c,l=i.trueValue;if(typeof t=="string"){let w=S.compile(t);if(c=b=>w({[a]:b}),l===void 0)try{l=S.integrateDefinite(S.parse(t),n,r,a)}catch{}}else c=t;let u=Math.max(1,Math.floor(s/wo)),h=r-n,f=[],m=0,p=0,d=0;for(let w=0;w<s;w++){let b=c(n+o.nextFloat()*h),y=w+1,E=b-m;m+=E/y,p+=E*(b-m),(y%u===0||y===s)&&(d=1.96*h*Math.sqrt((y>1?p/(y-1):0)/y),y%u===0&&f.push({n:y,estimate:h*m,errorBand:d}))}let x=h*m,g={estimate:x,errorBand:d,n:s,convergence:f};return l!==void 0&&(g.trueValue=l,g.absoluteError=Math.abs(x-l)),g}static histogram(t,n=20){Fe(n,"Bin count");let r=Number.POSITIVE_INFINITY,s=Number.NEGATIVE_INFINITY;for(let a of t)a<r&&(r=a),a>s&&(s=a);let o=(s-r)/n||1,i=Array.from({length:n},(a,c)=>({x0:r+c*o,x1:r+(c+1)*o,count:0}));for(let a of t)i[Math.min(n-1,Math.max(0,Math.floor((a-r)/o)))].count++;return i}static centralLimit(t,n,r,s=20){Fe(n,"Sample size"),Fe(r,"Trial count");let o=[];for(let c=0;c<r;c++){let l=0;for(let u=0;u<n;u++)l+=t();o.push(l/n)}let i=o.reduce((c,l)=>c+l,0)/r,a=r>1?o.reduce((c,l)=>c+(l-i)**2,0)/(r-1):0;return{means:o,mean:i,standardDeviation:Math.sqrt(a),bins:e.histogram(o,s)}}static randomWalk(t,n,r=1){if(Fe(t,"Step count"),![1,2,3].includes(r))throw new Error("dimensions must be 1, 2 or 3.");let s=new Array(r).fill(0),o=[[...s]];for(let i=0;i<t;i++)s[n.nextBelow(r)]+=n.nextBelow(2)===0?-1:1,o.push([...s]);return o}static bootstrap(t,n,r,s={}){let{resamples:o=1e3,level:i=.95}=s;if(t.length===0)throw new Error("bootstrap needs a non-empty sample.");if(Fe(o,"Resample count"),!(i>0&&i<1))throw new Error("level must be strictly between 0 and 1.");let a=t.length,c=[];for(let m=0;m<o;m++){let p=new Array(a);for(let d=0;d<a;d++)p[d]=t[r.nextBelow(a)];c.push(n(p))}let l=c.reduce((m,p)=>m+p,0)/o,u=Math.sqrt(o>1?c.reduce((m,p)=>m+(p-l)**2,0)/(o-1):0),h=[...c].sort((m,p)=>m-p),f=m=>{let p=(h.length-1)*m,d=Math.floor(p);return h[d]+(p-d)*((h[Math.min(d+1,h.length-1)]??h[d])-h[d])};return{estimate:n([...t]),replicates:c,standardError:u,confidenceInterval:[f((1-i)/2),f(1-(1-i)/2)]}}};var en=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,n=0,r=0,s=0){this.w=t,this.x=n,this.y=r,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,n){let[r,s,o]=t,i=Math.hypot(r,s,o)||1,a=n/2,c=Math.sin(a)/i;return new e(Math.cos(a),r*c,s*c,o*c)}rotateVector(t){let n=this.normalize(),r=new e(0,t[0],t[1],t[2]),s=n.multiply(r).multiply(n.conjugate());return[s.x,s.y,s.z]}toRotationMatrix(){let{w:t,x:n,y:r,z:s}=this.normalize();return[[1-2*(r*r+s*s),2*(n*r-s*t),2*(n*s+r*t)],[2*(n*r+s*t),1-2*(n*n+s*s),2*(r*s-n*t)],[2*(n*s-r*t),2*(r*s+n*t),1-2*(n*n+r*r)]]}static slerp(t,n,r){let s=t.normalize(),o=n.normalize(),i=s.dot(o);if(i<0&&(o=o.scale(-1),i=-i),i>.9995)return s.add(o.subtract(s).scale(r)).normalize();let a=Math.acos(i),c=a*r,l=Math.sin(a),u=Math.sin(a-c)/l,h=Math.sin(c)/l;return s.scale(u).add(o.scale(h))}toString(){return`${this.w} + ${this.x}i + ${this.y}j + ${this.z}k`}};function nc(e,t){let n=e&65535,r=e>>>16,s=t&65535,o=t>>>16,i=n*o+r*s,a=n*s+i%65536*65536,c=Math.floor(a/4294967296);return[r*o+Math.floor(i/65536)+c,a%4294967296]}var Zn=class{#e=0;#t=0;#r;#n;constructor(t=0n,n=1n){let r=(BigInt(n)<<1n|1n)&0xffffffffffffffffn;this.#r=Number(r>>32n),this.#n=Number(r&0xffffffffn),this.#s();let s=BigInt(t)&0xffffffffffffffffn,o=this.#t+Number(s&0xffffffffn);this.#t=o%4294967296,this.#e=(this.#e+Number(s>>32n)+Math.floor(o/4294967296))%4294967296,this.#s()}#s(){let[t,n]=nc(this.#t,1284865837),r=Math.imul(this.#e,1284865837)+Math.imul(this.#t,1481765933)>>>0,s=n+this.#n;this.#t=s%4294967296,this.#e=(t+r+this.#r+Math.floor(s/4294967296))%4294967296}nextUint32(){let t=this.#e,n=this.#t;this.#s();let r=(t^t>>>18)>>>0,o=((n^(t<<14|n>>>18)>>>0)>>>0>>>27|r<<5)>>>0,i=t>>>27;return(o>>>i|o<<(-i&31))>>>0}nextFloat(){return this.nextUint32()/4294967296}next=()=>this.nextFloat();nextBelow(t){if(!Number.isInteger(t)||t<=0)throw new RangeError(`nextBelow: bound must be a positive integer, got ${t}`);let n=Math.floor(4294967296/t)*t,r;do r=this.nextUint32();while(r>=n);return r%t}nextNormal(t=0,n=1){let r=this.nextFloat();r===0&&(r=Number.MIN_VALUE);let s=this.nextFloat();return t+n*Math.sqrt(-2*Math.log(r))*Math.cos(2*Math.PI*s)}};function nn(e){return new Zn(e)}var Or=Number.EPSILON;function Tr(e,t){switch(e){case"linear":return[t,1,0];case"huber":return t<=1?[t,1,0]:[2*Math.sqrt(t)-1,1/Math.sqrt(t),-.5*t**-1.5];case"soft_l1":{let n=1+t;return[2*(Math.sqrt(n)-1),1/Math.sqrt(n),-.5*n**-1.5]}case"cauchy":{let n=1+t;return[Math.log1p(t),1/n,-1/(n*n)]}case"arctan":return[Math.atan(t),1/(1+t*t),-2*t/(1+t*t)**2]}}function bo(e,t,n){return e==="linear"?.5*t.reduce((s,o)=>s+o*o,0):.5*(n*n)*t.reduce((s,o)=>s+Tr(e,(o/n)**2)[0],0)}function rc(e){let t=e.length,n=e.map((r,s)=>[...r,...Array.from({length:t},(o,i)=>s===i?1:0)]);for(let r=0;r<t;r++){let s=r;for(let i=r+1;i<t;i++)Math.abs(n[i][r])>Math.abs(n[s][r])&&(s=i);if(Math.abs(n[s][r])<1e-300)return null;[n[r],n[s]]=[n[s],n[r]];let o=n[r][r];for(let i=0;i<2*t;i++)n[r][i]/=o;for(let i=0;i<t;i++){if(i===r)continue;let a=n[i][r];if(a!==0)for(let c=0;c<2*t;c++)n[i][c]-=a*n[r][c]}}return n.map(r=>r.slice(t))}var yn=class e{static leastSquares(t,n,r={}){let{loss:s="linear",fScale:o=1,ftol:i=1e-8,xtol:a=1e-8,gtol:c=1e-8}=r,l=n.length,u=r.maxNfev??Math.max(1e3,200*l),h=0,f=0,m=k=>(h++,t(k)),p=(k,Y)=>{if(f++,r.jac)return r.jac(k);let P=Y.length,D=Array.from({length:P},()=>new Array(l).fill(0));for(let G=0;G<l;G++){let Z=Math.cbrt(Or)*Math.max(Math.abs(k[G]),1),pt=[...k],v=[...k];pt[G]+=Z,v[G]-=Z;let A=t(pt),j=t(v);for(let K=0;K<P;K++)D[K][G]=(A[K]-j[K])/(2*Z)}return D},d=[...n],x=m(d),g=bo(s,x,o),w=p(d,x),b=.001,y=0,E="The maximum number of function evaluations is exceeded.",N=(k,Y)=>{if(s==="linear")return{fs:k,Js:Y};let P=k.length,D=new Array(P),G=new Array(P);for(let Z=0;Z<P;Z++){let[,pt,v]=Tr(s,(k[Z]/o)**2),A=pt+2*v*(k[Z]/o)**2;A<Or&&(A=Or),A=Math.sqrt(A);let j=pt/A;D[Z]=k[Z]*j,G[Z]=Y[Z].map(K=>K*A)}return{fs:D,Js:G}},$=(k,Y)=>{let P=new Array(l).fill(0);for(let D=0;D<k.length;D++){let G=s==="linear"?1:Tr(s,(k[D]/o)**2)[1];for(let Z=0;Z<l;Z++)P[Z]+=Y[D][Z]*G*k[D]}return P},O=$(x,w),L=Math.max(0,...O.map(Math.abs));for(L<=c&&(y=1,E="`gtol` termination condition is satisfied.");y===0&&h<u;){let{fs:k,Js:Y}=N(x,w),P=Array.from({length:l},()=>new Array(l).fill(0)),D=new Array(l).fill(0);for(let v=0;v<k.length;v++)for(let A=0;A<l;A++){D[A]+=Y[v][A]*k[v];for(let j=A;j<l;j++)P[A][j]+=Y[v][A]*Y[v][j]}for(let v=0;v<l;v++)for(let A=0;A<v;A++)P[v][A]=P[A][v];let G=!1,Z=0,pt=0;for(let v=0;v<40&&!G&&h<u;v++){let A=P.map((gt,Nt)=>gt.map((Lt,Ot)=>Nt===Ot?Lt+b*Math.max(P[Nt][Nt],1e-12):Lt)),j;try{j=[...at.solve(A,D.map(gt=>-gt))]}catch{b*=10;continue}if(j.some(gt=>!Number.isFinite(gt))){b*=10;continue}let K=d.map((gt,Nt)=>gt+j[Nt]),I=m(K),H=bo(s,I,o);if(Number.isFinite(H)&&H<g){pt=g-H,Z=Math.hypot(...j);let gt=Math.hypot(...d),Nt=g;d=K,x=I,g=H,b=Math.max(b/10,1e-14),G=!0,w=p(d,x),O=$(x,w),L=Math.max(0,...O.map(Math.abs));let Lt=pt<i*Nt,Ot=Z<a*(a+gt);L<=c?(y=1,E="`gtol` termination condition is satisfied."):Lt&&Ot?(y=4,E="Both `ftol` and `xtol` termination conditions are satisfied."):Lt?(y=2,E="`ftol` termination condition is satisfied."):Ot&&(y=3,E="`xtol` termination condition is satisfied.")}else b*=10}if(!G){y=L<=Math.sqrt(c)||g===0?1:2,E="No further improvement is possible at this precision.";break}}return{x:d,cost:g,fun:x,jac:w,grad:O,optimality:L,nfev:h,njev:f,status:y,success:y>0,message:E}}static curveFit(t,n,r,s,o={}){if(n.length!==r.length)throw new Error("xs and ys must have the same length.");let i=n.length,a=s.length;if(i<a)throw new Error(`curveFit needs at least as many points (${i}) as parameters (${a}).`);let c=o.sigma,l=E=>c?1/c[E]:1,{jac:u,sigma:h,absoluteSigma:f,...m}=o,p=e.leastSquares(E=>n.map((N,$)=>(t(N,E)-r[$])*l($)),s,{...m,jac:u?E=>n.map((N,$)=>u(N,E).map(O=>O*l($))):void 0}),d=Array.from({length:a},(E,N)=>Array.from({length:a},($,O)=>p.jac.reduce((L,k)=>L+k[N]*k[O],0))),x=rc(d),g;if(!x)g=Array.from({length:a},()=>new Array(a).fill(Number.POSITIVE_INFINITY));else{let E=2*p.cost,N=f?1:i>a?E/(i-a):Number.POSITIVE_INFINITY;g=x.map($=>$.map(O=>O*N))}let w=r.reduce((E,N)=>E+N,0)/i,b=r.reduce((E,N)=>E+(N-w)**2,0),y=n.reduce((E,N,$)=>E+(r[$]-t(N,p.x))**2,0);return{params:p.x,covariance:g,standardErrors:g.map((E,N)=>Math.sqrt(E[N])),residualNorm:Math.sqrt(y),rSquared:b===0?y===0?1:0:1-y/b,iterations:p.nfev,converged:p.success,fit:p}}static huberLinear(t,n,r={}){let{delta:s=1,maxIterations:o=200,tolerance:i=1e-12}=r;if(t.length!==n.length)throw new Error("xs and ys must have the same length.");if(t.length<2)throw new Error("Enter at least two (x, y) rows.");if(!(s>0))throw new Error("delta must be positive.");let a=t.length,c=m=>{let p=0,d=0,x=0,g=0,w=0;for(let y=0;y<a;y++){let E=m[y];p+=E,d+=E*t[y],x+=E*n[y],g+=E*t[y]*t[y],w+=E*t[y]*n[y]}let b=p*g-d*d;return Math.abs(b)<1e-300?[0,x/p]:[(p*w-d*x)/b,(g*x-d*w)/b]},[l,u]=c(new Array(a).fill(1)),h=0,f=!1;for(;h<o;h++){let m=t.map((g,w)=>{let b=Math.abs(n[w]-(l*g+u));return b<=s?1:s/b}),[p,d]=c(m),x=Math.max(Math.abs(p-l),Math.abs(d-u));if(l=p,u=d,x<=i*(1+Math.abs(l)+Math.abs(u))){f=!0,h++;break}}return{slope:l,intercept:u,iterations:h,converged:f}}static outlierIndices(t,n,r,s,o=2.5){if(t.length===0)return[];let i=f=>{let m=[...f].sort((p,d)=>p-d);return m.length%2?m[(m.length-1)/2]:(m[m.length/2-1]+m[m.length/2])/2},a=n.map((f,m)=>f-(r*t[m]+s)),c=i(a),l=i(a.map(f=>Math.abs(f-c)));if(l===0)return[];let u=l*1.4826,h=[];return a.forEach((f,m)=>{Math.abs(f-c)/u>o&&h.push(m)}),h}};var vn=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??(n=>n),this._equalityMethod=t.equality??((n,r)=>n===r)}criterion(t){return this._criteria[t]}isMember(t){return this._criteria.every(n=>n(t)!==!1)}operation(t){return this._operations[t]}integerPower(t,n,r=0){let s=this.identity(r),o=this.operation(r),i=t,a=n;a<0&&(a=-a,i=this.inverse(r)(t));for(let c=0;c<a;c++)s=o(s,i);return s}get add(){return this._operations[0]}addPower(t,n){return this.integerPower(t,n,0)}get multiply(){return this._operations[1]}multiplyPower(t,n){return this.integerPower(t,n,1)}inverse(t=0){return this._inverses[t]}get negative(){return this.inverse(0)}get reciprocal(){return this.inverse(1)}subtract(t,n){return this.add(t,this.negative(n))}divide(t,n){return this.multiply(t,this.reciprocal(n))}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,n){return z.contains(t,n,this.equality)}wrapVector(t){return z.transform(t,this.wrap)}addVector(t,n){return z.combine(t,n,this.add,this.zero)}scaleVector(t,n){return z.transform(t,r=>this.multiply(n,r))}negativeVector(t){return z.transform(t,this.negative)}reciprocalVector(t){return z.transform(t,this.reciprocal)}inverseVector(t,n=0){return z.transform(t,this.inverse(n))}subtractVector(t,n){return this.addVector(t,this.negativeVector(n))}dotProduct(t,n){let r=z.combine(t,n,this.multiply,this.zero);return z.collapse(r,this.add)}crossProduct(t,n){let r=[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&&(r[c]=t[c]),c<n.length&&n[c]!=null&&(s[c]=n[c]);let o=this.subtract(this.multiply(r[1],s[2]),this.multiply(r[2],s[1])),i=this.subtract(this.multiply(r[2],s[0]),this.multiply(r[0],s[2])),a=this.subtract(this.multiply(r[0],s[1]),this.multiply(r[1],s[0]));return R.fromArray([o,i,a])}kroneckerProduct(t,n){let r=z.constantVector(t.length,null);return r=z.fillByIndex(r,s=>this.scaleVector(n,t[s])),z.flattenSDLevels(r,2)}generateIdentity(t=1,n=1){return z.generateIdentity(t,n,this.one,this.zero)}addMatrix(t,n){return z.combine(t,n,(r,s)=>this.addVector(r,s))}scaleMatrix(t,n){return z.transformEndNodes(t,r=>this.multiply(n,r))}negativeMatrix(t){return z.transformEndNodes(t,n=>this.negative(n))}subtractMatrix(t,n){return this.addMatrix(t,this.negativeMatrix(n))}scaleRow(t,n=0,r){let s=t.clone();return z.rowSet(s,this.scaleVector(s[n],r),n)}scaleColumn(t,n=0,r){return z.transpose(this.scaleRow(t,n,r))}trace(t){return z.collapse(z.diagonal(t),this.add)}kroneckerMatrixProduct(t,n){let r=z.constantMatrix(z.height(t),z.width(t),null);return r=z.fillMatrixByIndex(r,(s,o)=>this.scaleMatrix(n,t[s][o])),z.breakBlock(r)}multiplyMatrix(t,n){let r=new R;for(let s=0;s<z.width(t);s++)r.push(this.kroneckerMatrixProduct(z.getColumn(t,s),z.getRow(n,s)));return z.collapse(r,(s,o)=>this.addMatrix(s,o))}powerMatrix(t,n=1){if(n===0)return this.generateIdentity(z.height(t),z.width(t));let r=n>0?t.clone():this.invertMatrix(t),s=new R;for(let o=0;o<Math.abs(n);o++)s.push(r.clone());return z.collapse(s,(o,i)=>this.multiplyMatrix(o,i))}hasInverse(t){let n=this.reciprocal(t);return!(typeof n=="number"&&Number.isNaN(n))}noInverse(t,n){return new RangeError(`${t}: element ${String(n)} has no multiplicative inverse in this structure`)}determinantDivisionFree(t){let n=z.width(t),r=[...t].map(i=>[...i]),s=[this.one];for(let i=1;i<=n;i++){let a=i-1,c=[this.one,this.negative(r[a][a])],l=Array.from({length:a},(h,f)=>r[f][a]);for(let h=2;h<=i;h++){let f=this.zero;for(let m=0;m<a;m++)f=this.add(f,this.multiply(r[a][m],l[m]));c.push(this.negative(f)),h<i&&(l=Array.from({length:a},(m,p)=>{let d=this.zero;for(let x=0;x<a;x++)d=this.add(d,this.multiply(r[p][x],l[x]));return d}))}let u=[];for(let h=0;h<=i;h++){let f=this.zero;for(let m=0;m<i&&m<=h;m++)f=this.add(f,this.multiply(c[h-m],s[m]));u.push(f)}s=u}let o=s[n];return n%2===0?o:this.negative(o)}determinant(t){if(z.width(t)!==z.height(t))return this.zero;let n=z.width(t);if(n<2)return t[0][0];let r=[...t].map(i=>[...i]),s=this.one,o=this.one;for(let i=0;i<n;i++){if(this.equality(r[i][i],this.zero)||!this.hasInverse(r[i][i])){let l=this.equality(r[i][i],this.zero),u=-1;for(let h=i+1;h<n;h++)if(!this.equality(r[h][i],this.zero)&&this.hasInverse(r[h][i])){u=h;break}if(u===-1)return l&&r.slice(i+1).every(h=>this.equality(h[i],this.zero))?this.zero:this.determinantDivisionFree(t);[r[i],r[u]]=[r[u],r[i]],o=this.negative(o)}let a=r[i][i];s=this.multiply(s,a);let c=this.reciprocal(a);for(let l=i+1;l<n;l++){let u=this.multiply(r[l][i],c);if(!this.equality(u,this.zero))for(let h=i;h<n;h++)r[l][h]=this.subtract(r[l][h],this.multiply(u,r[i][h]))}}return this.multiply(o,s)}permanent(t){if(z.width(t)<2)return t[0][0];let n=new R;for(let r=0;r<z.width(t);r++){let s=z.columnRemoved(z.rowRemoved(t,0),r);n.push(this.multiply(t[0][r],this.permanent(s)))}return z.collapse(n,this.add)}invertMatrix(t,n=!0){let r=z.height(t),s=z.width(t);if(r!==s)throw new RangeError(`invertMatrix: matrix must be square, got ${r}x${s}`);if(n&&this.equality(this.determinant(t),this.zero))throw new RangeError("invertMatrix: matrix is singular");return this.invertByElimination(t)??this.invertByAdjugate(t)}invertByAdjugate(t){let n=z.height(t),r=[...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:n},()=>new Array(n));for(let a=0;a<n;a++)for(let c=0;c<n;c++){let l=r.filter((f,m)=>m!==a).map(f=>R.fromArray(f.filter((m,p)=>p!==c))),u=this.determinant(R.fromArray(l)),h=(a+c)%2===0?u:this.negative(u);i[c][a]=this.multiply(o,h)}return R.fromArray(i.map(a=>R.fromArray(a)))}invertByElimination(t){let n=z.height(t),r=[...t].map(o=>[...o]),s=[...this.generateIdentity(n,n)].map(o=>[...o]);for(let o=0;o<n;o++){if(this.equality(r[o][o],this.zero)||!this.hasInverse(r[o][o])){let a=this.equality(r[o][o],this.zero),c=-1;for(let l=o+1;l<n;l++)if(!this.equality(r[l][o],this.zero)&&this.hasInverse(r[l][o])){c=l;break}if(c===-1){if(a&&r.slice(o+1).every(l=>this.equality(l[o],this.zero)))throw new RangeError("invertMatrix: matrix is singular");return null}[r[o],r[c]]=[r[c],r[o]],[s[o],s[c]]=[s[c],s[o]]}let i=this.reciprocal(r[o][o]);for(let a=0;a<n;a++)r[o][a]=this.multiply(r[o][a],i),s[o][a]=this.multiply(s[o][a],i);for(let a=0;a<n;a++){if(a===o)continue;let c=r[a][o];for(let l=0;l<n;l++)r[a][l]=this.subtract(r[a][l],this.multiply(c,r[o][l])),s[a][l]=this.subtract(s[a][l],this.multiply(c,s[o][l]))}}return R.fromArray(s.map(o=>R.fromArray(o)))}vectorSum(t){return z.collapse(t,this.add)}vectorProduct(t){return z.collapse(t,this.multiply)}vectorCollapseOperation(t,n=0){return z.collapse(t,this.operation(n))}static realField(){return new e({criteria:[t=>typeof t=="number"],operations:[(t,n)=>t+n,(t,n)=>t*n],inverses:[t=>-t,t=>1/t],identities:[0,1],equality:(t,n)=>t===n,wrap:t=>Number(t)})}static complexField(){return new e({criteria:[t=>t instanceof ht],operations:[(t,n)=>t.add(n),(t,n)=>t.multiply(n)],inverses:[t=>t.neg(),t=>t.reciprocal()],identities:[ht.Zero,ht.One],equality:(t,n)=>t.equals(n),wrap:t=>t instanceof ht?t:new ht(t)})}static integersModulo(t){let n=s=>(s%t+t)%t,r=s=>{if(!Number.isInteger(s))return Number.NaN;let[o,i]=[n(s),t],[a,c]=[1,0];for(;i!==0;){let l=Math.floor(o/i);[o,i]=[i,o-l*i],[a,c]=[c,a-l*c]}return o!==1?NaN:n(a)};return new e({criteria:[s=>typeof s=="number"],operations:[(s,o)=>n(s+o),(s,o)=>n(s*o)],inverses:[s=>n(-s),r],identities:[0,1],equality:(s,o)=>n(s)===n(o),wrap:s=>n(Number(s))})}static booleanRing(){return e.integersModulo(2)}static rationalField(){return new e({criteria:[t=>t instanceof tt],operations:[(t,n)=>t.add(n),(t,n)=>t.multiply(n)],inverses:[t=>t.negate(),t=>t.reciprocal()],identities:[tt.Zero,tt.One],equality:(t,n)=>t.equals(n),wrap:t=>tt.from(t)})}static decimalField(){return new e({criteria:[t=>t instanceof Me],operations:[(t,n)=>t.add(n),(t,n)=>t.multiply(n)],inverses:[t=>t.negate(),t=>Me.One.divide(t)],identities:[Me.Zero,Me.One],equality:(t,n)=>t.equals(n),wrap:t=>Me.from(t)})}static quaternionRing(){return new e({criteria:[t=>t instanceof en],operations:[(t,n)=>t.add(n),(t,n)=>t.multiply(n)],inverses:[t=>t.negate(),t=>t.inverse()],identities:[en.Zero,en.Identity],equality:(t,n)=>t.equals(n)})}static dualNumbers(){return new e({criteria:[t=>t instanceof he],operations:[(t,n)=>t.add(n),(t,n)=>t.multiply(n)],inverses:[t=>t.negate(),t=>new he(1,0).divide(t)],identities:[new he(0,0),new he(1,0)],equality:(t,n)=>t.value===n.value&&t.deriv===n.deriv,wrap:t=>t instanceof he?t:he.constant(t)})}};var Xn=64,sc=1e5,Wn=1e6,oc=20,ic=10,ac=1e3,yo=1e5,vo=2e3,Mo=2e6,$o=1e12,Pr=(e,t="expression")=>{if(typeof e!="string"||!e.trim())throw new Error(`${t} is empty: write something like x^2 + 3*x`);if(e.length>vo)throw new Error(`${t} has at most ${vo} characters`);return e},No=/^[A-Za-z_][A-Za-z0-9_]*$/,So=(e,t="x")=>{let n=typeof e=="string"&&e.trim()?e.trim():t;if(!No.test(n))throw new Error(`variable "${n.slice(0,40)}" isn't a name: use letters, digits and _`);return n},qo=e=>({text:S.toString(e),latex:S.toLatex(e)}),Io=e=>typeof e=="number"&&Number.isFinite(e);function $t(e,t,n){if(e==null||typeof e=="string"&&!e.trim()){if(n!==void 0)return n;throw new Error(`${t} is a number`)}if(typeof e=="number"){if(!Number.isFinite(e))throw new Error(`${t} must be a finite number`);return e}if(typeof e!="string"||e.length>200)throw new Error(`${t} must be a number`);let r;try{r=S.evaluate(e,{})}catch{throw new Error(`${t} must be a number (such as 2, -1.5 or pi/2), got "${e.slice(0,40)}"`)}if(!Number.isFinite(r))throw new Error(`${t} must be a finite number, got "${e.slice(0,40)}"`);return r}var yt=(e,t,n,r,s)=>{let o=$t(e,t,n);if(!Number.isInteger(o)||o<r||o>s)throw new Error(`${t} is a whole number from ${r} to ${s}`);return o},Eo=(e,t)=>{let n=e;if(n==null||n==="")return{};if(typeof n=="string")try{n=JSON.parse(n)}catch{throw new Error(`${t} is a JSON object such as {"y": 1}`)}if(!n||typeof n!="object"||Array.isArray(n))throw new Error(`${t} is an object of names to numbers, like { "y": 1 }`);let r={};for(let[s,o]of Object.entries(n)){if(!No.test(s))throw new Error(`${t}: "${s.slice(0,40)}" isn't a name`);r[s]=$t(o,`${t}.${s}`)}return r};function jr(e,t,n,r){let s=Pr(e),o=So(t),i=$t(n,"lower"),a=$t(r,"upper"),c=S.compile(s),l=g=>({value:null,errorEstimate:null,method:null,antiderivative:null,numeric:null,error:g}),u=0,h=g=>{if(++u>Mo)throw new Error("budget");let w=c({[o]:g});if(!Number.isFinite(w))throw new RangeError(`not finite at ${o} = ${g}`);return w};if(i===a)return{value:0,errorEstimate:0,method:"exact",antiderivative:null,numeric:0,error:null};let f,m;try{f=pe.adaptiveSimpson(h,i,a,1e-10,30);let g=32,w=(a-i)/g;m=0;for(let b=0;b<g;b++)m+=pe.gaussLegendre(h,i+b*w,i+(b+1)*w)}catch(g){if(g instanceof RangeError)return l(`the integrand ${g.message}: the integral doesn't exist there or the interval crosses a pole`);if(g.message==="budget")return l(`the integrand needed more than ${Mo} evaluations: it is too rough or singular for a numeric integral`);throw g}let p=Math.abs(f-m),d=null,x=null;try{let g=S.integrate(s,o);d=qo(g);let w=S.compile(g);x=w({[o]:a})-w({[o]:i}),(!Number.isFinite(x)||Math.abs(x-f)>1e-6*Math.max(1,Math.abs(f))+10*p)&&(x=null)}catch{x=null}return x!==null?{value:x,errorEstimate:Math.abs(x-f),method:"exact",antiderivative:d,numeric:f,error:null}:{value:f,errorEstimate:p,method:"numeric",antiderivative:d,numeric:f,error:null}}function cc(e,t,n,r,s,o){let i=Pr(e),a=So(t),c=$t(n,"center",0),l=yt(r,"order",4,0,oc),u=$t(s,"radius",2);if(!(u>0))throw new Error("radius is a positive number");let h=yt(o,"points",101,2,2001),f=[],m=S.parse(i),p=1;for(let b=0;b<=l;b++){b>0&&(p*=b);let y=S.evaluate(m,{[a]:c});if(!Number.isFinite(y))return{text:null,latex:null,coefficients:f,series:[],error:`the ${b===0?"function":`derivative of order ${b}`} isn't a finite number at ${a} = ${c}: no Taylor series there`};f.push({n:b,derivative:y,coefficient:y/p}),b<l&&(m=S.differentiate(m,a))}let d=S.taylor(i,a,c,l),x=S.compile(i),g=b=>{let y=0;for(let E=l;E>=0;E--)y=y*(b-c)+f[E].coefficient;return y},w=[];for(let b=0;b<h;b++){let y=c-u+2*u*b/(h-1),E=x({[a]:y});w.push({x:y,f:Number.isFinite(E)?E:null,taylor:g(y)})}return{...qo(d),coefficients:f,series:w,error:null}}function lc(e){if(typeof e!="string"||!e.trim())throw new Error("equations is empty: one `y' = expression` per line, such as y' = -2*y");let t=e.split(`
38
+ `).map(r=>r.trim()).filter(r=>r&&!r.startsWith("#"));if(t.length>32)throw new Error("an ODE system has at most 32 equations");let n=[];for(let r of t){let s=/^([A-Za-z_][A-Za-z0-9_]*)\s*'\s*=\s*(.+)$/.exec(r);if(!s)throw new Error(`bad equation "${r.slice(0,60)}": write \`name' = expression\` (the independent variable is t), such as y' = -2*y`);if(s[1]==="t")throw new Error("t is the independent variable: it can't have an equation of its own");if(n.some(o=>o.name===s[1]))throw new Error(`${s[1]}' has two equations`);n.push({name:s[1],expression:Pr(s[2],`the equation for ${s[1]}'`)})}return n}var uc=[0,1/5,3/10,4/5,8/9,1,1],hc=[[],[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]],fc=[35/384,0,500/1113,125/192,-2187/6784,11/84,0],mc=[5179/57600,0,7571/16695,393/640,-92097/339200,187/2100,1/40];function pc(e,t,n,r,s,o,i,a){let c=lc(e),l=c.map(v=>v.name),u=Eo(t,"initial");for(let v of l)if(!(v in u))throw new Error(`initial has no value for ${v}: add "${v}": a number`);for(let v of Object.keys(u))if(!l.includes(v))throw new Error(`initial names ${v}, which has no equation`);let h=Eo(a,"parameters");for(let v of Object.keys(h))if(v==="t"||l.includes(v))throw new Error(`parameter ${v} clashes with t or an unknown`);let f=$t(n,"t0",0),m=$t(r,"t1");if(!(m>f))throw new Error("t1 must be greater than t0");let p=s==="rk4"?"rk4":s==="rk45"||s===void 0||s===""?"rk45":null;if(!p)throw new Error('method is "rk4" or "rk45"');let d=yt(o,"steps",1e3,1,sc),x=$t(i,"tolerance",1e-8);if(!(x>0))throw new Error("tolerance is a positive number");let g=new Set(["t",...l,...Object.keys(h)]),w=c.map(v=>{for(let A of S.freeVariables(v.expression))if(!g.has(A))throw new Error(`the equation for ${v.name}' uses ${A}, which is not t, an unknown or a parameter`);return S.compile(v.expression)}),b={...h},y=l.length,E=(v,A)=>{b.t=v;for(let j=0;j<y;j++)b[l[j]]=A[j];return w.map(j=>j(b))},N=(v,A)=>{let j={t:v};for(let K=0;K<y;K++)j[l[K]]=A[K];return j},$=["t",...l],O=v=>v.every(Number.isFinite),L=[N(f,l.map(v=>u[v]))],k=(v,A)=>({columns:$,points:L,steps:v,method:p,final:L[L.length-1],error:A}),Y=v=>`the solution stopped being a finite number near t = ${v}: the equation blows up or the steps are too coarse`;if(p==="rk4"){let v=(m-f)/d,A=l.map(j=>u[j]);for(let j=1;j<=d;j++){let K=f+(j-1)*v,I=E(K,A),H=E(K+v/2,A.map((Ot,se)=>Ot+v/2*I[se])),gt=E(K+v/2,A.map((Ot,se)=>Ot+v/2*H[se])),Nt=E(K+v,A.map((Ot,se)=>Ot+v*gt[se]));A=A.map((Ot,se)=>Ot+v/6*(I[se]+2*H[se]+2*gt[se]+Nt[se]));let Lt=j===d?m:f+j*v;if(!O(A))return k(j-1,Y(Lt));L.push(N(Lt,A))}return k(d,null)}let P=f,D=l.map(v=>u[v]),G=(m-f)/100,Z=0,pt=0;for(;P<m;){if(Z>=d)return k(Z,`steps ran out (${d}) at t = ${P}, before t1 = ${m}: raise steps or the tolerance`);if(++pt>20*d+100)return k(Z,`the step size kept shrinking near t = ${P}: the equation is too stiff or singular there`);P+G>m&&(G=m-P);let v=[];for(let I=0;I<7;I++){let H=D.map((gt,Nt)=>{let Lt=0;for(let Ot=0;Ot<I;Ot++)Lt+=hc[I][Ot]*v[Ot][Nt];return gt+G*Lt});v.push(E(P+uc[I]*G,H))}let A=D.map((I,H)=>I+G*fc.reduce((gt,Nt,Lt)=>gt+Nt*v[Lt][H],0)),j=D.map((I,H)=>I+G*mc.reduce((gt,Nt,Lt)=>gt+Nt*v[Lt][H],0)),K=0;for(let I=0;I<y;I++)K=Math.max(K,Math.abs(A[I]-j[I])/(x*(1+Math.max(Math.abs(D[I]),Math.abs(A[I])))));if(!Number.isFinite(K)){if(G/=4,G<1e-14*Math.max(1,Math.abs(P)))return k(Z,Y(P));continue}K<=1&&(P=P+G>=m-1e-14*Math.abs(m)?m:P+G,D=A,Z++,L.push(N(P,D))),G*=Math.min(5,Math.max(.2,.9*K**-.2||5))}return k(Z,null)}function Gt(e,t="matrix"){let n=e;if(typeof n=="string"){let s=n.trim();if(!s)throw new Error(`${t} is empty: one row per line, entries separated by spaces or commas`);if(s.length>2e5)throw new Error(`${t} is too long`);if(s.startsWith("["))try{n=JSON.parse(s)}catch{throw new Error(`${t} looks like JSON but isn't valid`)}else n=s.split(`
39
+ `).map(o=>o.trim()).filter(o=>o&&!o.startsWith("#")).map(o=>o.split(/[\s,;]+/).filter(Boolean).map(Number))}if(!Array.isArray(n)||!n.length)throw new Error(`${t} is empty`);if(n.every(s=>typeof s=="number")&&(n=n.map(s=>[s])),n.length>Xn)throw new Error(`${t} has at most ${Xn} rows (it has ${n.length})`);let r=Array.isArray(n[0])?n[0].length:0;if(!r)throw new Error(`${t} has an empty row`);if(r>Xn)throw new Error(`${t} has at most ${Xn} columns (it has ${r})`);return n.map((s,o)=>{if(!Array.isArray(s)||s.length!==r)throw new Error(`${t}: row ${o+1} has ${Array.isArray(s)?s.length:0} entries, row 1 has ${r}`);return s.map((i,a)=>{if(!Io(i))throw new Error(`${t}: entry (${o+1}, ${a+1}) isn't a finite number`);return i})})}var ze=(e,t)=>{if(e.length!==e[0].length)throw new Error(`${t} must be square (it is ${e.length} x ${e[0].length})`);return e.length},Qn=e=>Math.max(...e[0].map((t,n)=>e.reduce((r,s)=>r+Math.abs(s[n]),0))),Ae=e=>Math.max(...e.map(t=>Math.max(...t.map(Math.abs))),Number.MIN_VALUE);function Rr(e){let t=e.length,n=e.map(a=>[...a]),r=Array.from({length:t},(a,c)=>c),s=1,o=Ae(e)*t*Number.EPSILON*8,i=!1;for(let a=0;a<t;a++){let c=a;for(let l=a+1;l<t;l++)Math.abs(n[l][a])>Math.abs(n[c][a])&&(c=l);if(Math.abs(n[c][a])<=o){i=!0;continue}c!==a&&([n[c],n[a]]=[n[a],n[c]],[r[c],r[a]]=[r[a],r[c]],s=-s);for(let l=a+1;l<t;l++){n[l][a]/=n[a][a];for(let u=a+1;u<t;u++)n[l][u]-=n[l][a]*n[a][u]}}return{U:n,perm:r,sign:s,singular:i}}function Ao({U:e,perm:t},n){let r=e.length,s=t.map(o=>n[o]);for(let o=0;o<r;o++)for(let i=0;i<o;i++)s[o]-=e[o][i]*s[i];for(let o=r-1;o>=0;o--){for(let i=o+1;i<r;i++)s[o]-=e[o][i]*s[i];s[o]/=e[o][o]}return s}function ko(e){let t=e.length,n=Rr(e);if(n.singular)return null;let r=Array.from({length:t},(s,o)=>Ao(n,Array.from({length:t},(i,a)=>a===o?1:0)));return Array.from({length:t},(s,o)=>r.map(i=>i[o]))}var Oo="the matrix is singular (its rows are linearly dependent), so it has no inverse and Ax = b has no single solution",To=e=>`the matrix is ill-conditioned (condition number about ${e.toExponential(1)}): the result would have no reliable digits`;function dc(e,t){let n=Gt(e,"A"),r=Gt(t,"B");if(n[0].length!==r.length)throw new Error(`A is ${n.length} x ${n[0].length} and B is ${r.length} x ${r[0].length}: A's columns must equal B's rows`);let s=n.map(o=>r[0].map((i,a)=>o.reduce((c,l,u)=>c+l*r[u][a],0)));return{product:s,rows:s.length,columns:s[0].length,error:null}}function gc(e){let t=Gt(e,"A");return{transpose:t[0].map((n,r)=>t.map(s=>s[r])),rows:t[0].length,columns:t.length,error:null}}function xc(e){let t=Gt(e,"A"),n=ze(t,"A"),r=Rr(t);if(r.singular)return{determinant:0,singular:!0,error:null};let s=r.sign;for(let o=0;o<n;o++)s*=r.U[o][o];return{determinant:s,singular:!1,error:null}}function wc(e){let t=Gt(e,"A"),n=Ae(t),r=at.rank(t.map(s=>s.map(o=>o/n)));return{rank:r,rows:t.length,columns:t[0].length,fullRank:r===Math.min(t.length,t[0].length),error:null}}function bc(e){let t=Gt(e,"A");ze(t,"A");let n=ko(t);if(!n)return{inverse:null,conditionNumber:null,error:Oo};let r=Qn(t)*Qn(n);return r>$o?{inverse:null,conditionNumber:r,error:To(r)}:{inverse:n,conditionNumber:r,error:null}}function yc(e,t){let n=Gt(e,"A"),r=Gt(t,"b");if(r[0].length!==1)throw new Error("b is one column (a number per row)");if(r.length!==n.length)throw new Error(`A has ${n.length} rows and b has ${r.length} entries: they must match`);let s=r.map(c=>c[0]),o,i;if(n.length===n[0].length){let c=Rr(n);if(c.singular)return{solution:null,residual:null,conditionNumber:null,error:Oo};let l=ko(n);if(i=Qn(n)*Qn(l),i>$o)return{solution:null,residual:null,conditionNumber:i,error:To(i)};o=Ao(c,s)}else if(n.length>n[0].length){if(at.rank(n.map(c=>c.map(l=>l/Ae(n))))<n[0].length)return{solution:null,residual:null,conditionNumber:null,error:"the columns of A are linearly dependent: the least-squares solution isn't unique"};o=[...at.leastSquares(n,s)],i=null}else return{solution:null,residual:null,conditionNumber:null,error:`A has ${n.length} equations for ${n[0].length} unknowns: the system is underdetermined`};let a=Math.hypot(...n.map((c,l)=>c.reduce((u,h,f)=>u+h*o[f],0)-s[l]));return{solution:o,residual:a,conditionNumber:i,error:null}}function Po(e){let t=Gt(e,"A"),n=ze(t,"A"),r=Ae(t);for(let l=0;l<n;l++)for(let u=l+1;u<n;u++)if(Math.abs(t[l][u]-t[u][l])>1e-9*r)return{values:null,largest:null,smallest:null,vectors:null,error:`the matrix isn't symmetric (entries (${l+1}, ${u+1}) and (${u+1}, ${l+1}) differ): only real symmetric matrices are supported`};let s=t.map((l,u)=>l.map((h,f)=>(h+t[f][u])/2).map(h=>h/r)),{values:o,vectors:i}=at.eigenSymmetric(s),a=[...o].map(l=>l*r),c=[...i].map(l=>[...l]);return{values:a,largest:a[0],smallest:a[n-1],vectors:a.map((l,u)=>c.map(h=>h[u])),error:null}}function Dt(e,t="values",n){let r=e;if(typeof r=="string"){let o=r.trim();if(!o)throw new Error(`${t} is empty: numbers separated by commas, spaces or new lines`);if(o.startsWith("["))try{r=JSON.parse(o)}catch{throw new Error(`${t} looks like JSON but isn't valid`)}else{let i=o.split(/[\s,;]+/).filter(Boolean);if(i.length>Wn)throw new Error(`${t} has at most ${Wn} numbers`);r=i.map(a=>a===""?NaN:Number(a))}}if(!Array.isArray(r))throw new Error(`${t} is a list of numbers`);if(r.length>Wn)throw new Error(`${t} has at most ${Wn} numbers (it has ${r.length})`);if(!r.length)throw new Error(`${t} is empty`);let s=new Array(r.length);for(let o=0;o<r.length;o++){let i=r[o];if(i&&typeof i=="object"&&!Array.isArray(i)){let a=n&&n in i?n:null;if(!a)throw new Error(`${t}: row ${o+1} is an object, so name its column (${Object.keys(i).slice(0,8).join(", ")})`);i=i[a]}if(typeof i=="string"&&i.trim()&&(i=Number(i)),!Io(i))throw new Error(`${t}: item ${o+1} isn't a finite number`);s[o]=i}return s}var Yn=(e,t)=>{let n=t*(e.length-1),r=Math.floor(n),s=Math.ceil(n);return e[r]+(e[s]-e[r])*(n-r)};function vc(e){let t=Float64Array.from(e);return t.sort(),t}var Mc=e=>{let n=(e==null||e===""?"0.25, 0.5, 0.75":Array.isArray(e)?e.join(","):String(e)).split(/[\s,;]+/).filter(Boolean).map(Number);if(n.length>100)throw new Error("quantiles has at most 100 entries");for(let r of n)if(!(r>=0&&r<=1))throw new Error("quantiles are fractions from 0 to 1, such as 0.25, 0.5, 0.75");return n};function Ec(e,t,n){let r=Dt(e,"values",n),s=Mc(t),o=r.length,i=vc(r),a=0;for(let d=0;d<o;d++)a+=r[d];let c=a/o,l=0,u=0;for(let d=0;d<o;d++){let x=r[d]-c;l+=x*x,u+=x*x*x}let h=l/o,f=o>1?l/(o-1):null,m=Yn(i,.25),p=Yn(i,.75);return{count:o,sum:a,mean:c,median:Yn(i,.5),standardDeviation:f===null?null:Math.sqrt(f),variance:f,populationStandardDeviation:Math.sqrt(h),populationVariance:h,min:i[0],max:i[o-1],range:i[o-1]-i[0],q1:m,q3:p,interquartileRange:p-m,skewness:h>0?u/o/h**1.5:null,quantiles:s.map(d=>({q:d,value:Yn(i,d)})),error:null}}var $c=(e,t)=>{let n=e.length,r=0,s=0;for(let c=0;c<n;c++)r+=e[c],s+=t[c];r/=n,s/=n;let o=0,i=0,a=0;for(let c=0;c<n;c++)o+=(e[c]-r)*(t[c]-s),i+=(e[c]-r)**2,a+=(t[c]-s)**2;return i>0&&a>0?o/Math.sqrt(i*a):null};function Nc(e,t,n,r){let s=Dt(e,"x"),o=Dt(t,"y");if(s.length!==o.length)throw new Error(`x has ${s.length} numbers and y has ${o.length}: they must match`);if(s.length>yo)throw new Error(`a regression takes at most ${yo} points (there are ${s.length})`);let i=yt(n,"degree",1,1,ic),a=yt(r,"curvePoints",100,2,2e3),c=s.length,l=v=>({degree:i,coefficients:null,equation:null,slope:null,intercept:null,rSquared:null,adjustedRSquared:null,correlation:null,residuals:null,fitted:null,rmse:null,curve:[],error:v});if(c<=i)return l(`a degree ${i} fit needs more than ${i} points (there are ${c})`);let u=new Set(s).size;if(u<=i)return l(`a degree ${i} fit needs more than ${i} different x values (there are ${u})`);let h=1/0,f=-1/0;for(let v of s)v<h&&(h=v),v>f&&(f=v);let m=(h+f)/2,p=(f-h)/2||1,d=s.map(v=>{let A=(v-m)/p;return Array.from({length:i+1},(j,K)=>A**K)}),{Q:x,R:g}=at.qr(d),w=[...x].map(v=>[...v]),b=[...g].map(v=>[...v]);if(b.some((v,A)=>!(Math.abs(v[A])>1e-12)))return l("the points don't determine this polynomial (the columns are dependent): use a lower degree");let y=Array.from({length:i+1},(v,A)=>w.reduce((j,K,I)=>j+K[A]*o[I],0)),E=new Array(i+1).fill(0);for(let v=i;v>=0;v--){let A=y[v];for(let j=v+1;j<=i;j++)A-=b[v][j]*E[j];E[v]=A/b[v][v]}let N=[E[i]];for(let v=i-1;v>=0;v--){let A=new Array(N.length+1).fill(0);for(let j=0;j<N.length;j++)A[j+1]+=N[j]/p,A[j]+=N[j]*-m/p;A[0]+=E[v],N=A}let $=v=>{let A=0;for(let j=i;j>=0;j--)A=A*v+N[j];return A},O=s.map($),L=o.map((v,A)=>v-O[A]),k=0,Y=0,P=0;for(let v=0;v<c;v++)P+=o[v];P/=c;for(let v=0;v<c;v++)k+=L[v]**2,Y+=(o[v]-P)**2;let D=Y>0?1-k/Y:null,G=D===null||c-i-1<=0?null:1-(1-D)*(c-1)/(c-i-1),Z=Array.from({length:a},(v,A)=>{let j=h+(f-h)*A/(a-1);return{x:j,fit:$(j)}}),pt=N.map((v,A)=>`${v}${A===0?"":A===1?"*x":`*x^${A}`}`);return{degree:i,coefficients:N,equation:`y = ${pt.join(" + ")}`,slope:i===1?N[1]:null,intercept:N[0],rSquared:D,adjustedRSquared:G,correlation:i===1?$c(s,o):null,residuals:L,fitted:O,rmse:Math.sqrt(k/c),curve:Z,error:null}}function Sc(e,t,n,r,s){let o=Dt(e,"values",s),i=o.length,a=1/0,c=-1/0;for(let g=0;g<i;g++)o[g]<a&&(a=o[g]),o[g]>c&&(c=o[g]);let l=t==null||t===""?Math.max(1,Math.ceil(Math.log2(i)+1)):yt(t,"bins",10,1,ac),u=$t(n,"min",a),h=$t(r,"max",c);if(!(h>=u))throw new Error("max must not be below min");let f=h===u?1:(h-u)/l,m=new Array(l).fill(0),p=0;for(let g=0;g<i;g++){let w=o[g];if(w<u||w>h){p++;continue}m[Math.min(l-1,Math.floor((w-u)/f))]++}let d=i-p;return{bins:m.map((g,w)=>{let b=u+w*f,y=w===l-1&&h!==u?h:u+(w+1)*f;return{lower:b,upper:y,center:(b+y)/2,count:g,density:d?g/d/f:0,label:`${+b.toPrecision(6)} to ${+y.toPrecision(6)}`}}),binWidth:f,count:d,outside:p,error:null}}var Ut=Object.freeze({lines:64,line:500,params:8,depth:24,span:1e5,exponent:4096,deadlineMs:2e3}),qc=Object.freeze({float:{label:"float",help:"Ordinary decimal arithmetic, rounded to 12 digits so 0.1 + 0.2 shows 0.3. Names, functions and commands (simplify, diff, integrate, solve\u2026) work here. The exact switch turns the numbers into fractions."},units:{label:"units",help:"Numbers carry units. Write 5 km + 300 m, 5 m / 2 s, or 5 km in m to convert. Spaces separate the number, the unit and the operator; there are no parentheses. A name holds a plain number (the magnitude of what was stored)."},interval:{label:"interval",help:"Every result is a range [low, high] that is guaranteed to hold the true value, rounded outward. sqrt(2) shows the two floats on either side of it. Division by a range holding zero is refused. Powers take a whole number 0 or more; sin, cos, tan, exp, ln, sqrt and abs work. A stored name holds the middle of the range."},complex:{label:"complex",help:"Complex numbers with i as the imaginary unit: (3+4i)*(1-2i), sqrt(-4), exp(i*pi). A result with an imaginary part is shown but not stored in a name; a real one is."},modulus:{label:"Z/nZ",help:"Whole-number arithmetic modulo n (set n below). 3 - 5 is 5 in Z/7Z, and 1/3 is the inverse of 3, when there is one. Powers take a literal whole exponent such as 2^10."}}),Fr=Object.freeze(Object.keys(qc)),Cr=Object.freeze({rad:"radians",deg:"degrees"}),Fo=67108864,zr=Object.freeze(["simplify","expand","factor","diff","integrate","solve","taylor","limit"]),Ic="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,arcsin,arccos,arctan,arcsinh,arccosh,arctanh,arccot,arcsec,arccsc,arccoth,arcsech,arccsch,sgn,logistic,atan2,hypot,min,max,gcd,lcm,log,clamp,piecewise,sum,product".split(","),rn=Object.freeze(new Set(["pi","e",...Ic,...zr,"__proto__","constructor","prototype","toString","valueOf","hasOwnProperty"])),sn=/^[A-Za-z_][A-Za-z0-9_]*$/,jo=/^(.+?)\s*->\s*([A-Za-z_][A-Za-z0-9_]*)\s*$/s,Ac=/^\s*([A-Za-z_][A-Za-z0-9_]*)\s*<-\s*(.+)$/s,kc=/^\s*([A-Za-z_][A-Za-z0-9_]*)\s*(?:\(([^()]*)\))?\s*=(?!=)\s*(.*)$/s;function Ro(e){return sn.test(e)?rn.has(e)?`"${e}" is already something (a constant, a function or a command)`:null:`"${String(e).slice(0,40)}" isn't a name: use letters, digits and _`}function Co(e){let t=typeof e=="string"?e:"",n=t.trim();if(!n)return{kind:"blank",text:t};if(n.startsWith("#")||n.startsWith("//"))return{kind:"comment",text:t,comment:n.replace(/^(#|\/\/)\s?/,"")};let r=jo.exec(t)??Ac.exec(t);if(r){let u=jo.test(t),[h,f]=u?[r[2],r[1]]:[r[1],r[2]],m={kind:"assign",text:t,name:h,rhs:f.trim(),store:u?"right":"left"},p=Ro(h);return p&&(m.problem=p),m}let s=kc.exec(t);if(!s)return{kind:"expr",text:t,rhs:n};let[,o,i,a]=s,c={kind:i===void 0?"assign":"function",text:t,name:o,rhs:a.trim()},l=Ro(o);if(i!==void 0){let u=i.trim()?i.split(",").map(h=>h.trim()):[];c.params=u,u.length?u.length>Ut.params?c.problem=`a function has at most ${Ut.params} parameters`:u.some(h=>!sn.test(h))?c.problem=`the parameters of ${o} are names: use letters, digits and _`:new Set(u).size!==u.length?c.problem=`${o} has a parameter twice`:u.some(h=>rn.has(h))&&(c.problem=`a parameter of ${o} is a constant, function or command name`):c.problem=`${o}() needs at least one parameter`}return l&&!c.problem&&(c.problem=l),!c.rhs&&!c.problem&&(c.problem=`${o} = needs something on its right`),c}function Dr(e,t){let n=0;for(let r=t;r<e.length;r++)if(e[r]==="(")n++;else if(e[r]===")"&&--n===0)return r;return-1}function Lr(e){let t=[],n=0,r=0;for(let s=0;s<e.length;s++)e[s]==="("?n++:e[s]===")"?n--:e[s]===","&&n===0&&(t.push(e.slice(r,s).trim()),r=s+1);return t.push(e.slice(r).trim()),t}var zo=e=>String(e).replace(/[.*+?^${}()|[\]\\/-]/g,"\\$&");var Mn=["length","mass","time","current","temperature","amount","luminosity"],En=Object.freeze({length:0,mass:0,time:0,current:0,temperature:0,amount:0,luminosity:0});function mt(e){return Object.freeze({...En,...e})}function Jn(e,t){let n={};for(let r of Mn)n[r]=e[r]+t[r];return Object.freeze(n)}function Lo(e,t){let n={};for(let r of Mn)n[r]=e[r]-t[r];return Object.freeze(n)}function _n(e,t){let n={};for(let r of Mn)n[r]=e[r]*t;return Object.freeze(n)}function Vr(e,t){return Mn.every(n=>e[n]===t[n])}var Do={length:"L",mass:"M",time:"T",current:"I",temperature:"\u0398",amount:"N",luminosity:"J"};function Br(e){let t=Mn.filter(n=>e[n]!==0).map(n=>e[n]===1?Do[n]:`${Do[n]}^${e[n]}`);return t.length>0?t.join("*"):"dimensionless"}var Xt=class extends Error{constructor(t){super(t),this.name="UnitParseError"}},$n=class extends Xt{symbol;constructor(t){super(`unknown unit "${t}"`),this.name="UnknownUnitError",this.symbol=t}},Nn=class extends Error{left;right;constructor(t,n,r){super(r??`dimension mismatch: [${Br(t)}] vs [${Br(n)}]`),this.name="DimensionMismatchError",this.left=t,this.right=n}};var Vo={m:{dimension:mt({length:1}),scale:1,prefixable:!0},in:{dimension:mt({length:1}),scale:.0254},ft:{dimension:mt({length:1}),scale:.3048},yd:{dimension:mt({length:1}),scale:.9144},mi:{dimension:mt({length:1}),scale:1609.344},g:{dimension:mt({mass:1}),scale:.001,prefixable:!0},kg:{dimension:mt({mass:1}),scale:1},lb:{dimension:mt({mass:1}),scale:.45359237},oz:{dimension:mt({mass:1}),scale:.028349523125},s:{dimension:mt({time:1}),scale:1,prefixable:!0},min:{dimension:mt({time:1}),scale:60},h:{dimension:mt({time:1}),scale:3600},day:{dimension:mt({time:1}),scale:86400},A:{dimension:mt({current:1}),scale:1,prefixable:!0},K:{dimension:mt({temperature:1}),scale:1},degC:{dimension:mt({temperature:1}),scale:1,offset:273.15},degF:{dimension:mt({temperature:1}),scale:5/9,offset:273.15-32*(5/9)},mol:{dimension:mt({amount:1}),scale:1,prefixable:!0},cd:{dimension:mt({luminosity:1}),scale:1,prefixable:!0},Hz:{dimension:mt({time:-1}),scale:1,prefixable:!0},N:{dimension:mt({mass:1,length:1,time:-2}),scale:1,prefixable:!0},J:{dimension:mt({mass:1,length:2,time:-2}),scale:1,prefixable:!0},W:{dimension:mt({mass:1,length:2,time:-3}),scale:1,prefixable:!0},Pa:{dimension:mt({mass:1,length:-1,time:-2}),scale:1,prefixable:!0},L:{dimension:mt({length:3}),scale:.001,prefixable:!0}},Bo={y:1e-24,z:1e-21,a:1e-18,f:1e-15,p:1e-12,n:1e-9,u:1e-6,\u00B5:1e-6,m:.001,c:.01,d:.1,da:10,h:100,k:1e3,M:1e6,G:1e9,T:1e12,P:1e15,E:1e18,Z:1e21,Y:1e24},Oc=Object.keys(Bo).sort((e,t)=>t.length-e.length);function Gr(e){let t=Vo[e];if(t)return t;for(let n of Oc)if(e.length>n.length&&e.startsWith(n)){let r=e.slice(n.length),s=Vo[r];if(s?.prefixable)return{dimension:s.dimension,scale:s.scale*Bo[n]}}}function Ur(e){let t=e.trim();if(t.length===0)throw new Xt("empty unit expression");if(!/[*/^]/.test(t)){let i=Gr(t);if(!i)throw new $n(t);return{dimension:i.dimension,scale:i.scale,offset:i.offset??0,canonical:t}}let n=t.match(/[*/]|[^*/]+/g);if(!n)throw new Xt(`could not parse unit expression "${e}"`);let r=En,s=1,o="*";for(let i of n){if(i==="*"||i==="/"){o=i;continue}let a=i.trim();if(a.length===0)continue;let[c,l,...u]=a.split("^");if(u.length>0)throw new Xt(`too many "^" in term "${a}" (in "${e}")`);let h=l===void 0?1:Number(l);if(!Number.isFinite(h))throw new Xt(`invalid exponent in "${a}" (in "${e}")`);let f=Gr(c);if(!f)throw new $n(c);if(f.offset)throw new Xt(`affine unit "${c}" cannot be used inside a composite unit expression ("${e}") \u2014 use it standalone only`);let m=o==="/"?-h:h;r=Jn(r,_n(f.dimension,m)),s*=f.scale**m,o="*"}return{dimension:r,scale:s,offset:0,canonical:t}}function Go(e,t,n){return`${e}${n}${t}`}var De=class e{value;symbol;dimension;#e;#t;constructor(t,n,r,s,o){this.value=t,this.symbol=n,this.dimension=r,this.#e=s,this.#t=o}static of(t,n){let r=Ur(n);return new e(t,r.canonical,r.dimension,r.scale,r.offset)}static dimensionless(t){return new e(t,"",En,1,0)}get isDimensionless(){return this.symbol===""}#r(){return this.value*this.#e+this.#t}#n(t,n){if(!Vr(this.dimension,t.dimension))throw new Nn(this.dimension,t.dimension,`cannot ${n} "${this.symbol||"(dimensionless)"}" and "${t.symbol||"(dimensionless)"}"`)}to(t){let n=Ur(t);if(!Vr(this.dimension,n.dimension))throw new Nn(this.dimension,n.dimension,`cannot convert "${this.symbol}" to "${t}"`);let r=(this.#r()-n.offset)/n.scale;return new e(r,n.canonical,n.dimension,n.scale,n.offset)}add(t){if(this.#n(t,"add"),this.isDimensionless)return e.dimensionless(this.value+t.value);let n=t.to(this.symbol);return new e(this.value+n.value,this.symbol,this.dimension,this.#e,this.#t)}sub(t){if(this.#n(t,"subtract"),this.isDimensionless)return e.dimensionless(this.value-t.value);let n=t.to(this.symbol);return new e(this.value-n.value,this.symbol,this.dimension,this.#e,this.#t)}mul(t){if(typeof t=="number")return new e(this.value*t,this.symbol,this.dimension,this.#e,this.#t);if(this.#t!==0||t.#t!==0)throw new Xt(`cannot multiply affine units ("${this.symbol}"/"${t.symbol}") \u2014 convert to a non-affine unit (e.g. "K" instead of "degC") first`);let n=Jn(this.dimension,t.dimension),r=this.isDimensionless?t.symbol:t.isDimensionless?this.symbol:Go(this.symbol,t.symbol,"*");return new e(this.value*t.value,r,n,this.#e*t.#e,0)}div(t){if(typeof t=="number")return new e(this.value/t,this.symbol,this.dimension,this.#e,this.#t);if(this.#t!==0||t.#t!==0)throw new Xt(`cannot divide affine units ("${this.symbol}"/"${t.symbol}") \u2014 convert to a non-affine unit (e.g. "K" instead of "degC") first`);let n=Lo(this.dimension,t.dimension),r=t.isDimensionless?this.symbol:Go(this.symbol||"1",t.symbol,"/");return new e(this.value/t.value,r,n,this.#e/t.#e,0)}pow(t){if(this.#t!==0)throw new Xt(`cannot exponentiate an affine unit ("${this.symbol}")`);if(/[*/^]/.test(this.symbol))throw new Xt(`Unit.pow() only supports a simple (non-composite) unit symbol; "${this.symbol}" is composite \u2014 use repeated .mul() instead`);let n=_n(this.dimension,t),r=this.isDimensionless?"":t===1?this.symbol:`${this.symbol}^${t}`;return new e(this.value**t,r,n,this.#e**t,0)}toString(t){let n=t===void 0?String(this.value):this.value.toPrecision(t);return this.symbol?`${n} ${this.symbol}`:n}};var Tc={pi:ht.PI,e:ht.E};function Qt(e,t){switch(e.type){case"const":return ht.fromNumber(e.value);case"var":{let n=t[e.name]??Tc[e.name];if(!n)throw new Error(`${e.name} has no value`);return n}case"add":return Qt(e.left,t).add(Qt(e.right,t));case"sub":return Qt(e.left,t).subtract(Qt(e.right,t));case"mul":return Qt(e.left,t).multiply(Qt(e.right,t));case"div":return Qt(e.left,t).divide(Qt(e.right,t));case"pow":{let n=Qt(e.base,t),r=Qt(e.exp,t);if(r.im===0&&Number.isInteger(r.re)&&Math.abs(r.re)<=4096){let s=ht.fromNumber(1),o=n;for(let i=Math.abs(r.re);i>0;i=Math.floor(i/2))i%2&&(s=s.multiply(o)),o=o.multiply(o);return r.re<0?s.reciprocal():s}return n.power(r)}case"neg":{let n=Qt(e.arg,t).neg();return new ht(n.re+0,n.im+0)}case"func":return Pc(e.name,Qt(e.arg,t));default:throw new Error(`${e.type} has no complex value here`)}}function Pc(e,t){switch(e){case"sin":return t.sine();case"cos":return t.cosine();case"tan":return t.tangent();case"exp":return ht.E.power(t);case"ln":return t.logarithm();case"sqrt":return t.squareRoot();case"asin":return t.arcSine();case"acos":return t.arcCosine();case"atan":return t.arcTangent();case"sinh":return t.hyperbolicSine();case"cosh":return t.hyperbolicCosine();case"tanh":return t.hyperbolicTangent();case"cot":return t.tangent().reciprocal();case"sec":return t.cosine().reciprocal();case"csc":return t.sine().reciprocal();case"asinh":return t.arcHyperbolicSine();case"acosh":return t.arcHyperbolicCosine();case"atanh":return t.arcHyperbolicTangent();case"coth":return t.hyperbolicTangent().reciprocal();case"sech":return t.hyperbolicCosine().reciprocal();case"csch":return t.hyperbolicSine().reciprocal();case"acot":return t.reciprocal().arcTangent();case"asec":return t.reciprocal().arcCosine();case"acsc":return t.reciprocal().arcSine();case"acoth":return t.reciprocal().arcHyperbolicTangent();case"asech":return t.reciprocal().arcHyperbolicCosine();case"acsch":return t.reciprocal().arcHyperbolicSine();case"abs":return ht.fromNumber(t.magnitude());case"log10":return t.logarithm(10);case"log2":return t.logarithm(2);case"cbrt":return t.power(1/3);case"expm1":return ht.E.power(t).subtract(1);case"log1p":return t.add(1).logarithm();default:throw new Error(`${e} is a real-only function: it has no complex version here`)}}function Wo(e,t){let n={i:ht.I};for(let[s,o]of Object.entries(t))n[s]=ht.fromNumber(o);let r=Qt(e,n);if(Number.isNaN(r.re)||Number.isNaN(r.im))throw new Error("undefined");return{value:r.im===0?r.re:null,display:r.toString(),re:r.re,im:r.im}}var jc={pi:me.point(Math.PI),e:me.point(Math.E)};function Jt(e,t){switch(e.type){case"const":return me.point(e.value);case"var":{let n=jc[e.name]??t[e.name];if(!n)throw new Error(`${e.name} has no value`);return n}case"add":return Jt(e.left,t).add(Jt(e.right,t));case"sub":return Jt(e.left,t).subtract(Jt(e.right,t));case"mul":return Jt(e.left,t).multiply(Jt(e.right,t));case"div":return Jt(e.left,t).divide(Jt(e.right,t));case"pow":{let n=Jt(e.base,t),r=Jt(e.exp,t);if(r.lo!==r.hi||!Number.isInteger(r.lo)||r.lo<0)throw new Error("interval mode takes a whole exponent of 0 or more (x^3, not x^y or x^0.5)");return n.pow(r.lo)}case"neg":return Jt(e.arg,t).negate();case"func":return Rc(e.name,Jt(e.arg,t));default:throw new Error(`${e.type} has no interval value here`)}}function Rc(e,t){switch(e){case"sqrt":return t.sqrt();case"exp":return t.exp();case"ln":return t.log();case"sin":return t.sin();case"cos":return t.cos();case"abs":return t.abs();case"tan":return t.sin().divide(t.cos());default:throw new Error(`${e} isn't in interval mode (it has no rigorous interval version)`)}}function Yo(e,t){let n={};for(let[s,o]of Object.entries(t))n[s]=me.point(o);let r=Jt(e,n);return{value:r.midpoint,display:r.toString(),lo:r.lo,hi:r.hi}}function Qo(e,t){if(!Number.isInteger(e)||e<2||e>t)throw new Error(`the modulus is a whole number from 2 to ${t}`);return e}function Jo(e,t,n){for(let[o,i]of Object.entries(t))if(!Number.isInteger(i))throw new Error(`${o} is ${i}: in Z/${n}Z a name holds a whole number`);let r=o=>Array.isArray(o)?o.some(r):o!==null&&typeof o=="object"&&(o.type==="const"&&!Number.isInteger(o.value)||Object.values(o).some(r));if(r(e))throw new Error(`in Z/${n}Z a number is a whole number`);let s=S.evaluateOverStructure(e,vn.integersModulo(n),t);if(Number.isNaN(s))throw new Error(`undefined in Z/${n}Z`);return{value:s,display:String(s)}}var Fc=new Set(["+","-","*","/","in"]);function Cc(e,t={}){let n=e.trim().split(/\s+/).filter(Boolean);if(!n.length)throw new Error("nothing to work out");let r=n.indexOf("in");if(r===-1){let{value:c,pos:l}=Uo(n,0,t);if(l!==n.length)throw new Error(`unexpected "${n[l]}"`);return zc(c)}let s=n.slice(0,r),o=n.slice(r+1);if(!s.length)throw new Error('"in" needs an expression before it');if(o.length!==1)throw new Error('"in" needs exactly one unit after it');let{value:i,pos:a}=Uo(s,0,t);if(a!==s.length)throw new Error(`unexpected "${s[a]}" before "in"`);return i.to(o[0])}function _o(e,t){let n=Cc(e,t);return{value:n.value,display:n.toString(),unit:n.symbol}}function zc(e){let t=Dc(e.symbol);if(t===null)return e;let{factors:n,tokens:r}=t;if(n.size===r)return e;let s=[...n].filter(([,c])=>c!==0);if(!s.length)return De.dimensionless(e.value);let o=s.filter(([,c])=>c>0),i=s.filter(([,c])=>c<0);if(!o.length)return e;let a=o.map(([c,l])=>l===1?c:`${c}^${l}`).join("*")+i.map(([c,l])=>l===-1?`/${c}`:`/${c}^${-l}`).join("");try{return e.to(a)}catch{return e}}function Dc(e){if(e==="")return null;let t=new Map,n=0,r="*";for(let s of e.split(/([*/])/)){if(s==="*"||s==="/"){r=s;continue}let o=/^([A-Za-zµΩ°]+)(?:\^(-?\d+))?$/.exec(s);if(!o)return null;n++;let i=o[2]!==void 0?Number(o[2]):1;t.set(o[1],(t.get(o[1])??0)+(r==="/"?-i:i))}return{factors:t,tokens:n}}function Uo(e,t,n){let{value:r,pos:s}=Zo(e,t,n);for(;s<e.length&&(e[s]==="+"||e[s]==="-");){let o=e[s],i=Zo(e,s+1,n);r=o==="+"?r.add(i.value):r.sub(i.value),s=i.pos}return{value:r,pos:s}}function Zo(e,t,n){let{value:r,pos:s}=Xo(e,t,n);for(;s<e.length&&(e[s]==="*"||e[s]==="/");){let o=e[s],i=Xo(e,s+1,n);r=o==="*"?r.mul(i.value):r.div(i.value),s=i.pos}return{value:r,pos:s}}function Xo(e,t,n){let r=e[t];if(r===void 0)throw new Error("expected a number");let s=Number(r),o=Number.isNaN(s)?Object.hasOwn(n,r)?n[r]:Number.NaN:s;if(Number.isNaN(o))throw new Error(`"${r.slice(0,40)}" isn't a number or a name with a value`);let i=e[t+1];return i!==void 0&&!Fc.has(i)?{value:De.of(o,i),pos:t+2}:{value:De.dimensionless(o),pos:t+1}}var Lc=new Set(["sin","cos","tan","cot","sec","csc"]),Vc=new Set(["asin","acos","atan","acot","asec","acsc","arcsin","arccos","arctan","arccot","arcsec","arccsc"]),Bc={type:"const",value:Math.PI/180},Gc={type:"const",value:180/Math.PI};function Kn(e){if(Array.isArray(e))return e.map(Kn);if(e===null||typeof e!="object")return e;let t={};for(let[n,r]of Object.entries(e))t[n]=Kn(r);return t.type==="func"&&Lc.has(t.name)?{...t,arg:{type:"mul",left:t.arg,right:Bc}}:t.type==="func"&&Vc.has(t.name)||t.type==="call2"&&t.name==="atan2"?{type:"mul",left:t,right:Gc}:t}var Uc=Object.freeze({implicitMultiplication:!0}),Hn=/[A-Za-z_][A-Za-z0-9_]*/g,Ko=2e4,ni=e=>String(e?.message??e).replace(/^Error:\s*/,"");function Jr(e,t){return e.replace(Hn,(n,r)=>r>0&&/[0-9.]/.test(e[r-1])&&/^[eE][0-9]*$/.test(n)?n:t(n))}function Ho(e){let t=[];return Jr(e,n=>(t.push(n),n)),t}function Xr(e,t,n=0){if(n>Ut.depth)throw new Error("functions call each other too deeply (does one call itself?)");let r="",s=0;Hn.lastIndex=0;let o;for(;o=Hn.exec(e);){let i=o[0],a=o.index;if(a>0&&/[0-9.]/.test(e[a-1])&&/^[eE][0-9]*$/.test(i))continue;let c=a+i.length;for(;e[c]===" ";)c++;if(e[c]!=="(")continue;let l=t.scope.get(i);if(l?.kind==="fn"){let u=Dr(e,c);if(u<0)throw new Error(`the ( after ${i} is never closed`);let h=Lr(e.slice(c+1,u)).map(m=>Xr(m,t,n));if(h.length!==l.params.length||h.some(m=>!m))throw new Error(`${i} takes ${l.params.length} argument${l.params.length===1?"":"s"} (${l.params.join(", ")})`);let f=Jr(l.body,m=>l.params.includes(m)?`(${h[l.params.indexOf(m)]})`:m);if(r+=e.slice(s,a)+`(${Xr(f,t,n+1)})`,r.length>Ko)throw new Error("this expands to too much text");s=u+1,Hn.lastIndex=s}else if(i.length>=2&&!rn.has(i)&&!t.scope.has(i)&&!t.extra?.has(i))throw new Error(`${i}(\u2026) is not a function here: define it first (${i}(x) = \u2026)`)}if(r+=e.slice(s),r.length>Ko)throw new Error("this expands to too much text");return r}function Le(e,t,n=new Set){if(Array.isArray(e))return e.map(o=>Le(o,t,n));if(e===null||typeof e!="object")return e;if(e.type==="var")return n.has(e.name)?e:t(e)??e;let r=(e.type==="sum"||e.type==="product")&&typeof e.variable=="string"?new Set([...n,e.variable]):n,s={};for(let[o,i]of Object.entries(e))s[o]=o==="body"?Le(i,t,r):Le(i,t,n);return s}function Wr(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 n=t[3]??"",r=BigInt(t[2]+n),s=10n**BigInt(n.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?r*=10n**BigInt(o):s*=10n**BigInt(-o),new tt(t[1]?-r:r,s)}function ke(e){if(Array.isArray(e))return void e.forEach(ke);if(!(e===null||typeof e!="object")){if(e.type==="const"){let t=Number(e.value);if(!Number.isFinite(t)||tt.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))ke(t)}}function _r(e){let t=e.toString(),[n,r]=t.split("/"),s=i=>Number.isSafeInteger(Number(i)),o=i=>i.startsWith("-")?{type:"neg",arg:{type:"const",value:Number(i.slice(1))}}:{type:"const",value:Number(i)};return!s(n)||r!==void 0&&!s(r)?o(String(e.toNumber())):r===void 0?o(n):{type:"div",left:o(n),right:{type:"const",value:Number(r)}}}var Zc=e=>e<0||Object.is(e,-0)?{type:"neg",arg:{type:"const",value:-e}}:{type:"const",value:e};function ti(e){return Number.isFinite(e)?String(Number(e.toPrecision(12))):String(e)}var ri=e=>{try{return S.toLatex(e)}catch{return}};function Xc(e,t){let n=t.floatEnv(),r=s=>{if(Array.isArray(s))return void s.forEach(r);if(!(s===null||typeof s!="object")){if((s.type==="sum"||s.type==="product")&&s.from&&s.to){let o=Yr(s.from,n),i=Yr(s.to,n);if(o===void 0||i===void 0||i-o>Ut.span){if(o!==void 0&&i!==void 0)throw new Error(`a ${s.type} may have at most ${Ut.span} terms`);if(o===void 0&&i===void 0&&!(S.freeVariables(s.from).length||S.freeVariables(s.to).length))throw new Error(`a ${s.type} needs finite bounds`)}}if(t.exact&&s.type==="pow"&&s.exp?.type==="const"&&Math.abs(Number(s.exp.value))>Ut.exponent)throw new Error(`an exact power has an exponent of at most ${Ut.exponent}`);for(let o of Object.values(s))r(o)}};r(e)}function Yr(e,t){try{if(S.freeVariables(e).some(s=>!(s in t)))return;let r=S.evaluate(e,t);return Number.isFinite(r)?r:void 0}catch{return}}var In=class{constructor({exact:t,deadline:n,mode:r="float",modulus:s=null,angle:o="rad"}){this.exact=t,this.mode=r,this.modulus=s,this.angle=o,this.deadline=n,this.scope=new Map,this.failed=new Map}floatEnv(){let t={};for(let[n,r]of this.scope)r.kind==="num"&&(t[n]=r.value);return t}exactEnv(){let t={};for(let[n,r]of this.scope)r.kind==="num"&&(t[n]=r.exact??Wr(r.value));return t}};function on(e,t,n){let r=String(e??"").trim();if(!r)throw new Error("nothing to work out");if(r.length>Ut.line)throw new Error(`a line has at most ${Ut.line} characters`);t.extra=n;let s=Xr(r,t);for(let f of Ho(s)){if(t.failed.has(f)&&!n?.has(f))throw new Error(`${f} has no value: line ${t.failed.get(f)} failed`);if(t.scope.get(f)?.kind==="list")throw new Error(`${f} is a list of solutions: use one of its items elsewhere`)}let o=new Set([...t.scope].filter(([,f])=>f.kind!=="fn").map(([f])=>f));for(let f of n??[])o.add(f);let i=new Map,a=new Set([...Ho(s),...o]);for(let f of[...o].sort()){if(rn.has(f)||/^[A-Za-z](_[A-Za-z0-9]+)?$/.test(f))continue;let m=i.size,p=`Q_${m}`;for(;a.has(p);)p=`Q_${++m}`;a.add(p),i.set(f,p)}let c=new Map([...i].map(([f,m])=>[m,f])),l=i.size?Jr(s,f=>i.get(f)??f):s,u=S.parse(l,Uc),h=c.size?Le(u,f=>c.has(f.name)?{type:"var",name:c.get(f.name)}:void 0):u;return t.angle==="deg"?Kn(h):h}function Kr(e,t,n=new Set){return Le(e,r=>{if(n.has(r.name))return;let s=t.scope.get(r.name);return s?.kind==="expr"?s.expr:void 0})}function Qr(e,t,n=new Set){return Le(e,r=>{if(n.has(r.name))return;let s=t.scope.get(r.name);if(s?.kind==="num")return t.exact&&s.exact?_r(s.exact):Zc(s.value)})}var tr=(e,t)=>S.freeVariables(e).filter(n=>t.scope.get(n)?.kind!=="num");function nr(e,t){if(Xc(e,t),!t.exact)return{value:S.evaluate(e,t.floatEnv())};ke(e);let n;try{n=S.evaluateExact(e,t.exactEnv())}catch(o){throw new Error(`no exact value: ${ni(o)}`)}let r=n.toNumber(),s=S.evaluate(e,t.floatEnv());if(Number.isFinite(s)&&!(Math.abs(r-s)<=1e-9*Math.max(1,Math.abs(s))))throw new Error("no exact value: the exact result differs from the float one (a constant is not a fraction)");return{value:r,exact:n}}var qn=({value:e,exact:t})=>({kind:"number",value:e,rational:t,display:t?t.toString():ti(e),...t?{exact:t.toString(),approx:ti(e)}:{}});function er(e){if(Array.isArray(e))return e.map(er);if(e===null||typeof e!="object")return e;if(e.type==="const"&&!Number.isInteger(e.value)){let t=tt.fromNumber(Math.abs(e.value));if(t.toNumber()===Math.abs(e.value)){let n=_r(t);return e.value<0?{type:"neg",arg:n}:n}return e}return Object.fromEntries(Object.entries(e).map(([t,n])=>[t,er(n)]))}function Ve(e,t){return t.exact&&(ke(e),e=er(e)),{kind:"expr",expr:e,display:S.toString(e),latex:ri(e)}}function si(e,t){let n=Kr(on(e,t),t);return tr(n,t).length?Ve(Qr(n,t),t):qn(nr(n,t))}function Sn(e,t,n){let r=Kr(on(e,t),t);if(tr(r,t).length)throw new Error(`${n} must be a number (${tr(r,t).join(", ")} has no value)`);let s=nr(r,t);if(!Number.isFinite(s.value))throw new Error(`${n} must be a finite number`);return s}function Wc(e,t,n){if(t[1]!==void 0&&!(e==="integrate"||e==="diff"||e==="solve"||e==="factor"||e==="taylor"||e==="limit"))return"x";if(t[1]!==void 0&&t[1]!==""){if(!sn.test(t[1]))throw new Error(`${e}: the second argument is the variable's name, such as x`);return t[1]}let r=new Set(S.freeVariables(on(t[0],n)));return r.size===1?[...r][0]:"x"}function Zr(e,t,n){if(!n.exact)return Ve(t,n);if(!tr(e,n).length)return qn(nr(e,n));ke(t);let r=[...new Set([...S.freeVariables(e),...S.freeVariables(t)])];for(let s of[2,3]){let o={};r.forEach((c,l)=>o[c]=new tt(BigInt(s+l),BigInt(s+5)));let i,a;try{i=S.evaluateExact(e,o),a=S.evaluateExact(t,o)}catch{return Ve(t,n)}if(i.compare?i.compare(a)!==0:i.toString()!==a.toString())throw new Error("no exact value: the simplifier gave an approximation (a constant it folded is not a fraction)")}return Ve(t,n)}var oi=new RegExp(`^\\s*(${zr.join("|")})\\s*\\(`);function Yc(e,t){let n=oi.exec(e);if(!n)return null;let r=n[0].length-1,s=Dr(e,r);if(s<0||e.slice(s+1).trim())return null;let o=n[1],i=Lr(e.slice(r+1,s));if(!i[0])throw new Error(`${o}( ) needs an expression`);let a={simplify:[1,1],expand:[1,1],factor:[1,2],diff:[1,2],integrate:[1,4],solve:[1,2],taylor:[1,4],limit:[2,4]}[o];if(i.length<a[0]||i.length>a[1])throw new Error(`${o} takes ${a[0]===a[1]?a[0]:`${a[0]} to ${a[1]}`} argument${a[1]===1?"":"s"}`);let c=o==="simplify"||o==="expand"?null:o==="limit"?i[1]:Wc(o,i,t);if(c!==null&&!sn.test(c??""))throw new Error(`${o}: the second argument is the variable's name, such as x`);let l=new Set(c?[c]:[]),u=Kr(on(i[0],t,l),t,l),h=Qr(u,t,l);switch(t.exact&&ke(h),o){case"simplify":return Zr(h,S.simplify(h),t);case"expand":return Zr(h,S.expand(h),t);case"factor":return Zr(h,S.factor(h,c),t);case"diff":return Ve(S.differentiate(h,c),t);case"integrate":{if(i.length===3)throw new Error("integrate needs both bounds for a definite integral: integrate(e, x, from, to)");if(i.length<4)return Ve(S.integrate(h,c),t);let f=Sn(i[2],t,"the lower bound"),m=Sn(i[3],t,"the upper bound");if(!t.exact)return qn({value:S.integrateDefinite(h,f.value,m.value,c)});let p=S.integrate(h,c);ke(p);let d=g=>nr(Qr(Le(p,w=>w.name===c?_r(g.exact):void 0),t),t).exact,x=d(m).subtract(d(f));return qn({exact:x,value:x.toNumber()})}case"solve":{let m=S.solve(h,c).map(p=>[p,Yr(p,{})]).sort(([,p],[,d])=>p===void 0||d===void 0?0:p-d).map(([p])=>p).map(p=>t.exact?(ke(p),er(p)):p);return{kind:"list",items:m.map(p=>({expr:p,display:S.toString(p),latex:ri(p)})),display:m.length?m.map(p=>S.toString(p)).join(", "):"no solution"}}case"taylor":{let f=i[2]===void 0?0:Sn(i[2],t,"the centre").value,m=i[3]===void 0?5:Sn(i[3],t,"the order").value;if(!Number.isInteger(m)||m<0||m>20)throw new Error("the order of a Taylor series is a whole number from 0 to 20");return Ve(S.taylor(h,c,f,m),t)}case"limit":{if(t.exact)throw new Error("a limit is a numeric answer: it has no exact value (turn exact mode off)");let f=Sn(i[2],t,"the point").value,m=i[3];if(m!==void 0&&!["left","right","both"].includes(m))throw new Error("the direction of a limit is left, right or both");return qn({value:S.limit(h,c,f,m)})}default:return null}}function Qc(e,t){let n=oi.exec(e);if(n)throw new Error(`${n[1]} works in the float mode`);let r=t.floatEnv();if(t.mode==="units"){let a=_o(e,r);return{kind:"number",value:a.value,display:a.display,unit:a.unit}}let s=on(e,t),o={};for(let a of S.freeVariables(s))if(!(t.mode==="complex"&&a==="i"&&!(a in r))){if(!(a in r))throw new Error(`${a} has no value`);o[a]=r[a]}if(t.mode==="interval"){let a=Yo(s,o);return{kind:"number",value:a.value,display:a.display,lo:a.lo,hi:a.hi}}if(t.mode==="complex"){let a=Wo(s,o);return{kind:"number",value:a.value,display:a.display,re:a.re,im:a.im,...a.value===null?{notStored:!0}:{}}}let i=Jo(s,o,t.modulus);return{kind:"number",value:i.value,display:i.display}}function Jc(e,t){return t.mode!=="float"?Qc(e,t):Yc(e,t)??si(e,t)}function ei(e){let{expr:t,value:n,items:r,rational:s,notStored:o,...i}=e,a={...i};return e.kind==="number"&&(a.value=Number.isFinite(n)?n:null),o&&(a.note="not stored: the result is not a real number"),r&&(a.items=r.map(c=>({display:c.display,latex:c.latex}))),a}function _c(e,t,n){let r=new Map(n),s=(...o)=>{if(o.length!==t.params.length)throw new Error(`${e} takes ${t.params.length} argument${t.params.length===1?"":"s"} (${t.params.join(", ")})`);if(o.some(c=>typeof c!="number"||!Number.isFinite(c)))throw new Error(`${e} takes finite numbers`);let i=new In({exact:!1,deadline:1/0});i.scope=new Map(r);let a=si(`${e}(${o.map(c=>`(${c<0?`0-${-c}`:c})`).join(", ")})`,i);if(a.kind!=="number")throw new Error(`${e}(${o.join(", ")}) is not a number: ${a.display}`);return a.value};return Object.defineProperty(s,"name",{value:e}),Object.defineProperty(s,"toString",{value:()=>`${e}(${t.params.join(", ")}) = ${t.body}`}),s}function Kc(e={}){let t=Array.isArray(e.lines)?e.lines:[];if(t.length>Ut.lines)throw new Error(`a calc pane has at most ${Ut.lines} lines`);let n=Date.now()+Math.min(1e4,Math.max(1,Number(e.deadlineMs)||Ut.deadlineMs)),r=e.mode??"float";if(!Fr.includes(r))throw new Error(`mode is one of ${Fr.join(", ")}`);let s=e.angle??"rad";if(!Object.hasOwn(Cr,s))throw new Error(`angle is one of ${Object.keys(Cr).join(", ")}`);let o=r==="modulus"?Qo(e.modulus??7,Fo):null,i=e.exact===!0&&r==="float",a=new In({exact:i,deadline:n,mode:r,modulus:o,angle:s}),c=[];for(let[f,m]of Object.entries(e.wired??{}))if(!(typeof m!="number"||!Number.isFinite(m)||!sn.test(f)||rn.has(f)))try{a.scope.set(f,{kind:"num",value:m,...i?{exact:Wr(m)}:{}}),c.push(f)}catch{}let l=new Set,u=t.map((f,m)=>{let p=typeof f=="string"?f:"",d={index:m,text:p},x=Co(p);if(x.kind==="blank")return{...d,kind:"blank"};if(x.kind==="comment")return{...d,kind:"comment",display:x.comment};let g=x.name;try{if(Date.now()>n)throw new Error("stopped: this run took too long");if(p.length>Ut.line)throw new Error(`a line has at most ${Ut.line} characters`);if(x.problem)throw new Error(x.problem);if(x.kind==="function"){if(r!=="float")throw new Error("a function is defined in the float mode");if(Hc(x.rhs,g))throw new Error(`${g} can't call itself`);let b=new In({exact:i,deadline:n});return b.scope=new Map(a.scope),b.failed=new Map(a.failed),on(x.rhs,b,new Set(x.params)),a.scope.set(g,{kind:"fn",params:x.params,body:x.rhs}),a.failed.delete(g),l.add(g),{...d,kind:"function",name:g,params:x.params,display:`${g}(${x.params.join(", ")}) = ${x.rhs}`}}let w=Jc(x.rhs,a);if(x.kind==="assign"){if(w.notStored)return a.scope.delete(g),a.failed.set(g,m+1),l.delete(g),{...d,...ei(w),name:g};if(w.kind==="number"){if(!Number.isFinite(w.value))throw new Error(`${g} would be ${w.display}: a variable needs a finite number`);a.scope.set(g,{kind:"num",value:w.value,...i?{exact:w.rational??Wr(w.value)}:{}})}else if(w.kind==="expr"){if(S.freeVariables(w.expr).includes(g)&&a.scope.get(g)?.kind!=="num")throw new Error(`${g} isn't defined yet, so it can't be used to define itself`);a.scope.set(g,{kind:"expr",expr:w.expr})}else a.scope.set(g,{kind:"list",items:w.items});a.failed.delete(g),l.add(g)}return{...d,...ei(w),...x.kind==="assign"?{name:g}:{}}}catch(w){return g&&(x.kind==="assign"||x.kind==="function")&&(a.failed.set(g,m+1),a.scope.delete(g)),{...d,kind:"error",...g&&(x.kind==="assign"||x.kind==="function")?{name:g}:{},error:ni(w)}}}),h={};for(let f of l){let m=a.scope.get(f);m&&(m.kind==="num"?h[f]=m.value:m.kind==="expr"?h[f]=S.toString(m.expr):m.kind==="list"?h[f]=m.items.map(p=>p.display):m.kind==="fn"&&(h[f]=_c(f,m,a.scope)))}return{results:u,published:h,wired:c,exact:i,mode:r,modulus:o,angle:s}}function Hc(e,t){return new RegExp(`(?<![A-Za-z0-9_$])${zo(t)}\\s*\\(`).test(e)}var ii={attribution:"Derived from RuleBasedIntegration/MaximaSyntaxTestSuite (https://github.com/RuleBasedIntegration/MaximaSyntaxTestSuite), MIT License, Copyright (c) 2018 Rule-based Integration; the licence text is in RUBI-LICENSE.txt. Only the Rubi test suites are kept: the third-party 'Independent test suites' are left out, and so is every problem with a parameter besides x. Converted to @johnhenry/math syntax by graphculator's scripts/rubi-convert.mjs; each row is [integrand, antiderivative, Rubi's step count, source file].",problems:[["0","0",1,"1 Algebraic functions/1.1 Binomial products/1.1.1 Linear/1.1.1.2 (a+b x)^m (c+d x)^n"],["(3-x)^(1/2)*(-2+x)^(1/2)","-1/8*asin(5-2*x)-1/2*(3-x)^(3/2)*sqrt(-2+x)+1/4*sqrt(3-x)*sqrt(-2+x)",5,"1 Algebraic functions/1.1 Binomial products/1.1.1 Linear/1.1.1.2 (a+b x)^m (c+d x)^n"],["(1-2*x)*(3+5*x)^3/(2+3*x)^6","7/15*(3+5*x)^4/(2+3*x)^5+5/12*(3+5*x)^4/(2+3*x)^4",2,"1 Algebraic functions/1.1 Binomial products/1.1.1 Linear/1.1.1.3 (a+b x)^m (c+d x)^n (e+f x)^p"],["(1-2*x)^3*(2+3*x)^2/(3+5*x)^2","-1179/3125*x-427/625*x^2+164/125*x^3-18/25*x^4+(-1331/15625)/(3+5*x)+1452/3125*ln(3+5*x)",2,"1 Algebraic functions/1.1 Binomial products/1.1.1 Linear/1.1.1.3 (a+b x)^m (c+d x)^n (e+f x)^p"],["1/((1-2*x)^2*(3+5*x)^3)","4/1331/(1-2*x)+(-5/242)/(3+5*x)^2+(-20/1331)/(3+5*x)-60/14641*ln(1-2*x)+60/14641*ln(3+5*x)",2,"1 Algebraic functions/1.1 Binomial products/1.1.1 Linear/1.1.1.3 (a+b x)^m (c+d x)^n (e+f x)^p"],["sqrt(1-2*x)/((2+3*x)*(3+5*x)^2)","-2*atanh(sqrt(3/7)*sqrt(1-2*x))*sqrt(21)+68*atanh(sqrt(5/11)*sqrt(1-2*x))/sqrt(55)-sqrt(1-2*x)/(3+5*x)",6,"1 Algebraic functions/1.1 Binomial products/1.1.1 Linear/1.1.1.3 (a+b x)^m (c+d x)^n (e+f x)^p"],["(2+3*x)^2/((3+5*x)^3*sqrt(1-2*x))","-2313/3025*atanh(sqrt(5/11)*sqrt(1-2*x))/sqrt(55)-1/550*sqrt(1-2*x)/(3+5*x)^2-27/1210*sqrt(1-2*x)/(3+5*x)",4,"1 Algebraic functions/1.1 Binomial products/1.1.1 Linear/1.1.1.3 (a+b x)^m (c+d x)^n (e+f x)^p"],["(3+5*x)^(3/2)*sqrt(1-2*x)/(2+3*x)^2","41/27*asin(sqrt(2/11)*sqrt(3+5*x))*sqrt(5/2)+107/27*atan(sqrt(1-2*x)/(sqrt(7)*sqrt(3+5*x)))/sqrt(7)-1/3*(3+5*x)^(3/2)*sqrt(1-2*x)/(2+3*x)+10/9*sqrt(1-2*x)*sqrt(3+5*x)",7,"1 Algebraic functions/1.1 Binomial products/1.1.1 Linear/1.1.1.3 (a+b x)^m (c+d x)^n (e+f x)^p"],["(2+3*x)^4/((3+5*x)^(3/2)*sqrt(1-2*x))","143283/8000*asin(sqrt(2/11)*sqrt(3+5*x))/sqrt(10)-2/55*(2+3*x)^3*sqrt(1-2*x)/sqrt(3+5*x)-21/550*(2+3*x)^2*sqrt(1-2*x)*sqrt(3+5*x)-21/88000*(8987+3660*x)*sqrt(1-2*x)*sqrt(3+5*x)",5,"1 Algebraic functions/1.1 Binomial products/1.1.1 Linear/1.1.1.3 (a+b x)^m (c+d x)^n (e+f x)^p"],["1/(x^(7/2)*(1+x^2)^3)","(-117/80)/x^(5/2)+1/4/(x^(5/2)*(1+x^2)^2)+13/16/(x^(5/2)*(1+x^2))-117/32*atan(1-sqrt(2)*sqrt(x))/sqrt(2)+117/32*atan(1+sqrt(2)*sqrt(x))/sqrt(2)+117/64*ln(1+x-sqrt(2)*sqrt(x))/sqrt(2)-117/64*ln(1+x+sqrt(2)*sqrt(x))/sqrt(2)+117/16/sqrt(x)",14,"1 Algebraic functions/1.1 Binomial products/1.1.2 Quadratic/1.1.2.2 (c x)^m (a+b x^2)^p"],["1/(x^5*sqrt(-9+4*x^2))","2/81*atan(1/3*sqrt(-9+4*x^2))+1/36*sqrt(-9+4*x^2)/x^4+1/54*sqrt(-9+4*x^2)/x^2",5,"1 Algebraic functions/1.1 Binomial products/1.1.2 Quadratic/1.1.2.2 (c x)^m (a+b x^2)^p"],["x^7/(2+3*x^4)","1/12*x^4-1/18*ln(2+3*x^4)",3,"1 Algebraic functions/1.1 Binomial products/1.1.3 General/1.1.3.2 (c x)^m (a+b x^n)^p"],["1/(x^3*(1+x^6))","(-1/2)/x^2+1/6*ln(1+x^2)-1/12*ln(1-x^2+x^4)+1/2*atan((1-2*x^2)/sqrt(3))/sqrt(3)",8,"1 Algebraic functions/1.1 Binomial products/1.1.3 General/1.1.3.2 (c x)^m (a+b x^n)^p"],["x^5/((1-x^3)^(1/3)*(1+x^3))","-1/2*(1-x^3)^(2/3)+1/6*ln(1+x^3)/2^(1/3)-1/2*ln(2^(1/3)-(1-x^3)^(1/3))/2^(1/3)-atan((1+2^(2/3)*(1-x^3)^(1/3))/sqrt(3))/(2^(1/3)*sqrt(3))",6,"1 Algebraic functions/1.1 Binomial products/1.1.3 General/1.1.3.4 (e x)^m (a+b x^n)^p (c+d x^n)^q"],["(9+6*x+4*x^2)/(729-64*x^6)^2","1/157464/(3-2*x)+(-1/472392)/(3+2*x)+1/236196*(-3+4*x)/(9-6*x+4*x^2)-1/118098*ln(3-2*x)+1/354294*ln(3+2*x)+5/2834352*ln(9-6*x+4*x^2)+1/944784*ln(9+6*x+4*x^2)-1/52488*atan(1/3*(3-4*x)/sqrt(3))/sqrt(3)+1/472392*atan(1/3*(3+4*x)/sqrt(3))/sqrt(3)",14,"1 Algebraic functions/1.1 Binomial products/1.1.3 General/1.1.3.8 P(x) (c x)^m (a+b x^n)^p"],["1/(1+x^2+2*x*cos(1/7*pi))","atan(cot(1/7*pi)+x*csc(1/7*pi))*csc(1/7*pi)",2,"1 Algebraic functions/1.2 Trinomial products/1.2.1 Quadratic/1.2.1.1 (a+b x+c x^2)^p"],["x/(9+12*x+4*x^2)^(1/2)","-3/4*(3+2*x)*ln(3+2*x)/sqrt(9+12*x+4*x^2)+1/4*sqrt(9+12*x+4*x^2)",3,"1 Algebraic functions/1.2 Trinomial products/1.2.1 Quadratic/1.2.1.2 (d+e x)^m (a+b x+c x^2)^p"],["1/(x*sqrt(1+x)*sqrt(1-x+x^2))","-2/3*atanh(sqrt(1+x^3))*sqrt(1+x^3)/(sqrt(1+x)*sqrt(1-x+x^2))",4,"1 Algebraic functions/1.2 Trinomial products/1.2.1 Quadratic/1.2.1.4 (d+e x)^m (f+g x)^n (a+b x+c x^2)^p"],["(2+x+3*x^2-x^3+5*x^4)*sqrt(3-x+2*x^2)/(5+2*x)^8","-3667/4032*(3-x+2*x^2)^(3/2)/(5+2*x)^7+948341/1741824*(3-x+2*x^2)^(3/2)/(5+2*x)^6-1464037/13934592*(3-x+2*x^2)^(3/2)/(5+2*x)^5+19414831/4013162496*(3-x+2*x^2)^(3/2)/(5+2*x)^4+246159769/866843099136*(3-x+2*x^2)^(3/2)/(5+2*x)^3-289071245/285315214344192*atanh(1/12*(17-22*x)/(sqrt(2)*sqrt(3-x+2*x^2)))/sqrt(2)-12568315/23776267862016*(17-22*x)*sqrt(3-x+2*x^2)/(5+2*x)^2",8,"1 Algebraic functions/1.2 Trinomial products/1.2.1 Quadratic/1.2.1.9 P(x) (d+e x)^m (a+b x+c x^2)^p"],["1/(x^2*(1-x^4+x^8))","(-1)/x+1/8*ln(1+x^2-x*sqrt(2-sqrt(3)))*sqrt(1/3*(2-sqrt(3)))-1/8*ln(1+x^2+x*sqrt(2-sqrt(3)))*sqrt(1/3*(2-sqrt(3)))+1/4*atan((-2*x+sqrt(2-sqrt(3)))/sqrt(2+sqrt(3)))/sqrt(3*(2-sqrt(3)))-1/4*atan((2*x+sqrt(2-sqrt(3)))/sqrt(2+sqrt(3)))/sqrt(3*(2-sqrt(3)))-1/8*ln(1+x^2-x*sqrt(2+sqrt(3)))*sqrt(1/3*(2+sqrt(3)))+1/8*ln(1+x^2+x*sqrt(2+sqrt(3)))*sqrt(1/3*(2+sqrt(3)))-1/4*atan((-2*x+sqrt(2+sqrt(3)))/sqrt(2-sqrt(3)))/sqrt(3*(2+sqrt(3)))+1/4*atan((2*x+sqrt(2+sqrt(3)))/sqrt(2-sqrt(3)))/sqrt(3*(2+sqrt(3)))",22,"1 Algebraic functions/1.2 Trinomial products/1.2.3 General/1.2.3.2 (d x)^m (a+b x^n+c x^(2 n))^p"],["(1+x^3)/(-x^2+x^3)","1/x+x+2*ln(1-x)-ln(x)",3,"1 Algebraic functions/1.3 Miscellaneous/1.3.1 Rational functions"],["x^3*(sqrt(1-x)+sqrt(1+x))^2","1/2*x^4-2/3*(1-x^2)^(3/2)+2/5*(1-x^2)^(5/2)",5,"1 Algebraic functions/1.3 Miscellaneous/1.3.2 Algebraic functions"],["(-1+x^2)^3*sqrt(-1+1/x^2)/x","-35/48*(-1+1/x^2)^(3/2)*x^2-7/24*(-1+1/x^2)^(5/2)*x^4-1/6*(-1+1/x^2)^(7/2)*x^6-35/16*atan(sqrt(-1+1/x^2))+35/16*sqrt(-1+1/x^2)",8,"1 Algebraic functions/1.3 Miscellaneous/1.3.2 Algebraic functions"],["1/(-1+exp(1)^x+exp(1)^(2*x))","-x+1/10*ln(1+2*exp(1)^x+sqrt(5))*(5-sqrt(5))+1/10*ln(1+2*exp(1)^x-sqrt(5))*(5+sqrt(5))",6,"2 Exponentials/2.3 Exponential functions"],["1/(2+1/exp(1)^x+exp(1)^x)","(-1)/(1+exp(1)^x)",2,"2 Exponentials/2.3 Exponential functions"],["1/(2+1/3^x+3^x)","(-1)/((1+3^x)*ln(3))",2,"2 Exponentials/2.3 Exponential functions"],["exp(1)^x/(4+exp(1)^(2*x))","1/2*atan(1/2*exp(1)^x)",2,"2 Exponentials/2.3 Exponential functions"],["exp(1)^(x^2)*x^3","-1/2*exp(1)^(x^2)+1/2*exp(1)^(x^2)*x^2",2,"2 Exponentials/2.3 Exponential functions"],["exp(1)^(2-x^2)*x","-1/2*exp(1)^(2-x^2)",1,"2 Exponentials/2.3 Exponential functions"],["exp(1)^(2*x)/(1+exp(1)^(4*x))","1/2*atan(exp(1)^(2*x))",2,"2 Exponentials/2.3 Exponential functions"],["exp(1)^x/(1+exp(1)^(2*x))","atan(exp(1)^x)",2,"2 Exponentials/2.3 Exponential functions"],["x/sqrt(-1+exp(1)^(2*x^2))","1/2*atan(sqrt(-1+exp(1)^(2*x^2)))",4,"2 Exponentials/2.3 Exponential functions"],["exp(1)^(x^(3/2))*x^2","-2/3*exp(1)^(x^(3/2))+2/3*exp(1)^(x^(3/2))*x^(3/2)",3,"2 Exponentials/2.3 Exponential functions"],["exp(1)^(4*x)/sqrt(16+exp(1)^(8*x))","1/4*asinh(1/4*exp(1)^(4*x))",2,"2 Exponentials/2.3 Exponential functions"],["exp(1)^sqrt(x)/sqrt(x)","2*exp(1)^sqrt(x)",1,"2 Exponentials/2.3 Exponential functions"],["(exp(1)^x+exp(1)^(2*x)+exp(1)^(3*x))/exp(1)^(4*x)","(-1/3)/exp(1)^(3*x)+(-1/2)/exp(1)^(2*x)+(-1)/exp(1)^x",3,"2 Exponentials/2.3 Exponential functions"],["exp(1)^(2*x)/(1+exp(1)^x)","exp(1)^x-ln(1+exp(1)^x)",3,"2 Exponentials/2.3 Exponential functions"],["exp(1)^x*cos(4+3*x)","1/10*exp(1)^x*cos(4+3*x)+3/10*exp(1)^x*sin(4+3*x)",1,"2 Exponentials/2.3 Exponential functions"],["exp(1)^(2*x)/(1+exp(1)^x)^(1/3)","-3/2*(1+exp(1)^x)^(2/3)+3/5*(1+exp(1)^x)^(5/3)",3,"2 Exponentials/2.3 Exponential functions"],["exp(1)^(3*x)*(-x+x^2)","5/27*exp(1)^(3*x)-5/9*exp(1)^(3*x)*x+1/3*exp(1)^(3*x)*x^2",8,"2 Exponentials/2.3 Exponential functions"],["exp(1)^(3*x)/(1+exp(1)^(2*x))","exp(1)^x-atan(exp(1)^x)",3,"2 Exponentials/2.3 Exponential functions"],["exp(1)^(7*x)*x^3","-6/2401*exp(1)^(7*x)+6/343*exp(1)^(7*x)*x-3/49*exp(1)^(7*x)*x^2+1/7*exp(1)^(7*x)*x^3",4,"2 Exponentials/2.3 Exponential functions"],["exp(1)^(6*x)/(9-exp(1)^x)^(5/2)","39366/(9-exp(1)^x)^(3/2)+540*(9-exp(1)^x)^(3/2)-18*(9-exp(1)^x)^(5/2)+2/7*(9-exp(1)^x)^(7/2)+(-65610)/sqrt(9-exp(1)^x)-14580*sqrt(9-exp(1)^x)",3,"2 Exponentials/2.3 Exponential functions"],["exp(1)^(exp(1)^x+x)","exp(1)^(exp(1)^x)",2,"2 Exponentials/2.3 Exponential functions"],["1/(1/exp(1)^x+exp(1)^x)^2","(-1/2)/(1+exp(1)^(2*x))",2,"2 Exponentials/2.3 Exponential functions"],["exp(1)^x*((-1)/exp(1)^x+exp(1)^x)^3","1/2/exp(1)^(2*x)-3/2*exp(1)^(2*x)+1/4*exp(1)^(4*x)+3*x",4,"2 Exponentials/2.3 Exponential functions"],["1/(-exp(1)^x+exp(1)^(3*x))","1/exp(1)^x-atanh(exp(1)^x)",3,"2 Exponentials/2.3 Exponential functions"],["(1+exp(1)^x)/sqrt(exp(1)^x+x)","2*sqrt(exp(1)^x+x)",1,"2 Exponentials/2.3 Exponential functions"],["x*ln(x)*sqrt(4+x^2)","-1/9*(4+x^2)^(3/2)+8/3*atanh(1/2*sqrt(4+x^2))+1/3*(4+x^2)^(3/2)*ln(x)-4/3*sqrt(4+x^2)",6,"3 Logarithms/3.1.4 (f x)^m (d+e x^r)^q (a+b log(c x^n))^p"],["ln(-1+4*x+4*sqrt((-1+x)*x))/x^(3/2)","-8*atan(sqrt(x)/sqrt(-x+x^2))+4*atan(2*sqrt(2)*sqrt(x))*sqrt(2)-2*ln(-1+4*x+4*sqrt(-x+x^2))/sqrt(x)-4*atan(2/3*sqrt(2)*sqrt(-1+x))*sqrt(2)*sqrt(-x+x^2)/(sqrt(-1+x)*sqrt(x))",15,"3 Logarithms/3.5 Logarithm functions"],["sin(ln(x))^2/x","1/2*ln(x)-1/2*cos(ln(x))*sin(ln(x))",3,"3 Logarithms/3.5 Logarithm functions"],["cos(x)*ln(cos(x))","atanh(sin(x))-sin(x)+ln(cos(x))*sin(x)",4,"3 Logarithms/3.5 Logarithm functions"],["x*ln((1+3*x)^(1/3))","1/18*x-1/12*x^2+1/2*x^2*ln((1+3*x)^(1/3))-1/54*ln(1+3*x)",3,"3 Logarithms/3.5 Logarithm functions"],["ln((-11+5*x)/(5+76*x))","-1/5*(11-5*x)*ln((-11+5*x)/(5+76*x))-861/380*ln(5+76*x)",2,"3 Logarithms/3.5 Logarithm functions"],["sqrt(1-cos(x)^2)","-cot(x)*sqrt(sin(x)^2)",3,"4 Trig functions/4.2 Cosine/4.2.7 (d trig)^m (a+b (c cos)^n)^p"],["exp(1)^x*x*cos(x)","1/2*exp(1)^x*x*cos(x)-1/2*exp(1)^x*sin(x)+1/2*exp(1)^x*x*sin(x)",4,"4 Trig functions/4.7 Miscellaneous/4.7.6 f^(a+b x+c x^2) trig(d+e x+f x^2)^n"],["cos(2*x)*sin(6*x)^2","1/4*sin(2*x)-1/40*sin(10*x)-1/56*sin(14*x)",5,"4 Trig functions/4.7 Miscellaneous/4.7.7 Trig functions"],["1/(csc(x)-sin(x))","sec(x)",3,"4 Trig functions/4.7 Miscellaneous/4.7.7 Trig functions"],["x*sin(1+x^2)","-1/2*cos(1+x^2)",2,"4 Trig functions/4.7 Miscellaneous/4.7.7 Trig functions"],["acos(x)*sqrt(1-x^2)","1/4*x^2-1/4*acos(x)^2+1/2*x*acos(x)*sqrt(1-x^2)",3,"5 Inverse trig functions/5.2 Inverse cosine/5.2.5 Inverse cosine functions"],["acos(sqrt(x))/x^3","-1/2*acos(sqrt(x))/x^2+1/6*sqrt(1-x)/x^(3/2)+1/3*sqrt(1-x)/sqrt(x)",4,"5 Inverse trig functions/5.2 Inverse cosine/5.2.5 Inverse cosine functions"],["atan(sqrt(x))/x^(3/2)","ln(x)-ln(1+x)-2*atan(sqrt(x))/sqrt(x)",4,"5 Inverse trig functions/5.3 Inverse tangent/5.3.2 (d x)^m (a+b arctan(c x^n))^p"],["1/((1+x^2)*(2+atan(x)))","ln(2+atan(x))",1,"5 Inverse trig functions/5.3 Inverse tangent/5.3.7 Inverse tangent functions"],["acot(sqrt(x))/x^2","-acot(sqrt(x))/x+atan(sqrt(x))+1/sqrt(x)",4,"5 Inverse trig functions/5.4 Inverse cotangent/5.4.1 Inverse cotangent functions"],["exp(1)^x*sech(3*x)^2","-2/3*exp(1)^x/(1+exp(1)^(6*x))+2/9*atan(exp(1)^x)-1/9*atan(-2*exp(1)^x+sqrt(3))+1/9*atan(2*exp(1)^x+sqrt(3))-1/6*ln(1+exp(1)^(2*x)-exp(1)^x*sqrt(3))/sqrt(3)+1/6*ln(1+exp(1)^(2*x)+exp(1)^x*sqrt(3))/sqrt(3)",13,"6 Hyperbolic functions/6.2 Hyperbolic cosine/6.2.5 Hyperbolic cosine functions"],["(-1+cosh(x)^2)^(3/2)","1/3*coth(x)*(sinh(x)^2)^(3/2)-2/3*coth(x)*sqrt(sinh(x)^2)",4,"6 Hyperbolic functions/6.2 Hyperbolic cosine/6.2.7 hyper^m (a+b cosh^n)^p"],["cosh(x)/(1+tanh(x))","2/3*sinh(x)-1/3*cosh(x)/(1+tanh(x))",2,"6 Hyperbolic functions/6.3 Hyperbolic tangent/6.3.2 Hyperbolic tangent functions"],["tanh(x)/(1+tanh(x))^(3/2)","1/2*atanh(sqrt(1+tanh(x))/sqrt(2))/sqrt(2)+(-1/2)/sqrt(1+tanh(x))+1/3/(1+tanh(x))^(3/2)",4,"6 Hyperbolic functions/6.3 Hyperbolic tangent/6.3.2 Hyperbolic tangent functions"],["sech(x)/(1+coth(x))","atan(sinh(x))+cosh(x)-sinh(x)",8,"6 Hyperbolic functions/6.4 Hyperbolic cotangent/6.4.2 Hyperbolic cotangent functions"],["sqrt(1-sech(x)^2)","coth(x)*ln(cosh(x))*sqrt(tanh(x)^2)",3,"6 Hyperbolic functions/6.5 Hyperbolic secant/6.5.7 (d hyper)^m (a+b (c sech)^n)^p"],["coth(2*x)*sinh(x)","-1/2*atan(sinh(x))+sinh(x)",3,"6 Hyperbolic functions/6.7 Miscellaneous/6.7.1 Hyperbolic functions"],["cosh(x)*sech(2*x)","atan(sinh(x)*sqrt(2))/sqrt(2)",2,"6 Hyperbolic functions/6.7 Miscellaneous/6.7.1 Hyperbolic functions"],["1/(coth(x)+csch(x))^3","2/(1+cosh(x))+ln(1+cosh(x))",4,"6 Hyperbolic functions/6.7 Miscellaneous/6.7.1 Hyperbolic functions"],["1/(cosh(x)^2+sinh(x)^2)","atan(tanh(x))",2,"6 Hyperbolic functions/6.7 Miscellaneous/6.7.1 Hyperbolic functions"],["sech(x)^2*(2+tanh(x)^2)/(1+tanh(x)^3)","ln(1+tanh(x))-2*atan((1-2*tanh(x))/sqrt(3))/sqrt(3)",5,"6 Hyperbolic functions/6.7 Miscellaneous/6.7.1 Hyperbolic functions"],["exp(1)^atanh(x)*x/(1+x)","-sqrt(1-x)*sqrt(1+x)",2,"7 Inverse hyperbolic functions/7.3 Inverse hyperbolic tangent/7.3.6 Exponentials of inverse hyperbolic tangent functions"],["exp(1)^acoth(x)/(1+x)","atanh(sqrt(1+1/x)*sqrt((-1+x)/x))",4,"7 Inverse hyperbolic functions/7.4 Inverse hyperbolic cotangent/7.4.2 Exponentials of inverse hyperbolic cotangent functions"],["exp(1)^acoth(x)/sqrt(1+x)","2*x*sqrt(1+1/x)*sqrt((-1+x)/x)/sqrt(1+x)",3,"7 Inverse hyperbolic functions/7.4 Inverse hyperbolic cotangent/7.4.2 Exponentials of inverse hyperbolic cotangent functions"],["asech(sqrt(x))","x*asech(sqrt(x))+(-1+x)/(sqrt(x)*sqrt(-1+1/sqrt(x))*sqrt(1+1/sqrt(x)))",3,"7 Inverse hyperbolic functions/7.5 Inverse hyperbolic secant/7.5.2 Inverse hyperbolic secant functions"]]};var ai={attribution:'Original problems written for this project (MIT, like the rest of the repository), covering the kinds of the textbook sets left out of rubi-corpus.json: substitution, integration by parts, trigonometric powers and products, partial fractions, inverse trigonometric and hyperbolic forms, and radicals. No text is taken from any book. Each row is [integrand, antiderivative, difficulty step count, "original"]; test/practice.test.mjs differentiates every antiderivative back to its integrand.',problems:[["6*x^2+4*x","2*x^3+2*x^2",1,"original"],["(2*x+1)^3","(2*x+1)^4/8",1,"original"],["sqrt(3*x+1)","2/9*(3*x+1)^(3/2)",1,"original"],["5*exp(2*x)","5/2*exp(2*x)",1,"original"],["sin(4*x)","-cos(4*x)/4",1,"original"],["1/(3*x+2)","ln(3*x+2)/3",1,"original"],["cos(x/2)","2*sin(x/2)",1,"original"],["x*exp(x^2)","exp(x^2)/2",2,"original"],["x/(x^2+4)","ln(x^2+4)/2",2,"original"],["5*sec(x)^2","5*tan(x)",1,"original"],["1/(1+9*x^2)","atan(3*x)/3",1,"original"],["1/sqrt(1-4*x^2)","asin(2*x)/2",1,"original"],["cosh(2*x)","sinh(2*x)/2",1,"original"],["x^2*sqrt(x^3+1)","2/9*(x^3+1)^(3/2)",2,"original"],["sin(x)*cos(x)^2","-cos(x)^3/3",2,"original"],["exp(x)/(1+exp(x))","ln(1+exp(x))",2,"original"],["1/x^3","-1/(2*x^2)",1,"original"],["1/sqrt(x)","2*sqrt(x)",1,"original"],["sinh(x)*cosh(x)","sinh(x)^2/2",2,"original"],["tan(x)","-ln(cos(x))",2,"original"],["cos(3*x)+sin(2*x)","sin(3*x)/3-cos(2*x)/2",1,"original"],["(x+1)^5","(x+1)^6/6",1,"original"],["exp(-x)","-exp(-x)",1,"original"],["x^3-1/x^2","x^4/4+1/x",1,"original"],["x*exp(x)","x*exp(x)-exp(x)",3,"original"],["x*sin(x)","sin(x)-x*cos(x)",3,"original"],["x*cos(2*x)","x*sin(2*x)/2+cos(2*x)/4",3,"original"],["ln(x)","x*ln(x)-x",3,"original"],["x*ln(x)","x^2*ln(x)/2-x^2/4",3,"original"],["x^2*exp(x)","exp(x)*(x^2-2*x+2)",4,"original"],["atan(x)","x*atan(x)-ln(1+x^2)/2",4,"original"],["asin(x)","x*asin(x)+sqrt(1-x^2)",4,"original"],["sin(x)^3","-cos(x)+cos(x)^3/3",3,"original"],["sin(x)^2*cos(x)^3","sin(x)^3/3-sin(x)^5/5",4,"original"],["tan(x)^2","tan(x)-x",3,"original"],["1/(x^2-1)","ln((x-1)/(x+1))/2",4,"original"],["1/(x^2+2*x+5)","atan((x+1)/2)/2",4,"original"],["1/(x*(x+1))","ln(x/(x+1))",3,"original"],["(x+3)/(x^2-1)","2*ln(x-1)-ln(x+1)",5,"original"],["1/(x^2*(x+1))","-1/x-ln(x)+ln(x+1)",5,"original"],["x^2/(x^2+1)","x-atan(x)",3,"original"],["x^3/(x^2+1)","x^2/2-ln(x^2+1)/2",4,"original"],["sqrt(1-x^2)","x*sqrt(1-x^2)/2+asin(x)/2",4,"original"],["1/sqrt(x^2+1)","ln(x+sqrt(x^2+1))",4,"original"],["x/sqrt(1-x^2)","-sqrt(1-x^2)",3,"original"],["exp(x)*sin(x)","exp(x)*(sin(x)-cos(x))/2",5,"original"],["exp(2*x)*cos(x)","exp(2*x)*(2*cos(x)+sin(x))/5",5,"original"],["sinh(x)^2","sinh(2*x)/4-x/2",3,"original"],["1/(exp(x)+exp(-x))","atan(exp(x))",4,"original"],["cos(x)/(1+sin(x)^2)","atan(sin(x))",3,"original"],["sin(x)/(1+cos(x))","-ln(1+cos(x))",3,"original"],["x*sqrt(x+1)","2/5*(x+1)^(5/2)-2/3*(x+1)^(3/2)",4,"original"],["x/(x+1)^2","ln(x+1)+1/(x+1)",4,"original"],["x*ln(x)^2","x^2*ln(x)^2/2-x^2*ln(x)/2+x^2/4",5,"original"],["sin(3*x)*cos(x)","-cos(4*x)/8-cos(2*x)/4",3,"original"],["1/(1+cos(x))","tan(x/2)",3,"original"],["x^2*sin(x)","-x^2*cos(x)+2*x*sin(x)+2*cos(x)",6,"original"],["x*atan(x)","(x^2+1)*atan(x)/2-x/2",6,"original"],["x^3*exp(x^2)","exp(x^2)*(x^2-1)/2",6,"original"],["x^2*ln(x)","x^3*ln(x)/3-x^3/9",6,"original"],["ln(x)/x^2","-ln(x)/x-1/x",6,"original"],["ln(x^2+1)","x*ln(x^2+1)-2*x+2*atan(x)",7,"original"],["sin(x)^4","3*x/8-sin(2*x)/4+sin(4*x)/32",6,"original"],["tan(x)^3","tan(x)^2/2+ln(cos(x))",6,"original"],["sec(x)^4","tan(x)+tan(x)^3/3",6,"original"],["1/(x^3+x)","ln(x)-ln(x^2+1)/2",7,"original"],["1/(x^4-1)","ln((x-1)/(x+1))/4-atan(x)/2",8,"original"],["(2*x+3)/(x^2+2*x+5)","ln(x^2+2*x+5)+atan((x+1)/2)/2",7,"original"],["1/(x*sqrt(x^2-1))","atan(sqrt(x^2-1))",6,"original"],["sqrt(x^2+1)","x*sqrt(x^2+1)/2+ln(x+sqrt(x^2+1))/2",7,"original"],["x*asin(x)","x^2*asin(x)/2-asin(x)/4+x*sqrt(1-x^2)/4",8,"original"],["cos(sqrt(x))","2*cos(sqrt(x))+2*sqrt(x)*sin(sqrt(x))",7,"original"],["exp(sqrt(x))","2*exp(sqrt(x))*(sqrt(x)-1)",6,"original"],["1/sin(x)","ln(tan(x/2))",6,"original"],["sinh(x)^3","cosh(x)^3/3-cosh(x)",6,"original"],["atan(sqrt(x))","(x+1)*atan(sqrt(x))-sqrt(x)",8,"original"],["ln(x+sqrt(x^2+1))","x*ln(x+sqrt(x^2+1))-sqrt(x^2+1)",7,"original"],["sin(ln(x))","x*(sin(ln(x))-cos(ln(x)))/2",7,"original"],["1/(x^2+1)^2","x/(2*(x^2+1))+atan(x)/2",8,"original"],["x*exp(x)/(x+1)^2","exp(x)/(x+1)",7,"original"],["cos(x)^4","3*x/8+sin(2*x)/4+sin(4*x)/32",6,"original"],["x^2*cos(x)","x^2*sin(x)+2*x*cos(x)-2*sin(x)",6,"original"]]};var ci=Object.freeze(["antiderivative","derivative","equation","determinant"]),es=Object.freeze(["easy","medium","hard"]),li=500,an=Object.freeze({implicitMultiplication:!0}),nl=[.37,1.13,2.71,-.53,1.91,-1.7,.21,-.18],rl={antiderivative:"Antiderivative",derivative:"Derivative",equation:"Equation",determinant:"Determinant"};function sl(e){let t=2166136261;for(let n of e)t=Math.imul(t^n.codePointAt(0),16777619);return t>>>0}function ol(e,t){let n=e+sl(t)>>>0;return()=>{n=n+1831565813>>>0;let r=n;return r=Math.imul(r^r>>>15,r|1),r^=r+Math.imul(r^r>>>7,r|61),((r^r>>>14)>>>0)/4294967296}}var Be=(e,t,n)=>t+Math.floor(e()*(n-t+1)),sr=(e,t)=>t[Math.floor(e()*t.length)];function il(e,t,n){if(!ci.includes(e))throw new Error(`kind is one of ${ci.join(", ")}`);if(!es.includes(t))throw new Error(`difficulty is one of ${es.join(", ")}`);if(!Number.isInteger(n)||n<0||n>=2**32)throw new Error("the problem number is a whole number from 0 to 4294967295")}var al={problems:[...ii.problems,...ai.problems]},cl=e=>e<=2?"easy":e<=5?"medium":"hard",ll=Object.fromEntries(es.map(e=>[e,al.problems.filter(t=>cl(t[2])===e)]));var ul=(e,t,n)=>{let r=Be(e,t,n),s=Be(e,1,6);return r===1?s===1?"x":`${s}*x`:s===1?`x^${r}`:`${s}*x^${r}`},hl=e=>{let t=Be(e,1,3);return`${sr(e,["sin","cos","exp"])}(${t===1?"x":`${t}*x`})`},rr=e=>e()<.5?ul(e,1,4):hl(e);function fl(e,t){if(t!=="hard")return rr(e);let n=sr(e,["simple","simple","product","chain"]);if(n==="product")return`${rr(e)}*${rr(e)}`;if(n==="chain"){let r=Be(e,1,3);return`${sr(e,["sin","cos","exp"])}(${r===1?"x^2":`${r}*x^2`})`}return rr(e)}function ml(e){let t=[];for(let n=e.length-1;n>=0;n--){let r=e[n];if(r===0)continue;let s=Math.abs(r),o=n===0?`${s}`:n===1?s===1?"x":`${s}*x`:s===1?`x^${n}`:`${s}*x^${n}`;t.push(t.length===0?r<0?`-${o}`:o:r<0?`- ${o}`:`+ ${o}`)}return t.join(" ")||"0"}function pl(e){let t=e.map(o=>o.map(BigInt)),n=t.length,r=1n,s=1n;for(let o=0;o<n-1;o++){if(t[o][o]===0n){let i=t.findIndex((a,c)=>c>o&&a[o]!==0n);if(i<0)return 0;[t[o],t[i]]=[t[i],t[o]],r=-r}for(let i=o+1;i<n;i++)for(let a=o+1;a<n;a++)t[i][a]=(t[i][a]*t[o][o]-t[i][o]*t[o][a])/s;s=t[o][o]}return Number(r*t[n-1][n-1])}var Hr=e=>{try{return S.toLatex(S.parse(e,an))}catch{return e}};function ns(e,t,n){il(e,t,n);let r=ol(n,`${e}/${t}`);if(e==="antiderivative"){let[u,h]=sr(r,ll[t]);return{prompt:`Find an antiderivative of ${u} with respect to x.`,latex:`\\int ${Hr(u)}\\,dx`,hint:"Differentiate your answer to see if you get the integrand back. A constant added on does not matter.",integrand:u,answer:h}}if(e==="derivative"){let u=t==="easy"?1:t==="medium"?2:Be(r,2,3),h=Array.from({length:u},(m,p)=>{let d=fl(r,t);return p===0?r()<.15?`-${d}`:d:`${r()<.5?"+":"-"} ${d}`}).join(" "),f=S.differentiate(S.parse(h,an),"x");return{prompt:`Find the derivative of ${h} with respect to x.`,latex:`\\frac{d}{dx}\\left(${Hr(h)}\\right)`,hint:"Sum rule, product rule or chain rule, depending on the terms.",expression:h,derivative:f,answer:S.toString(S.simplify(f))}}if(e==="equation"){let u={easy:1,medium:2,hard:3}[t],h=t==="hard"?4:6,f=new Set;for(;f.size<u;){let x=Be(r,-h,h);x!==0&&f.add(x)}let m=[1];for(let x of f){let g=new Array(m.length+1).fill(0);m.forEach((w,b)=>{g[b]-=w*x,g[b+1]+=w}),m=g}let p=ml(m),d=[...f].sort((x,g)=>x-g);return{prompt:`Solve ${p} = 0 for x. Give every real root, separated by commas.`,latex:`${Hr(p)} = 0`,hint:"Try factoring, or test the whole numbers that divide the last term.",equation:p,roots:d,answer:d.join(", ")}}let s={easy:2,medium:3,hard:4}[t],o={easy:5,medium:4,hard:3}[t],i=Array.from({length:s},()=>Array.from({length:s},()=>Be(r,-o,o))),a=pl(i),c=Math.max(...i.flat().map(u=>String(u).length));return{prompt:`Find the determinant of this matrix:
40
+ ${i.map(u=>u.map(h=>String(h).padStart(c)).join(" ")).join(`
41
+ `)}`,latex:`\\det\\begin{pmatrix}${i.map(u=>u.join(" & ")).join(" \\\\ ")}\\end{pmatrix}`,hint:"Expand along a row, or eliminate to a triangle and multiply the diagonal.",matrix:i,answer:String(a),determinant:a}}function dl(e,t,n){let r=ns(e,t,n);return{kind:e,difficulty:t,seed:n,label:rl[e],prompt:r.prompt,latex:r.latex,hint:r.hint}}function gl(e,t,n){return{answer:ns(e,t,n).answer}}function xl(e){if(typeof e!="string")throw new Error("the answer is text");if(e.length>li)throw new Error(`an answer has at most ${li} characters`);return e.trim()}var ts=e=>({correct:!1,message:`Couldn't parse your answer: ${String(e?.message??e).replace(/^Error:\s*/,"").slice(0,160)}`});function ui(e,t){let n=0,r=0;for(let s of nl)try{let o=S.evaluate(e,{x:s}),i=S.evaluate(t,{x:s});if(!Number.isFinite(o)||!Number.isFinite(i))continue;n++,Math.abs(o-i)<.01*Math.max(1,Math.abs(o))&&r++}catch{}return{comparable:n,matches:r}}function hi({comparable:e,matches:t},n,r){if(!e)return{correct:!1,message:"Couldn't check your answer: every sample point was undefined for this problem."};let s=t===e;return{correct:s,message:s?`Correct! ${n} at ${e} sample point${e===1?"":"s"}.`:`Not quite. ${r} at ${e-t}/${e} sample points.`}}function wl(e,t,n,r){let s=ns(e,t,n),o=xl(r);if(!o)return{correct:!1,message:"Type an answer first."};if(e==="derivative"||e==="antiderivative"){let c;try{c=S.parse(o,an),e==="antiderivative"&&(c=S.differentiate(c,"x"))}catch(u){return ts(u)}let l=e==="derivative"?s.derivative:S.parse(s.integrand,an);return e==="derivative"?hi(ui(l,c),"Your answer matches the derivative","Your answer disagreed with the derivative"):hi(ui(l,c),"The derivative of your answer matches the integrand","The derivative of your answer disagreed with the integrand")}if(e==="equation"){let c;try{let u=o.split(",").map(h=>h.trim()).filter(Boolean);if(!u.length)return{correct:!1,message:"Type at least one root, separated by commas if there are several."};c=u.map(h=>S.evaluate(S.parse(h,an)))}catch(u){return ts(u)}if(c.some(u=>!Number.isFinite(u)))return{correct:!1,message:"One of your roots is not a real number."};if(c.length!==s.roots.length)return{correct:!1,message:`This equation has ${s.roots.length} real root${s.roots.length===1?"":"s"}; you gave ${c.length}.`};let l=[...c].sort((u,h)=>u-h);for(let u=1;u<l.length;u++)if(Math.abs(l[u]-l[u-1])<1e-6)return{correct:!1,message:"You listed the same root more than once."};for(let u of c)if(!S.verifySolution(s.equation,"x",u))return{correct:!1,message:`${Math.round(u*1e6)/1e6} doesn't satisfy the equation.`};return{correct:!0,message:`Correct! All ${c.length} root${c.length===1?"":"s"} check out.`}}let i;try{i=S.evaluate(S.parse(o,an))}catch(c){return ts(c)}if(!Number.isFinite(i))return{correct:!1,message:"Your answer is not a finite number."};let a=Math.abs(i-s.determinant)<1e-6*Math.max(1,Math.abs(s.determinant));return{correct:a,message:a?"Correct!":"Not quite. That is not the determinant of this matrix."}}var or=24,bl=600,fi=60,mi=20,Ht=e=>Array.from(e,t=>Array.from(t)),rs=e=>({re:e.value,im:e.iValue}),yl=e=>Number.isFinite(e)?e:null,pi=e=>Math.hypot(e.re,e.im);function xi(e){let t=Gt(e,"A"),n=ze(t,"A"),r=Ae(t),s;try{s=at.eigen(t.map(l=>l.map(u=>u/r)))}catch(l){return{values:null,vectors:null,largest:null,smallest:null,complex:null,realValues:null,error:`the eigenvalues did not converge: ${l instanceof Error?l.message:l}`}}let o=s.values.map((l,u)=>u).sort((l,u)=>pi(rs(s.values[u]))-pi(rs(s.values[l]))),i=o.map(l=>({re:s.values[l].value*r,im:s.values[l].iValue*r})),a=o.map(l=>Array.from({length:n},(u,h)=>rs(s.vectors[h][l]))),c=i.some(l=>Math.abs(l.im)>1e-9*Math.max(1,Math.abs(l.re)));return{values:i,vectors:a,largest:i[0],smallest:i[n-1],complex:c,realValues:c?null:i.map(l=>l.re),error:null}}var di=e=>String(+e.toPrecision(4));function vl(e){let t=Gt(e,"A");if(t.length>or||t[0].length>or)throw new Error(`a step-by-step reduction takes at most ${or} x ${or}: use linalg_rank or linalg_solve for a bigger matrix`);let n=t.map(f=>[...f]),r=n.length,s=n[0].length,o=1e-10*Ae(n),i=[],a=[],c=0,l=f=>{c++,i.length<bl&&i.push({description:f,matrix:n.map(m=>m.map(p=>Math.abs(p)<o?0:p))})},u=0;for(let f=0;f<s&&u<r;f++){let m=u;for(let d=u+1;d<r;d++)Math.abs(n[d][f])>Math.abs(n[m][f])&&(m=d);if(Math.abs(n[m][f])<=o)continue;m!==u&&([n[m],n[u]]=[n[u],n[m]],l(`Swap row ${m+1} and row ${u+1}`));let p=n[u][f];Math.abs(p-1)>1e-12&&(n[u]=n[u].map(d=>d/p),l(`R${u+1} <- R${u+1} / ${di(p)}`));for(let d=0;d<r;d++){if(d===u)continue;let x=n[d][f];Math.abs(x)<=o||(n[d]=n[d].map((g,w)=>g-x*n[u][w]),l(`R${d+1} <- R${d+1} - (${di(x)}) x R${u+1}`))}a.push(f),u++}let h=n.map(f=>f.map(m=>Math.abs(m)<o?0:m));return{rows:r,columns:s,initial:t,steps:i,stepCount:c,truncated:c>i.length,result:h,rank:a.length,pivots:a,error:null}}var Ge=e=>{try{return{value:e(),error:null}}catch(t){return{value:null,error:t instanceof Error?t.message:String(t)}}};function Ml(e){let t=Gt(e,"A"),n=t.length,r=t[0].length,s=n===r&&t.every((m,p)=>m.every((d,x)=>Math.abs(d-t[x][p])<=1e-9*Ae(t))),o=n===r?Ge(()=>{let m=at.lu(t);return{L:Ht(m.L),U:Ht(m.U),P:Ht(m.P),sign:m.sign}}):{value:null,error:"LU is for a square matrix"},i=Ge(()=>{let m=at.qr(t);return{Q:Ht(m.Q),R:Ht(m.R)}}),a=Ge(()=>{let m=at.svd(t);return{U:Ht(m.U),S:Array.from(m.S),V:Ht(m.V)}}),c=s?Ge(()=>Ht(at.cholesky(t))):{value:null,error:"Cholesky is for a symmetric matrix"},l=at.rank(t),u=Ge(()=>Ht(at.nullSpace(t))),h=Ge(()=>at.conditionNumber(t)),f=s?Ge(()=>{let m=at.eigenSymmetric(t);return{values:Array.from(m.values),vectors:Ht(m.vectors)}}):{value:null,error:null};return{rows:n,columns:r,rank:l,nullity:r-l,nullSpace:u.value,conditionNumber:yl(h.value),lu:o.value,qr:i.value,svd:a.value,cholesky:c.value,eigenSymmetric:f.value,symmetric:s,errors:{lu:o.error,qr:i.error,svd:a.error,cholesky:c.error,nullSpace:u.error},error:null}}var gi=(e,t)=>[e[0]*t[0]-e[1]*t[1],e[0]*t[1]+e[1]*t[0]],ss=(e,t)=>{let n=t[0]*t[0]+t[1]*t[1];return[(e[0]*t[0]+e[1]*t[1])/n,(e[1]*t[0]-e[0]*t[1])/n]};function wi(e,t){let n=[e[0],0],r=[0,0];for(let s=1;s<e.length;s++)r=gi(r,t),r=[r[0]+n[0],r[1]+n[1]],n=gi(n,t),n=[n[0]+e[s],n[1]];return[n,r]}function El(e,t){let[n]=wi(e,t),r=Math.hypot(t[0],t[1]),s=0;for(let o=0;o<e.length;o++)s+=Math.abs(e[o])*r**(e.length-1-o);return s>0&&Number.isFinite(s)?Math.hypot(n[0],n[1])/s:1/0}function $l(e){let t=e.length-1,n=[];for(let o=0;o<=t;o++)e[o]!==0&&n.push([o,Math.log(Math.abs(e[o]))]);let r=[];for(let o of n){for(;r.length>=2;){let[i,a]=r.slice(-2);if((a[1]-i[1])*(o[0]-i[0])<=(o[1]-i[1])*(a[0]-i[0]))r.pop();else break}r.push(o)}let s=[];for(let o=0;o+1<r.length;o++){let[i,a]=r[o],[c,l]=r[o+1],u=c-i,h=Math.exp((a-l)/u);for(let f=0;f<u;f++){let m=2*Math.PI*f/u+2*Math.PI*o/t+.4;s.push([h*Math.cos(m),h*Math.sin(m)])}}return s}function Nl(e){let t=Dt(e,"coefficients");for(;t.length&&t[0]===0;)t=t.slice(1);if(t.length<2)throw new Error("a polynomial needs a nonzero leading coefficient and a degree of at least 1 (such as `1 -3 2` for x^2 - 3x + 2)");if(t.length-1>fi)throw new Error(`a polynomial has at most degree ${fi}`);let n=0;for(;t.length>1&&t[t.length-1]===0;)t=t.slice(0,-1),n++;let r=t.concat(new Array(n).fill(0)),s=(l,u=null)=>({degree:r.length-1,coefficients:r,roots:u,realRoots:null,points:null,maxResidual:null,error:l}),o=t.length-1,i=o>=1?$l(t):[];if(t.some(l=>!Number.isFinite(l)))return s("the coefficients must be finite numbers");for(let l=0;l<500&&o>=1;l++){let u=0;for(let h=0;h<o;h++){let[f,m]=wi(t,i[h]);if(f[0]===0&&f[1]===0)continue;let p=ss(f,m);if(!Number.isFinite(p[0])||!Number.isFinite(p[1])){i[h]=[i[h][0]*(1+.001)+.001,i[h][1]+.001],u=1/0;continue}let d=[0,0];for(let w=0;w<o;w++){if(w===h)continue;let b=[i[h][0]-i[w][0],i[h][1]-i[w][1]];if(b[0]===0&&b[1]===0)continue;let y=ss([1,0],b);d=[d[0]+y[0],d[1]+y[1]]}let x=[1-(p[0]*d[0]-p[1]*d[1]),-(p[0]*d[1]+p[1]*d[0])],g=ss(p,x);!Number.isFinite(g[0])||!Number.isFinite(g[1])||(i[h]=[i[h][0]-g[0],i[h][1]-g[1]],u=Math.max(u,Math.hypot(g[0],g[1])/Math.max(Math.hypot(i[h][0],i[h][1]),1e-300)))}if(u<1e-15)break}let a=i.map(l=>({re:l[0],im:Math.abs(l[1])<=1e-12*Math.abs(l[0])?0:l[1]}));for(let l=0;l<n;l++)a.push({re:0,im:0});a.sort((l,u)=>l.re-u.re||l.im-u.im);let c=0;for(let l of a)l.re===0&&l.im===0&&n||(c=Math.max(c,El(t,[l.re,l.im])));return!a.every(l=>Number.isFinite(l.re)&&Number.isFinite(l.im))||!(c<=1e-8)?{...s(`the roots could not be found reliably (the worst backward error is ${Number.isFinite(c)?c.toExponential(1):"not a number"}): the coefficients span too wide a range or the polynomial is too ill-conditioned (Wilkinson's, for one) for double precision`,a),maxResidual:Number.isFinite(c)?c:null}:{degree:r.length-1,coefficients:r,roots:a,realRoots:a.filter(l=>l.im===0).map(l=>l.re),points:a.map(l=>({x:l.re,y:l.im})),maxResidual:c,error:null}}function Sl(e){let t=Gt(e,"A");ze(t,"A");let n=mr(t);return{size:t.length,order:n.order,permutation:Ht(n.P),permuted:Ht(n.permuted),blocks:n.blocks.map(r=>({component:[...r.component],start:r.start,end:r.end})),blockCount:n.blocks.length,irreducible:n.irreducible,error:null}}function ql(e,t){let n=Gt(e,"A"),r=ze(n,"A"),s=Array.isArray(t)?t.map(String):String(t??"").split(/[\s,;]+/).filter(Boolean);if(s.length&&s.length!==r)throw new Error(`${s.length} labels for ${r} nodes: give one each, or none for 0, 1, 2, ...`);let o=s.length?s:n.map((c,l)=>String(l));if(new Set(o).size!==r)throw new Error("labels must be different from each other");let i=[];n.forEach((c,l)=>c.forEach((u,h)=>u!==0&&i.push(`${o[l]} ${o[h]}${u===1?"":` ${u}`}`)));let a=new Set(i.flatMap(c=>c.split(" ").slice(0,2)));return{vertices:o,edges:[...o.filter(c=>!a.has(c)),...i].join(`
42
+ `),edgeCount:i.length,directed:!0,error:null}}function Il(e){for(let t=0;t<e.length;t++){if(e[t]!=="=")continue;let n=e[t-1],r=e[t+1];if(!(n==="="||n==="!"||n==="<"||n===">"||r==="="))return`(${e.slice(0,t)})-(${e.slice(t+1)})`}return e}function Al(e,t,n){let r=(Array.isArray(e)?e.map(String):String(e??"").split(`
43
+ `)).map(f=>f.trim()).filter(f=>f&&!f.startsWith("#"));if(!r.length)throw new Error("equations is empty: one equation per line, such as 2*x + 3*y = 12");if(r.length>mi)throw new Error(`a system has at most ${mi} equations`);for(let f of r)if(f.length>1e3)throw new Error("an equation has at most 1000 characters");let s=r.map(Il),o;if(typeof t=="string"&&t.trim())o=t.split(/[\s,;]+/).filter(Boolean);else if(Array.isArray(t)&&t.length)o=t.map(String);else{let f=new Set;for(let m of s)try{for(let p of S.freeVariables(m))f.add(p)}catch(p){throw new Error(`can't read "${m.slice(0,60)}": ${p instanceof Error?p.message:p}`)}o=[...f].sort()}for(let f of o)if(!/^[A-Za-z_][A-Za-z0-9_]*$/.test(f))throw new Error(`variable "${f.slice(0,30)}" isn't a name`);if(o.length!==r.length)throw new Error(`${r.length} equation${r.length===1?"":"s"} for ${o.length} unknown${o.length===1?"":"s"} (${o.join(", ")||"none"}): a system needs as many equations as unknowns`);let i=n==null||n===""?void 0:Dt(n,"guess");if(i&&i.length!==o.length)throw new Error(`guess has ${i.length} numbers for ${o.length} unknowns`);let a=(f,m)=>({variables:o,method:m,solution:null,residual:null,equations:r.length,error:f}),c,l="linear";try{c=S.solveSystem(s,o)}catch(f){if(f?.name!=="NonLinearSystemError"&&!/not linear|nonlinear/i.test(String(f?.message)))return a(f instanceof Error?f.message:String(f),"linear");l="newton";try{c=S.solveSystemNumeric(s,o,i)}catch(m){return a(m instanceof Error?m.message:String(m),"newton")}}let u=Object.fromEntries(o.map(f=>[f,c[f]])),h=Math.max(...s.map(f=>Math.abs(S.evaluate(f,u))));return{variables:o,method:l,solution:Object.fromEntries(o.map(f=>[f,c[f]])),residual:h,equations:r.length,error:null}}var ln=1e6,kl=2e5,Ol=5e7,bi=1e5,Tl=2e3,Si=/^[A-Za-z_][A-Za-z0-9_]*$/,is=(e,t="parameters")=>{let n=e;if(n==null||n==="")return{};if(typeof n=="string")try{n=JSON.parse(n)}catch{throw new Error(`${t} is a JSON object such as {"mean": 0, "sd": 1}`)}if(!n||typeof n!="object"||Array.isArray(n))throw new Error(`${t} is an object of names to numbers`);let r={};for(let[s,o]of Object.entries(n))r[s]=$t(o,`${t}.${s}`);return r},Oe=e=>Number.isFinite(e)?+e.toPrecision(12):null,un=e=>Number.isFinite(e)?e:null,os=["normal","binomial","poisson","studentT","chiSquare"],Pl={normal:{mean:0,sd:1},binomial:{n:10,p:.5},poisson:{lambda:4},studentT:{df:5},chiSquare:{df:3}};function jl(e,t){let n={...Pl[e],...t};switch(e){case"normal":if(!(n.sd>0))throw new Error("normal: sd must be above 0");return{dist:vt.normal(n.mean,n.sd),discrete:!1,used:{mean:n.mean,sd:n.sd}};case"binomial":if(!Number.isInteger(n.n)||n.n<0||n.n>ln)throw new Error(`binomial: n is a whole number from 0 to ${ln}`);if(!(n.p>=0&&n.p<=1))throw new Error("binomial: p is a probability from 0 to 1");return{dist:vt.binomial(n.n,n.p),discrete:!0,used:{n:n.n,p:n.p}};case"poisson":if(!(n.lambda>0)||n.lambda>ln)throw new Error(`poisson: lambda is above 0 and at most ${ln}`);return{dist:vt.poisson(n.lambda),discrete:!0,used:{lambda:n.lambda}};case"studentT":if(!(n.df>0))throw new Error("studentT: df (degrees of freedom) must be above 0");return{dist:vt.studentT(n.df),discrete:!1,used:{df:n.df}};case"chiSquare":if(!(n.df>0))throw new Error("chiSquare: df (degrees of freedom) must be above 0");return{dist:vt.chiSquare(n.df),discrete:!1,used:{df:n.df}};default:throw new Error(`distribution is one of ${os.join(", ")}`)}}var Rl=e=>{let t=typeof e=="string"?e.trim():"";if(!os.includes(t))throw new Error(`distribution is one of ${os.join(", ")} (got "${String(e).slice(0,30)}")`);return t},cn=e=>{try{return un(e())}catch{return null}};function Fl(e,t,n,r,s){let o=Rl(e),{dist:i,discrete:a,used:c}=jl(o,is(t)),l=$t(n,"x",0),u=yt(r,"points",101,2,2e3),h=(Array.isArray(s)?s:String(s??"0.025, 0.5, 0.975").split(/[\s,;]+/).filter(Boolean)).map(Number);if(h.length>50)throw new Error("quantiles has at most 50 entries");for(let g of h)if(!(g>0&&g<1))throw new Error("quantiles are probabilities strictly between 0 and 1");let f=a?g=>i.pmf(g):g=>i.pdf(g),m=cn(()=>i.ppf(.001))??l-3,p=cn(()=>i.ppf(.999))??l+3,d=[];if(a){let g=Math.max(0,Math.floor(m)),w=Math.min(Math.ceil(p),g+1999);for(let b=g;b<=w;b++)d.push({x:b,pdf:Oe(f(b)),cdf:Oe(i.cdf(b))})}else for(let g=0;g<u;g++){let w=m+(p-m)*g/(u-1);d.push({x:Oe(w),pdf:Oe(f(w)),cdf:Oe(i.cdf(w))})}let x=a?Math.round(l):l;return{distribution:o,discrete:a,parameters:c,x:l,pdf:Oe(f(x)),cdf:Oe(i.cdf(x)),sf:Oe(i.sf(x)),mean:cn(()=>i.mean()),variance:cn(()=>i.variance()),standardDeviation:cn(()=>i.std()),quantiles:h.map(g=>({p:g,value:cn(()=>i.ppf(g))})),curve:d,error:null}}var yi=["oneSampleT","welchT","chiSquareGoF"],vi=["two-sided","less","greater"],ar=e=>e.reduce((t,n)=>t+n,0)/e.length,Cl=e=>{let t=$t(e,"alpha",.05);if(!(t>0&&t<1))throw new Error("alpha is strictly between 0 and 1");return t},zl=e=>{let t=typeof e=="string"&&e.trim()?e.trim():"two-sided";if(!vi.includes(t))throw new Error(`alternative is one of ${vi.join(", ")}`);return t};function Dl(e,t,n,r,s,o,i){let a=e==="twoSampleT"?"welchT":typeof e=="string"?e.trim():"";if(!yi.includes(a))throw new Error(`test is one of ${yi.join(", ")} (got "${String(e).slice(0,30)}")`);let c=Cl(o),l=zl(i),u=Dt(t,"sample"),h,f=u.length;if(a==="oneSampleT"){if(u.length<2)throw new Error("a one-sample t-test needs at least 2 values");h=ue.tTestOneSample(u,$t(r,"mu0",0),{alternative:l})}else if(a==="welchT"){let g=Dt(n,"sampleB");if(u.length<2||g.length<2)throw new Error("Welch's t-test needs at least 2 values in each sample");h=ue.tTestTwoSample(u,g,{alternative:l}),f=u.length+g.length}else{let g=s==null||s===""?void 0:Dt(s,"expected");if(g&&g.length!==u.length)throw new Error(`observed has ${u.length} categories and expected ${g.length}: they must match`);if(g?.some(w=>w<=0))throw new Error("expected counts must be above 0");if(u.some(w=>w<0))throw new Error("observed counts can't be negative");h=ue.chiSquareGoodnessOfFit(u,g)}let{statistic:m,df:p,pValue:d}=h;if(![m,d].every(Number.isFinite))return{test:a,statistic:null,df:un(p),pValue:null,alpha:c,alternative:l,reject:null,verdict:null,n:f,error:"the test statistic is not a number (the sample has no spread?)"};let x=d<c;return{test:a,statistic:m,df:un(p),pValue:d,alpha:c,alternative:a==="chiSquareGoF"?"greater":l,reject:x,verdict:x?`Reject H0 at alpha = ${c} (p = ${d.toFixed(4)} < ${c})`:`Fail to reject H0 at alpha = ${c} (p = ${d.toFixed(4)} >= ${c})`,n:f,error:null}}function Ll(e,t,n){let r=Dt(e,"sample");if(r.length<2)throw new Error("a confidence interval needs at least 2 values");let s=$t(t,"level",.95);if(!(s>0&&s<1))throw new Error("level is strictly between 0 and 1, such as 0.95");let[o,i]=ue.confidenceIntervalMean(r,s),a=ar(r),c=null;if(n!=null&&n!==""){let l=Dt(n,"sampleB");if(l.length<2)throw new Error("sampleB needs at least 2 values");let[u,h]=ue.confidenceIntervalDifference(r,l,s);c={meanDifference:a-ar(l),lower:u,upper:h}}return{level:s,n:r.length,mean:a,lower:o,upper:i,margin:(i-o)/2,difference:c,error:null}}function Vl(e,t){if(!Number.isInteger(t)||t<1||t%2===0)throw new Error("width is an odd whole number (1, 3, 5, ...)");if(e==="gaussian"){let n=t/6,r=(t-1)/2,s=Array.from({length:t},(i,a)=>Math.exp(-((a-r)**2)/(2*n*n))),o=s.reduce((i,a)=>i+a,0);return s.map(i=>i/o)}if(e!=="moving-average")throw new Error('kernel is "moving-average" or "gaussian"');return new Array(t).fill(1/t)}function Bl(e,t,n,r){let s=Dt(e,"values",r),o=yt(n,"width",5,1,10001),i=Vl(typeof t=="string"&&t.trim()?t.trim():"moving-average",o);if(o>s.length)throw new Error(`width (${o}) can't be more than the number of values (${s.length})`);if(s.length*o>Ol)throw new Error("that many values at that width is over this pane's budget: use fewer values or a narrower kernel");let a=(o-1)/2,c=[],l=[],u=[],h=0;for(let f=a;f<s.length-a;f++){let m=0;for(let d=0;d<o;d++)m+=s[f+d-a]*i[d];let p=s[f]-m;c.push({index:f,raw:s[f],smoothed:m,residual:p}),l.push(m),u.push(p),h+=p*p}return{kernel:typeof t=="string"&&t.trim()?t.trim():"moving-average",weights:i,width:o,trimmed:a,rows:c,smoothed:l,residuals:u,rmsResidual:c.length?Math.sqrt(h/c.length):null,error:null}}var Mi=["linear","huber","soft_l1","cauchy","arctan"],Ei=e=>{let t=[...e].sort((r,s)=>r-s),n=t.length>>1;return t.length%2?t[n]:(t[n-1]+t[n])/2};function Gl(e,t,n,r,s,o,i,a){let c=Dt(e,"x"),l=Dt(t,"y");if(c.length!==l.length)throw new Error(`x has ${c.length} numbers and y has ${l.length}: they must match`);if(c.length>bi)throw new Error(`a fit takes at most ${bi} points (there are ${c.length})`);let u=typeof n=="string"?n.trim():"";if(!u)throw new Error("model is empty: write something like a*x + b or a*exp(b*x)");if(u.length>1e3)throw new Error("model has at most 1000 characters");let h=typeof s=="string"&&s.trim()?s.trim():"linear";if(!Mi.includes(h))throw new Error(`loss is one of ${Mi.join(", ")}`);let f=$t(i,"outlierMads",2.5);if(!(f>0))throw new Error("outlierMads is above 0");let m=yt(a,"curvePoints",100,2,2e3),p=is(r,"initial"),d;try{d=S.freeVariables(u)}catch(I){throw new Error(`model can't be read: ${I instanceof Error?I.message:I}`)}let x=Object.keys(p).filter(I=>!d.includes(I));if(x.length)throw new Error(`initial names ${x.join(", ")}, which the model doesn't use (it uses ${d.filter(I=>I!=="x").join(", ")||"no parameters"})`);let g=[...new Set([...Object.keys(p),...d.filter(I=>I!=="x")])];for(let I of g)if(!Si.test(I)||I==="x")throw new Error(`parameter "${I.slice(0,30)}" isn't a usable name`);if(!g.length)throw new Error("model has no parameters to fit: name them, such as a*x + b");if(g.length>10)throw new Error("a model has at most 10 parameters");if(c.length<g.length)return ir(u,h,`${g.length} parameters need at least ${g.length} points (there are ${c.length})`);let w=S.compile(u,{declaredVariables:["x",...g]}),b=(I,H)=>{let gt={x:I};for(let Nt=0;Nt<g.length;Nt++)gt[g[Nt]]=H[Nt];return w(gt)},y=g.map(I=>I in p?p[I]:1),E=Math.max(...l)-Math.min(...l)||1,N={loss:h,maxNfev:2e3};h!=="linear"&&(N.fScale=o==null||o===""?1.345*E*.1:$t(o,"fScale"));let $;try{$=yn.curveFit(b,c,l,y,N)}catch(I){return ir(u,h,`the fit failed: ${I instanceof Error?I.message:I}`)}let O=$.params;if(!O.every(Number.isFinite))return ir(u,h,"the fit did not converge to finite parameters: try other starting values in `initial`");let L=c.map(I=>b(I,O));if(!L.every(Number.isFinite))return ir(u,h,"the model isn't a number at some of the points with these parameters: try other starting values");let k=l.map((I,H)=>I-L[H]),Y=ar(l),P=0,D=0;for(let I=0;I<l.length;I++)P+=k[I]**2,D+=(l[I]-Y)**2;let G=Ei(k),Z=Ei(k.map(I=>Math.abs(I-G)))*1.4826,pt=[];Z>1e-9*E&&k.forEach((I,H)=>Math.abs(I-G)/Z>f&&pt.push(H));let v=1/0,A=-1/0;for(let I of c)I<v&&(v=I),I>A&&(A=I);let j=[];for(let I=0;I<m;I++){let H=v+(A-v)*I/(m-1),gt=b(H,O);j.push({x:H,fit:Number.isFinite(gt)?gt:null})}let K=new Set(pt);return{model:u,loss:h,parameters:Object.fromEntries(g.map((I,H)=>[I,O[H]])),parameterList:g.map((I,H)=>({name:I,value:O[H],standardError:un($.standardErrors?.[H])})),rSquared:D>0?1-P/D:null,rmse:Math.sqrt(P/c.length),iterations:$.iterations,converged:$.converged,fitted:L,residuals:k,outliers:pt,points:c.map((I,H)=>({x:I,y:l[H],fit:L[H],residual:k[H],outlier:K.has(H)})),curve:j,equation:`y = ${u.replace(/\b[A-Za-z_][A-Za-z0-9_]*\b/g,I=>g.includes(I)?String(+O[g.indexOf(I)].toPrecision(6)):I)}`,error:$.converged?null:"the fit stopped before it converged: the parameters are the last estimate (try other starting values or more points)"}}var ir=(e,t,n)=>({model:e,loss:t,parameters:null,parameterList:null,rSquared:null,rmse:null,iterations:null,converged:!1,fitted:null,residuals:null,outliers:null,points:null,curve:null,equation:null,error:n});var qi=(e,t)=>{if(e.length<=t)return e;let n=(e.length-1)/(t-1);return Array.from({length:t},(r,s)=>e[Math.round(s*n)])};function Ul(e,t,n){let r=yt(e,"n",1e3,1,kl),s=yt(t,"seed",1,0,2**31),o=yt(n,"shown",500,0,Tl),i=Ce.estimatePi(r,nn(s)),a=i.points.reduce((l,u)=>l+(u.inside?1:0),0),c=a/r;return{n:r,seed:s,piEstimate:i.piEstimate,absoluteError:Math.abs(i.piEstimate-Math.PI),standardError:4*Math.sqrt(c*(1-c)/r),inside:a,points:i.points.slice(0,o),convergence:qi(i.convergence,200),error:null}}function Zl(e,t,n,r,s,o){if(typeof e!="string"||!e.trim())throw new Error("expression is empty: write something like sin(x)");if(e.length>2e3)throw new Error("expression has at most 2000 characters");let i=typeof t=="string"&&t.trim()?t.trim():"x";if(!Si.test(i))throw new Error(`variable "${i.slice(0,40)}" isn't a name`);let a=$t(n,"lower"),c=$t(r,"upper");if(!(c>a))throw new Error("upper must be above lower");let l=yt(s,"n",1e4,2,ln),u=yt(o,"seed",1,0,2**31),h;try{h=Ce.integrate(e,a,c,l,nn(u),{variable:i})}catch(m){throw new Error(`can't integrate that: ${m instanceof Error?m.message:m}`)}let f=null;try{f=jr(e,i,a,c).value}catch{}return Number.isFinite(h.estimate)?{n:l,seed:u,estimate:h.estimate,errorBand:h.errorBand,reference:un(f),absoluteError:f===null||!Number.isFinite(f)?null:Math.abs(h.estimate-f),convergence:qi(h.convergence,200),error:null}:{n:l,seed:u,estimate:null,errorBand:null,reference:un(f),absoluteError:null,convergence:[],error:"the expression isn't a number at some of the sample points (a pole or a value outside its domain in the range)"}}var $i=["normal","uniform","exponential","binomial","poisson"];function Ni(e,t,n,r,s,o){if(s<10)throw new Error(`${o} is over this pane's budget (${cr.toLocaleString("en-US")} steps) and too skewed to approximate by a normal curve: use fewer draws or smaller parameters`);let i=vt.normal(e.mean(),Math.sqrt(s),t);return{dist:Object.create(e,{sample:{value:()=>Math.min(r,Math.max(n,Math.round(i.sample())))}}),approximation:`normal approximation (${o} is over the ${cr.toLocaleString("en-US")}-step budget: draws are rounded normal values with the true mean and variance)`}}var cr=2e7;function Ii(e,t,n,r=1){let s=typeof e=="string"?e.trim():"";if(!$i.includes(s))throw new Error(`distribution is one of ${$i.join(", ")} (got "${String(e).slice(0,30)}")`);let o=is(t),i=()=>n.nextFloat();switch(s){case"normal":{let a={mean:0,sd:1,...o};if(!(a.sd>0))throw new Error("normal: sd must be above 0");return{dist:vt.normal(a.mean,a.sd,i),discrete:!1,used:a,approximation:null}}case"uniform":{let a={a:0,b:1,...o};if(!(a.b>a.a))throw new Error("uniform: b must be above a");return{dist:vt.uniform(a.a,a.b,i),discrete:!1,used:a,approximation:null}}case"exponential":{let a={rate:1,...o};if(!(a.rate>0))throw new Error("exponential: rate must be above 0");return{dist:vt.exponential(a.rate,i),discrete:!1,used:a,approximation:null}}case"binomial":{let a={n:10,p:.5,...o};if(!Number.isInteger(a.n)||a.n<0||a.n>1e5)throw new Error("binomial: n is a whole number from 0 to 100000");if(!(a.p>=0&&a.p<=1))throw new Error("binomial: p is a probability from 0 to 1");let c=vt.binomial(a.n,a.p,i);return a.n*r<=cr?{dist:c,discrete:!0,used:a,approximation:null}:{dist:c,discrete:!0,used:a,...Ni(c,i,0,a.n,a.n*a.p*(1-a.p),`binomial n = ${a.n} over ${r} draws`)}}default:{let a={lambda:4,...o};if(!(a.lambda>0)||a.lambda>1e3)throw new Error("poisson: lambda is above 0 and at most 1000");let c=vt.poisson(a.lambda,i);return a.lambda*r<=cr?{dist:c,discrete:!0,used:a,approximation:null}:{dist:c,discrete:!0,used:a,...Ni(c,i,0,1/0,a.lambda,`Poisson lambda = ${a.lambda} over ${r} draws`)}}}}function Ai(e,t){let n=1/0,r=-1/0;for(let i of e)i<n&&(n=i),i>r&&(r=i);let s=(r-n)/t||1,o=new Array(t).fill(0);for(let i of e)o[Math.min(t-1,Math.max(0,Math.floor((i-n)/s)))]++;return o.map((i,a)=>({lower:n+a*s,upper:n+(a+1)*s,center:n+(a+.5)*s,count:i,density:i/e.length/s,label:`${+(n+a*s).toPrecision(5)} to ${+(n+(a+1)*s).toPrecision(5)}`}))}function Xl(e,t,n,r,s){let o=yt(n,"n",1e4,2,ln),i=yt(r,"seed",1,0,2**31),a=yt(s,"bins",20,1,500),{dist:c,discrete:l,used:u,approximation:h}=Ii(e,t,nn(i),o),f=new Array(o);for(let x=0;x<o;x++)f[x]=c.sample();let m=ar(f),p=f.reduce((x,g)=>x+(g-m)**2,0)/o,d=Ai(f,a);return{distribution:e,parameters:u,approximation:h,n:o,seed:i,bins:d,binWidth:d[0].upper-d[0].lower,sampleMean:m,sampleVariance:p,theoreticalMean:c.mean(),theoreticalVariance:c.variance(),curve:d.map(x=>{let g=l?Math.round(x.center):x.center;return{x:x.center,density:l?c.pmf(g):c.pdf(g)}}),error:null}}function Wl(e,t,n,r,s,o){let i=yt(n,"sampleSize",30,1,1e4),a=yt(r,"trials",2e3,2,1e5);if(i*a>5e6)throw new Error("sampleSize x trials is over 5,000,000 draws: use fewer");let c=yt(s,"seed",1,0,2**31),l=yt(o,"bins",25,1,500),{dist:u,used:h,approximation:f}=Ii(e,t,nn(c),i*a),m=Ce.centralLimit(()=>u.sample(),i,a,l),p=u.mean(),d=Math.sqrt(u.variance()/i),x=Ai(m.means,l);return{distribution:e,parameters:h,approximation:f,sampleSize:i,trials:a,seed:c,bins:x,mean:m.mean,standardDeviation:m.standardDeviation,theoreticalMean:p,theoreticalStandardDeviation:d,curve:x.map(g=>({x:g.center,density:Math.exp(-((g.center-p)**2)/(2*d*d))/(d*Math.sqrt(2*Math.PI))})),means:m.means.slice(0,200),error:null}}var Yl=18,Ql=200,ki=30,Oi=64,Ti=5,It=e=>e>=-9007199254740991n&&e<=9007199254740991n?Number(e):e.toString();function lr(e,t,n=Ql){if(typeof e=="bigint")return e;if(typeof e=="number"){if(!Number.isSafeInteger(e))throw new Error(`${t} is a whole number (write a big one as digits in text)`);return BigInt(e)}let r=typeof e=="string"?e.trim():"";if(!/^[+-]?\d+$/.test(r))throw new Error(`${t} is a whole number, such as 360 (got "${String(e).slice(0,30)}")`);if(r.replace(/^[+-]/,"").length>n)throw new Error(`${t} has at most ${n} digits`);return BigInt(r)}var Pi=(e,t,n)=>{let r=Array.isArray(e)?e:String(e??"").split(/[\s,;]+/).filter(Boolean);if(!r.length)throw new Error(`${t} is empty: whole numbers separated by commas or spaces`);if(r.length>ki)throw new Error(`${t} has at most ${ki} numbers`);return r.map((s,o)=>lr(s,`${t} ${o+1}`,n))};function Jl(e,t){let n=lr(e,"a"),r=lr(t,"b"),s=[],o=n<0n?-n:n,i=r<0n?-r:r;for(;i!==0n;){let c=o/i,l=o%i;s.push({a:It(o),b:It(i),q:It(c),r:It(l)}),o=i,i=l}let a=Ft.extendedGcd(n,r);return{a:It(n),b:It(r),gcd:It(o),lcm:It(Ft.lcm(n,r)),steps:s,bezout:{x:It(a.x),y:It(a.y)},coprime:o===1n,error:null}}function _l(e){let t=lr(e,"n",Yl);if(t<2n)throw new Error("n is a whole number from 2 up");let n=Ft.factorize(t);return{n:It(t),factors:n.map(([r,s])=>({prime:It(r),exponent:s})),text:n.map(([r,s])=>s===1?`${r}`:`${r}^${s}`).join(" * "),isPrime:n.length===1&&n[0][1]===1,totient:It(Ft.eulerPhi(t)),divisors:n.reduce((r,[,s])=>r*(s+1),1),error:null}}function Kl(e,t){let n=Pi(e,"remainders"),r=Pi(t,"moduli");if(n.length!==r.length)throw new Error(`${n.length} remainders for ${r.length} moduli: they pair up one to one`);if(r.some(u=>u<2n))throw new Error("every modulus is a whole number from 2 up");let s=n.map((u,h)=>`x = ${Ft.mod(u,r[h])} (mod ${r[h]})`),o=u=>({x:null,modulus:null,congruences:s,steps:null,check:null,error:u}),i=Ft.crt(n,r);if(i===null)return o("no solution: the moduli aren't pairwise coprime, or two congruences contradict each other");let a=r.reduce((u,h)=>u*h,1n),c=r.map((u,h)=>{let f=a/u,m=Ft.modInverse(f,u);return{remainder:It(Ft.mod(n[h],u)),modulus:It(u),partial:It(f),inverse:m===null?null:It(m),term:m===null?null:It(Ft.mod(n[h]*f*m,a))}}),l=r.every((u,h)=>i.x%u===Ft.mod(n[h],u));return{x:It(i.x),modulus:It(i.modulus),congruences:s,steps:c,check:l,error:null}}var ji=["cyclic","multiplication","units","symmetric","custom"];function as(e,t,n,r){let s=t.length,o=new Map(t.map((m,p)=>[r(m),p])),i=t.map(m=>t.map(p=>o.get(r(n(m,p)))??-1)),a=i.every(m=>m.every(p=>p>=0)),c=null;if(a)for(let m=0;m<s&&c===null;m++)i[m].every((p,d)=>p===d)&&i.every((p,d)=>p[m]===d)&&(c=m);let l=a;for(let m=0;m<s&&l;m++)for(let p=0;p<s&&l;p++)for(let d=0;d<s;d++)if(i[i[m][p]][d]!==i[m][i[p][d]]){l=!1;break}let u=c!==null&&i.every(m=>m.includes(c))&&i.every((m,p)=>m.some((d,x)=>d===c&&i[x][p]===c)),h=a&&l&&c!==null&&u,f=a&&i.every((m,p)=>m.every((d,x)=>d===i[x][p]));return{labels:e,table:i,closed:a,associative:l,identity:c===null?null:e[c],identityIndex:c,inverses:u,isGroup:h,isAbelian:h&&f,commutative:f,orders:t.map((m,p)=>({element:e[p],order:c===null||!a?null:Hl(p,i,c,s)}))}}function Hl(e,t,n,r){let s=e;for(let o=1;o<=r;o++){if(s===n)return o;s=t[s][e]}return null}function tu(e,t){let n=(Array.isArray(e)?e.map(a=>Array.isArray(a)?a.join(" "):String(a)):String(e??"").split(`
44
+ `)).map(a=>a.trim()).filter(a=>a&&!a.startsWith("#")).map(a=>a.split(/[\s,;]+/).filter(Boolean));if(!n.length)throw new Error("table is empty: one row per line, the product of each element with every element");let r=n.length;if(r>32)throw new Error("a custom table has at most 32 elements");let s=Array.isArray(t)?t.map(String):String(t??"").split(/[\s,;]+/).filter(Boolean),o=s.length?s:Array.from({length:r},(a,c)=>String(c));if(o.length!==r)throw new Error(`${o.length} element names for ${r} rows: they must match`);if(new Set(o).size!==r)throw new Error("element names must be different from each other");n.forEach((a,c)=>{if(a.length!==r)throw new Error(`row ${c+1} has ${a.length} entries and there are ${r} elements: the table is square`)});let i=new Map(o.map((a,c)=>[a,c]));return{names:o,grid:n.map((a,c)=>a.map((l,u)=>i.has(l)?i.get(l):-1-(c*r+u))),rows:n,n:r}}function eu(e,t,n,r){let s=typeof e=="string"?e.trim():"";if(!ji.includes(s))throw new Error(`kind is one of ${ji.join(", ")} (got "${String(e).slice(0,30)}")`);if(s==="custom"){let l=tu(n,r),u=Array.from({length:l.n},(f,m)=>m);if(l.grid.some(f=>f.some(m=>m<0))){let f=l.grid.flatMap((m,p)=>m.map((d,x)=>[d,p,x])).find(([m])=>m<0);return{kind:s,n:l.n,size:l.n,labels:l.names,table:l.grid.map(m=>m.map(p=>p<0?-1:p)),closed:!1,associative:!1,identity:null,identityIndex:null,inverses:!1,isGroup:!1,isAbelian:!1,commutative:!1,orders:l.names.map(m=>({element:m,order:null})),error:`row ${f[1]+1}, column ${f[2]+1} is "${l.rows[f[1]][f[2]].slice(0,20)}", which isn't one of the elements (${l.names.slice(0,12).join(", ")})`}}return{kind:s,n:l.n,size:l.n,...as(l.names,u,(f,m)=>l.grid[f][m],String),error:null}}let o=Number(t);if(!Number.isInteger(o)||o<1)throw new Error("n is a whole number from 1 up");if(s==="symmetric"){if(o>Ti)throw new Error(`S_n is limited to n = ${Ti} here (n! elements)`);let l=pn.symmetricGroup(o);return{kind:s,n:o,size:l.length,...as(l.map(u=>u.toString()),l,(u,h)=>te.compose(u,h),u=>u.toString()),error:null}}if(o>Oi)throw new Error(`Z/n is limited to n = ${Oi}`);let i=(l,u)=>u===0?l:i(u,l%u),a=Array.from({length:o},(l,u)=>u),c=(l,u)=>(l+u)%o;return(s==="multiplication"||s==="units")&&(c=(l,u)=>l*u%o),s==="units"&&(a=a.filter(l=>i(l,o)===1)),{kind:s,n:o,size:a.length,...as(a.map(String),a,c,String),error:null}}var Ri=2e3,Fi=2e3;function hn(e,t="expression"){if(typeof e!="string"||!e.trim())throw new Error(`${t} is empty: write something like x^2 + 3*x`);if(e.length>Ri)throw new Error(`${t} has at most ${Ri} characters`);return e}var cs=e=>{let t=typeof e=="string"&&e.trim()?e.trim():"x";if(!/^[A-Za-z_][A-Za-z0-9_]*$/.test(t))throw new Error(`variable "${t.slice(0,40)}" isn't a name: use letters, digits and _`);return t},An=e=>({text:S.toString(e),latex:S.toLatex(e)});function nu(e){let t=e.split("=");if(t.length===1)return e;if(t.length===2)return`(${t[0]}) - (${t[1]})`;throw new Error("an equation has at most one '='")}var Ci=(e,t)=>{if(e==null||e==="")return;let n=typeof e=="number"?e:Number(String(e).trim());if(!Number.isFinite(n))throw new Error(`${t} must be a number`);return n};function df(e){let t=S.parse(hn(e));return{...An(t),freeVariables:S.freeVariables(t)}}function gf(e){return An(S.simplify(hn(e)))}function xf(e,t){return An(S.differentiate(hn(e),cs(t)))}function wf(e,t,n,r){let s=hn(e),o=cs(t),i=Ci(n,"lower"),a=Ci(r,"upper");if(i===void 0!=(a===void 0))throw new Error("give both lower and upper for a definite integral, or neither");return i!==void 0?{value:S.integrateDefinite(s,i,a,o)}:An(S.integrate(s,o))}function bf(e,t){return{solutions:S.solve(nu(hn(e)),cs(t)).map(An)}}function yf(e,t={}){if(!t||typeof t!="object"||Array.isArray(t))throw new Error("variables is an object of names to numbers, like { x: 3 }");let n={};for(let[r,s]of Object.entries(t)){if(typeof s!="number"||!Number.isFinite(s))throw new Error(`variable ${r} must be a finite number`);n[r]=s}return S.evaluate(hn(e),n)}function ye(e,t){if(typeof e!="string")throw new Error("the edge list is text: one `from to [weight]` per line");let n=e.split(`
45
+ `).map(s=>s.trim()).filter(s=>s&&!s.startsWith("#"));if(!n.length)throw new Error("the edge list is empty: one `from to [weight]` edge (or a lone vertex name) per line");if(n.length>Fi)throw new Error(`an edge list has at most ${Fi} lines`);let r=new Pe(t===void 0?!0:!!t);for(let s of n){let o=s.split(/\s+/);if(o.length===1){r.addVertex(o[0]);continue}if(o.length>3)throw new Error(`bad edge line "${s.slice(0,60)}": expected \`from to [weight]\``);let i=o.length===3?Number(o[2]):1;if(!Number.isFinite(i))throw new Error(`bad weight in edge line "${s.slice(0,60)}"`);r.addEdge(o[0],o[1],i)}return r}function Ue(e,t){let n=String(t??"");if(!e.vertices().includes(n))throw new Error(`start vertex "${n.slice(0,40)}" isn't in the graph (vertices: ${e.vertices().slice(0,20).join(", ")})`);return n}function vf(e,t){let n=ye(e,t),r=n.toAdjacencyMatrix(),s=null;try{s=n.topologicalSort()}catch{}return{vertices:n.vertices(),hasCycle:n.hasCycle(),connectedComponents:n.connectedComponents(),stronglyConnectedComponents:n.stronglyConnectedComponents(),componentOf:Object.fromEntries(n.stronglyConnectedComponents().flatMap((o,i)=>o.map(a=>[a,i]))),topologicalOrder:s??null,adjacencyMatrix:{order:r.order,matrix:r.matrix.map(o=>o.map(i=>Number.isFinite(i)?i:null))}}}function Mf(e,t,n){let r=ye(e,t);return r.bfs(Ue(r,n))}function Ef(e,t,n){let r=ye(e,t);return r.dfs(Ue(r,n))}function $f(e,t,n){let r=ye(e,t);return[...r.dijkstra(Ue(r,n)).entries()].map(([s,o])=>({vertex:s,distance:Number.isFinite(o)?o:null}))}function Nf(e,t){let n=ye(e,t),r=n.stronglyConnectedComponents(),s=Object.fromEntries(r.flatMap((o,i)=>o.map(a=>[a,i])));return{vertices:n.vertices(),components:r,componentOf:s,count:r.length}}function ru(e,t,n,r){let s=ye(e,t),o=Ue(s,n),i=String(r??"");if(!s.vertices().includes(i))throw new Error(`end vertex "${i.slice(0,40)}" isn't in the graph (vertices: ${s.vertices().slice(0,20).join(", ")})`);let a=null;try{a=s.shortestPath(o,i)}catch{}return!a||!Number.isFinite(a.distance)||!a.path?.length?{start:o,end:i,reachable:!1,distance:null,path:null,edges:[]}:{start:o,end:i,reachable:!0,distance:a.distance,path:a.path,edges:a.path.slice(0,-1).map((c,l)=>({from:c,to:a.path[l+1]}))}}function su(e,t){let n=ye(e,!1),r=t==="prim"?"prim":"kruskal",s=n.mst(r);return{algorithm:r,edges:s.edges.map(o=>({from:o.from,to:o.to,weight:o.weight})),totalWeight:s.totalWeight,components:s.components,isTree:s.components===1,vertices:n.vertices()}}function Sf(e){let n=ye(e,!0).condensation(),r=new Set,s=[];for(let a of n.graph.edges()){let c=`${a.from}>${a.to}`;a.from===a.to||r.has(c)||(r.add(c),s.push({from:a.from,to:a.to}))}let o=null;try{o=n.graph.topologicalSort()}catch{}let i=Object.fromEntries(n.componentOf);return{components:n.components,componentOf:i,edges:s,topologicalOrder:o,labels:n.components.map(a=>a.join(", ")),isDag:o!==null}}function qf(e,t,n,r,s){let o=ye(e,t),i=String(n??""),a=(c,l)=>c.map((u,h)=>({visitedVertices:c.slice(0,h+1).map(f=>f.vertex),visitedEdges:[],label:l(u)}));if(i==="bfs"){let c=Ue(o,r),l=o.bfs(c),u=new Map([[c,0]]),h=[c];for(let p=0;p<h.length;p++)for(let d of o.neighbors(h[p]))u.has(d)||(u.set(d,u.get(h[p])+1),h.push(d));let f=[];for(let p of l)(f[u.get(p)]??=[]).push(p);let m=[];return{algorithm:i,steps:f.map((p,d)=>(m.push(...p),{visitedVertices:[...m],visitedEdges:[],label:`Layer ${d}: ${p.join(", ")}`}))}}if(i==="dfs")return{algorithm:i,steps:a(o.dfs(Ue(o,r)).map(c=>({vertex:c})),c=>`Visit ${c.vertex}`)};if(i==="dijkstra"){let c=[...o.dijkstra(Ue(o,r)).entries()].filter(([,l])=>Number.isFinite(l)).sort((l,u)=>l[1]-u[1]).map(([l,u])=>({vertex:l,distance:u}));return{algorithm:i,steps:a(c,l=>`Finalize ${l.vertex}: distance = ${l.distance}`)}}if(i==="mst"){let c=su(e,"kruskal").edges;return{algorithm:i,steps:c.map((l,u)=>({visitedVertices:[],visitedEdges:c.slice(0,u+1).map(h=>({from:h.from,to:h.to})),label:`Add ${l.from}-${l.to} (weight ${l.weight})`}))}}if(i==="path"){let c=ru(e,t,r,s);return{algorithm:i,steps:c.edges.map((l,u)=>({visitedVertices:[],visitedEdges:c.edges.slice(0,u+1),label:`${l.from} -> ${l.to}`}))}}throw new Error("algorithm is one of bfs, dfs, dijkstra, mst, path")}var kf=(e,t)=>t?xi(e):Po(e);export{Fi as MAX_EDGE_LINES,Ri as MAX_EXPRESSION,jr as calcIntegral,pc as calcOde,cc as calcTaylor,xf as differentiate,eu as discreteCayley,Kl as discreteCrt,_l as discreteFactor,Jl as discreteGcd,Al as equationsSolve,yf as evaluate,vf as graphAnalyze,Mf as graphBfs,Nf as graphComponents,Sf as graphCondensation,Ef as graphDfs,$f as graphDijkstra,su as graphMst,ru as graphShortestPath,qf as graphSteps,wf as integrate,Ml as linalgDecompose,xc as linalgDeterminant,kf as linalgEigen,Sl as linalgFrobenius,bc as linalgInverse,ql as linalgMatrixDigraph,dc as linalgMultiply,Nl as linalgPolynomialRoots,wc as linalgRank,vl as linalgRrefSteps,yc as linalgSolve,gc as linalgTranspose,Wl as monteCarloClt,Zl as monteCarloIntegrate,Ul as monteCarloPi,Xl as monteCarloSample,df as parse,wl as practiceCheck,dl as practiceProblem,gl as practiceReveal,Kc as runCalc,gf as simplify,bf as solve,Ll as statsConfidenceInterval,Ec as statsDescribe,Fl as statsDistribution,Sc as statsHistogram,Dl as statsHypothesisTest,Nc as statsRegression,Gl as statsRegressionFit,Bl as statsSmooth};