@mathzetta/inlinemath 0.1.0 → 0.3.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.
- package/README.md +98 -50
- package/dist/cas.external.js +2 -2
- package/dist/cas.js +2 -2
- package/dist/chunks/calculate-BGMEvf3f.js +2 -0
- package/dist/chunks/draw-q86mDDWm.js +2 -0
- package/dist/chunks/edit-CTMRUElt.js +2 -0
- package/dist/chunks/edit-D2RO7fg0.js +2 -0
- package/dist/chunks/html-1wCO6EpZ.js +2 -0
- package/dist/chunks/html-D5QiXGXD.js +2 -0
- package/dist/chunks/lite-Bo8THzyq.js +2 -0
- package/dist/fonts/README-inlinemath-greek.txt +15 -0
- package/dist/fonts/fonts.css +19 -1
- package/dist/fonts/inlinemath-greek-italic.woff2 +0 -0
- package/dist/fonts/inlinemath-greek-regular.woff2 +0 -0
- package/dist/inlinemath-cas.external.global.min.js +2 -2
- package/dist/inlinemath-cas.global.min.js +2 -2
- package/dist/inlinemath-lite-calc.global.min.js +2 -2
- package/dist/inlinemath-lite.external.global.min.js +2 -2
- package/dist/inlinemath-lite.global.min.js +2 -2
- package/dist/inlinemath.css +48 -7
- package/dist/inlinemath.external.global.min.js +2 -2
- package/dist/inlinemath.external.js +2 -2
- package/dist/inlinemath.global.min.js +2 -2
- package/dist/inlinemath.js +2 -2
- package/dist/lite-calc.js +2 -2
- package/dist/lite.external.js +2 -2
- package/dist/lite.js +2 -2
- package/dist/markdown.external.js +2 -2
- package/dist/markdown.js +2 -2
- package/fonts/README-inlinemath-greek.txt +15 -0
- package/fonts/fonts.css +19 -1
- package/fonts/inlinemath-greek-italic.woff2 +0 -0
- package/fonts/inlinemath-greek-regular.woff2 +0 -0
- package/inlinemath.css +48 -7
- package/package.json +6 -6
- package/src/cas.d.ts +1 -1
- package/src/cas.js +38 -17
- package/src/draw.js +13 -9
- package/src/edit.js +103 -0
- package/src/glyphs.js +2 -0
- package/src/html.js +1 -1
- package/src/index.d.ts +2 -2
- package/src/index.js +2 -2
- package/src/layout.js +142 -41
- package/src/lite.js +1 -1
- package/src/markdown.d.ts +3 -3
- package/src/markdown.js +476 -79
- package/src/mathzetta.js +3 -2
- package/src/select.js +7 -0
- package/src/types.d.ts +86 -13
- package/src/variables.js +262 -0
- package/src/view.js +286 -15
- package/dist/chunks/calculate-BX9lJ7Ff.js +0 -2
- package/dist/chunks/draw-Cm4exbg7.js +0 -2
- package/dist/chunks/html-CvuSyhzk.js +0 -2
- package/dist/chunks/html-DWtfytjA.js +0 -2
- package/dist/chunks/lite-Bj_L6w2g.js +0 -2
|
@@ -1,2 +1,2 @@
|
|
|
1
|
-
/* Inline Math 0.
|
|
2
|
-
var InlineMath=function(e,n,t,r,i){"use strict";const s={"(":{fill:"M0.92,0 C0.1,0.2 0.1,0.8 0.92,1 L1,0.975 C0.48,0.75 0.48,0.25 1,0.025 Z"},")":{fill:"M0.08,0 C0.9,0.2 0.9,0.8 0.08,1 L0,0.975 C0.52,0.75 0.52,0.25 0,0.025 Z"},"{":{fill:"M1,0 C0.45,0 0.5,0.05 0.5,0.2 L0.5,0.38 C0.5,0.46 0.35,0.49 0.05,0.5 C0.35,0.51 0.5,0.54 0.5,0.62 L0.5,0.8 C0.5,0.95 0.45,1 1,1 L1,0.985 C0.68,0.985 0.64,0.95 0.64,0.8 L0.64,0.62 C0.64,0.53 0.55,0.505 0.3,0.5 C0.55,0.495 0.64,0.47 0.64,0.38 L0.64,0.2 C0.64,0.05 0.68,0.015 1,0.015 Z"},"}":{fill:"M0,0 C0.55,0 0.5,0.05 0.5,0.2 L0.5,0.38 C0.5,0.46 0.65,0.49 0.95,0.5 C0.65,0.51 0.5,0.54 0.5,0.62 L0.5,0.8 C0.5,0.95 0.55,1 0,1 L0,0.985 C0.32,0.985 0.36,0.95 0.36,0.8 L0.36,0.62 C0.36,0.53 0.45,0.505 0.7,0.5 C0.45,0.495 0.36,0.47 0.36,0.38 L0.36,0.2 C0.36,0.05 0.32,0.015 0,0.015 Z"},sqrt:{stroke:"M0,0.62 L0.18,0.55 L0.45,0.97 L0.98,0.015"},int:{stroke:"M0.95,0.09 C0.9,0.01 0.72,0 0.66,0.12 C0.6,0.25 0.42,0.75 0.34,0.88 C0.28,0.99 0.1,0.99 0.05,0.91"},sum:{fill:"M0.04,0 L0.94,0 L0.98,0.24 L0.94,0.24 C0.9,0.1 0.8,0.07 0.62,0.07 L0.24,0.07 L0.58,0.5 L0.2,0.93 L0.64,0.93 C0.82,0.93 0.92,0.9 0.95,0.76 L0.99,0.76 L0.94,1 L0.02,1 L0.47,0.47 Z"},prod:{fill:"M0,0 L1,0 L1,0.04 L0.88,0.05 L0.88,0.95 L1,0.96 L1,1 L0.62,1 L0.62,0.96 L0.74,0.95 L0.74,0.06 L0.26,0.06 L0.26,0.95 L0.38,0.96 L0.38,1 L0,1 L0,0.96 L0.12,0.95 L0.12,0.05 L0,0.04 Z"}};function o(e,n,t=""){const r=s[e];return`<svg class="${n}" viewBox="0 0 1 1" preserveAspectRatio="none" aria-hidden="true"${t?` style="${t}"`:""}>${r.fill?`<path d="${r.fill}" fill="currentColor"/>`:`<path d="${r.stroke}" fill="none" stroke="currentColor" vector-effect="non-scaling-stroke"/>`}</svg>`}const a=.8,l=.2,u=.25,c=.7,p="−",f={"+":"add","-":"sub","*":"mul","/":"frac","^":"pow",_:"subscript",neg:"neg",pm:"pm","!":"factorial","=":"eq","===":"eq","≠":"neq","≠=":"neq","<":"lt",">":"gt","≤":"le","≥":"ge","≈":"approx","≡":"equiv","∈":"in","∉":"notin","∪":"union","∩":"intersect","→":"to","±":"pm","&":"and","|":"or","\\not":"not","\\xor":"xor","\\nand":"nand","\\nor":"nor","?:":"cases","()":"tuple","[]":"list","{}":"set","(]":"interval","[)":"interval","\\sumidx":"sum","\\prodidx":"prod",mod:"mod",pmod:"pmod"},h={"=":"=","===":"=","≠":"≠","≠=":"≠","<":"<",">":">","≤":"≤","≥":"≥","∈":"∈","∉":"∉","→":"→","≈":"≈","≡":"≡","&":"∧","|":"∨","\\xor":"⊕","\\nand":"↑","\\nor":"↓"},d={"±":"±","∪":"∪","∩":"∩",mod:"mod"},m=["sin","cos","tan","csc","sec","cot","sinh","cosh","tanh"],g={arcsin:"sin",arccos:"cos",arctan:"tan",arcsinh:"sinh",arccosh:"cosh",arctanh:"tanh"},v=[...m,...Object.keys(g),"ln"],b={atan2:"atan2",max:"max",min:"min",gcd:"gcd",mean:"mean",round:"round",fixed:"fixed",expm1:"expm1",random:"random"},y={"()":["(",")"],"[]":["[","]"],"{}":["{","}"],"(]":["(","]"],"[)":["[",")"]},w={"\\partial":"∂","\\nabla":"∇","\\ell":"ℓ","\\infty":"∞","\\emptyset":"∅"},x={vec:"→",hat:"ˆ",widehat:"ˆ",tilde:"˜",dot:"˙",ddot:"¨"},k=["boxed","overline","bar","underline","cancel",...Object.keys(x)],q={prefix:"mv",display:!0,fnParens:"auto",trigPowers:!0,inverseTrig:"arc",derivativeBrackets:"[",scriptFractions:"slash",cases:!0,label:!0,attributes:null,style:null},$=e=>String(e).replace(/&/g,"&").replace(/</g,"<").replace(/>/g,">").replace(/"/g,"""),S=e=>+e.toFixed(3)+"em",M=(e,n=a,t=l)=>({html:e,h:n,d:t});function O(...e){const n=e.flat().filter(Boolean);return{html:n.map(e=>e.html).join(""),h:Math.max(a,...n.map(e=>e.h)),d:Math.max(l,...n.map(e=>e.d))}}function A(e,n={}){const t=new N({...q,...n}),i=t.render(e,{level:0}),s=`${t.p}${t.o.display?` ${t.p}-display`:""}`,o=function(e,n){if(!1===n||null===n)return null;if("string"==typeof n)return n;try{return"function"==typeof n?n(e):r.toSpeech(e)}catch{return null}}(e,t.o.label),a=null===o?i.html:i.html.replace(/^<span /,'<span aria-hidden="true" ');return{html:`<span class="${s}"${null===o?"":` role="math" aria-label="${$(o)}"`}>${a}</span>`,h:i.h,d:i.d}}class N{constructor(e){this.o=e,this.p=e.prefix}el(e,n,t="",r=""){return`<span class="${e.split(" ").map(e=>`${this.p}-${e}`).join(" ")}"${t?` style="${t}"`:""}${r}>${n}</span>`}text(e,n){const t=M(this.el(e,$(n)));return t.leaf={kind:e,content:$(n)},t}bin(e){return this.text("bin",e)}rel(e){return this.text("rel",e)}punct(e){return this.text("punct",e)}word(e){return this.text("word",e)}wrap(e,n,t){let r="";void 0!==e.id&&(r+=` data-node="${e.id}"`),"op"===e.type&&(r+=` data-op="${$(e.op)}"`);const i=this.o.attributes&&this.o.attributes(e)||{};for(const[e,n]of Object.entries(i))"class"!==e&&"style"!==e&&(r+=` ${e}="${$(n)}"`);const s=[i.style,this.o.style&&this.o.style(e)].filter(Boolean).join(";"),o=(t.leaf?["n",...n,t.leaf.kind]:["n",...n]).map(e=>`${this.p}-${e}`).concat(i.class?[i.class]:[]).join(" "),a=t.leaf?t.leaf.content:t.html;return{html:`<span class="${o}"${s?` style="${$(s)}"`:""}${r}>${a}</span>`,h:t.h,d:t.d}}render(e,n){return"number"===e.type?this.number(e):"string"===e.type?this.wrap(e,["text"],this.text("text",e.value.replace(/^["'`]|["'`]$/g,""))):"symbol"===e.type?this.wrap(e,["symbol"],this.symbol(e.value)):this.operation(e,n)}number(e){return this.wrap(e,["number"],this.text("num",e.value.replace(/^-/,p)))}symbol(e){return t.GREEK[e]&&(e=t.GREEK[e]),w[e]?this.text("ord",w[e]):"\\+"===e||"\\-"===e?this.text("ord",e[1]):"-∞"===e?this.text("ord","−∞"):/^[A-Za-z]$/.test(e)||/^[α-ω]$/.test(e)?this.text("var",e):/^[A-Za-z]′+$/.test(e)?M(this.el("var",$(e[0]))+this.el("prime",$(e.slice(1)))):/^Δ[A-Za-z]$/.test(e)?M(this.el("ord","Δ")+this.el("var",e[1])):e.endsWith("⁻¹")?this.script(this.symbol(e.slice(0,-2)),this.text("num","−1"),{level:0}):/^\\[A-Za-z]+$/.test(e)?this.text("name",e.slice(1)):/^[A-Za-z]{2,}$/.test(e)?this.text("name",e):this.text("ord",e)}operation(e,n){const{op:r,args:i}=e,[s,o]=i,a=(e,t={})=>this.render(e,{...n,...t,forceParens:t.forceParens||!1,before:t.before||!1}),l=f[r]??(/^[a-z0-9]+$/i.test(r)?r:"other"),u=n=>this.wrap(e,["op",`op-${l}`],n),c=(n,r)=>t.needsBrackets(e,n,r)&&"/"!==n.op?this.fence(a(n)):a(n);if(v.includes(r)||"log"===r)return u(this.named(e,n));if(b[r])return u(O(this.word(b[r]),this.fence(this.list(i,n))));if(t.isCustomFunction(r))return u(this.custom(e,n));if(y[r])return u(this.fence(this.list(i,n),...y[r]));if(h[r]&&2===i.length)return u(O(c(s,"left"),this.rel(h[r]),c(o,"right")));if(d[r]&&2===i.length)return u(O(c(s,"left"),this.bin(d[r]),c(o,"right")));switch(r){case"+":return t.isMinusOneTimes(o)?u(O(c(s,"left"),this.bin(p),this.wrap(o,["op","op-mul"],this.render(o.args[1],n)))):"number"===o.type&&o.value.startsWith("-")?u(O(c(s,"left"),this.bin(p),this.wrap(o,["number"],this.text("num",o.value.slice(1))))):u(O(c(s,"left"),this.bin("+"),this.signed(o,c(o,"right"))));case"-":return u(O(c(s,"left"),this.bin(p),this.signed(o,c(o,"right"))));case"*":return u(this.product(e,n));case"/":return u(this.fraction(e,n));case"^":return u(this.power(e,n));case"_":return u(this.script(a(s,{forceParens:!0}),null,n,a(o,{level:n.level+1})));case"neg":return u(O(this.text("sign",p),t.unaryNeedsBrackets(r,s)?this.fence(a(s)):a(s,{before:n.before})));case"pm":return u(O(this.text("sign","±"),t.unaryNeedsBrackets(r,s)?this.fence(a(s)):a(s)));case"!":return u(O(t.unaryNeedsBrackets(r,s)?this.fence(a(s)):a(s,{forceParens:!0}),this.text("ord","!")));case"\\not":return u(O(this.text("sign","¬"),t.unaryNeedsBrackets(r,s)?this.fence(a(s)):a(s)));case"pmod":return u(O(a(s),this.fence(O(this.word("mod"),this.text("space",""),a(o)))));case"sqrt":return u(this.radical(a(s)));case"root":return u(this.radical(a(o),this.render(s,{level:n.level+2})));case"abs":return u(this.fence(a(s),"|","|"));case"floor":return u(this.fence(a(s),"⌊","⌋"));case"ceil":return u(this.fence(a(s),"⌈","⌉"));case"loglog":return u(O(this.word("ln"),this.fence(O(this.word("ln"),this.fence(a(s))))));case"logloglog":return u(O(this.word("ln"),this.fence(O(this.word("ln"),this.fence(O(this.word("ln"),this.fence(a(s))))))));case"perm":return u(this.script(this.script(M(""),this.render(s,{level:n.level+1}),n),null,n,this.render(o,{level:n.level+1}),this.word("P")));case"comb":return u(this.fence(this.stack(a(s),a(o),!1)));case"?:":return u(this.o.cases?this.cases(e,n):O(a(s),this.bin("?"),a(o),this.bin(":"),a(i[2])));case"sum":return u(O(i.map((e,n)=>n?[this.bin("+"),a(e)]:[a(e)]).flat()));case"prod":return u(O(i.map((e,n)=>n?[this.bin("·"),a(e)]:[a(e)]).flat()));case"der":return u(this.derivative(e,n));case"int":return u(this.integral(i,n));case"lim":return u(this.limit(i,n));case"\\sumidx":return u(this.bigOperator("sum",i,n));case"\\prodidx":return u(this.bigOperator("prod",i,n))}throw new Error(`Inline Math cannot draw '${r}'`)}signed(e,n){return("number"===e.type?e.value.startsWith("-"):"neg"===e.op||"pm"===e.op)&&!n.fenced?this.fence(n):n}list(e,n){return O(e.map((e,t)=>t?[this.punct(","),this.render(e,n)]:[this.render(e,n)]).flat())}product(e,n){const[r,i]=e.args;if(t.isMinusOneTimes(e))return O(this.text("sign",p),this.render(i,n));const s=t.bracketedSides(e),o=t.isImplicitProduct(r,i,s),a=function(e){for(;"op"===e.type;){if(v.includes(e.op)||"log"===e.op||b[e.op]||t.isCustomFunction(e.op))return!0;if("^"!==e.op&&"*"!==e.op)return!1;e=e.args[0]}return!1}(i),l=s.left?this.fence(this.render(r,n)):this.render(r,{...n,before:o&&!a}),u=s.right?this.fence(this.render(i,n)):this.render(i,{...n,before:n.before});return O(l,o?M(this.el(a?"fnspace":"times","")):this.bin("·"),u)}named(e,n,t=null){const{op:r,args:i}=e,s="log"===r?i[1]:i[0];let o;o=g[r]&&"power"===this.o.inverseTrig?this.script(this.word(g[r]),this.text("num","−1"),n):this.word(r),t&&(o=this.script(o,t,n)),"log"===r&&(o=this.script(o,null,n,this.render(i[0],{level:n.level+1})));const a="auto"===this.o.fnParens&&!n.forceParens&&!n.before&&I(s),l=this.render(s,{...n,forceParens:!1,before:!1});return O(o,a?O(M(this.el("fnspace","")),l):this.fence(l))}custom(e,n){const r=t.customName(e.op),i=e.args;if(k.includes(r)&&1===i.length)return this.decorate(r,this.render(i[0],n));return O(/^[A-Za-z]′*(⁻¹)?$/.test(r)?this.symbol(r):this.word(r),M(this.el("callgap","")),this.fence(this.list(i,n)))}decorate(e,n){switch(e){case"boxed":return M(this.el("boxed",n.html),n.h+.22,n.d+.22);case"cancel":return M(this.el("cancel",n.html),n.h,n.d);case"underline":return M(this.el("underline",n.html),n.h,n.d+.12);case"overline":case"bar":return M(this.el("over",n.html),n.h+.14,n.d);default:return M(this.el("accent",this.el("accent-mark",x[e])+n.html),n.h+.3,n.d)}}fraction(e,n){const[t,r]=e.args;if(n.level>0&&"slash"===this.o.scriptFractions&&I(t,!0)&&I(r,!0)){const e=e=>"op"!==e.type||I(e)?this.render(e,n):this.fence(this.render(e,n));return O(e(t),this.text("ord","/"),e(r))}const i=n.level>0||n.inFraction||!this.o.display?.8:1,s={...n,inFraction:!0,forceParens:!1,before:!1};return this.stack(this.render(t,s),this.render(r,s),!0,i)}stack(e,n,t=!0,r=1){const i=e=>1===r?e.html:this.el("scaled",e.html,`font-size:${S(r)}`),s=t?.06:0,o=u+s/2+.1+Math.max(l,r*e.d),c=this.el("frac"+(t?"":" frac-nobar"),this.el("numer",i(e))+this.el("denom",i(n)),`vertical-align:${S(o)}`);return M(c,o+Math.max(a,r*e.h),Math.max(a,r*n.h)+Math.max(l,r*n.d)+.1+s/2-u)}power(e,n){const[r,i]=e.args,s={...n,level:n.level+1,forceParens:!1,before:!1,inFraction:!1},o=()=>this.render(i,s);if(this.o.trigPowers&&m.includes(r.op)&&T(i))return this.wrap(r,["op",`op-${r.op}`],this.named(r,n,o()));if("_"===r.op){const e=this.render(r.args[1],s);return this.wrap(r,["op","op-subscript"],this.script(this.render(r.args[0],{...n,forceParens:!0}),o(),n,e))}const a=t.needsBrackets(e,r,"left")||"number"===r.type&&r.value.startsWith("-")||"/"===r.op||v.includes(r.op)?this.fence(this.render(r,n)):this.render(r,{...n,forceParens:!0});return this.script(a,o(),n)}script(e,n,t,r=null,i=null){const s=t.level>0?.8:c,o=i?O(e,i):e;let a=n?Math.max(.42,e.h-.38,s*n.d+.12):0,l=r?Math.max(.2,e.d-.05,s*r.h-.45):0;if(n&&r){const e=.1-(a-s*n.d-(s*r.h-l));e>0&&(l+=e)}const u=e=>this.el("script",e.html,`font-size:${S(s)}`);if(n&&!r)return M(e.html+this.el("sup",n.html,`font-size:${S(s)};vertical-align:${S(a/s)}`),Math.max(o.h,a+s*n.h),Math.max(o.d,s*n.d-a));if(r&&!n)return M(o.html+this.el("sub",r.html,`font-size:${S(s)};vertical-align:${S(-l/s)}`),Math.max(o.h,s*r.h-l),Math.max(o.d,l+s*r.d));const p=a+s*n.h,f=l+s*r.d,h=this.el("subsup",u(n)+u(r),`vertical-align:${S(a)};height:${S(p+f)}`);return M(o.html+h,Math.max(o.h,p),Math.max(o.d,f))}radical(e,n=null){const t=Math.max(e.h,a)+.1+.06,r=Math.max(e.d,l),i=t+r,s=o("sqrt",`${this.p}-hook`,`height:${S(i)};width:${S(.5+.06*(i-1))};vertical-align:${S(-r)}`);let u="";if(n){const e=.8*c;u=this.el("rootindex",n.html,`font-size:${S(e)};vertical-align:${S((.55*i-r)/e)}`)}return M(this.el("sqrt",u+s+this.el("radicand",e.html)),t,r)}fence(e,n="(",t=")"){const r=Math.max(e.h,a)+Math.max(e.d,l),i=r>1.25,s=i?.1:0,u=(e,n)=>{if(!e)return{html:"",w:0};const t={"(":.26,")":.26,"{":.36,"}":.36}[e];if(t){const s=t+(i?Math.min(.2,.05*(r-1)):0);return{html:o(e,`${this.p}-delim ${this.p}-delim-${n}`,`width:${S(s)}`),w:s+.1}}const s={"[":"lbrack","]":"rbrack","|":"vert","⌊":"lfloor","⌋":"rfloor","⌈":"lceil","⌉":"rceil"}[e];return{html:this.el(`delim ${s} delim-${n}`,""),w:"|"===e?.18:.3}},c=u(n,"l"),p=u(t,"r"),f=`padding:${S(s)} ${S(p.w)} ${S(s)} ${S(c.w)}`,h=M(this.el("fence",c.html+e.html+p.html,f),Math.max(e.h,a)+s,Math.max(e.d,l)+s);return h.fenced=!0,h}derivative(e,n){const{n:r,body:i,by:s,variable:o}=t.derivativeOrder(e),a={...n,level:n.level+1},l=()=>this.text("d","d"),u=()=>r>1?this.render({type:"number",value:String(r)},a):null,c={...n,inFraction:!0},p=O(l(),u()?this.script(this.render(s,c),u(),c):this.render(s,c)),f=e=>O(u()?this.script(l(),u(),c):l(),e||[]),h=n.level>0||n.inFraction||!this.o.display?.8:1;if(o)return this.stack(f(this.render(i,c)),p,!0,h);const d=t.bracketOp(i)&&t.precedenceOf(t.bracketOp(i))<100,[m,g]="("===this.o.derivativeBrackets?["(",")"]:["[","]"],v=d?this.fence(this.render(i,n),m,g):this.render(i,n);return O(this.stack(f(),p,!0,h),v)}integral(e,n){const[r,i,s,o]=e,a=e=>this.render(e,n),l=e=>e?this.render(e,{...n,level:n.level+1}):null,u=()=>this.text("var",t.firstVariable(r)||"x");let c,p=null,f=null;switch(e.length){case 1:c=u();break;case 2:t.isVariable(i)?c=a(i):(c=u(),p=l(i));break;case 3:t.isVariable(i)?(c=a(i),p=l(s)):(c=u(),p=l(i),f=l(s));break;default:c=a(i),p=l(s),f=l(o)}const h=a(r),d=M(this.el("dx",this.el("d","d")+c.html),c.h,c.d);return O(this.bigSign("int",h,p,f,n),h,d)}bigSign(e,n,t,r,i){const s=!this.o.display||i.level>0,a=Math.max(s?.6:.95,Math.max(n.h-u,n.d+u)+.12),l=o(e,`${this.p}-bigsign ${this.p}-${e}sign`,`height:${S(2*a)};width:${S(s?.38:.5)};vertical-align:${S(u-a)}`);if(!t&&!r)return M(l,u+a,a-u);const p=c,f=r||M(""),h=t||M(""),d=u+a-p*f.h;h.d;const m=this.el("limits",this.el("script",f.html,`font-size:${S(p)}`)+this.el("script lower",h.html,`font-size:${S(p)}`),`vertical-align:${S(d)};height:${S(2*a)}`);return M(l+m,u+a,a-u)}limit(e,n){const[r,i,s,o]=e,a={...n,level:n.level+1},l=e=>this.render(e,a),u=()=>this.rel("→");let c;switch(e.length){case 1:return O(this.word("lim"),M(this.el("fnspace","")),this.render(r,n));case 2:{const e=t.firstVariable(r),n="number"===i.type||"symbol"===i.type&&i.value.includes("∞");c=e&&n?O(this.text("var",e),u(),l(i)):l(i);break}case 3:c=O(l(i),u(),l(s));break;default:{const e=t.firstLeaf(o).toLowerCase().startsWith("r")?"+":p;c=O(l(i),u(),this.script(l(s),this.wrap(o,["symbol"],this.text("ord",e)),a))}}return O(this.under(this.word("lim"),c,n),this.render(r,n))}under(e,n,t){return!this.o.display||t.level>0?this.script(e,null,t,n):M(this.el("under",e.html+this.el("script",n.html,`font-size:${S(.7)}`)),e.h,Math.max(e.d,l)+.05+.7*(n.h+n.d))}bigOperator(e,n,t){const[r,i,s]=n,a={...t,level:t.level+1},l=i?this.render(i,a):null,p=s?this.render(s,a):null,f=this.render(r,t);if(!this.o.display||t.level>0){const n=.55,r=o(e,`${this.p}-bigsign`,`height:${S(2*n)};width:${S(.8)};vertical-align:${S(u-n)}`);return O(this.script(M(r,u+n,n-u),p,t,l),f)}const h=.68,d=c,m=o(e,`${this.p}-bigsign`,`height:${S(1.36)};width:${S("sum"===e?1:1.05)}`),g=p?1.01+d*p.d:u-h,v=e=>this.el("script",e.html,`font-size:${S(d)}`),b=this.el("bigop",(p?v(p):"")+m+(l?v(l):""),`vertical-align:${S(g)}`);return O(M(b,.93+(p?.08+d*(p.h+p.d):0),h-u+(l?.08+d*(l.h+l.d):0)),f)}cases(e,n){const t=[];let r=e;for(;"op"===r.type&&"?:"===r.op;)t.push([this.render(r.args[1],n),O(this.word("if"),this.text("space",""),this.render(r.args[0],n))]),r=r.args[2];t.push([this.render(r,n),this.word("otherwise")]);const i=t.map(([e,n])=>({h:Math.max(e.h,n.h),d:Math.max(e.d,n.d)})),s=i.reduce((e,n)=>e+n.h+n.d,0)+.25*(t.length-1),o=u+s/2-i[0].h,a=t.map(([e,n])=>this.el("case-value",e.html)+this.el("case-cond",n.html)).join(""),l=M(this.el("cases",a,`vertical-align:${S(o)}`),u+s/2,s/2-u);return this.fence(l,"{","")}}function I(e,n=!1){return"number"===e.type?!e.value.startsWith("-")||n:"symbol"===e.type||"op"===e.type&&("abs"===e.op?!n:!n||"neg"!==e.op&&"^"!==e.op?"*"===e.op&&!t.isMinusOneTimes(e)&&e.args.every(e=>"number"===e.type&&!e.value.startsWith("-")||E(e)||"*"===e.op&&I(e,n)):I(e.args[0],!0)&&("neg"===e.op||I(e.args[1],!0)))}const E=e=>"symbol"===e.type&&(1===e.value.length||/^[α-ωΑ-Ω]$/.test(e.value)||Boolean(t.GREEK[e.value])),T=e=>"number"===e.type&&/^[1-9]\d*$/.test(e.value)&&Number(e.value)<10;const j=e=>t.toPostfix(e).join(" ");function C(e,n){const r=new Set;L(e,n,r);const i=[];return t.walk(e,e=>{r.has(e)&&i.push(e)}),i}function L(e,n,r){if(null!=n)if(Array.isArray(n))n.forEach(n=>L(e,n,r));else if("number"!=typeof n)if("function"!=typeof n){if("string"==typeof n){const i=j(t.parseTree(n));return void t.walk(e,e=>{j(e)===i&&r.add(e)})}if(n.path){const t=Z(e,n.path);return void(t&&r.add(t))}if(n.type){const i=j(n);t.walk(e,e=>{e!==n&&j(e)!==i||r.add(e)})}}else t.walk(e,(e,t)=>{n(e,t)&&r.add(e)});else t.walk(e,e=>{e.id===n&&r.add(e)})}function Z(e,n){let t=e;for(const e of n){if("op"!==t.type||!t.args[e])return null;t=t.args[e]}return t}function z(e,n){const t=[],r=e=>{if(e.id===n)return!0;if("op"!==e.type)return!1;for(let n=0;n<e.args.length;n++){if(t.push(n),r(e.args[n]))return!0;t.pop()}return!1};return r(e)?t:null}function B(e){let n=0;const r=e=>{"op"===e.type&&(e.args.forEach(r),t.operator(e.op)?.arity===t.VARIADIC&&n++),e.id=n++};return r(e),e}function D(e,n={}){const{blocks:r}=n;if("string"==typeof e)return t.parseTree(e,r?{blocks:e=>r(e,n.scope)}:{});if(Array.isArray(e))return t.fromPostfix(e);if(e&&"object"==typeof e&&e.type)return void 0===e.id?B(structuredClone(e)):e;throw new Error("Inline Math needs an expression, standard postfix or a tree")}function F(e,n){const{colors:t,highlight:r,scope:i,blocks:s,...o}=n,a=new Map;for(const[n,r]of function(e){return e?Array.isArray(e)?e:Object.entries(e).map(([e,n])=>[/^\d+$/.test(e)?Number(e):e,n]):[]}(t))if(R(r))for(const t of C(e,n))a.set(t,`color:${r}`);const l=new Set(void 0===r?[]:C(e,r));if(!a.size&&!l.size)return o;const u=o.prefix||"mv";return{...o,style:e=>[a.get(e),o.style&&o.style(e)].filter(Boolean).join(";"),attributes:e=>{const n={...o.attributes?o.attributes(e):{}};return l.has(e)&&(n.class=[n.class,`${u}-hl`].filter(Boolean).join(" ")),n}}}function R(e){return"string"==typeof e&&/^[#\w\s.,%()/+-]+$/.test(e)&&!/url\s*\(|expression/i.test(e)}function P(e,t={}){return D(e,{...t,blocks:t.blocks??n.calculateBlock})}function V(e,t={}){return function(e,n={}){const t=D(e,n);return A(t,F(t,n)).html}(e,{...t,blocks:t.blocks??n.calculateBlock})}class W{constructor(e,n,t={}){this.element=e,this.options=t,this.p=t.prefix||"mv",this.handlers=[],this.set(n)}set(e,{animate:n=!1,duration:t=600,easing:r="ease-in-out"}={}){const i=n&&this.tree?this.snapshot():null;return this.tree=P(e,this.options),this.element.innerHTML=A(this.tree,F(this.tree,this.options)).html,this.root=this.element.firstElementChild,this.handlers.length&&this.root.classList.add(`${this.p}-clickable`),i&&this.morph(i,{duration:t,easing:r}),this}nodes(e){return C(this.tree,e)}elements(e){return this.nodes(e).map(e=>this.elementOf(e)).filter(Boolean)}elementOf(e){return void 0===e.id?null:this.root.querySelector(`[data-node="${e.id}"]`)}highlight(e,n=`${this.p}-hl`){return this.elements(e).forEach(e=>e.classList.add(n)),this}unhighlight(e=null,n=`${this.p}-hl`){return(null===e?this.root.querySelectorAll(`.${n}`):this.elements(e)).forEach(e=>e.classList.remove(n)),this}color(e,n){return this.elements(e).forEach(e=>{e.style.color=n||""}),this}on(e,n){const t=e=>{const t=e.target.closest?.("[data-node]");if(!t||!this.root.contains(t))return;const r=Number(t.dataset.node),i=C(this.tree,r)[0];n({node:i,id:r,path:z(this.tree,r),element:t,event:e})};return this.element.addEventListener(e,t),this.handlers.push([e,t]),this.root.classList.add(`${this.p}-clickable`),()=>this.element.removeEventListener(e,t)}segments(e={}){return r.toSpeechSegments(this.tree,e)}showSegment(e,n=`${this.p}-hl`){return this.unhighlight(null,n),e&&void 0!==e.id&&this.highlight(e.id,n),this}snapshot(){const e=new Map,n=t=>{const r=this.elementOf(t);if(r){const n=j(t);e.has(n)||e.set(n,[]),e.get(n).push(r.getBoundingClientRect())}"op"===t.type&&t.args.forEach(n)};return n(this.tree),e}morph(e,{duration:n,easing:t}){if("undefined"==typeof Element||!Element.prototype.animate)return;const r=i=>{const s=this.elementOf(i),o=s&&e.get(j(i));if(o&&o.length){const e=o.shift(),r=s.getBoundingClientRect(),i=e.left-r.left,a=e.top-r.top,l=r.width?e.width/r.width:1,u=r.height?e.height/r.height:1;return void((Math.abs(i)+Math.abs(a)>.5||Math.abs(l-1)+Math.abs(u-1)>.01)&&s.animate([{transformOrigin:"0 0",transform:`translate(${i}px, ${a}px) scale(${l}, ${u})`},{transformOrigin:"0 0",transform:"none"}],{duration:n,easing:t}))}"op"===i.type?i.args.forEach(r):s&&s.animate([{opacity:0},{opacity:0},{opacity:1}],{duration:n,easing:t})};r(this.tree)}}const U=new RegExp("(\\d+)","g");function _(e,{delimiters:n=["$$","$","\\[","\\("]}={}){const t=[];let r="",i=0;const s=String(e),o=e=>0===e||"\n"===s[e-1],a=(e,n,r)=>(t.push({source:e,display:n,raw:r}),`${t.length-1}`);for(;i<s.length;){if(o(i)){const e=/^( {0,3})(`{3,}|~{3,})([^\n]*)\n?/.exec(s.slice(i));if(e){const n=e[2],t=new RegExp(`\\n {0,3}${"`"===n[0]?"`":"~"}{${n.length},}[ \\t]*(?=\\n|$)`),o=s.slice(i+e[0].length),l=t.exec(`\n${o}`),u=l?o.slice(0,Math.max(0,l.index-1)):o,c=e[0].length+(l?l.index-1+l[0].length:o.length),p=s.slice(i,i+c);"math"===e[3].trim()?r+=a(u,!0,p):r+=p,i+=c;continue}}const e=s[i];if("`"===e){const e=/^`+/.exec(s.slice(i))[0],n=s.indexOf(e,i+e.length);if(n>-1){r+=s.slice(i,n+e.length),i=n+e.length;continue}r+=e,i+=e.length;continue}if("\\"===e){const e=s.slice(i,i+2),t="\\["===e?"\\]":"\\("===e?"\\)":null;if(t&&n.includes(e)){const n=s.indexOf(t,i+2);if(n>-1){r+=a(s.slice(i+2,n),"\\["===e,s.slice(i,n+2)),i=n+2;continue}}r+=e,i+=2;continue}if("$"===e)if("$"===s[i+1]&&n.includes("$$")){const e=s.indexOf("$$",i+2);if(e>-1){r+=a(s.slice(i+2,e),!0,s.slice(i,e+2)),i=e+2;continue}}else if(n.includes("$")&&s[i+1]&&!/\s/.test(s[i+1])){const e=H(s,i+1);if(e>-1){r+=a(s.slice(i+1,e),!1,s.slice(i,e+1)),i=e+1;continue}}r+=e,i++}return{text:r,math:t}}function H(e,n){for(let t=n;t<e.length;t++){const n=e[t];if("\\"!==n){if("`"===n)return-1;if("\n"===n&&/^\n[ \t]*\n/.test(e.slice(t)))return-1;if("$"===n&&!/\s/.test(e[t-1])&&!/\d/.test(e[t+1]??"")&&"$"!==e[t+1])return t}else t++}return-1}const J=e=>String(e).replace(/&/g,"&").replace(/</g,"<").replace(/>/g,">").replace(/"/g,"""),K=/^\s*([A-Za-zͰ-Ͽ](?:_\{?\w+\}?)?)\s*(?::=|=)\s*([^=<>≤≥]+)$/;function G(e,t,r){const{source:i,display:s}=e;try{const e=V(i,{...t.math,display:s,blocks:t.blocks,scope:r});return!1!==t.define&&function(e,t){const r=K.exec(e);if(!r||/\{\{/.test(r[2]))return;try{const e=n.calculate(r[2],t);"number"!=typeof e.value&&"bigint"!=typeof e.value||(t[r[1].replace(/[{}]/g,"")]=e.exact?e.text:e.value)}catch{}}(i,r),s?`<span class="mv-md-display">${e}</span>`:`<span class="mv-md-math">${e}</span>`}catch(n){return`<span class="mv-md-error" title="${J(n.message)}"><code>${J(e.raw)}</code></span>`}}const Q=/^(https?:|mailto:|#|\/|\.{0,2}\/|[^:]*$)/i,Y=e=>Q.test(e.trim())?J(e.trim()):"#";function X(e,n,t){const r=[],i=e=>(r.push(e),`${r.length-1}`);let s=e;return s=s.replace(/(`+)([\s\S]*?[^`])\1(?!`)/g,(e,n,r)=>i(`<code>${J(t(r.trim()))}</code>`)),s=s.replace(/\\([\\`*_{}[\]()#+\-.!|~$<>"'])/g,(e,n)=>i(J(n))),s=s.replace(/<((?:https?:\/\/|mailto:)[^\s>]+)>/g,(e,n)=>i(`<a href="${Y(n)}">${J(n)}</a>`)),n.html&&(s=s.replace(/<\/?[A-Za-z][^>]*>/g,e=>i(e))),s=s.replace(/!\[([^\]]*)\]\(\s*((?:[^\s()]|\([^\s()]*\))+)(?:\s+"([^"]*)")?\s*\)/g,(e,n,t,r)=>i(`<img src="${Y(t)}" alt="${J(n)}"${r?` title="${J(r)}"`:""}>`)),s=s.replace(/\[([^\]]+)\]\(\s*((?:[^\s()]|\([^\s()]*\))+)(?:\s+"([^"]*)")?\s*\)/g,(e,r,s,o)=>i(`<a href="${Y(s)}"${o?` title="${J(o)}"`:""}>${X(r,n,t)}</a>`)),s=J(s),s=s.replace(/(\*\*|__)(?=\S)([\s\S]*?\S)\1/g,"<strong>$2</strong>"),s=s.replace(/(^|[^*\w])\*(?=\S)([\s\S]*?\S)\*(?!\*)/g,"$1<em>$2</em>"),s=s.replace(/(^|[^_\w])_(?=\S)([\s\S]*?\S)_(?![_\w])/g,"$1<em>$2</em>"),s=s.replace(/~~(?=\S)([\s\S]*?\S)~~/g,"<del>$1</del>"),s=s.replace(/( {2,}|\\)\n/g,"<br>\n"),s.replace(/(\d+)/g,(e,n)=>r[Number(n)])}const ee=/^( {0,3})(#{1,6}\s|>|```|~~~|([-*+]|\d{1,9}[.)])\s|(\*[ \t]*){3,}$|(-[ \t]*){3,}$|(_[ \t]*){3,}$)/,ne=/^( {0,3})([-*+]|\d{1,9}[.)])(\s+|$)/,te=/^\s*\|?\s*:?-+:?\s*(\|\s*:?-+:?\s*)*\|?\s*$/;function re(e,n,t){const r=[];let i=0;const s=e=>X(e,n,t);for(;i<e.length;){const o=e[i];if(!o.trim()){i++;continue}const a=/^ {0,3}(`{3,}|~{3,})\s*([^\s`]*)/.exec(o);if(a){const n=[];for(i++;i<e.length&&!new RegExp(`^ {0,3}${"`"===a[1][0]?"`":"~"}{${a[1].length},}\\s*$`).test(e[i]);)n.push(e[i++]);i++;const s=a[2]?` class="language-${J(a[2])}"`:"";r.push(`<pre><code${s}>${J(t(n.join("\n")))}</code></pre>`);continue}const l=/^ {0,3}(#{1,6})\s+(.*?)\s*#*\s*$/.exec(o);if(l){r.push(`<h${l[1].length}>${s(l[2])}</h${l[1].length}>`),i++;continue}if(/^ {0,3}((\*[ \t]*){3,}|(-[ \t]*){3,}|(_[ \t]*){3,})$/.test(o)){r.push("<hr>"),i++;continue}if(/^ {0,3}>/.test(o)){const s=[];for(;i<e.length&&e[i].trim()&&(/^ {0,3}>/.test(e[i])||s.length);)s.push(e[i].replace(/^ {0,3}> ?/,"")),i++;r.push(`<blockquote>\n${re(s,n,t)}\n</blockquote>`);continue}const u=ne.exec(o);if(u){const s=/\d/.test(u[2]),o=s?parseInt(u[2],10):1,a=[];let l=!1;for(;i<e.length;){const n=ne.exec(e[i]);if(!n||/\d/.test(n[2])!==s)break;const t=n[0].length,r=[e[i].slice(t)];for(i++;i<e.length;){const n=e[i];if(!n.trim()){const n=e[i+1];if(void 0!==n&&n.startsWith(" ".repeat(Math.min(t,4)))&&n.trim()){r.push(""),l=!0,i++;continue}void 0!==n&&ne.test(n)&&(l=!0);break}if(n.startsWith(" ".repeat(Math.min(t,4))))r.push(n.slice(Math.min(t,4)));else{if(ne.test(n)||ee.test(n))break;r.push(n)}i++}for(a.push(r);i<e.length&&!e[i].trim()&&void 0!==e[i+1]&&ne.test(e[i+1]);)i++}const c=s?"ol":"ul",p=a.map(e=>{let r=re(e,n,t);return l||(r=r.replace(/^<p>([\s\S]*?)<\/p>/,"$1").replace(/\n<p>([\s\S]*?)<\/p>/g,"\n$1")),`<li>${r}</li>`});r.push(`<${c}${s&&1!==o?` start="${o}"`:""}>\n${p.join("\n")}\n</${c}>`);continue}if(o.includes("|")&&void 0!==e[i+1]&&te.test(e[i+1])&&e[i+1].includes("-")){const n=e=>e.trim().replace(/^\|/,"").replace(/\|$/,"").split(/(?<!\\)\|/).map(e=>e.trim()),t=n(e[i+1]).map(e=>e.startsWith(":")&&e.endsWith(":")?"center":e.endsWith(":")?"right":e.startsWith(":")?"left":""),a=(e,n,r)=>`<${e}${t[r]?` style="text-align:${t[r]}"`:""}>${s(n)}</${e}>`,l=n(o);i+=2;const u=[];for(;i<e.length&&e[i].trim()&&e[i].includes("|");)u.push(n(e[i++]));r.push(`<table>\n<thead><tr>${l.map((e,n)=>a("th",e,n)).join("")}</tr></thead>\n<tbody>\n${u.map(e=>`<tr>${l.map((n,t)=>a("td",e[t]??"",t)).join("")}</tr>`).join("\n")}\n</tbody>\n</table>`);continue}if(/^( {4}|\t)/.test(o)){const n=[];for(;i<e.length&&(/^( {4}|\t)/.test(e[i])||!e[i].trim());)n.push(e[i++].replace(/^( {4}|\t)/,""));for(;n.length&&!n[n.length-1].trim();)n.pop();r.push(`<pre><code>${J(t(n.join("\n")))}</code></pre>`);continue}const c=[];for(;i<e.length&&e[i].trim()&&(!c.length||!ee.test(e[i])||/^ {0,3}[-=]+\s*$/.test(e[i]));){if(c.length&&/^ {0,3}(=+|-+)\s*$/.test(e[i])){const n="="===e[i].trim()[0]?1:2;r.push(`<h${n}>${s(c.join("\n"))}</h${n}>`),c.length=0,i++;break}c.push(e[i].replace(/^ {0,3}/,"")),i++}c.length&&r.push(`<p>${s(c.join("\n"))}</p>`)}return r.join("\n")}function ie(e,n={},t=e=>e){return re(String(e).replace(/\r\n?/g,"\n").split("\n"),n,t)}function se(e,n={}){const{text:t,math:r}=_(e,n),i={...n.scope??{}},s=r.map(e=>G(e,n,i));return(n.render?n.render(t):ie(t,n,e=>e.replace(U,(e,n)=>r[Number(n)].raw))).replace(new RegExp("<p>\\s*(\\d+)\\s*</p>","g"),(e,n)=>r[Number(n)].display?`<div class="mv-md-block">${s[Number(n)]}</div>`:e).replace(U,(e,n)=>s[Number(n)])}const oe=new Map,ae=-1,le="\\:",ue=e=>"string"==typeof e&&e.startsWith(le)&&e.length>2;function ce(e){if(!e||!e.symbol)throw new Error("operator needs a symbol");if(!Number.isInteger(e.arity)||e.arity<0&&e.arity!==ae)throw new Error(`operator "${e.symbol}" needs an integer arity >= 0, or VARIADIC`);if(e.commutative&&2!==e.arity)throw new Error(`only binary operators can be commutative ("${e.symbol}")`);const n={symbol:e.symbol,arity:e.arity,commutative:!!e.commutative,fold:"function"==typeof e.fold?e.fold:null,label:e.label||e.symbol};return oe.set(n.symbol,n),n}const pe=Object.freeze({symbol:le,arity:ae,commutative:!1,fold:null,label:"function"});function fe(e){const n=oe.get(e);return n||(ue(e)?{...pe,symbol:e,label:e.slice(2)}:null)}function he(e){return oe.has(e)||ue(e)}const de=e=>Number.isFinite(e)&&Number.isInteger(e)?e:null,me=e=>Number.isFinite(e)?e:null;!function(){ce({symbol:"+",arity:2,commutative:!0,label:"add",fold:(e,n)=>me(e+n)}),ce({symbol:"-",arity:2,label:"subtract",fold:(e,n)=>me(e-n)}),ce({symbol:"*",arity:2,commutative:!0,label:"multiply",fold:(e,n)=>me(e*n)}),ce({symbol:"/",arity:2,label:"divide",fold:(e,n)=>0===n?null:de(e/n)}),ce({symbol:"^",arity:2,label:"power",fold:(e,n)=>Number.isInteger(n)&&Math.abs(n)<=64?me(e**n):null}),ce({symbol:"neg",arity:1,label:"negate",fold:e=>me(-e)}),ce({symbol:"pm",arity:1,label:"plus or minus"}),ce({symbol:"±",arity:2,label:"plus or minus"}),ce({symbol:"mod",arity:2,label:"modulo",fold:(e,n)=>0===n?null:de((e%n+n)%n)}),ce({symbol:"!",arity:1,label:"factorial",fold:e=>Number.isInteger(e)&&e>=0&&e<=18?[...Array(e).keys()].reduce((e,n)=>e*(n+1),1):null}),ce({symbol:"_",arity:2,label:"subscript"}),ce({symbol:"der",arity:2,label:"derivative"}),ce({symbol:"int",arity:ae,label:"integral"}),ce({symbol:"lim",arity:ae,label:"limit"}),ce({symbol:"\\sumidx",arity:ae,label:"sum over an index"}),ce({symbol:"\\prodidx",arity:ae,label:"product over an index"}),ce({symbol:"abs",arity:1,label:"absolute value",fold:e=>me(Math.abs(e))}),ce({symbol:"floor",arity:1,label:"floor",fold:e=>me(Math.floor(e))}),ce({symbol:"ceil",arity:1,label:"ceiling",fold:e=>me(Math.ceil(e))}),ce({symbol:"round",arity:2,label:"round",fold:(e,n)=>Number.isInteger(n)?me(Math.round(e*10**n)/10**n):null}),ce({symbol:"fixed",arity:2,label:"fixed",fold:()=>null}),ce({symbol:"sqrt",arity:1,label:"square root",fold:e=>de(Math.sqrt(e))}),ce({symbol:"root",arity:2,label:"nth root",fold:(e,n)=>de(Math.round(n**(1/e))**e===n?Math.round(n**(1/e)):NaN)});for(const e of["sin","cos","tan","csc","sec","cot","sinh","cosh","tanh","arcsin","arccos","arctan","arcsinh","arccosh","arctanh","ln","loglog","logloglog","expm1"])ce({symbol:e,arity:1,label:e});ce({symbol:"log",arity:2,label:"log to a base"}),ce({symbol:"atan2",arity:2,label:"atan2"}),ce({symbol:"perm",arity:2,label:"permutations"}),ce({symbol:"comb",arity:2,label:"combinations"}),ce({symbol:"random",arity:0,label:"random"});for(const e of["max","min","gcd","mean","sum","prod"])ce({symbol:e,arity:ae,label:e});for(const e of["()","[]","{}","(]","[)"])ce({symbol:e,arity:ae,label:"group"});for(const e of["=","===","≠","≠=","<",">","≤","≥","∈","∉","∪","∩","≈","≡","→","pmod","&","|","\\xor","\\nand","\\nor"])ce({symbol:e,arity:2,label:e});ce({symbol:"\\not",arity:1,label:"not"}),ce({symbol:"?:",arity:3,label:"if then else"})}();const ge="num",ve="sym",be="op",ye=Object.freeze([]);class we extends Error{constructor(e){super(e),this.name="ExprError"}}function xe(e){if("number"!=typeof e||!Number.isFinite(e))throw new we(`not a finite number: ${e}`);const n=(t=e,Object.is(t,-0)?"0":String(t));var t;return Object.freeze({type:ge,token:n,value:e,args:ye,s:n})}function ke(e){if("string"!=typeof e||""===e)throw new we("symbol needs a non-empty token");return Object.freeze({type:ve,token:e,value:null,args:ye,s:e})}function qe(e){const n=/^(-?)0*(\d+?)(?:\.(\d*?)0*)?$/.exec(String(e));if(!n)throw new we(`not an exact decimal: ${e}`);const[,t,r,i=""]=n,s=i?`${r}.${i}`:r,o=/^0(\.0*)?$/.test(s)?"0":t+s;return Object.freeze({type:ge,token:o,value:Number(o),args:ye,s:o})}const $e=/^-?\d+(\.\d+)?$/;function Se(e){const n=String(e);if($e.test(n))return qe(n);if(""!==n&&!/\s/.test(n)){const e=Number(n);if(Number.isFinite(e))return xe(e)}return ke(n)}function Me(e,n){const t=fe(e);if(!t)throw new we(`unknown operator "${e}"`);if(t.arity!==ae&&n.length!==t.arity)throw new we(`"${e}" takes ${t.arity} operand(s), got ${n.length}`);const r=Object.freeze(n.slice()),i=t.arity===ae?` ${r.length}`:"",s=`${r.length?r.map(e=>e.s).join(" "):""}${r.length,""}${i} ${e}`.trimStart();return Object.freeze({type:be,op:e,token:e,value:null,args:r,s:s})}const Oe=e=>e.type===ge,Ae=e=>e.type===be;function Ne(e){return Ie(function(e){const n=String(e).trim();return""===n?[]:n.split(/\s+/)}(e))}function Ie(e){if(!Array.isArray(e))throw new we("fromPostfix needs an array of tokens");if(0===e.length)throw new we("empty expression");const n=[];for(let t=0;t<e.length;t++){const r=String(e[t]);if(he(r)){let e=fe(r).arity;if(e===ae){const i=n.pop();if(e=i&&i.type===ge&&Number.isInteger(i.value)&&i.value>=0?i.value:-1,e<0)throw new we(`"${r}" at position ${t+1} takes any number of operands, so a count must come before it`)}if(n.length<e)throw new we(`"${r}" at position ${t+1} needs ${e} operand(s), only ${n.length} on the stack`);const i=n.splice(n.length-e,e);n.push(Me(r,i))}else n.push(Se(r))}if(1!==n.length){const t=[...new Set(e.filter(e=>!he(e)))];throw new we(`expression leaves ${n.length} values on the stack; it should leave exactly 1. Read as operands: ${t.join(", ")} — is one of those meant to be an operator?`)}return n[0]}function Ee(e){if(e.type!==be)return 0;let n=0;for(const t of e.args)n=Math.max(n,Ee(t));return n+1}function Te(e){if(e.type!==be)return 1;let n=1;for(const t of e.args)n+=Te(t);return n}function je(e,n=[]){if(e.type!==be)n.push(e.token);else for(const t of e.args)je(t,n);return n}function Ce(e){return e.type===ge||e.type!==ve&&e.args.every(Ce)}function Le(e,n="pre",t=[],r=[]){"pre"===n&&r.push({node:e,path:t});for(let i=0;i<e.args.length;i++)Le(e.args[i],n,t.concat(i),r);return"post"===n&&r.push({node:e,path:t}),r}function Ze(e,n,t){if(0===n.length)return t;const[r,...i]=n,s=e.args.slice();return s[r]=Ze(s[r],i,t),Me(e.op,s)}class ze extends Error{constructor(e){super(e),this.name="CasError"}}const Be=1e5,De=e=>e<0n?-e:e,Fe=e=>0n===e?0:De(e).toString(2).length;function Re(e,n){for(e=De(e),n=De(n);n;)[e,n]=[n,e%n];return e}class Pe{constructor(e,n=1n){if(0n===n)throw new ze("division by zero");n<0n&&(e=-e,n=-n);const t=Re(e,n)||1n;if(this.n=e/t,this.d=n/t,Fe(this.n)>Be||Fe(this.d)>Be)throw new ze("a number too large to keep exactly")}static of(e){return new Pe(BigInt(e))}add(e){return new Pe(this.n*e.d+e.n*this.d,this.d*e.d)}sub(e){return new Pe(this.n*e.d-e.n*this.d,this.d*e.d)}mul(e){return new Pe(this.n*e.n,this.d*e.d)}div(e){if(0n===e.n)throw new ze("division by zero");return new Pe(this.n*e.d,this.d*e.n)}neg(){return new Pe(-this.n,this.d)}abs(){return this.n<0n?this.neg():this}inv(){return Pe.ONE.div(this)}pow(e){if((e=BigInt(e))<0n)return this.inv().pow(-e);if((0n===this.n||1n===De(this.n))&&1n===this.d)return 0n===e||-1n===this.n&&e%2n==0n?Pe.ONE:this;if(BigInt(Math.max(Fe(this.n),Fe(this.d)))*e>BigInt(Be))throw new ze("a power too large to work out exactly");return new Pe(this.n**e,this.d**e)}get isZero(){return 0n===this.n}get isOne(){return 1n===this.n&&1n===this.d}get isInteger(){return 1n===this.d}get sign(){return this.n<0n?-1:this.n>0n?1:0}equals(e){return this.n===e.n&&this.d===e.d}compare(e){const n=this.n*e.d,t=e.n*this.d;return n<t?-1:n>t?1:0}floor(){const e=this.n/this.d;return new Pe(this.n<0n&&e*this.d!==this.n?e-1n:e)}ceil(){return this.neg().floor().neg()}toNumber(){const e=Number(this.n),n=Number(this.d);if(Number.isFinite(e)&&Number.isFinite(n))return e/n;const t=BigInt(Math.max(Fe(this.n),Fe(this.d))-1e3);return Number(this.n>>t)/Number(this.d>>t)}toString(){return 1n===this.d?String(this.n):`${this.n}/${this.d}`}}function Ve(e){const n=/^(-?)(\d*)(?:\.(\d*))?(?:[eE]([+-]?\d+))?$/.exec(String(e));if(!n||""===n[2]&&!n[3])return null;const[,t,r,i="",s="0"]=n;let o=new Pe(BigInt((r||"0")+i),10n**BigInt(i.length));const a=Number(s);return a&&(o=o.mul(Pe.of(10).pow(a))),t?o.neg():o}function We(e,n){if(e<2n)return e;if(n>=Fe(e))return 1n;const t=BigInt(n);let r=1n<<BigInt(Math.ceil(Fe(e)/n));for(;;){const n=((t-1n)*r+e/r**(t-1n))/t;if(n>=r)break;r=n}for(;r**t>e;)r--;for(;(r+1n)**t<=e;)r++;return r}Pe.ZERO=new Pe(0n),Pe.ONE=new Pe(1n),Pe.MINUS_ONE=new Pe(-1n),Pe.HALF=new Pe(1n,2n);const Ue=(()=>{const e=[],n=new Uint8Array(1e4);for(let t=2;t<n.length;t++)if(!n[t]){e.push(BigInt(t));for(let e=t*t;e<n.length;e+=t)n[e]=1}return e})();function _e(e,n){const t=BigInt(n);let r=1n,i=1n,s=e;for(const e of Ue){if(e*e>s)break;if(s%e)continue;let n=0n;for(;s%e===0n;)s/=e,n++;r*=e**(n/t),i*=e**(n%t)}if(s>1n){const e=function(e,n){if(e<0n)return null;if(e<2n)return e;const t=We(e,n);return t**BigInt(n)===e?t:null}(s,n);null!==e?r*=e:i*=s}return{outside:r,inside:i}}const He=new Set(["pi","e","π"]),Je={complex:!1};function Ke(e,n){const t=Je.complex;Je.complex=Boolean(e);try{return n()}finally{Je.complex=t}}const Ge=e=>He.has(e)||Je.complex&&"i"===e,Qe=e=>Je.complex&&"atom"===e.k&&"sym"===e.node.type&&"i"===e.node.token,Ye=e=>({k:"num",q:e}),Xe=Ye(Pe.ONE),en=Ye(Pe.ZERO),nn=Ye(Pe.HALF),tn=e=>"num"===e.k,rn=e=>({k:"atom",node:e}),sn=new WeakMap;function on(e){let n=sn.get(e);return void 0===n&&sn.set(e,n=Bn(e).s),n}function an(e){if("num"===e.k)return 0;if("atom"===e.k)return"sym"===e.node.type&&Ge(e.node.token)?0:1;if("add"===e.k)return Math.max(...e.terms.map(e=>an(e.x)));let n=0;for(const t of e.fs){const e=an(t.b);e&&(n+=e*(tn(t.e)?t.e.q.toNumber():1))}return n}function ln(e,n){return"num"===e.k?n&&!tn(n)?3:0:Qe(e)?1.5:"atom"===e.k&&"sym"===e.node.type?Ge(e.node.token)?n&&!tn(n)?3:1:2:"atom"===e.k?3:4}const un=(e,n)=>e<n?-1:e>n?1:0;function cn(e){const n=new Map,t=(e,t)=>{"atom"!==e.k||"sym"!==e.node.type||Ge(e.node.token)||n.set(e.node.token,(n.get(e.node.token)??0)+t)};if("mul"===e.k)for(const n of e.fs)t(n.b,tn(n.e)?n.e.q.toNumber():1);else t(e,1);return n}function pn(e,n){const t=an(n.x)-an(e.x);if(t)return t;const r=cn(e.x),i=cn(n.x);for(const e of[...new Set([...r.keys(),...i.keys()])].sort()){const n=(i.get(e)??0)-(r.get(e)??0);if(n)return n}return un(on(e.x),on(n.x))}function fn(e,n){return e.isOne?n:e.isZero?en:gn([Ye(e),n])}function hn(e){if("num"===e.k)return{coef:e.q,rest:null};if("mul"!==e.k||e.c.isOne)return{coef:Pe.ONE,rest:e};const n=1===e.fs.length&&tn(e.fs[0].e)&&e.fs[0].e.q.isOne?e.fs[0].b:{k:"mul",c:Pe.ONE,fs:e.fs};return{coef:e.c,rest:n}}function dn(e){let n=Pe.ZERO;const t=new Map,r=(e,n)=>{const r=on(n),i=t.get(r);i?i.coef=i.coef.add(e):t.set(r,{coef:e,x:n})};for(const t of e)if("num"===t.k)n=n.add(t.q);else if("add"===t.k){n=n.add(t.c);for(const e of t.terms)r(e.coef,e.x)}else{const{coef:e,rest:n}=hn(t);r(e,n)}const i=[...t.values()].filter(e=>!e.coef.isZero);return i.length?n.isZero&&1===i.length?fn(i[0].coef,i[0].x):(i.sort(pn),{k:"add",c:n,terms:i}):Ye(n)}function mn(e,n){if(!tn(n))return e.isOne?{coef:Pe.ONE,fs:[]}:{coef:Pe.ONE,fs:[{b:Ye(e),e:n}]};const t=n.q;if(t.isInteger)return{coef:e.pow(t.n),fs:[]};if(e.isZero){if(t.sign<0)throw new ze("division by zero");return{coef:Pe.ZERO,fs:[]}}if(e.isOne)return{coef:Pe.ONE,fs:[]};if(e.sign<0){if(t.d%2n==1n){const{coef:r,fs:i}=mn(e.neg(),n);return{coef:t.n%2n==0n?r:r.neg(),fs:i}}if(Je.complex&&2n===t.d){const{coef:r,fs:i}=mn(e.neg(),n);return{coef:r,fs:[...i,{b:yn,e:Ye(new Pe(t.n))}]}}return{coef:Pe.ONE,fs:[{b:Ye(e),e:n}]}}if(!e.isInteger){const r=mn(new Pe(e.n),n),i=mn(new Pe(e.d),Ye(t.neg()));return{coef:r.coef.mul(i.coef),fs:[...r.fs,...i.fs]}}const r=t.floor(),i=t.sub(r);if(BigInt(Fe(e.n))*i.n>BigInt(Be)||i.d>1000n)return{coef:Pe.ONE,fs:[{b:Ye(e),e:n}]};let s=r.isZero?Pe.ONE:e.pow(r.n);const{outside:o,inside:a}=_e(e.n**i.n,Number(i.d));s=s.mul(new Pe(o));return{coef:s,fs:a>1n?[{b:Ye(new Pe(a)),e:Ye(new Pe(1n,i.d))}]:[]}}function gn(e){let n=Pe.ONE;const t=new Map,r=(e,n)=>{const r=on(e),i=t.get(r);i?i.e=dn([i.e,n]):t.set(r,{b:e,e:n})};for(const t of e)if("num"===t.k)n=n.mul(t.q);else if("mul"===t.k){n=n.mul(t.c);for(const e of t.fs)r(e.b,e.e)}else r(t,Xe);if(n.isZero)return en;const i=[],s=new Map;for(const e of t.values())if(!tn(e.e)||!e.e.q.isZero){if("num"===e.b.k){if(tn(e.e)&&!e.e.q.isInteger&&e.b.q.sign>0&&e.b.q.isInteger){const n=e.e.q.toString(),t=s.get(n);t?t.n*=e.b.q.n:s.set(n,{n:e.b.q.n,e:e.e});continue}const t=mn(e.b.q,e.e);n=n.mul(t.coef),i.push(...t.fs);continue}if("mul"===e.b.k&&tn(e.e)&&e.e.q.isInteger){const t=vn(e.b,e.e);"mul"===t.k?(n=n.mul(t.c),i.push(...t.fs)):"num"===t.k?n=n.mul(t.q):i.push({b:t,e:Xe});continue}i.push(e)}for(const{n:e,e:t}of s.values()){const r=mn(new Pe(e),t);n=n.mul(r.coef),i.push(...r.fs)}if(n.isZero)return en;const o=new Map;for(const e of i){const n=on(e.b),t=o.get(n);t?t.e=dn([t.e,e.e]):o.set(n,{...e})}let a=[...o.values()].filter(e=>!(tn(e.e)&&e.e.q.isZero));if(Je.complex){a=a.flatMap(e=>{if(!Qe(e.b)||!tn(e.e)||!e.e.q.isInteger)return[e];const t=(e.e.q.n%4n+4n)%4n;return t>=2n&&(n=n.neg()),t%2n?[{b:e.b,e:Xe}]:[]});const e=a.filter(e=>"add"===e.b.k&&tn(e.e)&&e.e.q.isInteger&&xn(e.b)),t=a.some(e=>Qe(e.b)),r=e.every(e=>(e.e.q.sign<0?-e.e.q.n:e.e.q.n)<=60n);if(e.length&&r&&(e.length>1||t||!e[0].e.q.isOne)){const r=a.filter(n=>!e.includes(n)&&!Qe(n.b));let i=t?[yn]:[Xe];for(const n of e){const e=n.e.q.sign<0?$n(n.b):n.b;for(let t=0n;t<(n.e.q.sign<0?-n.e.q.n:n.e.q.n);t++)i=kn(i,Pn(e))}return gn([Ye(n),dn(i),...r.map(e=>bn(e.b,e.e))])}}if(a.some(e=>"num"===e.b.k&&tn(e.e)&&e.e.q.compare(Pe.ONE)>=0))return gn([Ye(n),...a.map(e=>"num"===e.b.k?vn(e.b,e.e):{k:"mul",c:Pe.ONE,fs:[e]})]);if(!a.length)return Ye(n);if(1===a.length&&!n.isOne&&"add"===a[0].b.k&&tn(a[0].e)&&a[0].e.q.isOne){const e=a[0].b;return dn([Ye(n.mul(e.c)),...e.terms.map(e=>fn(n.mul(e.coef),e.x))])}return n.isOne&&1===a.length&&tn(a[0].e)&&a[0].e.q.isOne?a[0].b:(a=a.sort((e,n)=>ln(e.b,e.e)-ln(n.b,n.e)||un(on(e.b),on(n.b))),{k:"mul",c:n,fs:a})}function vn(e,n){if(Je.complex&&tn(n)&&n.q.isInteger){if(Qe(e))return gn([{k:"mul",c:Pe.ONE,fs:[{b:e,e:n}]}]);if("add"===e.k&&xn(e)&&!n.q.isOne)return gn([{k:"mul",c:Pe.ONE,fs:[{b:e,e:n}]}])}if(tn(n)){if(n.q.isZero){if(tn(e)&&e.q.isZero)throw new ze("0^0 is undefined");return Xe}if(n.q.isOne)return e}if(tn(e)){const t=mn(e.q,n);if(!t.fs.length)return Ye(t.coef);if(t.fs.some(e=>Qe(e.b)))return gn([Ye(t.coef),...t.fs.map(e=>({k:"mul",c:Pe.ONE,fs:[e]}))]);const r={k:"mul",c:t.coef,fs:t.fs};return t.coef.isOne&&1===t.fs.length&&tn(t.fs[0].e)&&t.fs[0].e.q.isOne?t.fs[0].b:r}if(Je.complex&&tn(n)&&2n===n.q.d&&xn(e)){const t=qn(e);if(t&&tn(t.im)&&!t.im.q.isZero){const e=e=>vn(e,Ye(Pe.of(2))),r=vn(dn([e(t.re),e(t.im)]),nn),i=vn(gn([dn([r,t.re]),Ye(Pe.HALF)]),nn),s=vn(gn([dn([r,On(t.re)]),Ye(Pe.HALF)]),nn);return vn(dn([i,gn([Ye(Pe.of(t.im.q.sign)),s,yn])]),Ye(new Pe(n.q.n)))}}if("mul"===e.k){if(tn(n)&&n.q.isInteger)return gn([Ye(e.c.pow(n.q.n)),...e.fs.map(e=>bn(e.b,gn([e.e,n])))]);if(!e.c.isOne&&e.c.sign>0)return gn([vn(Ye(e.c),n),vn({k:"mul",c:Pe.ONE,fs:e.fs},n)]);if(e.c.isOne&&1===e.fs.length){const[t]=e.fs;if(tn(t.e)&&tn(n)&&1n===t.e.q.n&&t.e.q.d%2n==1n)return bn(t.b,gn([t.e,n]))}}return{k:"mul",c:Pe.ONE,fs:[{b:e,e:n}]}}function bn(e,n){return tn(n)&&n.q.isZero?Xe:tn(e)?vn(e,n):tn(n)&&n.q.isOne?e:{k:"mul",c:Pe.ONE,fs:[{b:e,e:n}]}}const yn=rn(ke("i")),wn=e=>Je.complex&&Bn(e).s.split(" ").includes("i");function xn(e){return Je.complex&&wn(e)&&0===Rn(Bn(e)).size}function kn(e,n){const t=[];for(const r of e)for(const e of n)t.push(gn([r,e]));return Pn(dn(t))}function qn(e){const n=[],t=[];for(const r of Pn(e)){const{coef:e,rest:i}=hn(r),s=i?Vn(i):[],o=s.filter(e=>Qe(e)),a=s.filter(e=>!Qe(e));if(a.some(e=>wn(e)))return null;(o.length?t:n).push(gn([Ye(e),...a]))}return{re:dn(n),im:dn(t)}}function $n(e){const n=qn(e);if(!n)return vn(e,Ye(Pe.MINUS_ONE));const t=dn([vn(n.re,Ye(Pe.of(2))),vn(n.im,Ye(Pe.of(2)))]);return gn([dn([n.re,gn([Ye(Pe.MINUS_ONE),n.im,yn])]),vn(t,Ye(Pe.MINUS_ONE))])}const Sn={re:([e])=>qn(e)?.re??null,im:([e])=>qn(e)?.im??null,conj:([e])=>{const n=qn(e);return n?dn([n.re,gn([Ye(Pe.MINUS_ONE),n.im,yn])]):null},arg:([e])=>{const n=qn(e);return n?En("atan2",[n.im,n.re]):null},abs:([e])=>{const n=qn(e);return!n||tn(n.im)&&n.im.q.isZero?null:vn(dn([vn(n.re,Ye(Pe.of(2))),vn(n.im,Ye(Pe.of(2)))]),nn)}},Mn={Re:"re",re:"re",Im:"im",im:"im",conj:"conj",overline:"conj",bar:"conj",arg:"arg"},On=e=>gn([Ye(Pe.MINUS_ONE),e]),An=(e,n)=>gn([e,vn(n,Ye(Pe.MINUS_ONE))]),Nn=3000n,In={abs:([e])=>tn(e)?Ye(e.q.abs()):"mul"!==e.k||e.c.isOne?null:gn([Ye(e.c.abs()),En("abs",[hn(e).rest])]),floor:([e])=>tn(e)?Ye(e.q.floor()):null,ceil:([e])=>tn(e)?Ye(e.q.ceil()):null,"!":([e])=>{if(!tn(e)||!e.q.isInteger||e.q.sign<0||e.q.n>Nn)return null;let n=1n;for(let t=2n;t<=e.q.n;t++)n*=t;return Ye(new Pe(n))},mod:([e,n])=>tn(e)&&tn(n)&&!n.q.isZero?Ye(e.q.sub(n.q.mul(e.q.div(n.q).floor()))):null,max:e=>e.every(tn)&&e.length?e.reduce((e,n)=>n.q.compare(e.q)>0?n:e):null,min:e=>e.every(tn)&&e.length?e.reduce((e,n)=>n.q.compare(e.q)<0?n:e):null,gcd:e=>e.length&&e.every(e=>tn(e)&&e.q.isInteger)?Ye(new Pe(e.reduce((e,n)=>Re(e,n.q.n),0n))):null,log:([e,n])=>{if(!tn(e)||!tn(n)||e.q.sign<=0||n.q.sign<=0||e.q.isOne)return null;if(n.q.isOne)return en;const t=Math.log(n.q.toNumber())/Math.log(e.q.toNumber());if(!Number.isFinite(t))return null;for(let r=1;r<=12;r++){const i=Math.round(t*r);if(!(Math.abs(t*r-i)>1e-9||0===i)&&(Math.abs(i)<=256&&e.q.pow(BigInt(i)).equals(n.q.pow(BigInt(r)))))return Ye(new Pe(BigInt(i),BigInt(r)))}return null},comb:([e,n])=>tn(e)&&tn(n)&&e.q.isInteger&&n.q.isInteger&&e.q.sign>=0&&n.q.sign>=0&&e.q.n<=Nn?Ye(function(e,n){if(n>e)return Pe.ZERO;n>e-n&&(n=e-n);let t=1n;for(let r=1n;r<=n;r++)t=t*(e-n+r)/r;return new Pe(t)}(e.q.n,n.q.n)):null,perm:([e,n])=>{if(!(tn(e)&&tn(n)&&e.q.isInteger&&n.q.isInteger&&e.q.sign>=0&&n.q.sign>=0&&e.q.n<=Nn))return null;if(n.q.n>e.q.n)return en;let t=1n;for(let r=0n;r<n.q.n;r++)t*=e.q.n-r;return Ye(new Pe(t))}};function En(e,n){if(Je.complex&&Sn[e]){const t=Sn[e](n);if(t)return t}const t=In[e];if(t){const e=t(n);if(e)return e}return rn(Me(e,n.map(Bn)))}const Tn=new Map;function jn(e){const n=Je.complex?`ℂ ${e.s}`:e.s,t=Tn.get(n);if(t)return t;const r=function(e){if("num"===e.type){const n=Ve(e.token);if(!n)throw new ze(`not an exact number: ${e.token}`);return Ye(n)}if("sym"===e.type)return"π"===e.token?rn(ke("pi")):rn(e);const n=e.args.map(jn);switch(e.op){case"+":return dn(n);case"-":return((e,n)=>dn([e,On(n)]))(n[0],n[1]);case"neg":return On(n[0]);case"*":return gn(n);case"/":return An(n[0],n[1]);case"^":return vn(n[0],n[1]);case"sqrt":return vn(n[0],nn);case"root":return vn(n[1],vn(n[0],Ye(Pe.MINUS_ONE)));default:{const t=e.op.startsWith("\\:")?e.op.slice(2):null;return t&&Je.complex&&Mn[t]&&1===n.length?En(Mn[t],n):t&&he(t)&&fe(t).arity===n.length?En(t,n):En(e.op,n)}}}(e);return Tn.size>2e4&&Tn.clear(),Tn.set(n,r),r}const Cn=e=>Bn(jn(e)),Ln=e=>qe(String(e));function Zn(e){return e.isInteger?Ln(e.n):Me("/",[Ln(e.n),Ln(e.d)])}const zn=new WeakMap;function Bn(e){let n=zn.get(e);return n||zn.set(e,n=function(e){switch(e.k){case"num":return Zn(e.q);case"atom":return e.node;case"mul":return function(e,n){const t=[],r=[];for(const e of n)tn(e.e)&&e.e.q.sign<0?r.push(Dn(e.b,Ye(e.e.q.neg()))):t.push(Dn(e.b,e.e));let i=1n!==e.n&&-1n!==e.n||!t.length?Fn([Ln(e.n),...t]):Fn(t);-1n===e.n&&t.length&&(i=Me("neg",[i]));1n!==e.d&&r.unshift(Ln(e.d));return r.length?Me("/",[i,Fn(r)]):i}(e.c,e.fs);case"add":return function(e){let n=null;const t=e=>Je.complex&&wn(e.x)&&0===Rn(Bn(e.x)).size,r=[...e.terms.filter(e=>!t(e)),...e.terms.filter(t)],i=e.c,s=()=>{i.isZero||(n=n?i.sign<0?Me("-",[n,Zn(i.neg())]):Me("+",[n,Zn(i)]):Zn(i))};let o=!1;for(const e of r)!o&&t(e)&&(s(),o=!0),n=n?e.coef.sign<0?Me("-",[n,Bn(fn(e.coef.neg(),e.x))]):Me("+",[n,Bn(fn(e.coef,e.x))]):Bn(fn(e.coef,e.x));o||s();return n}(e);default:throw new Error(`bad form ${e.k}`)}}(e)),n}function Dn(e,n){const t=Bn(e);if(tn(n)){const e=n.q;if(e.isOne)return t;if(1n===e.n&&2n===e.d)return Me("sqrt",[t]);if(1n===e.n)return Me("root",[Ln(e.d),t])}return Me("^",[t,Bn(n)])}const Fn=e=>e.reduce((e,n)=>e?Me("*",[e,n]):n,null);function Rn(e,n=new Set){if("sym"===e.type)Ge(e.token)||n.add(e.token);else if(Ae(e))for(const t of e.args)Rn(t,n);return n}function Pn(e){if("add"!==e.k)return[e];const n=e.terms.map(e=>fn(e.coef,e.x));return e.c.isZero||n.push(Ye(e.c)),n}function Vn(e){if("num"===e.k)return[e];if("mul"!==e.k)return[e];const n=e.c.isOne?[]:[Ye(e.c)];for(const t of e.fs)n.push(bn(t.b,t.e));return n}const Wn="_",Un=new WeakMap;function _n(e,n){return[...n,...fe(e.op)?.arity===ae?[String(e.args.length)]:[],e.op].join(" ")}function Hn(e,n){let t=Un.get(e);t||Un.set(e,t=new Map);const r=t.get(n);if(r)return r;const i=function(e,n){const t={key:Wn,slots:[e]};if(e.type!==be||n<=0)return[t];const r=e.args.map(e=>Hn(e,n-1)),i=[t],s=new Array(r.length).fill(0);for(;;){const n=[],t=[];for(let e=0;e<r.length;e++){const i=r[e][s[e]];n.push(i.key);for(const e of i.slots)t.push(e)}if(i.push({key:_n(e,n),slots:t}),i.length>=4096)break;let o=r.length-1;for(;o>=0&&!(++s[o]<r[o].length);o--)s[o]=0;if(o<0)break}return i}(e,n);return t.set(n,i),i}function Jn(e){return e.type!==be?Wn:_n(e,e.args.map(Jn))}function Kn(e,n=[]){if(e.type!==be)n.push(e);else for(const t of e.args)Kn(t,n);return n}const Gn=new Map,Qn=new Map;class Yn extends Error{constructor(e){super(e),this.name="RequirementError"}}function Xn(e,n,t=""){Gn.set(e,{name:e,fn:n,doc:t,arity:Math.max(0,n.length-1)})}function et(e,n,t=""){Qn.set(e,{name:e,fn:n,doc:t})}function nt(e){return Gn.get(e)||null}function tt(e){return Qn.get(e)||null}const rt=e=>e.type===ge;function it(e,n){return e.type===be&&(e.op===n||e.args.some(e=>it(e,n)))}Xn("always",()=>!0,"matches anything"),Xn("never",()=>!1,"matches nothing"),Xn("isLeaf",e=>e.type!==be,"a bare operand, not an operation"),Xn("isCompound",e=>e.type===be,"an operation, not a bare operand"),Xn("isSymbol",e=>e.type===ve,"a non-numeric operand such as x"),Xn("isOperation",(e,n)=>e.type===be&&e.op===n,"is this specific operation"),Xn("notOperation",(e,n)=>!(e.type===be&&e.op===n),"is anything except this operation"),Xn("isNumber",rt,"a numeric literal"),Xn("isInteger",e=>rt(e)&&Number.isInteger(e.value),"a whole number"),Xn("isPositive",e=>rt(e)&&e.value>0,"greater than zero"),Xn("isNegative",e=>rt(e)&&e.value<0,"less than zero"),Xn("isNonNegative",e=>rt(e)&&e.value>=0,"zero or greater"),Xn("isZero",e=>rt(e)&&0===e.value,"exactly 0"),Xn("isOne",e=>rt(e)&&1===e.value,"exactly 1"),Xn("isNonZero",e=>rt(e)&&0!==e.value,"a number that is provably not 0"),Xn("isNotZeroLiteral",e=>!(rt(e)&&0===e.value),"anything except a literal 0"),Xn("isPositiveInteger",e=>rt(e)&&Number.isInteger(e.value)&&e.value>0,"a whole number above 0"),Xn("isNegativeInteger",e=>rt(e)&&Number.isInteger(e.value)&&e.value<0,"a whole number below 0"),Xn("isEven",e=>rt(e)&&Number.isInteger(e.value)&&e.value%2==0,"a whole even number"),Xn("isOdd",e=>rt(e)&&Number.isInteger(e.value)&&1===Math.abs(e.value%2),"a whole odd number"),Xn("greaterThan",(e,n)=>rt(e)&&e.value>Number(n),"above a given value"),Xn("lessThan",(e,n)=>rt(e)&&e.value<Number(n),"below a given value"),Xn("isValue",(e,n)=>rt(e)&&e.value===Number(n),"equals a given number"),Xn("isNumeric",Ce,"contains no symbols: a constant (it need not fold to a number: 1 sin)"),Xn("hasSymbol",e=>!Ce(e),"mentions a symbol somewhere, so it is not just a number"),Xn("isVar",(e,n)=>e.type===ve&&e.token===String(n),"is exactly this symbol"),Xn("contains",(e,n)=>je(e).includes(String(n)),"mentions this operand somewhere"),Xn("isFree",(e,n)=>!je(e).includes(String(n)),"never mentions this operand"),Xn("hasOperation",(e,n)=>it(e,String(n)),"uses this operation somewhere inside"),Xn("equals",(e,n)=>e.s===String(n),"is exactly this postfix expression");const st=e=>e.type===be?null:e.token;function ot(e){if("string"==typeof e)return{name:e,args:[]};if(Array.isArray(e)&&e.length>0&&"string"==typeof e[0])return{name:e[0],args:e.slice(1)};throw new Yn(`bad requirement: ${JSON.stringify(e)}`)}et("freeOf",(e,n)=>{const t=st(n);return null!==t&&!je(e).includes(t)},"the first operand never mentions the second"),et("dependsOn",(e,n)=>{const t=st(n);return null!==t&&je(e).includes(t)},"the first operand does mention the second"),et("sameAs",(...e)=>e.every(n=>n.s===e[0].s),"these operands are structurally identical"),et("differs",(...e)=>new Set(e.map(e=>e.s)).size===e.length,"these operands are all different"),et("sameValue",(...e)=>e.every(e=>rt(e))&&e.every(n=>n.value===e[0].value),"these operands are the same number");const at="simplify";class lt extends Error{constructor(e,n){super(n?`rule "${n}": ${e}`:e),this.name="RuleError",this.ruleId=n}}const ut=/^[A-Za-z_][A-Za-z0-9_]*$/;function ct(e,n){if(Oe(e))return{literal:e.value};const t=e.token;if(t.startsWith("=")){const e=t.slice(1);if(""===e)throw new lt('"=" needs an operand after it',n);return{token:e}}if(!ut.test(t))throw new lt(`"${t}" is not a usable slot name; use letters, digits and _`,n);if(he(t))throw new lt(`slot name "${t}" collides with an operator`,n);return{name:t}}function pt(e){if(!Ae(e))return[e];const n=e.args.map(pt),t=fe(e.op),r=[];for(const i of function(e){let n=[[]];for(const t of e){const e=[];for(const r of n)for(const n of t)e.push(r.concat([n]));if(n=e,n.length>64)return n.slice(0,64)}return n}(n))if(r.push(Me(e.op,i)),t.commutative&&2===i.length&&i[0].s!==i[1].s&&r.push(Me(e.op,[i[1],i[0]])),r.length>=64)break;return r}function ft(e,n=[]){return"op"===e.kind?e.args.forEach(e=>ft(e,n)):"const"===e.kind&&e.free&&n.push(e.node.token),n}function ht(e){if(!e||"object"!=typeof e)throw new lt("rule must be a mapping");const n=e.id||e.name;if(!n)throw new lt("rule needs an id");if(!e.pattern)throw new lt("rule needs a pattern",n);if(void 0===e.output||null===e.output)throw new lt("rule needs an output",n);let t;try{t=Ne(String(e.pattern))}catch(e){if(e instanceof we)throw new lt(`bad pattern: ${e.message}`,n);throw e}const r=Kn(t).map(e=>ct(e,n)),i=new Set(r.filter(e=>e.name).map(e=>e.name)),s=function(e,n,t){const r=[],i=e.when||{};if("object"!=typeof i||Array.isArray(i))throw new lt('"when" must map slot names to lists of requirements',t);for(const[e,s]of Object.entries(i)){if(!n.has(e))throw new lt(`"when" mentions "${e}", which is not a slot in the pattern`,t);const i=Array.isArray(s)?s:[s];for(const n of i){const{name:i,args:s}=ot(n),o=nt(i);if(!o)throw new lt(`unknown requirement "${i}"`,t);r.push({slot:e,name:i,args:s,fn:o.fn})}}return r}(e,i,n),o=function(e,n,t){const r=[],i=e.require||[];if(!Array.isArray(i))throw new lt('"require" must be a list of relations',t);for(const e of i){const{name:i,args:s}=ot(e),o=tt(i);if(!o)throw new lt(`unknown relation "${i}"`,t);if(s.length<2)throw new lt(`relation "${i}" needs at least two operands`,t);for(const e of s)if("string"==typeof e&&!n.has(e)&&ut.test(e))throw new lt(`relation "${i}" mentions "${e}", which is not a slot in the pattern`,t);r.push({name:i,args:s,fn:o.fn})}return r}(e,i,n),a=function(e,n,t){let r;try{r=Ne(e)}catch(n){throw new lt(`bad output "${e}": ${n.message}`,t)}const i=e=>Ae(e)?{kind:"op",op:e.op,args:e.args.map(i)}:Oe(e)?{kind:"const",node:e}:n.has(e.token)?{kind:"slot",name:e.token}:e.token.startsWith("=")?{kind:"const",node:ke(e.token.slice(1))}:{kind:"const",node:e,free:!0};return i(r)}(String(e.output),i,n),l=e.commutative?pt(t):[t],u=[],c=new Set;for(const e of l){const t=Jn(e),r=Kn(e).map(e=>ct(e,n)),i=t+"\0"+r.map(e=>e.name??(void 0!==e.literal?`#${e.literal}`:`=${e.token}`)).join(",");c.has(i)||(c.add(i),u.push({key:t,slots:r}))}const p={id:String(n),name:e.name?String(e.name):String(n),pattern:String(e.pattern),patternTree:t,output:String(e.output),outputTemplate:a,explain:e.explain?String(e.explain).trim():"",mode:e.mode?String(e.mode):at,tags:Array.isArray(e.tags)?e.tags.map(String):[],priority:Number.isFinite(e.priority)?e.priority:0,fold:!!e.fold,commutative:!!e.commutative,enabled:void 0===e.enabled||!!e.enabled,when:s,require:o,slots:[...i],depth:Ee(t),bindings:u,freeSymbols:ft(a),source:e};for(const e of u)e.rule=p;return p}function dt(e){const n={};for(const t of e.when)(n[t.slot]||=[]).push(t.args.length?[t.name,...t.args]:t.name);const t={id:e.id};return e.name!==e.id&&(t.name=e.name),e.mode!==at&&(t.mode=e.mode),t.pattern=e.pattern,Object.keys(n).length&&(t.when=n),e.require.length&&(t.require=e.require.map(e=>[e.name,...e.args])),t.output=e.output,e.explain&&(t.explain=e.explain),e.fold&&(t.fold=!0),e.commutative&&(t.commutative=!0),e.priority&&(t.priority=e.priority),e.tags.length&&(t.tags=e.tags),e.enabled||(t.enabled=!1),t}class mt extends Error{constructor(e,n){super(null==n?e:`${e} (line ${n+1})`),this.name="YamlError",this.line=n}}class gt{constructor(e){this.records=e,this.i=0,this.pushed=[]}peek(){if(this.pushed.length)return this.pushed[this.pushed.length-1];for(;this.i<this.records.length&&this.records[this.i].blank;)this.i++;return this.i<this.records.length?this.records[this.i]:null}next(){if(this.pushed.length)return this.pushed.pop();const e=this.peek();return e&&this.i++,e}push(e){this.pushed.push(e)}}const vt=e=>"-"===e||e.startsWith("- ");function bt(e){let n=null,t=0;for(let r=0;r<e.length;r++){const i=e[r];if(n)i===n?"'"===n&&"'"===e[r+1]?r++:n=null:'"'===n&&"\\"===i&&r++;else if('"'===i||"'"===i)n=i;else if("["===i||"{"===i)t++;else if("]"===i||"}"===i)t--;else if(":"===i&&0===t&&(r+1===e.length||" "===e[r+1])){const n=e.slice(0,r).trim();return""===n?null:{key:yt(n),rest:e.slice(r+1).trim()}}}return null}function yt(e){return e.length>=2&&'"'===e[0]&&'"'===e[e.length-1]?JSON.parse(e):e.length>=2&&"'"===e[0]&&"'"===e[e.length-1]?e.slice(1,-1).replace(/''/g,"'"):e}function wt(e){const n=new gt(function(e){return String(e).split(/\r?\n/).map((e,n)=>{const t=e.search(/\S/);if(-1===t)return{raw:e,n:n,indent:0,text:"",blank:!0};const r=function(e){let n=null;for(let t=0;t<e.length;t++){const r=e[t];if(n)r===n?"'"===n&&"'"===e[t+1]?t++:n=null:'"'===n&&"\\"===r&&t++;else if('"'===r||"'"===r)n=r;else if("#"===r&&(0===t||/\s/.test(e[t-1])))return e.slice(0,t)}return e}(e.slice(t)).trimEnd();return{raw:e,n:n,indent:t,text:r,blank:""===r}})}(e));let t=n.peek();if(t&&"---"===t.text&&(n.next(),t=n.peek()),!t)return null;const r=kt(n,t.indent),i=n.peek();if(i&&"..."!==i.text&&"---"!==i.text)throw new mt(`unexpected content "${i.text}"`,i.n);return r}const xt=/^[|>][-+]?\d*$/;function kt(e,n){const t=e.peek();return!t||t.indent<n?null:vt(t.text)?qt(e,t.indent):bt(t.text)?function(e,n){const t={};for(;;){const r=e.peek();if(!r||r.indent!==n)break;const i=bt(r.text);if(!i)break;e.next();const{key:s,rest:o}=i;if(""===o){const r=e.peek();r&&r.indent>n?t[s]=kt(e,r.indent):r&&r.indent===n&&vt(r.text)?t[s]=qt(e,n):t[s]=null}else xt.test(o)?t[s]=$t(e,o,n):t[s]=St(o,r.n)}return t}(e,t.indent):(e.next(),xt.test(t.text)?$t(e,t.text,t.indent-1):St(t.text,t.n))}function qt(e,n){const t=[];for(;;){const r=e.peek();if(!r||r.indent!==n||!vt(r.text))break;if(e.next(),"-"===r.text){const r=e.peek();t.push(r&&r.indent>n?kt(e,r.indent):null);continue}if(xt.test(r.text.slice(2).trim())){t.push($t(e,r.text.slice(2).trim(),n));continue}const i=r.text.slice(2),s=n+2+(i.length-i.trimStart().length);e.push({raw:r.raw,n:r.n,indent:s,text:i.trim(),blank:!1}),t.push(kt(e,s))}return t}function $t(e,n,t){const r=n[0],i=(n.match(/[-+]/)||[""])[0],s=(n.match(/\d+/)||[null])[0];let o=s?t+Number(s):null;const a=[];for(;e.i<e.records.length;){const n=e.records[e.i];if(""===n.raw.trim()){a.push(""),e.i++;continue}const r=n.raw.search(/\S/);if(r<=t)break;if(null===o&&(o=r),r<o)break;a.push(n.raw.slice(o)),e.i++}for(;a.length&&""===a[a.length-1];)a.pop();let l;if("|"===r)l=a.join("\n");else{const e=[];for(const n of a)""===n?e.push("\n"):e.length&&"\n"!==e[e.length-1]?e[e.length-1]+=" "+n:e.push(n);l=e.join("").replace(/\n(?!$)/g,"\n")}return"-"===i?l:"+"===i?l+"\n":""===l?"":l+"\n"}function St(e,n){const t=e.trim();return""===t||"~"===t||"null"===t||"Null"===t||"NULL"===t?null:"true"===t||"True"===t||"TRUE"===t||"false"!==t&&"False"!==t&&"FALSE"!==t&&("["===t[0]||"{"===t[0]?function(e,n){const t={text:e,i:0,line:n},r=Ot(t);if(Mt(t),t.i<t.text.length)throw new mt(`unexpected "${t.text.slice(t.i)}" in flow value`,n);return r}(t,n):'"'===t[0]||"'"===t[0]?yt(t):/^[-+]?(\d+\.?\d*|\.\d+)([eE][-+]?\d+)?$/.test(t)?Number(t):t)}const Mt=e=>{for(;e.i<e.text.length&&/\s/.test(e.text[e.i]);)e.i++};function Ot(e){Mt(e);const n=e.text[e.i];return"["===n?function(e){e.i++;const n=[];for(;;){if(Mt(e),e.i>=e.text.length)throw new mt("unterminated [",e.line);if("]"===e.text[e.i])return e.i++,n;if(n.push(Ot(e)),Mt(e),","===e.text[e.i])e.i++;else if("]"!==e.text[e.i])throw new mt(`expected , or ] near "${e.text.slice(e.i)}"`,e.line)}}(e):"{"===n?function(e){e.i++;const n={};for(;;){if(Mt(e),e.i>=e.text.length)throw new mt("unterminated {",e.line);if("}"===e.text[e.i])return e.i++,n;const t=String(Ot(e));if(Mt(e),":"!==e.text[e.i])throw new mt(`expected : after "${t}"`,e.line);if(e.i++,n[t]=Ot(e),Mt(e),","===e.text[e.i])e.i++;else if("}"!==e.text[e.i])throw new mt(`expected , or } near "${e.text.slice(e.i)}"`,e.line)}}(e):St(function(e){const n=e.text[e.i];if('"'===n||"'"===n){const t=e.i;for(e.i++;e.i<e.text.length;)if("\\"===e.text[e.i]&&'"'===n)e.i+=2;else if(e.text[e.i]===n){if("'"!==n||"'"!==e.text[e.i+1])return e.i++,e.text.slice(t,e.i);e.i+=2}else e.i++;throw new mt("unterminated quoted string",e.line)}const t=e.i;for(;e.i<e.text.length;){const n=e.text[e.i];if(","===n||"]"===n||"}"===n)break;if(":"===n){const n=e.text[e.i+1];if(void 0===n||/[\s,\]}]/.test(n))break}e.i++}return e.text.slice(t,e.i).trim()}(e),e.line)}const At=/^(true|false|null|yes|no|on|off|~)$/i;function Nt(e){if(null==e)return"null";if("boolean"==typeof e)return e?"true":"false";if("number"==typeof e){if(!Number.isFinite(e))throw new mt(`cannot serialise ${e}`);return String(e)}const n=String(e);return function(e){return!!(""===e||/^\s|\s$/.test(e)||/[\u0000-\u001f\u007f]/.test(e)||/^[-?:,[\]{}#&*!|>'"%@`]/.test(e)||/: |\s#/.test(e)||At.test(e)||/^[-+]?(\d+\.?\d*|\.\d+)([eE][-+]?\d+)?$/.test(e))}(n)?JSON.stringify(n):n}const It=e=>null==e||"object"!=typeof e;function Et(e){return Array.isArray(e)?`[${e.map(Et).join(", ")}]`:e&&"object"==typeof e?`{${Object.entries(e).map(([e,n])=>`${Nt(e)}: ${Et(n)}`).join(", ")}}`:Nt(e)}function Tt(e){return Array.isArray(e)?!!e.every(e=>It(e)||Array.isArray(e)&&e.every(It))&&Et(e).length<=72:!(!e||"object"!=typeof e)&&(Object.values(e).every(e=>It(e)||Array.isArray(e)&&e.every(It))&&Et(e).length<=72)}function jt(e){const n=[];return Ct(e,0,n),n.length?n.join("\n")+"\n":""}function Ct(e,n,t){const r=" ".repeat(n);if(Array.isArray(e)){if(0===e.length)return void t.push(r+"[]");for(const r of e)Lt(r,n,t)}else{if(e&&"object"==typeof e){const i=Object.entries(e).filter(([,e])=>void 0!==e);if(0===i.length)return void t.push(r+"{}");for(const[e,r]of i)Zt(e,r,n,t);return}!function(e,n,t){if("string"==typeof e&&e.includes("\n")){t.push(n+"|-");for(const r of e.replace(/\n+$/,"").split("\n"))t.push(n+" "+r);return}t.push(n+Nt(e))}(e,r,t)}}function Lt(e,n,t){const r=" ".repeat(n);if(null!==e&&"object"==typeof e&&!Tt(e)){const i=[];if(Ct(e,n+2,i),0===i.length)return void t.push(r+"-");t.push(r+"- "+i[0].slice(n+2));for(let e=1;e<i.length;e++)t.push(i[e]);return}if(null===e||"object"!=typeof e)if("string"==typeof e&&e.includes("\n")){t.push(r+"- |-");for(const r of e.replace(/\n+$/,"").split("\n"))t.push(" ".repeat(n+4)+r)}else t.push(r+"- "+Nt(e));else t.push(r+"- "+Et(e))}function Zt(e,n,t,r){const i=" ".repeat(t),s=Nt(e);if("string"==typeof n&&n.includes("\n")){r.push(`${i}${s}: |-`);for(const e of n.replace(/\n+$/,"").split("\n"))r.push(" ".repeat(t+2)+e)}else{if(null!==n&&"object"==typeof n)return Tt(n)?void r.push(`${i}${s}: ${Et(n)}`):(r.push(`${i}${s}:`),void Ct(n,Array.isArray(n)?t:t+2,r));r.push(`${i}${s}: ${Nt(n)}`)}}class zt{constructor(e=[]){this.index=new Map,this.rules=[],this.maxDepth=0,this.name="",this.views=new Map;for(const n of e)this.add(n)}add(e){const n=e&&e.bindings?e:ht(e);if(this.rules.some(e=>e.id===n.id))throw new lt(`duplicate rule id "${n.id}"`);return this.rules.push(n),n.enabled&&this.link(n),n.depth>this.maxDepth&&(this.maxDepth=n.depth),this.views.clear(),n}view(e){if(!e)return this;let n=this.views.get(e);return n||(n=new zt(this.rules.filter(n=>n.mode===e)),n.name=this.name,this.views.set(e,n)),n}modes(){return[...new Set(this.rules.map(e=>e.mode))].sort((e,n)=>e===at?-1:n===at?1:e.localeCompare(n))}link(e){for(const n of e.bindings){let e=this.index.get(n.key);e||this.index.set(n.key,e=[]),e.push(n),e.sort((e,n)=>n.rule.priority-e.rule.priority||n.rule.depth-e.rule.depth)}}remove(e){const n=this.rules.findIndex(n=>n.id===e);return-1!==n&&(this.rules.splice(n,1),this.reindex(),!0)}setEnabled(e,n){const t=this.get(e);return!!t&&(t.enabled=!!n,this.reindex(),!0)}reindex(){this.index=new Map,this.maxDepth=0,this.views.clear();for(const e of this.rules)e.enabled&&this.link(e),e.depth>this.maxDepth&&(this.maxDepth=e.depth)}get(e){return this.rules.find(n=>n.id===e)||null}candidates(e){return this.index.get(e)||null}get size(){return this.rules.length}static fromYaml(e,{strict:n=!0}={}){const t=wt(e);return zt.fromSpecs(t,{strict:n})}static fromSpecs(e,{strict:n=!0}={}){let t=e,r="";if(e&&!Array.isArray(e)&&"object"==typeof e&&(t=e.rules,r=e.name?String(e.name):""),!Array.isArray(t))throw new lt('expected a list of rules, or a mapping with a "rules" list');const i=new zt;i.name=r;const s=[];for(let e=0;e<t.length;e++)try{i.add(t[e])}catch(n){s.push(`#${e+1}: ${n.message}`)}if(s.length&&n)throw new lt(`${s.length} rule(s) failed to compile:\n ${s.join("\n ")}`);return i.errors=s,i}toSpecs(){return this.rules.map(dt)}toYaml(){const e=this.toSpecs();return this.name?jt({name:this.name,rules:e}):jt(e)}keyReport(){return[...this.index.entries()].map(([e,n])=>({key:e,rules:n.map(e=>e.rule.id)})).sort((e,n)=>e.key.localeCompare(n.key))}}function Bt(e,n){const t=Object.create(null),r=e.slots;for(let e=0;e<r.length;e++){const i=r[e],s=n[e];if(void 0!==i.literal){if(!Oe(s)||s.value!==i.literal)return null;continue}if(void 0!==i.token){if(s.s!==i.token)return null;continue}const o=t[i.name];if(void 0!==o){if(o.s!==s.s)return null}else t[i.name]=s}return t}function Dt(e,n){for(const t of e.when){const e=n[t.slot];if(void 0===e)return!1;if(!t.fn(e,...t.args))return!1}for(const t of e.require){const e=t.args.map(e=>void 0!==n[e]?n[e]:e);if(!t.fn(...e))return!1}return!0}function Ft(e,n){return n.rule.priority-e.rule.priority||n.rule.depth-e.rule.depth}function Rt(e,n){const t=[];if(0===n.maxDepth)return t;for(const{key:r,slots:i}of function(e,n){const t=Hn(e,n),r=[];for(const e of t)e.key!==Wn&&r.push(e);return r}(e,n.maxDepth)){const e=n.candidates(r);if(e)for(const n of e){const e=Bt(n,i);e&&(Dt(n.rule,e)&&t.push({rule:n.rule,binding:n,key:r,bound:e}))}}return t.sort(Ft)}function Pt(e,n){switch(e.kind){case"slot":{const t=n[e.name];if(!t)throw new Error(`output references unbound slot "${e.name}"`);return t}case"const":return e.node;case"op":return Me(e.op,e.args.map(e=>Pt(e,n)));default:throw new Error(`bad output template: ${JSON.stringify(e)}`)}}const Vt=4e5,Wt=()=>new ze("a number too large to approximate"),Ut=e=>e<0n?-e:e;class _t{constructor(e){this.P=e,this.S=10n**BigInt(e),this.cache=new Map}fromQ(e){return e.n*this.S/e.d}mul(e,n){return e*n/this.S}div(e,n){if(0n===n)throw new ze("division by zero");return e*this.S/n}sqrt(e){if(e<0n)throw new ze("the square root of a negative number is not real");return We(e*this.S,2)}series(e,n){let t=0n,r=e;for(let e=1;0n!==r;e++)if(t+=r,r=n(r,e),e>1e5)throw new ze("a series did not converge");return t}atanhInv(e){const n=BigInt(e),t=n*n;let r=this.S/n,i=0n;for(let e=1n;0n!==r;e+=2n)i+=r/e,r/=t;return i}atanInv(e){const n=BigInt(e),t=n*n;let r=this.S/n,i=0n;for(let e=1n,n=1n;0n!==r;e+=2n,n=-n)i+=n*r/e,r/=t;return i}get pi(){return this.memo("pi",()=>16n*this.atanInv(5)-4n*this.atanInv(239))}get ln2(){return this.memo("ln2",()=>2n*this.atanhInv(3))}get e(){return this.memo("e",()=>this.exp(this.S))}memo(e,n){return this.cache.has(e)||this.cache.set(e,n()),this.cache.get(e)}exp(e){const n=(e+(e>=0n?this.ln2/2n:-this.ln2/2n))/this.ln2;if(n>BigInt(Vt))throw Wt();if(n<-BigInt(Vt))return 0n;const t=e-n*this.ln2,r=this.series(this.S,(e,n)=>e*t/this.S/BigInt(n));return n>=0n?r<<n:r>>-n}ln(e){if(e<=0n)throw new ze("the log of a number that is not positive is not real");let n=0n,t=e;for(;t>=this.S;)t>>=1n,n++;for(;t<this.S/2n;)t<<=1n,n--;const r=this.div(t-this.S,t+this.S),i=this.mul(r,r);let s=r,o=0n;for(let e=1n;0n!==s;e+=2n)o+=s/e,s=this.mul(s,i);return 2n*o+n*this.ln2}sin(e){const n=2n*this.pi;let t=e%n;t>this.pi&&(t-=n),t<-this.pi&&(t+=n);const r=this.mul(t,t);return this.series(t,(e,n)=>-e*r/this.S/BigInt(2*n*(2*n+1)))}cos(e){return this.sin(e+this.pi/2n)}atan(e){if(Ut(e)>this.S){const n=this.pi/2n;return(e>0n?n:-n)-this.atan(this.div(this.S,e))}let n=e;for(let e=0;e<2;e++)n=this.div(n,this.S+this.sqrt(this.S+this.mul(n,n)));const t=this.mul(n,n);let r=n,i=0n;for(let e=1n,n=1n;0n!==r;e+=2n,n=-n)i+=n*r/e,r=this.mul(r,t);return 4n*i}asin(e){if(Ut(e)>this.S)throw new ze("arcsin of a number beyond ±1 is not real");return Ut(e)===this.S?e>0n?this.pi/2n:-this.pi/2n:this.atan(this.div(e,this.sqrt(this.S-this.mul(e,e))))}}function Ht(e,n,t){if(t>0n)return e.atan(e.div(n,t));if(t<0n)return e.atan(e.div(n,t))+(n>=0n?e.pi:-e.pi);if(0n===n)throw new ze("the argument of 0 is undefined");return n>0n?e.pi/2n:-e.pi/2n}const Jt={add:(e,n)=>[e[0]+n[0],e[1]+n[1]],sub:(e,n)=>[e[0]-n[0],e[1]-n[1]],mul:(e,n,t)=>[e.mul(n[0],t[0])-e.mul(n[1],t[1]),e.mul(n[0],t[1])+e.mul(n[1],t[0])],div(e,n,t){const r=e.mul(t[0],t[0])+e.mul(t[1],t[1]);if(0n===r)throw new ze("division by zero");return[e.div(e.mul(n[0],t[0])+e.mul(n[1],t[1]),r),e.div(e.mul(n[1],t[0])-e.mul(n[0],t[1]),r)]},abs:(e,n)=>e.sqrt(e.mul(n[0],n[0])+e.mul(n[1],n[1])),exp(e,n){const t=e.exp(n[0]);return[e.mul(t,e.cos(n[1])),e.mul(t,e.sin(n[1]))]},ln(e,n){const t=Jt.abs(e,n);if(0n===t)throw new ze("the log of 0 is undefined");return[e.ln(t),Ht(e,n[1],n[0])]},pow(e,n,t,r){if(0n===n[0]&&0n===n[1])return[0n,0n];if(r&&r.isInteger){let t=r.n<0n?-r.n:r.n,i=[e.S,0n],s=n;for(;t>0n;)1n&t&&(i=Jt.mul(e,i,s)),s=Jt.mul(e,s,s),t>>=1n;return r.n<0n?Jt.div(e,[e.S,0n],i):i}return Jt.exp(e,Jt.mul(e,t,Jt.ln(e,n)))},sinh:(e,n)=>(e.exp(n)-e.exp(-n))/2n,cosh:(e,n)=>(e.exp(n)+e.exp(-n))/2n},Kt={sin:(e,[n,t])=>[e.mul(e.sin(n),Jt.cosh(e,t)),e.mul(e.cos(n),Jt.sinh(e,t))],cos:(e,[n,t])=>[e.mul(e.cos(n),Jt.cosh(e,t)),-e.mul(e.sin(n),Jt.sinh(e,t))],tan:(e,n)=>Jt.div(e,Kt.sin(e,n),Kt.cos(e,n)),ln:(e,n)=>Jt.ln(e,n),sqrt:(e,n)=>Jt.exp(e,Jt.mul(e,[e.S/2n,0n],Jt.ln(e,n))),sinh:(e,[n,t])=>[e.mul(Jt.sinh(e,n),e.cos(t)),e.mul(Jt.cosh(e,n),e.sin(t))],cosh:(e,[n,t])=>[e.mul(Jt.cosh(e,n),e.cos(t)),e.mul(Jt.sinh(e,n),e.sin(t))]},Gt=e=>({q:e}),Qt=([e,n])=>0n===n?{f:e}:{z:[e,n]};function Yt(e,n,t){const r=e=>((e,n)=>n.z??[Xt(e,n),0n])(t,n[e]);switch(e.op){case"+":return Qt(Jt.add(r(0),r(1)));case"-":return Qt(Jt.sub(r(0),r(1)));case"neg":return Qt([-r(0)[0],-r(0)[1]]);case"*":return Qt(Jt.mul(t,r(0),r(1)));case"/":return Qt(Jt.div(t,r(0),r(1)));case"^":return Qt(Jt.pow(t,r(0),r(1),n[1].q));case"sqrt":return Qt(Kt.sqrt(t,r(0)));case"root":return Qt(Jt.pow(t,r(1),Jt.div(t,[t.S,0n],r(0)),n[0].q?.inv()));case"abs":return{f:Jt.abs(t,r(0))};case"arg":return{f:Ht(t,r(0)[1],r(0)[0])};case"re":return{f:r(0)[0]};case"im":return{f:r(0)[1]};case"conj":return Qt([r(0)[0],-r(0)[1]]);case"log":return Qt(Jt.div(t,Jt.ln(t,r(1)),Jt.ln(t,r(0))));default:{const i=Kt[e.op];if(!i||1!==n.length)throw new ze(`no complex value for ${e.op}`);return Qt(i(t,r(0)))}}}function Xt(e,n){return n.q?e.fromQ(n.q):n.f}const er={sin:(e,n)=>e.sin(n),cos:(e,n)=>e.cos(n),tan:(e,n)=>e.div(e.sin(n),e.cos(n)),sec:(e,n)=>e.div(e.S,e.cos(n)),csc:(e,n)=>e.div(e.S,e.sin(n)),cot:(e,n)=>e.div(e.cos(n),e.sin(n)),arcsin:(e,n)=>e.asin(n),arccos:(e,n)=>e.pi/2n-e.asin(n),arctan:(e,n)=>e.atan(n),sinh:(e,n)=>(e.exp(n)-e.exp(-n))/2n,cosh:(e,n)=>(e.exp(n)+e.exp(-n))/2n,tanh:(e,n)=>{const t=e.exp(n),r=e.exp(-n);return e.div(t-r,t+r)},arcsinh:(e,n)=>e.ln(n+e.sqrt(e.mul(n,n)+e.S)),arccosh:(e,n)=>{if(n<e.S)throw new ze("arccosh of a number below 1 is not real");return e.ln(n+e.sqrt(e.mul(n,n)-e.S))},arctanh:(e,n)=>{if(Ut(n)>=e.S)throw new ze("arctanh of a number beyond ±1 is not real");return e.ln(e.div(e.S+n,e.S-n))/2n},ln:(e,n)=>e.ln(n),loglog:(e,n)=>e.ln(e.ln(n)),logloglog:(e,n)=>e.ln(e.ln(e.ln(n))),expm1:(e,n)=>e.exp(n)-e.S};function nr(e,n,t){if("num"===e.type)return Gt(Ve(e.token));if("sym"===e.type){if("pi"===e.token||"π"===e.token)return{f:n.pi};if("e"===e.token)return{f:n.e};if("i"===e.token&&Je.complex)return{z:[0n,n.S]};if(t&&e.token in t){const n=t[e.token],r="number"==typeof n||"string"==typeof n||"bigint"==typeof n?Ve(String(n)):null;if(!r)throw new ze(`the value of ${e.token} is not a number`);return Gt(r)}throw new ze(`${e.token} has no value`)}Je.complex&&e.op.startsWith("\\:")&&Mn[e.op.slice(2)]&&(e=Me(Mn[e.op.slice(2)],e.args));const r=e.args.map(e=>nr(e,n,t));if(r.some(e=>e.z)||["re","im","conj","arg"].includes(e.op)||function(e,n){if(!Je.complex)return!1;const t=e=>e.q?e.q.sign<0:void 0!==e.f&&e.f<0n;return"sqrt"===e.op||"ln"===e.op||"log"===e.op?t(n["log"===e.op?1:0])||"log"===e.op&&t(n[0]):"^"===e.op?t(n[0])&&!(n[1].q&&n[1].q.d%2n==1n):"root"===e.op&&t(n[1])&&!(n[0].q&&n[0].q.isInteger&&n[0].q.n%2n==1n)}(e,r))return Yt(e,r,n);const i=r.every(e=>e.q),s=e=>Xt(n,r[e]);switch(e.op){case"+":return i?Gt(r[0].q.add(r[1].q)):{f:s(0)+s(1)};case"-":return i?Gt(r[0].q.sub(r[1].q)):{f:s(0)-s(1)};case"neg":return r[0].q?Gt(r[0].q.neg()):{f:-r[0].f};case"*":return i?Gt(r[0].q.mul(r[1].q)):{f:n.mul(s(0),s(1))};case"/":return i?Gt(r[0].q.div(r[1].q)):{f:n.div(s(0),s(1))};case"^":return rr(n,r[0],r[1]);case"sqrt":return rr(n,r[0],Gt(Pe.HALF));case"root":return rr(n,r[1],r[0].q?Gt(r[0].q.inv()):{f:n.div(n.S,r[0].f)});case"abs":return r[0].q?Gt(r[0].q.abs()):{f:Ut(r[0].f)};case"floor":return Gt(r[0].q?r[0].q.floor():new Pe(tr(r[0].f,n.S)));case"ceil":return Gt(r[0].q?r[0].q.ceil():new Pe(-tr(-r[0].f,n.S)));case"log":return{f:n.div(n.ln(s(1)),n.ln(s(0)))};case"atan2":return{f:Ht(n,s(0),s(1))};case"max":case"min":if(!r.length)throw new ze(`${e.op} of nothing`);return i?Gt(r.map(e=>e.q).reduce((n,t)=>("max"===e.op?t.sub(n).sign>0:t.sub(n).sign<0)?t:n)):{f:r.map((e,n)=>s(n)).reduce((n,t)=>"max"===e.op?t>n?t:n:t<n?t:n)};case"sum":return i?Gt(r.reduce((e,n)=>e.add(n.q),Pe.ZERO)):{f:r.reduce((e,n,t)=>e+s(t),0n)};case"prod":return i?Gt(r.reduce((e,n)=>e.mul(n.q),Pe.ONE)):{f:r.reduce((e,t,r)=>n.mul(e,s(r)),n.S)};case"mean":if(!r.length)throw new ze("mean of nothing");return i?Gt(r.reduce((e,n)=>e.add(n.q),Pe.ZERO).div(new Pe(BigInt(r.length)))):{f:r.reduce((e,n,t)=>e+s(t),0n)/BigInt(r.length)};case"mod":{if(i){if(r[1].q.isZero)throw new ze("mod 0 is undefined");return Gt(r[0].q.sub(r[1].q.mul(r[0].q.div(r[1].q).floor())))}const e=s(1);if(0n===e)throw new ze("mod 0 is undefined");return{f:s(0)-n.mul(e,tr(n.div(s(0),e),n.S)*n.S)}}case"round":{if(!r[1].q?.isInteger)throw new ze("round needs a whole number of places");const e=10n**Ut(r[1].q.n),t=r[0].q??new Pe(s(0),n.S),i=r[1].q.sign>=0,o=(i?t.mul(new Pe(e)):t.div(new Pe(e))).add(Pe.HALF).floor();return Gt(i?o.div(new Pe(e)):o.mul(new Pe(e)))}case"!":{if(!r[0].q?.isInteger||r[0].q.sign<0)throw new ze("factorial is only worked out for whole numbers");let e=1n;for(let n=2n;n<=r[0].q.n;n++)if(e*=n,0n==(255n&n)&&Fe(e)>Vt)throw Wt();return Gt(new Pe(e))}default:{const t=er[e.op];if(!t||1!==r.length)throw new ze(`no numeric value for ${e.op}`);return{f:t(n,s(0))}}}}const tr=(e,n)=>{const t=e/n;return e<0n&&t*n!==e?t-1n:t};function rr(e,n,t){if(t.q&&t.q.isInteger){if(n.q)return Gt(n.q.pow(t.q.n));let r=t.q.n;const i=r<0n;i&&(r=-r);let s=e.S,o=n.f;for(;r>0n;){if(1n&r&&(s=e.mul(s,o)),o=e.mul(o,o),Fe(s)>Vt+4*e.P||Fe(o)>8e5){if(i)return{f:0n};throw Wt()}r>>=1n}return{f:i?e.div(e.S,s):s}}const r=Xt(e,n);if(0n===r){if(t.q?t.q.sign>0:t.f>0n)return Gt(Pe.ZERO);throw new ze("0 to a power that is not positive is undefined")}if(r<0n){if(t.q&&t.q.d%2n==1n){const n=rr(e,{f:-r},t).f;return{f:t.q.n%2n==0n?n:-n}}throw new ze("a negative number to a fractional power is not real")}if(t.q&&1n===Ut(t.q.n)&&t.q.d<=64n){const n=We(r*e.S**(t.q.d-1n),Number(t.q.d));return{f:t.q.n<0n?e.div(e.S,n):n}}return{f:e.exp(e.mul(Xt(e,t),e.ln(r)))}}function ir(e,n,t){const r=e<0n?"-":"",i=Ut(e);if(0n===i)return{sign:"",digits:"0",point:1};const s=i.toString(),o=s.length-n.P;let a=s.slice(0,t);s.length>t&&s[t]>="5"&&(a=(BigInt(a)+1n).toString());let l=o;return a.length>t&&(a=a.slice(0,t),l++),{sign:r,digits:a.replace(/0+$/,"")||"0",point:l}}function sr({sign:e,digits:n,point:t}){if("0"===n)return"0";if(t>21||t<-6){return`${e}${n.length>1?`${n[0]}.${n.slice(1)}`:n}e${t-1}`}return t<=0?`${e}0.${"0".repeat(-t)}${n}`:t>=n.length?`${e}${n}${"0".repeat(t-n.length)}`:`${e}${n.slice(0,t)}.${n.slice(t)}`}function or(e){let n=0n,t=0n,r=e.d;for(;r%2n==0n;)r/=2n,n++;for(;r%5n==0n;)r/=5n,t++;const i=n>t?n:t;let s=Ut(e.n)*10n**i/e.d;if(0n===s)return 1;for(;s%10n==0n;)s/=10n;return s.toString().length}function ar(e){let n=e.d;for(;n%2n==0n;)n/=2n;for(;n%5n==0n;)n/=5n;return 1n===n}function lr(e){const n=/^(-?[\d.]+)e(-?\d+)$/.exec(e);return n?Me("*",[qe(n[1]),Me("^",[qe("10"),qe(n[2])])]):qe(e)}function ur(e,{digits:n=15,scope:t}={}){if(!Number.isInteger(n)||n<1||n>1e5)throw new ze("digits must be a whole number from 1 to 100000");let r=n+25,i=null;for(let s=0;s<4;s++){const o=new _t(r),a=nr(e,o,t);if(a.z){const e=pr(a.z,o,n);if(e.retry&&s<3){r+=e.retry;continue}return void 0===e.real?e:cr(e.real,o,n,null)}if(a.q&&a.q.isInteger&&Ut(a.q.n).toString().length<=n)return{text:a.q.n.toString(),node:qe(a.q.n.toString()),number:Number(a.q.n),re:Number(a.q.n),im:0,exact:!0};const l=Xt(o,a);if(0n===l&&(!a.q||!a.q.isZero)&&s<3){i=null,r*=4;continue}const u=ir(l,o,n);if(i&&u.point<-10&&i.point-u.point>=(r-i.P)/2)return{text:"0",node:qe("0"),number:0,re:0,im:0,exact:!1};if(!(u.point<-10&&s<3)||i&&i.point===u.point)return cr(l,o,n,a.q);i={point:u.point,P:r},r+=10-u.point}throw new ze("could not approximate")}function cr(e,n,t,r){const i=sr(ir(e,n,t));return{text:i,node:lr(i),number:Number(i),re:Number(i),im:0,exact:Boolean(r)&&ar(r)&&or(r)<=t}}function pr([e,n],t,r){const i=10n**BigInt(Math.max(0,t.P-r-12)),s=e=>Ut(e)>i;if(!s(n))return{real:e};const o=ir(n,t,r);if(o.point<-10&&s(n))return{retry:10-o.point};const a=sr(o),l="1"===a?"i":"-1"===a?"-i":`${a}i`,u="1"===a?ke("i"):Me("*",[lr(a.replace(/^-/,"")),ke("i")]);if(!s(e))return{text:l,node:a.startsWith("-")?Me("neg",[u]):u,number:NaN,re:0,im:Number(a),exact:!1};const c=sr(ir(e,t,r)),p=a.startsWith("-"),f="1"===a.replace(/^-/,"")?ke("i"):Me("*",[lr(a.replace(/^-/,"")),ke("i")]);return{text:`${c} ${p?"-":"+"} ${l.replace(/^-/,"")}`,node:Me(p?"-":"+",[lr(c),f]),number:NaN,re:Number(c),im:Number(a),exact:!1}}function fr(e,n={}){const t=e=>(e=>0===Rn(e).size)(e)?"num"===e.type&&/^-?\d+$/.test(e.token)?e:ur(e,n).node:Ae(e)?Me(e.op,e.args.map(t)):e;return t(e)}const hr={variable:null},dr=(e,n)=>null!==n&&Rn(e).has(n);function mr(e){if("num"===e.type)return Ve(e.token);if(Ae(e)&&"/"===e.op&&e.args.every(e=>"num"===e.type)){const n=Ve(e.args[0].token),t=Ve(e.args[1].token);return n&&t&&!t.isZero?n.div(t):null}return null}const gr=e=>0===Rn(e).size;function vr(e,n,t){const r=function(e){const n=jn(e);return"num"===n.k?n.q.isZero?n.q:null:"atom"===n.k&&"sym"===n.node.type&&"pi"===n.node.token?Ve("1"):"mul"===n.k&&1===n.fs.length&&"atom"===n.fs[0].b.k&&"pi"===n.fs[0].b.node.token&&"num"===n.fs[0].e.k&&n.fs[0].e.q.isOne?n.c:null}(e);if(!r)return!1;const[i,s="1"]=String(n).split("/");return t(r.compare(Ve(i).div(Ve(s))))}function br(e){if(!gr(e))return NaN;try{const{number:n}=ur(e,{digits:30});return Math.sign(n)}catch{return NaN}}function yr(){nt("hasVariable")||(Xn("hasVariable",e=>dr(e,hr.variable),"mentions the variable being solved for"),Xn("freeOfVariable",e=>null!==hr.variable&&!dr(e,hr.variable),"does not mention the variable being solved for"),Xn("isRational",e=>null!==mr(e),"an exact number: 3, -2, 1/2"),Xn("isWhole",e=>mr(e)?.isInteger??!1,"a whole number (any size)"),Xn("isEvenWhole",e=>{const n=mr(e);return Boolean(n?.isInteger&&n.n%2n==0n)},"an even whole number"),Xn("isOddWhole",e=>{const n=mr(e);return Boolean(n?.isInteger&&n.n%2n!=0n)},"an odd whole number"),Xn("isPositiveRational",e=>(mr(e)?.sign??0)>0,"an exact number above 0"),Xn("isNegativeRational",e=>(mr(e)?.sign??0)<0,"an exact number below 0"),Xn("isConstant",gr,"has no unknowns (numbers, π and e only)"),Xn("notOne",e=>{const n=mr(e);return!n||!n.isOne},"anything except the number 1"),Xn("notMinusOne",e=>{const n=mr(e);return!n||!n.equals(Ve("-1"))},"anything except the number -1"),Xn("hasMinusSign",e=>function(e){const n=jn(e);return"num"===n.k?n.q.sign<0:"mul"===n.k&&n.c.sign<0}(e),"written with a leading minus: -x, -2x, -π/6"),Xn("piMultipleAtLeast",(e,n)=>vr(e,n,e=>e>=0),"a multiple of π, at least k·π"),Xn("piMultipleAbove",(e,n)=>vr(e,n,e=>e>0),"a multiple of π, above k·π"),Xn("piMultipleBelow",(e,n)=>vr(e,n,e=>e<0),"a multiple of π, below k·π"),Xn("piMultipleAtMost",(e,n)=>vr(e,n,e=>e<=0),"a multiple of π, at most k·π"),Xn("isPositiveConstant",e=>br(e)>0,"no unknowns, and above 0 (e, π, √2, 3)"),Xn("isNegativeConstant",e=>br(e)<0,"no unknowns, and below 0"),Xn("hasImaginaryPart",e=>{if(!Je.complex)return!1;const n=qn(jn(e));return Boolean(n)&&!("num"===n.im.k&&n.im.q.isZero)},"complex mode: has a nonzero imaginary part (unknowns count as real)"),Xn("isSymbolNode",e=>"sym"===e.type&&!He.has(e.token),"a single unknown such as x"))}function wr(e){const n=new Map;for(const t of e){const e=t.id??t.name;if(!e)throw new Error(`a rule needs an id (pattern ${t.pattern})`);n.set(String(e),{...n.get(String(e))??{},...t})}const t=[...n.values()].map(e=>{const n={...e};try{void 0!==n.pattern&&(n.pattern=function(e){const n=Ne(e),t=e=>"num"===e.type||("sym"===e.type?e.token.startsWith("="):e.args.every(t)),r=e=>"sym"===e.type?ke(e.token.slice(1)):"num"===e.type?e:Me(e.op,e.args.map(r)),i=e=>"sym"===e.type?ke(`=${e.token}`):"num"===e.type?e:Me(e.op,e.args.map(i)),s=e=>"op"!==e.type?e:t(e)?i(Cn(r(e))):Me(e.op,e.args.map(s));return s(n).s}(String(n.pattern)))}catch(e){throw new Error(`rule "${n.id}": bad pattern "${n.pattern}": ${e.message}`)}return"hidden"===n.step&&(n.tags=[...n.tags??[],"hidden"]),n});return zt.fromSpecs(t,{strict:!0})}function xr(e,n,t,r){return e.explain?e.explain.replace(/\{(\w+)\}/g,(e,i)=>"result"===i?t?r(t):e:n[i]?r(n[i]):e).trim():""}const kr=e=>Ae(e)&&("+"===e.op||"-"===e.op),qr=e=>Ae(e)&&("*"===e.op||"/"===e.op);function*$r(e,n,{order:t="pre"}={}){for(const r of function(e,n,{order:t="post"}={}){const r=[];for(const{node:i,path:s}of Le(e,t))for(const e of Rt(i,n))r.push({...e,node:i,path:s});return r}(e,n,{order:t})){const n=Pt(r.rule.outputTemplate,r.bound);yield{rule:r.rule,bound:r.bound,path:r.path,before:r.node,after:n,next:()=>Cn(Ze(e,r.path,n))}}for(const{node:r,path:i}of Le(e,t)){const t=kr(r);if(!t&&!qr(r))continue;const s=t?Pn(jn(r)):Vn(jn(r));if(s.length<3)continue;const o=t?dn:gn;for(let t=0;t<s.length;t++)for(let r=t+1;r<s.length;r++){const a=Bn(o([s[t],s[r]]));for(const l of Rt(a,n)){const n=Pt(l.rule.outputTemplate,l.bound),u=s.filter((e,n)=>n!==t&&n!==r);yield{rule:l.rule,bound:l.bound,path:i,before:a,after:n,next:()=>Cn(Ze(e,i,Bn(o([jn(n),...u]))))}}}}}function Sr(e,n,{format:t,order:r="pre",maxSteps:i=200,variable:s=null}={}){const o=hr.variable;hr.variable=s;try{let s=Cn(e);const o=new Set([s.s]),a=[];for(let e=0;e<i;e++){let e=null;for(const t of $r(s,n,{order:r})){const n=t.next();if(n.s!==s.s&&!o.has(n.s)){e={c:t,next:n};break}}if(!e)break;const{c:i,next:l}=e;a.push({id:i.rule.id,name:i.rule.name,tags:i.rule.tags,from:s.s,to:l.s,path:i.path,before:i.before.s,after:i.after.s,explanation:xr(i.rule,i.bound,Cn(i.after),t)}),s=l,o.add(s.s)}return{node:s,steps:a}}finally{hr.variable=o}}const Mr={full:[],normal:["hidden"],brief:["hidden","tidy","identity","value","split","base","arithmetic"]},Or=(e,n)=>"all"===n||"*"===n||Array.isArray(n)&&n.some(n=>n===e.id||e.tags?.includes(n));function Ar(e){if(!1===e)return null;if(void 0===e||!0===e)return{show:"all",hide:Mr.normal,explain:!0};if("string"==typeof e){if(!Mr[e])throw new Error(`steps: "${e}" is not one of ${Object.keys(Mr).join(", ")}`);return{show:"all",hide:Mr[e],explain:!0}}const n=e.detail??"normal";if(!Mr[n])throw new Error(`steps.detail: "${n}" is not one of ${Object.keys(Mr).join(", ")}`);return{show:e.show??"all",hide:[...Mr[n],...e.hide??[]],explain:e.explain??!0}}function Nr(e,n){if(!n)return[];const t=[];let r=null;for(const i of e){if(!(Or(i,n.show)&&!Or(i,n.hide))){r=r??{from:i.from,ids:[]},r.ids.push(i.id);continue}const e={...i};r&&(e.from=r.from,e.also=r.ids,e.path=null,r=null);!0===n.explain||!1!==n.explain&&Or(i,n.explain)||delete e.explanation,t.push(e)}if(r&&t.length){const n=t[t.length-1];n.to=e[e.length-1].to,n.also=[...n.also??[],...r.ids]}return t}const Ir=Ye(Pe.ONE),Er=(e,n)=>"atom"===e.k&&"sym"===e.node.type&&e.node.token===n;function Tr(e){switch(e.k){case"num":default:return e;case"atom":return"op"===e.node.type?En(e.node.op,e.node.args.map(e=>Tr(jn(e)))):e;case"add":return dn(Pn(e).map(Tr));case"mul":{let n=[Ye(e.c)];for(const t of e.fs){const e=Tr(t.b);if("add"===e.k&&tn(t.e)&&t.e.q.isInteger&&t.e.q.sign>0&&t.e.q.n<=BigInt(60))for(let r=0n;r<t.e.q.n;r++)n=jr(n,Pn(e));else n=jr(n,[bn(e,t.e)])}return dn(n)}}}function jr(e,n){const t=[];for(const r of e)for(const e of n)t.push(gn([r,e]));return Pn(dn(t))}function Cr(e,n){const t=new Map;for(const r of Pn(Tr(e))){const{coef:e,rest:i}=hn(r);let s=0;const o=[Ye(e)];for(const e of i?Vn(i):[]){const{b:t,e:r}="mul"===e.k&&1===e.fs.length&&e.c.isOne?e.fs[0]:{b:e,e:Ir};if(Er(t,n)){if(!tn(r)||!r.q.isInteger||r.q.sign<0)return null;s+=Number(r.q.n)}else{if(Lr(t,n)||Lr(r,n))return null;o.push(e)}}t.set(s,dn([t.get(s)??Ye(Pe.ZERO),gn(o)]))}for(const[e,n]of t)tn(n)&&n.q.isZero&&t.delete(e);return t}const Lr=(e,n)=>Rn(Bn(e)).has(n);function Zr(e){if(!e)return null;const n=Math.max(0,...e.keys());if(n>256)return null;const t=[];for(let r=0;r<=n;r++){const n=e.get(r)??Ye(Pe.ZERO);if(!tn(n))return null;t.push(n.q)}return t}function zr(e,n){const t=jn(ke(n));return dn(e.map((e,n)=>gn([Ye(e),vn(t,Ye(Pe.of(n)))])))}const Br=e=>{const n=e.slice();for(;n.length>1&&n[n.length-1].isZero;)n.pop();return n},Dr=(e,n)=>e.reduceRight((e,t)=>e.mul(n).add(t),Pe.ZERO);function Fr(e,n){const t=e.length-1,r=new Array(t);let i=Pe.ZERO;for(let s=t;s>=1;s--)i=e[s].add(i.mul(n)),r[s-1]=i;return r}function Rr(e){if(0n===(e=(e=>e<0n?-e:e)(e)))return null;if(e>10n**14n)return null;const n=[];let t=e;for(let e=2n;e*e<=t;e+=2n===e?1n:2n){if(t%e)continue;let r=0;for(;t%e===0n;)t/=e,r++;n.push([e,r])}t>1n&&n.push([t,1]);let r=[1n];for(const[e,t]of n){const n=[];for(const i of r)for(let r=0,s=1n;r<=t;r++,s*=e)n.push(i*s);if(r=n,r.length>2e4)return null}return r.sort((e,n)=>e<n?-1:e>n?1:0)}function Pr(e){let n=Br(e);const t=[];for(;n.length>1&&n[0].isZero;)t.push(Pe.ZERO),n=n.slice(1);if(n.length<=1)return{roots:t,rest:n};const r=n.reduce((e,n)=>e*n.d/Re(e,n.d),1n),i=n.map(e=>e.n*r/e.d),s=Rr(i[0]),o=Rr(i[i.length-1]);if(!s||!o)return{roots:t,rest:n};const a=new Map;for(const e of s)for(const n of o)for(const t of[1n,-1n]){const r=new Pe(t*e,n);a.set(r.toString(),r)}const l=[...a.values()].sort((e,n)=>e.compare(n));for(const e of l)for(;n.length>1&&Dr(n,e).isZero;)t.push(e),n=Fr(n,e);return{roots:t.sort((e,n)=>e.compare(n)),rest:n}}function Vr(e){if("num"===e.k)return{coef:e.q,factors:[],notes:[]};if("atom"===e.k)return{coef:Pe.ONE,factors:[{base:e,exp:Ir}],notes:[]};if("mul"===e.k){let n=e.c;const t=[],r=[];for(const i of e.fs)if("add"===i.b.k&&tn(i.e)&&i.e.q.isInteger){const e=Vr(i.b);n=n.mul(e.coef.pow(i.e.q.n));for(const n of e.factors)t.push({base:n.base,exp:gn([n.exp,i.e])});r.push(...e.notes)}else t.push({base:i.b,exp:i.e});return Wr(n,t,r)}return function(e){const n=Pn(e),t=[],r=n.map(e=>{const{coef:n,rest:t}=hn(e);return{coef:n,fs:t?Vn(t).map(_r):[]}}),i=r.reduce((e,n)=>({n:Re(e.n,n.coef.n),d:e.d*n.coef.d/Re(e.d,n.coef.d)}),{n:0n,d:1n});let s=new Pe(i.n||1n,i.d);Ur(e)<0&&(s=s.neg());const o=[];for(const e of r[0].fs){if(!tn(e.e)||e.e.q.sign<=0)continue;let n=e.e.q;const t=on(e.b);let i=!0;for(const e of r.slice(1)){const r=e.fs.find(e=>on(e.b)===t&&tn(e.e)&&e.e.q.sign>0);if(!r){i=!1;break}r.e.q.compare(n)<0&&(n=r.e.q)}i&&o.push({base:e.b,exp:Ye(n)})}let a=e;if(!s.isOne||o.length){const e=gn([Ye(s),...o.map(e=>bn(e.base,e.exp))]);a=dn(n.map(n=>gn([n,vn(e,Ye(Pe.MINUS_ONE))]))),t.push({id:"factor.common",values:{common:e}})}const l="add"===a.k?function(e,n){const t=[...Hr(e)];for(const r of t){const i=Zr(Cr(e,r));if(!i||i.length<3)continue;if(1!==t.length)break;const{roots:s,rest:o}=Pr(i);if(!s.length)break;const a=[];let l=o[o.length-1]??Pe.ONE;const u=o.map(e=>e.div(l)),c=[...s].sort((e,n)=>e.abs().compare(n.abs())||n.sign-e.sign);for(const e of c){const t=zr([new Pe(-e.n),new Pe(e.d)],r);a.push({base:t,exp:Ir}),l=l.div(new Pe(e.d)),n.push({id:"factor.root",values:{root:Ye(e),factor:t}})}if(u.length>1){const e=u.reduce((e,n)=>e*n.d/Re(e,n.d),1n),n=u.map(n=>n.mul(new Pe(e))),t=n.reduce((e,n)=>Re(e,n.n),0n)||1n;l=l.mul(new Pe(t,e)),a.push({base:zr(n.map(e=>e.div(new Pe(t))),r),exp:Ir})}return Wr(l,a,[])}const r=Pn(e);if(2===r.length){const[e,t]=r;for(const r of[2,3]){const i=Jr(e,r),s=Jr(On(t),r),o=3===r?Jr(t,r):null;if(i&&s&&2===r){n.push({id:"factor.squares",values:{a:i,b:s}});const e=Vr(dn([i,On(s)])),t=Vr(dn([i,s]));return Wr(e.coef.mul(t.coef),[...e.factors,...t.factors],[...e.notes,...t.notes])}if(3===r&&i&&(s||o)){const e=s??o,t=s?-1:1;n.push({id:t<0?"factor.cubes-difference":"factor.cubes-sum",values:{a:i,b:e}});const r=dn(t<0?[i,On(e)]:[i,e]),a=dn([vn(i,Ye(Pe.of(2))),t<0?gn([i,e]):On(gn([i,e])),vn(e,Ye(Pe.of(2)))]),l=Vr(r);return Wr(l.coef,[...l.factors,{base:a,exp:Ir}],l.notes)}}}return{coef:Pe.ONE,factors:[{base:e,exp:Ir}],notes:[]}}(a,t):Vr(a);return Wr(s.mul(l.coef),[...o,...l.factors],[...t,...l.notes.filter(e=>!t.includes(e))])}(e)}function Wr(e,n,t){const r=new Map;for(const e of n){const n=on(e.base),t=r.get(n);t?t.exp=dn([t.exp,e.exp]):r.set(n,{...e})}return{coef:e,factors:[...r.values()].filter(e=>!(tn(e.exp)&&e.exp.q.isZero)),notes:t}}const Ur=e=>hn(Pn(e)[0]).coef.sign;const _r=e=>"mul"===e.k&&e.c.isOne&&1===e.fs.length?{b:e.fs[0].b,e:e.fs[0].e}:{b:e,e:Ir},Hr=e=>Rn(Bn(e));function Jr(e,n){const{coef:t,rest:r}=hn(e);if(t.sign<0)return null;const i=function(e,n){const t=e=>{if(e<0n)return null;let t=0n,r=1n;for(;r**BigInt(n)<=e;)r*=2n;for(;t<r-1n;){const i=(t+r)/2n;i**BigInt(n)<=e?t=i:r=i}return t**BigInt(n)===e?t:null},r=t(e.n),i=t(e.d);return null!==r&&null!==i?new Pe(r,i):null}(t,n);if(!i)return null;const s=[Ye(i)];for(const e of r?Vn(r).map(_r):[]){if(!tn(e.e))return null;const t=e.e.q.div(Pe.of(n));if(!t.isInteger)return null;s.push(bn(e.b,Ye(t)))}return gn(s)}function Kr({coef:e,factors:n}){const t=[],r=[];for(const e of n){const n=tn(e.exp)&&e.exp.q.sign<0,i=n?Ye(e.exp.q.neg()):e.exp,s=Bn(bn(e.base,i));(n?r:t).push(s)}const i=e=>e.reduce((e,n)=>e?Me("*",[e,n]):n,null),s=e.n<0n?-e.n:e.n;let o=t.length?i(1n===s?t:[Bn(Ye(new Pe(s))),...t]):Bn(Ye(new Pe(s)));return e.n<0n&&(o=Me("neg",[o])),1n!==e.d&&r.unshift(Bn(Ye(new Pe(e.d)))),r.length?Me("/",[o,i(r)]):o}function Gr(e){if("mul"!==e.k)return{num:e,den:Ir};const n=[Ye(new Pe(e.c.n))],t=[Ye(new Pe(e.c.d))];for(const r of e.fs)tn(r.e)&&r.e.q.sign<0?t.push(bn(r.b,Ye(r.e.q.neg()))):n.push(bn(r.b,r.e));return{num:gn(n),den:gn(t)}}function Qr(e){if("add"!==e.k)return Gr(e);const n=Pn(e).map(Gr),t=new Map;let r=1n;for(const e of n){const{coef:n,rest:i}=hn(e.den);r=r*n.n/Re(r,n.n);for(const e of i?Vn(i).map(_r):[]){const n=on(e.b),r=t.get(n);(!r||tn(e.e)&&tn(r.e)&&e.e.q.compare(r.e.q)>0)&&t.set(n,e)}}const i=gn([Ye(new Pe(r)),...[...t.values()].map(e=>bn(e.b,e.e))]);if(tn(i)&&i.q.isOne)return{num:e,den:Ir};return{num:Tr(dn(n.map(e=>gn([e.num,i,vn(e.den,Ye(Pe.MINUS_ONE))])))),den:i}}function Yr(e){const{num:n,den:t}=Qr(e);if(tn(t)&&t.q.isOne)return null;const r=Vr(n),i=Vr(t),s=new Set(r.factors.map(e=>on(e.base))),o=i.factors.filter(e=>s.has(on(e.base))),a=[...r.factors,...i.factors.map(e=>({base:e.base,exp:On(e.exp)}))];return{...Wr(r.coef.div(i.coef),a,[...r.notes,...i.notes]),cancelled:o.map(e=>e.base)}}const Xr=(e,n)=>Me("=",[e,n]),ei=Cn(Me("+",[ke("x"),Me("neg",[ke("x")])])),ni=e=>Ae(e)&&"="===e.op;function ti(e,n,t,r={}){const i=[],s=(n,t,r,s,o,a={})=>i.push(e.step(n,t,r,s,o,a));s.raw=e=>i.push(e);const o=ni(n)?n:Xr(n,ei),a=Xr(Cn(o.args[0]),Cn(o.args[1]));a.s!==o.s&&s("normal","Work out each side",["tidy","arithmetic"],o,a);const l=[],u=[],c=new Set;l.numeric=c,li(e,a,t,r,s,l,u,0);const p=[],f=new Set;for(const n of l.map(n=>c.has(n)?n:(n=>Sr(n,e.set.view("simplify"),{format:e.format}).node)(n))){const e=n.s;if(f.has(e))continue;f.add(e);const r=c.has(n)?null:si(o,t,n);r?s("solve.reject","Check the answer",["check"],Xr(ke(t),n),Xr(ke(t),n),{value:n,reason:r}):p.push(n)}return p.sort(ri),{solutions:p,unsolved:u,steps:i,always:u.some(e=>e.always)}}function ri(e,n){const t=ii(e),r=ii(n);return null===t||null===r?e.s<n.s?-1:1:(Math.abs(t.im)>0)-(Math.abs(r.im)>0)||t.re-r.re||t.im-r.im}function ii(e){if(Rn(e).size)return null;try{const{re:n,im:t}=ur(e,{digits:20});return{re:n,im:t}}catch{return null}}function si(e,n,t){const[r,i]=e.args,s=new Set([...Rn(r),...Rn(i),...Rn(t)]);if(s.delete(n),s.size)return null;const o=e=>oi(e,n,t);try{const e=ur(o(r),{digits:40}),n=ur(o(i),{digits:40}),t=Math.max(1,Math.hypot(e.re,e.im),Math.hypot(n.re,n.im));return Math.hypot(e.re-n.re,e.im-n.im)>1e-12*t?"it does not make the two sides equal":null}catch(e){return`the original equation has no value there (${e.message})`}}function oi(e,n,t){return"sym"===e.type?e.token===n?t:e:Ae(e)?Me(e.op,e.args.map(e=>oi(e,n,t))):e}const ai=24;function li(e,n,t,r,i,s,o,a){if(a>ai)return mi(e,n,t,r,i,s,o);const l=function(e){const n=[],t=e=>{if(Ae(e)&&"|"===e.op)return void e.args.forEach(t);if(!ni(e))return void n.push(e);const r=e.args[1],i=Le(r,"pre").find(({node:e})=>Ae(e)&&"pm"===e.op);if(!i)return void n.push(e);const s=i.node.args[0],o=Cn(Ze(r,i.path,s)),a=Cn(Ze(r,i.path,Me("neg",[s])));t(Xr(e.args[0],o)),a.s!==o.s&&t(Xr(e.args[0],a))};return t(e),n}(n);if(l.length>1){i("solve.split","Two cases",["split"],n,l.reduce((e,n)=>e?Me("|",[e,n]):n,null));for(const n of l)li(e,n,t,r,i,s,o,a+1);return}if(1===l.length&&l[0].s!==n.s)return li(e,l[0],t,r,i,s,o,a+1);const[u,c]=n.args;if("sym"===u.type&&u.token===t&&!Lr(jn(c),t))return void s.push(c);const p=dn([jn(u),On(jn(c))]);if(!Lr(p,t))return tn(p)&&p.q.isZero?(i("solve.always","Always true",["check"],n,n,{v:t}),void o.push(Object.assign(Object.create(n),{always:!0}))):void i("solve.never","No solution",["check"],n,n,{v:t});const f=Pn(p).filter(e=>Lr(e,t)),h=Pn(p).filter(e=>!Lr(e,t)),d=dn(f),m=On(dn(h));if(Je.complex){const l=Cr(p,t);if(l&&[...l.values()].every(e=>!Lr(e,t))&&Math.max(...l.keys())>=2){const u=Xr(Bn(p),ei);return u.s!==n.s&&i("solve.one-side","Everything on one side",["move"],n,u,{v:t}),hi(e,p,l,t,r,i,s,o,a,u)}}if(1===f.length)return ui(e,n,d,m,t,r,i,s,o,a);const g=Xr(Bn(p),ei),v=Cr(p,t);if(v&&[...v.values()].every(e=>!Lr(e,t))&&Math.max(...v.keys())>=2)return g.s!==n.s&&i("solve.one-side","Everything on one side",["move"],n,g,{v:t}),hi(e,p,v,t,r,i,s,o,a,g);const b=Vr(p),y=b.factors.filter(e=>Lr(e.base,t)&&!(tn(e.exp)&&e.exp.q.sign<0));if(y.length>=2||1===y.length&&b.factors.length>1){const l=Xr(Kr(b),ei);g.s!==n.s&&i("solve.one-side","Everything on one side",["move"],n,g,{v:t}),l.s!==g.s&&i("solve.factor","Factor",["factor"],g,l,{});const u=y.map(e=>Xr(Bn(e.base),ei));u.length>1&&i("solve.zero-product","A product is zero when a factor is",["split"],l,u.reduce((e,n)=>e?Me("|",[e,n]):n,null),{});for(const n of u)li(e,n,t,r,i,s,o,a+1);return}const w=Qr(p);if(Lr(w.den,t)){const l=Xr(Bn(w.num),ei);return i("solve.clear-denominator","Clear the denominator",["move"],n,l,{den:Bn(w.den)}),li(e,l,t,r,i,s,o,a+1)}const x=f.filter(e=>!fi(e,t));if(1===x.length&&/\b(sqrt|root|abs)\b/.test(Bn(x[0]).s))return ui(e,n,x[0],On(dn(Pn(p).filter(e=>e!==x[0]))),t,r,i,s,o,a);const k=function(e,n){const t=Bn(e),r=new Map;for(const{node:e}of Le(t,"pre"))if(Ae(e)&&Rn(e).has(n))if("^"!==e.op||Rn(e.args[0]).has(n))["sin","cos","tan","ln","sqrt","abs"].includes(e.op)&&e.args[0].s===n&&r.set(e.s,e);else{const t=jn(e.args[1]),{coef:i,rest:s}=hn(t);if(s&&i.isInteger&&Bn(s).s===n){const t=Bn(vn(jn(e.args[0]),jn(ke(n))));r.set(t.s,t)}}const i="u"===n?"w":"u";for(const e of r.values()){const r=di(t,e,n,i);if(!r||Rn(r).has(n))continue;const s=jn(r),o=Cr(s,i);if(o&&Math.max(...o.keys())>=1)return{kernel:jn(e),poly:s,symbol:i}}return null}(p,t);if(k){const n=k.symbol;i("solve.substitute","Substitute",["substitute"],g,Xr(Bn(k.poly),ei),{u:ke(n),kernel:Bn(k.kernel)});const l=[];li(e,Xr(Bn(k.poly),ei),n,r,i,l,o,a+1);for(const n of l)li(e,Xr(Bn(k.kernel),n),t,r,i,s,o,a+1);return}return mi(e,g,t,r,i,s,o)}function ui(e,n,t,r,i,s,o,a,l,u){let c=Xr(Bn(t),Bn(r));c.s!==n.s&&o("solve.move","Move the terms",["move"],n,c,{v:i});const{coef:p,rest:f}=hn(t),h=f?Vn(f):[],d=gn([Ye(p),...h.filter(e=>!Lr(e,i))]);if(!tn(d)||!d.q.isOne){const e=gn(h.filter(e=>Lr(e,i))),n=Xr(Bn(e),Bn(An(r,d))),t=tn(d)&&!d.q.isInteger&&(1n===d.q.n||-1n===d.q.n);o(t?"solve.multiply":"solve.divide",t?"Multiply both sides":"Divide both sides",["move"],c,n,{by:Bn(t?Ye(d.q.inv()):d),v:i}),c=n}if("sym"===c.args[0].type&&c.args[0].token===i)return void a.push(c.args[1]);const m=jn(c.args[1]);if(tn(m)&&m.q.isZero){const n=jn(c.args[0]),t=Vn(n).filter(e=>Lr(e,i)&&!ci(e));if(t.length>1||t.length<Vn(n).filter(e=>Lr(e,i)).length){const n=t.map(e=>Xr(Bn(pi(e)),ei));o("solve.zero-product","A product is zero when a factor is",["split"],c,n.reduce((e,n)=>e?Me("|",[e,n]):n,null),{});for(const t of n)li(e,t,i,s,o,a,l,u+1);return}}const g=Sr(c,e.set.view("isolate"),{format:e.format,maxSteps:1,variable:i});return g.steps.length?(function(e,n){for(const t of n)e.raw(t)}(o,g.steps),li(e,g.node,i,s,o,a,l,u+1)):mi(e,c,i,s,o,a,l)}const ci=e=>"mul"===e.k&&e.c.isOne&&1===e.fs.length&&tn(e.fs[0].e)&&e.fs[0].e.q.sign<0,pi=e=>"mul"===e.k&&e.c.isOne&&1===e.fs.length&&tn(e.fs[0].e)&&e.fs[0].e.q.sign>0?e.fs[0].b:e,fi=(e,n)=>{const t=Cr(e,n);return Boolean(t)&&[...t.values()].every(e=>!Lr(e,n))};function hi(e,n,t,r,i,s,o,a,l,u){const c=Math.max(...t.keys()),p=Zr(t);if(Je.complex&&c>=3&&c<=64&&p&&p.every((e,n)=>0===n||n===c||e.isZero)&&!p[0].isZero){const n=p[0].neg().div(p[c]),t=vn(Ye(n.abs()),Ye(new Pe(1n,BigInt(c)))),i=[];for(let r=0;r<c;r++){const s=gn([Ye(new Pe(BigInt((n.sign<0?1:0)+2*r),BigInt(c))),jn(ke("pi"))]),o=Me("*",[Bn(t),Me("+",[Me("cos",[Bn(s)]),Me("*",[ke("i"),Me("sin",[Bn(s)])])])]);i.push(Sr(o,e.set.view("simplify"),{format:e.format}).node)}return s("solve.roots","All n roots",["complex"],u,i.map(e=>Xr(ke(r),e)).reduce((e,n)=>e?Me("|",[e,n]):n),{v:r,n:String(c),last:String(c-1),r:Bn(Ye(n))}),void o.push(...i)}if(p){const{roots:t}=Pr(p);if(t.length){const t=Vr(n),c=Xr(Kr(t),ei);if(t.factors.length>1||t.factors.some(e=>!(tn(e.exp)&&e.exp.q.isOne))){s("solve.factor","Factor",["factor"],u,c,{});const n=t.factors.filter(e=>Lr(e.base,r)).map(e=>Xr(Bn(e.base),ei));n.length>1&&s("solve.zero-product","A product is zero when a factor is",["split"],c,n.reduce((e,n)=>e?Me("|",[e,n]):n,null),{});for(const t of n)li(e,t,r,i,s,o,a,l+1);return}}}if(2===c){const e=t.get(2),n=t.get(1)??Ye(Pe.ZERO),i=t.get(0)??Ye(Pe.ZERO),a=dn([vn(n,Ye(Pe.of(2))),gn([Ye(Pe.of(-4)),e,i])]);if(tn(a)&&a.q.sign<0&&!Je.complex)return void s("solve.no-real","No real solutions",["quadratic"],u,u,{D:Bn(a)});const l=gn([Ye(Pe.of(2)),e]),c=vn(a,Ye(Pe.HALF)),p=Bn(An(dn([On(n),c]),l)),f=Bn(An(dn([On(n),On(c)]),l)),h=p.s===f.s?Xr(ke(r),p):Me("|",[Xr(ke(r),p),Xr(ke(r),f)]);return s(Je.complex&&tn(a)&&a.q.sign<0?"solve.quadratic-complex":"solve.quadratic","The quadratic formula",["quadratic"],u,h,{a:Bn(e),b:Bn(n),c:Bn(i),D:Bn(a),root:Bn(c),v:r}),o.push(p),void(f.s!==p.s&&o.push(f))}return mi(e,u,r,i,s,o,a)}function di(e,n,t,r){if(e.s===n.s)return ke(r);if(!Ae(e))return e;if("^"===e.op&&"^"===n.op&&e.args[0].s===n.args[0].s){const n=jn(e.args[1]),{coef:i,rest:s}=hn(n);if(s&&Bn(s).s===t&&i.isInteger)return Me("^",[ke(r),Bn(Ye(i))])}return Me(e.op,e.args.map(e=>di(e,n,t,r)))}function mi(e,n,t,r,i,s,o){if(r.approximate){const e="number"==typeof r.approximate?r.approximate:15,o=jn(Me("-",[n.args[0],n.args[1]])),a=Je.complex?Zr(Cr(o,t)):null,l=a&&a.length>2?function(e,n){const t=e.length-1,r=e[t],i=e.map(e=>e/r),s=(e,n)=>{let r=1,s=0;for(let o=t-1;o>=0;o--)[r,s]=[r*e-s*n+i[o],r*n+s*e];return[r,s]};let o=Array.from({length:t},(e,n)=>[1.3*Math.cos(2*Math.PI*n/t+.4),1.3*Math.sin(2*Math.PI*n/t+.4)]);for(let e=0;e<500;e++){let e=0;if(o=o.map(([n,r],i)=>{let[a,l]=s(n,r);for(let e=0;e<t;e++){if(e===i)continue;const t=n-o[e][0],s=r-o[e][1],u=t*t+s*s;[a,l]=[(a*t+l*s)/u,(l*t-a*s)/u]}return e=Math.max(e,Math.hypot(a,l)),[n-a,r-l]}),e<1e-15)break}const a=e=>Math.abs(e)<1e-12?0:Number(e.toPrecision(n));return o.map(([e,n])=>[a(e),a(n)]).sort((e,n)=>(0!==e[1])-(0!==n[1])||e[0]-n[0]||e[1]-n[1]).map(([e,n])=>{const t=gi(e);if(0===n)return t;const r=Me("*",[gi(Math.abs(n)),ke("i")]);return 0===e?n<0?Me("neg",[r]):r:Me(n<0?"-":"+",[t,r])})}(a.map(e=>e.toNumber()),Math.min(e,14)):function(e,n,t){const r=jn(Me("-",[e.args[0],e.args[1]])),i=Bn(r),s=e=>{try{return ur(oi(i,n,vi(e)),{digits:30}).number}catch{return NaN}},o=[],a=[];for(let e=-400;e<=400;e++)a.push(Math.sign(e)*(Math.abs(e)/20)**2);for(let e=0;e+1<a.length;e++){let n=a[e],r=a[e+1],i=s(n);const l=s(r);if(Number.isNaN(i)||Number.isNaN(l))continue;if(0===i){o.push(vi(n));continue}if(i*l>0)continue;for(let e=0;e<200&&r-n>1e-16*Math.abs(n);e++){const e=(n+r)/2,t=s(e);if(Number.isNaN(t))break;i*t<=0?r=e:(n=e,i=t)}const u=(n+r)/2;Math.abs(s(u))<1e-6&&o.push(vi(Number(u.toPrecision(Math.min(t,15)))))}return o}(n,t,e);for(const e of l)s.numeric?.add(e);return i("solve.numeric","Numeric solutions",["numeric"],n,l.length?l.map(e=>Xr(ke(t),e)).reduce((e,n)=>e?Me("|",[e,n]):n):n,{v:t,count:String(l.length)}),void s.push(...l)}i("solve.unsolved","No exact method",["unsolved"],n,n,{v:t}),o.push(n)}const gi=e=>qe(String(e).includes("e")?e.toFixed(20):String(e)),vi=e=>qe(Number.isInteger(e)?String(e):e.toFixed(17));const bi=(e,n)=>Me("int",[e,"string"==typeof n?ke(n):n]);function yi(e,n,t,r=0){if(r>6)throw new ze("integration went too deep");const i=[],s=e.set.view("integrate"),o=Sr(n,e.set.view("simplify"),{format:e.format});i.push(...o.steps);let a=Cn(bi(o.node,t));for(let n=0;n<40;n++){const n=Sr(a,s,{format:e.format});i.push(...n.steps),a=n.node;const t=Le(a,"pre").find(({node:e})=>{return Ae(n=e)&&"int"===n.op&&2===n.args.length;var n});if(!t)return{node:a,steps:i};const o=wi(e,t.node,r);if(!o)throw new ze(`no rule for ∫ ${e.format(t.node.args[0])} d${t.node.args[1].token}`);i.push(...o.steps),a=Cn(Ze(a,t.path,o.node))}throw new ze("integration did not finish")}function wi(e,n,t){const[r,i]=n.args,s=i.token,o=jn(r),a=function(e,n){const{num:t,den:r}=Qr(e),i=Vr(t),s=Vr(r),o=i.coef.div(s.coef);if(o.isOne||!Lr(e,n))return null;const a=gn([...i.factors.map(e=>bn(e.base,e.exp)),...s.factors.map(e=>bn(e.base,On(e.exp)))]);return{c:o,rest:a}}(o,s);if(a){const t=Me("*",[Bn(Ye(a.c)),bi(Bn(a.rest),i)]);return{node:t,steps:[e.step("integrate.constant","Take the number out",["split"],n,t,{c:Bn(Ye(a.c))})]}}const l=Tr(o);if(Bn(l).s!==r.s&&"add"===l.k){const t=bi(Bn(l),i);return{node:t,steps:[e.step("integrate.expand","Multiply out",["expand"],n,t,{})]}}const u=function(e,n){const t=new Map;for(const{node:r}of Le(e,"pre")){if(!Ae(r))continue;const e="^"===r.op?r.args:"/"===r.op?[r.args[1]]:"der"===r.op||"int"===r.op?[]:1===r.args.length||"root"===r.op?[r.args[r.args.length-1]]:[];for(const r of e){if("sym"===r.type||!Rn(r).has(n))continue;const e=Cr(jn(r),n);if(!e||1!==Math.max(...e.keys()))continue;const i=e.get(1);Lr(i,n)||tn(i)&&i.q.isZero||t.set(r.s,{node:r,a:i})}}for(const r of t.values()){if(!Rn(xi(e,r.node,ke("§"))).has(n))return r}return null}(r,s);if(u){const i="u"===s?"t":"u",o=xi(r,u.node,ke(i));if(!Rn(o).has(s)){const r=yi(e,Cn(o),i,t+1),a=Cn(oi(r.node,i,u.node)),l=Bn(An(jn(a),u.a));return{node:l,steps:[e.step("integrate.substitute","Substitute",["substitute"],n,Cn(bi(o,i)),{u:ke(i),inside:u.node,a:Bn(u.a),v:s}),...r.steps,e.step("integrate.back","Substitute back",["substitute"],r.node,l,{u:ke(i),inside:u.node})]}}}const c=function(e,n,t,r){const{num:i,den:s}=Qr(t);if(!Lr(s,r))return null;const o=Zr(Cr(i,r)),a=Zr(Cr(s,r));if(!o||!a||a.length<2)return null;const l=jn(ke(r)),u=e=>zr(e,r);if(o.length>=a.length){const{q:t,r:i}=function(e,n){const t=Br(n);let r=Br(e);const i=t[t.length-1];if(i.isZero)throw new ze("division by the zero polynomial");const s=new Array(Math.max(1,r.length-t.length+1)).fill(Pe.ZERO);for(;r.length>=t.length&&(1!==r.length||!r[0].isZero);){const e=r.length-t.length,n=r[r.length-1].div(i);if(s[e]=n,r=Br(r.map((r,i)=>i>=e&&i-e<t.length?r.sub(n.mul(t[i-e])):r)),r.length-1<e+t.length-1&&r[r.length-1].isZero)break;if(r.length<t.length)break}return{q:Br(s),r:r}}(o,a),s=bi(Bn(dn([u(t),An(u(i),u(a))])),ke(r));return{node:s,steps:[e.step("integrate.divide","Divide the polynomials",["divide"],n,s,{})]}}const{roots:c,rest:p}=Pr(a),f=new Set(c.map(String)).size===c.length;if(!c.length||!f||1!==p.length)return null;const h=(e=>e.length<=1?[Pe.ZERO]:e.slice(1).map((e,n)=>e.mul(Pe.of(n+1))))(a),d=c.map(e=>An(Ye(Dr(o,e).div(Dr(h,e))),dn([l,Ye(e.neg())]))),m=bi(Bn(dn(d)),ke(r));return{node:m,steps:[e.step("integrate.partial-fractions","Partial fractions",["partial-fractions"],n,m,{})]}}(e,n,o,s);return c||function(e,n,t,r,i){if(i>=6)return null;const s=Vn(t),o=s.filter(e=>ki(e,r)||!Lr(e,r)),a=s.filter(e=>!o.includes(e));if(1!==a.length)return null;const l=gn(o),u=a[0];if(!Lr(l,r))return null;const c=Bn(u),p=Ae(c)?c.op:"";let f,h,d;"ln"===p||"arctan"===p||"arcsin"===p?(f=u,h=l):(f=l,h=u);try{d=yi(e,Bn(h),r,i+1)}catch{return null}const m=jn(e.differentiate(Bn(f),r)),g=gn([f,jn(d.node)]),v=bi(Bn(gn([m,jn(d.node)])),ke(r)),b=Cn(Me("-",[Bn(g),v]));return{node:b,steps:[e.step("integrate.parts","Integration by parts",["parts"],n,b,{u:Bn(f),dv:Bn(h),V:d.node,du:Bn(m),v:r})]}}(e,n,o,s,t)}function xi(e,n,t){return e.s===n.s?t:Ae(e)?Me(e.op,e.args.map(e=>xi(e,n,t))):e}const ki=(e,n)=>{const t=Cr(e,n);return Boolean(t)&&[...t.values()].every(e=>!Lr(e,n))&&Math.max(...t.keys())>=1};function qi(e,n,t,r,i,s){for(const e of[r,i])if(Rn(e).has("∞")||/∞|infinity/.test(e.s))throw new ze("integrals to infinity need limits, which this CAS does not do yet");if(s&&!Rn(r).size&&!Rn(i).size){const o=ur(r,{digits:20}).number,a=ur(i,{digits:20}).number,l=[...Rn(s)].filter(e=>e!==t);if(!l.length){const[r,i]=o<=a?[o,a]:[a,o];for(const o of function(e,n){const t=[],r={tan:"cos",sec:"cos",csc:"sin",cot:"sin"};return Le(e,"pre").forEach(({node:e})=>{if(!Ae(e))return;let i=null;"/"===e.op?i=e.args[1]:"^"===e.op&&"num"===e.args[1].type&&e.args[1].value<0||"^"===e.op&&Ae(e.args[1])&&"neg"===e.args[1].op?i=e.args[0]:r[e.op]&&(i=Me(r[e.op],[e.args[0]])),i&&Rn(i).has(n)&&!t.some(e=>e.s===i.s)&&t.push(i)}),t}(s,t)){let s=[];try{s=e.solve(Me("=",[o,qe("0")]),t,{steps:!1}).solutions}catch{continue}for(const o of s){const s=ur(o,{digits:20});if(!Number.isFinite(s.number)||s.im||s.number<r||s.number>i)continue;if(s.number>r&&s.number<i)throw new ze(`the integrand has no value at ${t} = ${e.format(o)}, between the limits, so F(b) - F(a) would be wrong`);let a=NaN;try{a=ur(Cn(oi(n,t,o)),{digits:15}).number}catch{}if(!Number.isFinite(a))throw new ze(`the integral diverges at ${t} = ${e.format(o)}: F has no value at that limit`)}}}for(let e=0;!l.length&&e<=64;e++){const n=o+(a-o)*(e+.5)/65;try{const e=ur(oi(s,t,qe(n.toFixed(15))),{digits:15}).number;if(!Number.isFinite(e))throw new ze("not finite")}catch(e){throw new ze(`the integrand has no value at ${t} = ${n.toPrecision(6)}, between the limits, so F(b) - F(a) would be wrong`)}}}const o=e=>Cn(oi(n,t,e)),a=Cn(Me("-",[o(i),o(r)])),l=Me("-",[o(i),o(r)]);return{value:a,step:e.step("integrate.evaluate","Between the limits",["evaluate"],n,l,{a:r,b:i,F:n,v:t})}}const $i={"=":1,"≠":1,"<":1,">":1,"≤":1,"≥":1,"+":2,"-":2,"±":2,"*":3,"/":3,neg:4,pm:4,"^":5},Si={pi:"π","≤":"≤","≥":"≥"};function Mi(e){return Ei(e).text}function Oi(e,n,t=!1){return e.prec<n||t&&e.prec===n?`(${e.text})`:e.text}const Ai=e=>"op"===e.type?e.op:null,Ni=e=>e.text.startsWith("-"),Ii={"()":["(",")"],"[]":["[","]"],"{}":["{","}"],"(]":["(","]"],"[)":["[",")"]};function Ei(e){if("num"===e.type)return{text:e.token,prec:e.token.startsWith("-")?4:9};if("sym"===e.type)return{text:Si[e.token]??e.token,prec:9};const n=e.args.map(Ei),t=$i[e.op];switch(e.op){case"+":case"-":case"±":{const r="+"===e.op&&["+","-"].includes(Ai(e.args[1])),i=Ni(n[1])?`(${n[1].text})`:r?n[1].text:Oi(n[1],t,!0);return{text:`${Oi(n[0],t)} ${"±"===e.op?"±":e.op} ${i}`,prec:t}}case"*":{const r=Oi(n[0],t),i=Ni(n[1])?`(${n[1].text})`:"*"===Ai(e.args[1])?n[1].text:Oi(n[1],t,!0);return{text:"num"===e.args[0].type&&"num"!==e.args[1].type&&!/^[\d(-]/.test(i)||"sym"===e.args[1].type&&"i"===e.args[1].token&&!/[\dA-Za-z]$/.test(r)?`${r}${i}`:`${r}·${i}`,prec:t}}case"/":return{text:`${Oi(n[0],t)}/${Oi(n[1],t,!0)}`,prec:t};case"^":return{text:`${Oi(n[0],t+1)}^${Oi(n[1],t)}`,prec:t};case"neg":return{text:`-${Oi(n[0],3)}`,prec:4};case"pm":return{text:`±${Oi(n[0],4)}`,prec:4};case"!":return{text:`${Oi(n[0],9)}!`,prec:6};case"abs":return{text:`|${n[0].text}|`,prec:9};case"root":return{text:`root(${n[0].text}, ${n[1].text})`,prec:9};case"der":return{text:`d/d${n[1].text} (${n[0].text})`,prec:6};case"int":return{text:4===n.length?`∫ from ${n[2].text} to ${n[3].text} of ${n[0].text} d${n[1].text}`:`∫ ${n[0].text} d${n[1].text}`,prec:1};case"|":return{text:`${n[0].text} or ${n[1].text}`,prec:0};case"_":return{text:`${Oi(n[0],9)}_${n[1].prec>=9&&!/\s/.test(n[1].text)?n[1].text:`(${n[1].text})`}`,prec:9};case"()":case"[]":case"{}":case"(]":case"[)":return{text:`${Ii[e.op][0]}${n.map(e=>e.text).join(", ")}${Ii[e.op][1]}`,prec:9};case"&":return{text:`${n[0].text} and ${n[1].text}`,prec:0};default:return void 0!==t?{text:`${Oi(n[0],t)} ${e.op} ${Oi(n[1],t,!0)}`,prec:t}:{text:`${e.op.replace(/^\\:?/,"")}(${n.map(e=>e.text).join(", ")})`,prec:9}}}const Ti=['name: Differentiation\n\n# `u v der` means d(u)/dv (MathZetta\'s postfix: mathzetta/docs/postfix.md). Every rule here rewrites one derivative into smaller\n# derivatives, so differentiating always terminates: the expressions sitting\n# under a `D` get strictly smaller at every step.\n#\n# The variable is a slot, not a fixed letter, so these rules work for d/dx,\n# d/dt or anything else. That is what freeOf and dependsOn are for: they ask\n# whether one operand mentions whatever the variable slot bound to.\n#\n# Where two rules share a structure key, requirements keep them apart and\n# priority picks the one that reads better. The constant-multiple rule outranks\n# the product rule for exactly that reason.\n\nrules:\n # ---- the two base cases ----------------------------------------------\n - id: d-constant\n name: Derivative of a constant\n mode: differentiate\n pattern: c v der\n require:\n - [freeOf, c, v]\n output: "0"\n priority: 10\n explain: "{c} does not change when {v} changes, so its rate of change is 0."\n tags: [base]\n\n - id: d-variable\n name: Derivative of the variable\n mode: differentiate\n pattern: u v der\n require:\n - [sameAs, u, v]\n output: "1"\n priority: 10\n explain: "{v} changes exactly as fast as itself, so the rate is 1."\n tags: [base]\n\n # ---- splitting a derivative into smaller ones ------------------------\n - id: d-sum\n name: Sum rule\n mode: differentiate\n pattern: u w + v der\n output: u v der w v der +\n explain: "Differentiate {u} and {w} separately, then add the two results."\n tags: [split]\n\n - id: d-difference\n name: Difference rule\n mode: differentiate\n pattern: u w - v der\n output: u v der w v der -\n explain: "Differentiate {u} and {w} separately, then subtract the second from the first."\n tags: [split]\n\n - id: d-negate\n name: Derivative of a negative\n mode: differentiate\n pattern: u neg v der\n output: u v der neg\n explain: "The minus sign just carries through to the derivative of {u}."\n tags: [split]\n\n - id: d-constant-multiple\n name: Constant multiple rule\n mode: differentiate\n pattern: c u * v der\n commutative: true\n require:\n - [freeOf, c, v]\n - [dependsOn, u, v]\n output: c u v der *\n priority: 5\n explain: "{c} is only a scale factor, so it comes along unchanged while {u} is differentiated."\n tags: [split]\n\n - id: d-constant-divisor\n name: Dividing by a constant\n mode: differentiate\n pattern: u c / v der\n require:\n - [freeOf, c, v]\n output: u v der c /\n priority: 5\n explain: "Dividing by {c} is only a scale factor, so differentiate {u} and keep the division."\n tags: [split]\n\n - id: d-product\n name: Product rule\n mode: differentiate\n pattern: u w * v der\n require:\n - [dependsOn, u, v]\n - [dependsOn, w, v]\n output: u v der w * u w v der * +\n explain: "Differentiate {u} and keep {w}, then keep {u} and differentiate {w}, and add the two."\n tags: [split]\n\n - id: d-quotient\n name: Quotient rule\n mode: differentiate\n pattern: u w / v der\n output: u v der w * u w v der * - w 2 ^ /\n explain: "Bottom times the derivative of the top, minus top times the derivative of the bottom, all over {w} squared."\n tags: [split]\n\n # ---- powers -----------------------------------------------------------\n - id: d-power-of-variable\n name: Power rule\n mode: differentiate\n pattern: u n ^ v der\n require:\n - [sameAs, u, v]\n - [freeOf, n, v]\n output: n u n 1 - ^ *\n fold: true\n priority: 6\n explain: "Bring the {n} down in front and drop the power by one."\n tags: [power]\n\n - id: d-power-chain\n name: Power rule with the chain rule\n mode: differentiate\n pattern: u n ^ v der\n require:\n - [freeOf, n, v]\n - [dependsOn, u, v]\n output: n u n 1 - ^ * u v der *\n fold: true\n explain: "Bring the {n} down and drop the power by one, then multiply by the derivative of {u}."\n tags: [power, chain]\n\n - id: d-exponential-base\n name: Derivative of a constant to a power\n mode: differentiate\n pattern: a u ^ v der\n require:\n - [freeOf, a, v]\n - [dependsOn, u, v]\n output: a u ^ a ln * u v der *\n explain: "A constant base gives itself back, multiplied by the natural log of {a} and the derivative of {u}."\n tags: [power, chain]\n\n # ---- the standard functions, each with its chain-rule factor ---------\n # e^u is `=e u ^`: the base is the literal symbol e. Outranks the general\n # a^u rule (which would give e^u · ln e · u\').\n - id: d-exp\n name: Derivative of e to a power\n mode: differentiate\n pattern: =e u ^ v der\n require:\n - [dependsOn, u, v]\n output: =e u ^ u v der *\n priority: 7\n explain: "e to a power is its own derivative, times the derivative of {u}."\n tags: [chain]\n\n - id: d-ln\n name: Derivative of a natural log\n mode: differentiate\n pattern: u ln v der\n output: u v der u /\n explain: "The derivative of {u} over {u} itself."\n tags: [chain]\n\n - id: d-sqrt\n name: Derivative of a square root\n mode: differentiate\n pattern: u sqrt v der\n output: u v der 2 u sqrt * /\n explain: "The derivative of {u}, over twice the square root of {u}."\n tags: [chain]\n\n - id: d-sin\n name: Derivative of sine\n mode: differentiate\n pattern: u sin v der\n output: u cos u v der *\n explain: "Sine differentiates to cosine, times the derivative of {u}."\n tags: [chain, trig]\n\n - id: d-cos\n name: Derivative of cosine\n mode: differentiate\n pattern: u cos v der\n output: u sin u v der * neg\n explain: "Cosine differentiates to minus sine, times the derivative of {u}."\n tags: [chain, trig]\n\n - id: d-tan\n name: Derivative of tangent\n mode: differentiate\n pattern: u tan v der\n output: u v der u cos 2 ^ /\n explain: "The derivative of {u}, over cosine squared of {u}."\n tags: [chain, trig]\n\n # ---- the rest of the standard functions -----------------------------\n - id: d-csc\n name: Derivative of cosecant\n mode: differentiate\n pattern: u csc v der\n output: u csc u cot * u v der * neg\n explain: "Cosecant differentiates to minus cosecant times cotangent, times the derivative of {u}."\n tags: [chain, trig]\n\n - id: d-sec\n name: Derivative of secant\n mode: differentiate\n pattern: u sec v der\n output: u sec u tan * u v der *\n explain: "Secant differentiates to secant times tangent, times the derivative of {u}."\n tags: [chain, trig]\n\n - id: d-cot\n name: Derivative of cotangent\n mode: differentiate\n pattern: u cot v der\n output: u v der u sin 2 ^ / neg\n explain: "Minus the derivative of {u}, over sine squared of {u}."\n tags: [chain, trig]\n\n - id: d-arcsin\n name: Derivative of arcsine\n mode: differentiate\n pattern: u arcsin v der\n output: u v der 1 u 2 ^ - sqrt /\n explain: "The derivative of {u}, over the square root of 1 minus {u} squared."\n tags: [chain, trig]\n\n - id: d-arccos\n name: Derivative of arccosine\n mode: differentiate\n pattern: u arccos v der\n output: u v der 1 u 2 ^ - sqrt / neg\n explain: "Minus the derivative of {u}, over the square root of 1 minus {u} squared."\n tags: [chain, trig]\n\n - id: d-arctan\n name: Derivative of arctangent\n mode: differentiate\n pattern: u arctan v der\n output: u v der 1 u 2 ^ + /\n explain: "The derivative of {u}, over 1 plus {u} squared."\n tags: [chain, trig]\n\n - id: d-sinh\n name: Derivative of hyperbolic sine\n mode: differentiate\n pattern: u sinh v der\n output: u cosh u v der *\n explain: "Hyperbolic sine differentiates to hyperbolic cosine, times the derivative of {u}."\n tags: [chain, hyperbolic]\n\n - id: d-cosh\n name: Derivative of hyperbolic cosine\n mode: differentiate\n pattern: u cosh v der\n output: u sinh u v der *\n explain: "Hyperbolic cosine differentiates to hyperbolic sine — no minus sign, unlike cosine — times the derivative of {u}."\n tags: [chain, hyperbolic]\n\n - id: d-tanh\n name: Derivative of hyperbolic tangent\n mode: differentiate\n pattern: u tanh v der\n output: u v der u cosh 2 ^ /\n explain: "The derivative of {u}, over hyperbolic cosine squared of {u}."\n tags: [chain, hyperbolic]\n\n - id: d-arcsinh\n name: Derivative of inverse hyperbolic sine\n mode: differentiate\n pattern: u arcsinh v der\n output: u v der u 2 ^ 1 + sqrt /\n explain: "The derivative of {u}, over the square root of {u} squared plus 1."\n tags: [chain, hyperbolic]\n\n - id: d-arccosh\n name: Derivative of inverse hyperbolic cosine\n mode: differentiate\n pattern: u arccosh v der\n output: u v der u 2 ^ 1 - sqrt /\n explain: "The derivative of {u}, over the square root of {u} squared minus 1."\n tags: [chain, hyperbolic]\n\n - id: d-arctanh\n name: Derivative of inverse hyperbolic tangent\n mode: differentiate\n pattern: u arctanh v der\n output: u v der 1 u 2 ^ - /\n explain: "The derivative of {u}, over 1 minus {u} squared."\n tags: [chain, hyperbolic]\n\n # log base a: `a u log` in MathZetta\'s postfix\n - id: d-log\n name: Derivative of a logarithm\n mode: differentiate\n pattern: a u log v der\n require:\n - [freeOf, a, v]\n output: u v der u a ln * /\n explain: "The derivative of {u}, over {u} times the natural log of {a}."\n tags: [chain]\n\n - id: d-abs\n name: Derivative of an absolute value\n mode: differentiate\n pattern: u abs v der\n output: u u abs / u v der *\n explain: "The absolute value keeps the sign of {u}: {u} over its absolute value, times the derivative of {u}."\n tags: [chain]\n\n # n-th root: `n u root`\n - id: d-root\n name: Derivative of a root\n mode: differentiate\n pattern: n u root v der\n require:\n - [freeOf, n, v]\n output: u v der n n u root n 1 - ^ * /\n fold: true\n explain: "The derivative of {u}, over {n} times the {n}th root of {u} to the power {n} minus 1."\n tags: [chain]\n','name: More derivatives\n\n# Derivative rules the CAS adds to rules/calculus.yaml (which calcvidnew also uses).\n\nrules:\n - id: d-general-power\n name: A power with the variable in both places\n mode: differentiate\n pattern: u w ^ v der\n require:\n - [dependsOn, u, v]\n - [dependsOn, w, v]\n output: u w ^ w v der u ln * w u v der * u / + *\n explain: "Write {u}^{w} as e^({w} ln {u}) and use the chain rule: the derivative is {u}^{w} times the derivative of {w} ln {u}."\n tags: [chain]\n','name: Integrals\n\n# mode: integrate. `f v 2 int` is ∫ f dv (MathZetta\'s postfix; the 2 counts f and v).\n# Each rule turns one integral into smaller ones, or into an answer. The CAS also\n# tries, when no rule fits: multiplying out, a linear substitution (∫ f(ax + b) dx\n# from the rule for ∫ f(u) du), and integration by parts for polynomial × e^, sin,\n# cos, ln, arctan. Definite integrals are the antiderivative between the limits.\n#\n# Patterns see the normal form: 1/x is "1 x /", x^-2 is "1 x 2 ^ /", √x is "x sqrt",\n# 1/√(1 - x²) is "1 x 2 ^ neg 1 + sqrt /".\n\nrules:\n # ---- splitting -----------------------------------------------------------\n - id: i-sum\n name: Sum rule\n mode: integrate\n pattern: u w + v 2 int\n output: u v 2 int w v 2 int +\n explain: "Integrate {u} and {w} separately, and add."\n tags: [split]\n\n - id: i-difference\n name: Difference rule\n mode: integrate\n pattern: u w - v 2 int\n output: u v 2 int w v 2 int -\n explain: "Integrate {u} and {w} separately, and subtract."\n tags: [split]\n\n - id: i-negate\n name: A minus sign\n mode: integrate\n pattern: u neg v 2 int\n output: u v 2 int neg\n explain: "The minus sign comes out of the integral."\n tags: [split]\n\n - id: i-constant-multiple\n name: Constant multiple\n mode: integrate\n pattern: c u * v 2 int\n commutative: true\n require:\n - [freeOf, c, v]\n - [dependsOn, u, v]\n output: c u v 2 int *\n priority: 5\n explain: "{c} doesn\'t change with {v}, so it comes out of the integral."\n tags: [split]\n\n - id: i-constant-divisor\n name: Dividing by a constant\n mode: integrate\n pattern: u c / v 2 int\n require:\n - [freeOf, c, v]\n - [dependsOn, u, v]\n output: u v 2 int c /\n priority: 5\n explain: "Dividing by {c} comes out of the integral."\n tags: [split]\n\n - id: i-constant-over\n name: A constant over something\n mode: integrate\n pattern: c u / v 2 int\n require:\n - [freeOf, c, v]\n - [dependsOn, u, v]\n when:\n c: [notOne]\n output: c 1 u / v 2 int *\n priority: 4\n explain: "{c} comes out of the integral, leaving ∫ 1/{u}."\n tags: [split]\n\n # ---- the table -----------------------------------------------------------\n - id: i-constant\n name: Integral of a constant\n mode: integrate\n pattern: c v 2 int\n require:\n - [freeOf, c, v]\n output: c v *\n priority: 10\n explain: "A constant {c} integrates to {c}·{v}."\n tags: [base]\n\n - id: i-variable\n name: Integral of the variable\n mode: integrate\n pattern: u v 2 int\n require:\n - [sameAs, u, v]\n output: v 2 ^ 2 /\n priority: 10\n explain: "∫ {v} d{v} = {v}²/2."\n tags: [base]\n\n - id: i-power\n name: Power rule\n mode: integrate\n pattern: u n ^ v 2 int\n require:\n - [sameAs, u, v]\n - [freeOf, n, v]\n when:\n n: [notMinusOne]\n output: v n 1 + ^ n 1 + /\n explain: "Add 1 to the power and divide by the new power: {result}."\n tags: [power]\n\n - id: i-reciprocal\n name: Integral of 1/x\n mode: integrate\n pattern: 1 u / v 2 int\n require:\n - [sameAs, u, v]\n output: v abs ln\n explain: "∫ 1/{v} d{v} = ln|{v}| (the power rule can\'t divide by 0 here)."\n tags: [log]\n\n - id: i-reciprocal-power\n name: Power rule (a power below)\n mode: integrate\n pattern: 1 u n ^ / v 2 int\n require:\n - [sameAs, u, v]\n - [freeOf, n, v]\n when:\n n: [notOne]\n output: v 1 n - ^ 1 n - /\n explain: "1/{v}^{n} is {v}^(-{n}): add 1 to the power and divide by it."\n tags: [power]\n\n - id: i-sqrt\n name: Integral of a square root\n mode: integrate\n pattern: u sqrt v 2 int\n require:\n - [sameAs, u, v]\n output: 2 v 3 2 / ^ * 3 /\n explain: "√{v} is {v}^(1/2): add 1 to the power and divide by 3/2."\n tags: [power]\n\n - id: i-reciprocal-sqrt\n name: Integral of 1/√x\n mode: integrate\n pattern: 1 u sqrt / v 2 int\n require:\n - [sameAs, u, v]\n output: 2 v sqrt *\n explain: "1/√{v} is {v}^(-1/2): add 1 to the power and divide by 1/2."\n tags: [power]\n\n - id: i-root\n name: Integral of a root\n mode: integrate\n pattern: n u root v 2 int\n require:\n - [sameAs, u, v]\n - [freeOf, n, v]\n output: v 1 n / 1 + ^ 1 n / 1 + /\n explain: "The {n}th root of {v} is {v}^(1/{n}): add 1 to the power and divide by it."\n tags: [power]\n\n - id: i-exp\n name: Integral of e^x\n mode: integrate\n pattern: =e u ^ v 2 int\n require:\n - [sameAs, u, v]\n output: =e v ^\n explain: "e^{v} is its own integral."\n tags: [exp]\n\n - id: i-exponential\n name: Integral of a^x\n mode: integrate\n pattern: a u ^ v 2 int\n require:\n - [sameAs, u, v]\n - [freeOf, a, v]\n output: a v ^ a ln /\n explain: "∫ {a}^{v} d{v} = {a}^{v} / ln {a}."\n tags: [exp]\n\n - id: i-ln\n name: Integral of ln x\n mode: integrate\n pattern: u ln v 2 int\n require:\n - [sameAs, u, v]\n output: v v ln * v -\n explain: "By parts: ∫ ln {v} d{v} = {v} ln {v} - {v}."\n tags: [log]\n\n - { id: i-sin, name: Integral of sin, mode: integrate, pattern: u sin v 2 int, require: [[sameAs, u, v]], output: v cos neg, tags: [trig], explain: "The derivative of -cos {v} is sin {v}." }\n - { id: i-cos, name: Integral of cos, mode: integrate, pattern: u cos v 2 int, require: [[sameAs, u, v]], output: v sin, tags: [trig], explain: "The derivative of sin {v} is cos {v}." }\n - { id: i-tan, name: Integral of tan, mode: integrate, pattern: u tan v 2 int, require: [[sameAs, u, v]], output: v cos abs ln neg, tags: [trig], explain: "tan = sin/cos, and -ln|cos {v}| differentiates to it." }\n - { id: i-sec-squared, name: Integral of sec², mode: integrate, pattern: 1 u cos 2 ^ / v 2 int, require: [[sameAs, u, v]], output: v tan, tags: [trig], explain: "The derivative of tan {v} is 1/cos²{v}." }\n - { id: i-sec-squared-written, name: Integral of sec², mode: integrate, pattern: u sec 2 ^ v 2 int, require: [[sameAs, u, v]], output: v tan, tags: [trig], explain: "The derivative of tan {v} is sec²{v}." }\n - { id: i-csc-squared, name: Integral of csc², mode: integrate, pattern: 1 u sin 2 ^ / v 2 int, require: [[sameAs, u, v]], output: v cot neg, tags: [trig], explain: "The derivative of -cot {v} is 1/sin²{v}." }\n - { id: i-sin-squared, name: Integral of sin², mode: integrate, pattern: u sin 2 ^ v 2 int, require: [[sameAs, u, v]], output: v 2 / 2 v * sin 4 / -, tags: [trig], explain: "sin²{v} = (1 - cos 2{v})/2, which integrates term by term." }\n - { id: i-cos-squared, name: Integral of cos², mode: integrate, pattern: u cos 2 ^ v 2 int, require: [[sameAs, u, v]], output: v 2 / 2 v * sin 4 / +, tags: [trig], explain: "cos²{v} = (1 + cos 2{v})/2, which integrates term by term." }\n - { id: i-sinh, name: Integral of sinh, mode: integrate, pattern: u sinh v 2 int, require: [[sameAs, u, v]], output: v cosh, tags: [trig], explain: "The derivative of cosh {v} is sinh {v}." }\n - { id: i-cosh, name: Integral of cosh, mode: integrate, pattern: u cosh v 2 int, require: [[sameAs, u, v]], output: v sinh, tags: [trig], explain: "The derivative of sinh {v} is cosh {v}." }\n - { id: i-arctan, name: Integral of 1/(1 + x²), mode: integrate, pattern: 1 u 2 ^ 1 + / v 2 int, require: [[sameAs, u, v]], output: v arctan, tags: [trig], explain: "The derivative of arctan {v} is 1/(1 + {v}²)." }\n - { id: i-arcsin, name: Integral of 1/√(1 - x²), mode: integrate, pattern: 1 u 2 ^ neg 1 + sqrt / v 2 int, require: [[sameAs, u, v]], output: v arcsin, tags: [trig], explain: "The derivative of arcsin {v} is 1/√(1 - {v}²)." }\n','name: Values and identities\n\n# The CAS\'s simplify rules (mode: simplify). They see expressions in normal form\n# (src/cas/form.js), as drawn: x/2, 2x - 3, -x, √x is "x sqrt",\n# ∛x is "3 x root", π/6 is "=pi 6 /", 2π/3 is "2 =pi * 3 /", e^x is "=e x ^".\n#\n# - a word is a slot (u, v, n …); a fixed symbol is written =pi, =e\n# - a number is itself; "1 2 /" is ½\n# - arithmetic (2 + 3, x + x, √8 = 2√2) is done for you before and after every rule\n# - a rule for a sum or product of two parts also fires on any two parts of a longer one\n# - tags pick what a step list shows (steps: \'brief\' hides value, identity, tidy …)\n#\n# To change one: copy it into a file of your own with the same id and edit it;\n# to turn one off: give its id with enabled: false. createCAS({ rules: [yours] }).\n\nrules:\n # ---- logs and exponentials -------------------------------------------\n - id: ln-one\n name: Log of 1\n pattern: 1 ln\n output: "0"\n explain: "e^0 = 1, so ln 1 = 0."\n tags: [value]\n\n - id: ln-e\n name: Log of e\n pattern: =e ln\n output: "1"\n explain: "e^1 = e, so ln e = 1."\n tags: [value]\n\n - id: ln-exp\n name: Log undoes e to a power\n pattern: =e u ^ ln\n output: u\n explain: "ln and e^ undo each other: ln(e^{u}) = {u}."\n tags: [inverse]\n\n - id: exp-ln\n name: e to a power undoes the log\n pattern: =e u ln ^\n output: u\n explain: "e^ and ln undo each other: e^(ln {u}) = {u} (for {u} > 0)."\n tags: [inverse]\n\n - id: exp-multiple-ln\n name: A multiple of a log in a power\n pattern: =e n u ln * ^\n when:\n n: [isRational]\n output: u n ^\n explain: "e^({n} ln {u}) = (e^(ln {u}))^{n} = {result}."\n tags: [inverse]\n\n - id: log-same-base\n name: Log of its own base\n pattern: b b log\n output: "1"\n explain: "{b}^1 = {b}, so the log of {b} to base {b} is 1."\n tags: [value]\n\n - id: log-of-power\n name: Log undoes a power of its base\n pattern: b b u ^ log\n output: u\n explain: "log base {b} and {b}^ undo each other."\n tags: [inverse]\n\n - id: power-of-log\n name: A power undoes the log to its base\n pattern: b b u log ^\n output: u\n explain: "{b}^(log base {b} of {u}) = {u}."\n tags: [inverse]\n\n # ---- roots and absolute value --------------------------------------------\n - id: sqrt-of-square\n name: Square root of a square\n pattern: u 2 ^ sqrt\n output: u abs\n explain: "√({u}²) is the size of {u}, whatever its sign: |{u}|."\n tags: [identity]\n\n - id: abs-squared\n name: Absolute value squared\n pattern: u abs 2 ^\n output: u 2 ^\n explain: "Squaring removes the sign anyway: |{u}|² = {u}²."\n tags: [identity]\n\n - id: abs-of-abs\n name: Absolute value twice\n pattern: u abs abs\n output: u abs\n explain: "|{u}| is never negative, so its absolute value is itself."\n tags: [identity]\n\n - id: abs-positive\n name: Absolute value of a positive number\n pattern: u abs\n when:\n u: [isPositiveConstant]\n output: u\n explain: "{u} is positive, so |{u}| = {u}."\n tags: [value]\n\n - id: abs-negative\n name: Absolute value of a negative number\n pattern: u abs\n when:\n u: [isNegativeConstant]\n output: u neg\n explain: "{u} is negative, so |{u}| = -({u})."\n tags: [value]\n\n - id: abs-of-exp\n name: e to a power is positive\n pattern: =e u ^ abs\n output: =e u ^\n explain: "e to any power is positive, so the absolute value changes nothing."\n tags: [identity]\n\n # ---- trigonometry: signs and turns ---------------------------------------\n - id: sin-odd\n name: Sine of a negative angle\n pattern: u sin\n when:\n u: [hasMinusSign]\n output: u neg sin neg\n explain: "sin(-θ) = -sin θ."\n tags: [symmetry]\n\n - id: cos-even\n name: Cosine of a negative angle\n pattern: u cos\n when:\n u: [hasMinusSign]\n output: u neg cos\n explain: "cos(-θ) = cos θ."\n tags: [symmetry]\n\n - id: tan-odd\n name: Tangent of a negative angle\n pattern: u tan\n when:\n u: [hasMinusSign]\n output: u neg tan neg\n explain: "tan(-θ) = -tan θ."\n tags: [symmetry]\n\n - id: sin-full-turn\n name: A full turn\n pattern: u sin\n when:\n u: [[piMultipleAtLeast, 2]]\n output: u 2 =pi * - sin\n explain: "Turning a full 2π brings you back: sin({u}) = sin({u} - 2π)."\n tags: [symmetry]\n\n - id: cos-full-turn\n name: A full turn\n pattern: u cos\n when:\n u: [[piMultipleAtLeast, 2]]\n output: u 2 =pi * - cos\n explain: "Turning a full 2π brings you back: cos({u}) = cos({u} - 2π)."\n tags: [symmetry]\n\n - id: tan-half-turn\n name: Tangent repeats every π\n pattern: u tan\n when:\n u: [[piMultipleAtLeast, 1]]\n output: u =pi - tan\n explain: "tan repeats every π: tan({u}) = tan({u} - π)."\n tags: [symmetry]\n\n - id: sin-half-turn\n name: A half turn\n pattern: u sin\n when:\n u: [[piMultipleAbove, 1], [piMultipleBelow, 2]]\n output: u =pi - sin neg\n explain: "Half a turn flips the sign: sin({u}) = -sin({u} - π)."\n tags: [symmetry]\n\n - id: cos-half-turn\n name: A half turn\n pattern: u cos\n when:\n u: [[piMultipleAbove, 1], [piMultipleBelow, 2]]\n output: u =pi - cos neg\n explain: "Half a turn flips the sign: cos({u}) = -cos({u} - π)."\n tags: [symmetry]\n\n - id: sin-second-quarter\n name: The second quarter turn\n pattern: u sin\n when:\n u: [[piMultipleAbove, 1/2], [piMultipleAtMost, 1]]\n output: =pi u - sin\n explain: "sin({u}) = sin(π - {u})."\n tags: [symmetry]\n\n - id: cos-second-quarter\n name: The second quarter turn\n pattern: u cos\n when:\n u: [[piMultipleAbove, 1/2], [piMultipleAtMost, 1]]\n output: =pi u - cos neg\n explain: "cos({u}) = -cos(π - {u})."\n tags: [symmetry]\n\n - id: tan-second-quarter\n name: The second quarter turn\n pattern: u tan\n when:\n u: [[piMultipleAbove, 1/2], [piMultipleBelow, 1]]\n output: =pi u - tan neg\n explain: "tan({u}) = -tan(π - {u})."\n tags: [symmetry]\n\n # ---- trigonometry: the standard angles -------------------------------------\n - { id: sin-0, name: Sine of 0, pattern: 0 sin, output: "0", tags: [value], explain: "sin 0 = 0." }\n - { id: sin-pi-6, name: Sine of π/6, pattern: =pi 6 / sin, output: 1 2 /, tags: [value], explain: "sin(π/6) = 1/2." }\n - { id: sin-pi-4, name: Sine of π/4, pattern: =pi 4 / sin, output: 2 sqrt 2 /, tags: [value], explain: "sin(π/4) = √2/2." }\n - { id: sin-pi-3, name: Sine of π/3, pattern: =pi 3 / sin, output: 3 sqrt 2 /, tags: [value], explain: "sin(π/3) = √3/2." }\n - { id: sin-pi-2, name: Sine of π/2, pattern: =pi 2 / sin, output: "1", tags: [value], explain: "sin(π/2) = 1." }\n - { id: sin-pi, name: Sine of π, pattern: =pi sin, output: "0", tags: [value], explain: "sin π = 0." }\n - { id: cos-0, name: Cosine of 0, pattern: 0 cos, output: "1", tags: [value], explain: "cos 0 = 1." }\n - { id: cos-pi-6, name: Cosine of π/6, pattern: =pi 6 / cos, output: 3 sqrt 2 /, tags: [value], explain: "cos(π/6) = √3/2." }\n - { id: cos-pi-4, name: Cosine of π/4, pattern: =pi 4 / cos, output: 2 sqrt 2 /, tags: [value], explain: "cos(π/4) = √2/2." }\n - { id: cos-pi-3, name: Cosine of π/3, pattern: =pi 3 / cos, output: 1 2 /, tags: [value], explain: "cos(π/3) = 1/2." }\n - { id: cos-pi-2, name: Cosine of π/2, pattern: =pi 2 / cos, output: "0", tags: [value], explain: "cos(π/2) = 0." }\n - { id: cos-pi, name: Cosine of π, pattern: =pi cos, output: "-1", tags: [value], explain: "cos π = -1." }\n - { id: tan-0, name: Tangent of 0, pattern: 0 tan, output: "0", tags: [value], explain: "tan 0 = 0." }\n - { id: tan-pi-6, name: Tangent of π/6, pattern: =pi 6 / tan, output: 3 sqrt 3 /, tags: [value], explain: "tan(π/6) = √3/3." }\n - { id: tan-pi-4, name: Tangent of π/4, pattern: =pi 4 / tan, output: "1", tags: [value], explain: "tan(π/4) = 1." }\n - { id: tan-pi-3, name: Tangent of π/3, pattern: =pi 3 / tan, output: 3 sqrt, tags: [value], explain: "tan(π/3) = √3." }\n - { id: arcsin-0, name: Arcsine of 0, pattern: 0 arcsin, output: "0", tags: [value], explain: "sin 0 = 0, so arcsin 0 = 0." }\n - { id: arcsin-half, name: Arcsine of 1/2, pattern: 1 2 / arcsin, output: =pi 6 /, tags: [value], explain: "sin(π/6) = 1/2, so arcsin(1/2) = π/6." }\n - { id: arcsin-1, name: Arcsine of 1, pattern: 1 arcsin, output: =pi 2 /, tags: [value], explain: "sin(π/2) = 1, so arcsin 1 = π/2." }\n - { id: arccos-0, name: Arccosine of 0, pattern: 0 arccos, output: =pi 2 /, tags: [value], explain: "cos(π/2) = 0, so arccos 0 = π/2." }\n - { id: arccos-half, name: Arccosine of 1/2, pattern: 1 2 / arccos, output: =pi 3 /, tags: [value], explain: "cos(π/3) = 1/2, so arccos(1/2) = π/3." }\n - { id: arccos-1, name: Arccosine of 1, pattern: 1 arccos, output: "0", tags: [value], explain: "cos 0 = 1, so arccos 1 = 0." }\n - { id: arccos-minus-1, name: Arccosine of -1, pattern: -1 arccos, output: =pi, tags: [value], explain: "cos π = -1, so arccos(-1) = π." }\n - { id: arctan-0, name: Arctangent of 0, pattern: 0 arctan, output: "0", tags: [value], explain: "tan 0 = 0, so arctan 0 = 0." }\n - { id: arctan-1, name: Arctangent of 1, pattern: 1 arctan, output: =pi 4 /, tags: [value], explain: "tan(π/4) = 1, so arctan 1 = π/4." }\n - { id: sinh-0, name: sinh of 0, pattern: 0 sinh, output: "0", tags: [value], explain: "sinh 0 = 0." }\n - { id: cosh-0, name: cosh of 0, pattern: 0 cosh, output: "1", tags: [value], explain: "cosh 0 = 1." }\n - { id: tanh-0, name: tanh of 0, pattern: 0 tanh, output: "0", tags: [value], explain: "tanh 0 = 0." }\n\n - { id: arctan-sqrt3, name: Arctangent of √3, pattern: 3 sqrt arctan, output: =pi 3 /, tags: [value], explain: "tan(π/3) = √3, so arctan √3 = π/3." }\n - { id: arctan-sqrt3-over-3, name: Arctangent of √3/3, pattern: 3 sqrt 3 / arctan, output: =pi 6 /, tags: [value], explain: "tan(π/6) = √3/3, so arctan(√3/3) = π/6." }\n\n # atan2(y, x): the angle of the point (x, y), in (-π, π]\n - id: atan2-right\n name: The angle of a point to the right\n pattern: y x atan2\n when:\n x: [isPositiveConstant]\n output: y x / arctan\n explain: "For x > 0, atan2(y, x) = arctan(y/x)."\n tags: [value]\n - id: atan2-left-up\n name: The angle of a point to the left\n pattern: y x atan2\n when:\n x: [isNegativeConstant]\n y: [isPositiveConstant]\n output: y x / arctan =pi +\n explain: "For x < 0 and y > 0, atan2(y, x) = arctan(y/x) + π."\n tags: [value]\n - id: atan2-left-down\n name: The angle of a point to the left\n pattern: y x atan2\n when:\n x: [isNegativeConstant]\n y: [isNegativeConstant]\n output: y x / arctan =pi -\n explain: "For x < 0 and y < 0, atan2(y, x) = arctan(y/x) - π."\n tags: [value]\n - { id: atan2-negative-axis, name: The angle of a point on the negative axis, pattern: 0 x atan2, when: { x: [isNegativeConstant] }, output: =pi, tags: [value], explain: "A point on the negative x-axis is at angle π." }\n - { id: atan2-up, name: Straight up, pattern: y 0 atan2, when: { y: [isPositiveConstant] }, output: =pi 2 /, tags: [value], explain: "A point straight up is at angle π/2." }\n - { id: atan2-down, name: Straight down, pattern: y 0 atan2, when: { y: [isNegativeConstant] }, output: =pi 2 / neg, tags: [value], explain: "A point straight down is at angle -π/2." }\n\n # the odd inverses take the sign out; arccos(-u) = π - arccos u\n - id: arcsin-odd\n name: Arcsine of a negative\n pattern: u arcsin\n when:\n u: [hasMinusSign]\n output: u neg arcsin neg\n explain: "arcsin(-x) = -arcsin x."\n tags: [symmetry]\n\n - id: arctan-odd\n name: Arctangent of a negative\n pattern: u arctan\n when:\n u: [hasMinusSign]\n output: u neg arctan neg\n explain: "arctan(-x) = -arctan x."\n tags: [symmetry]\n\n - id: arccos-negative\n name: Arccosine of a negative\n pattern: u arccos\n when:\n u: [hasMinusSign]\n output: =pi u neg arccos -\n explain: "arccos(-x) = π - arccos x."\n tags: [symmetry]\n\n # ---- trigonometry: identities --------------------------------------------\n - id: pythagorean\n name: sin² + cos² = 1\n pattern: u sin 2 ^ u cos 2 ^ +\n commutative: true\n output: "1"\n explain: "sin²{u} + cos²{u} = 1 for every angle."\n tags: [identity]\n\n - id: pythagorean-multiple\n name: sin² + cos² = 1\n pattern: a u sin 2 ^ * a u cos 2 ^ * +\n commutative: true\n output: a\n explain: "{a}·sin²{u} + {a}·cos²{u} = {a}(sin²{u} + cos²{u}) = {a}."\n tags: [identity]\n\n - id: one-minus-sin-squared\n name: 1 - sin² = cos²\n pattern: u sin 2 ^ neg 1 +\n output: u cos 2 ^\n explain: "1 - sin²{u} = cos²{u}."\n tags: [identity]\n\n - id: one-minus-cos-squared\n name: 1 - cos² = sin²\n pattern: u cos 2 ^ neg 1 +\n output: u sin 2 ^\n explain: "1 - cos²{u} = sin²{u}."\n tags: [identity]\n\n - id: sin-over-cos\n name: sin/cos is tan\n pattern: u sin u cos /\n output: u tan\n explain: "sin {u} / cos {u} = tan {u}."\n tags: [identity]\n\n - id: cos-over-sin\n name: cos/sin is cot\n pattern: u cos u sin /\n output: u cot\n explain: "cos {u} / sin {u} = cot {u}."\n tags: [identity]\n\n - id: sin-arcsin\n name: sin undoes arcsin\n pattern: u arcsin sin\n output: u\n explain: "sin(arcsin {u}) = {u}."\n tags: [inverse]\n\n - id: cos-arccos\n name: cos undoes arccos\n pattern: u arccos cos\n output: u\n explain: "cos(arccos {u}) = {u}."\n tags: [inverse]\n\n - id: tan-arctan\n name: tan undoes arctan\n pattern: u arctan tan\n output: u\n explain: "tan(arctan {u}) = {u}."\n tags: [inverse]\n\n - id: cosh-squared-minus-sinh-squared\n name: cosh² - sinh² = 1\n pattern: u cosh 2 ^ u sinh 2 ^ -\n output: "1"\n explain: "cosh²{u} - sinh²{u} = 1."\n tags: [identity]\n\n # ---- logs: opt-in rewrites (run with cas.rewrite(x, \'expand-log\') or \'combine-log\') ----\n - id: ln-product\n name: Log of a product\n mode: expand-log\n pattern: a b * ln\n output: a ln b ln +\n explain: "ln({a}·{b}) = ln {a} + ln {b} (for positive {a}, {b})."\n tags: [log]\n\n - id: ln-quotient\n name: Log of a quotient\n mode: expand-log\n pattern: a b / ln\n output: a ln b ln -\n explain: "ln({a}/{b}) = ln {a} - ln {b} (for positive {a}, {b})."\n tags: [log]\n\n - id: ln-power\n name: Log of a power\n mode: expand-log\n pattern: a n ^ ln\n output: n a ln *\n explain: "ln({a}^{n}) = {n}·ln {a} (for positive {a})."\n tags: [log]\n\n - id: ln-root\n name: Log of a square root\n mode: expand-log\n pattern: a sqrt ln\n output: a ln 2 /\n explain: "ln √{a} = ½ ln {a}."\n tags: [log]\n\n - id: ln-sum-combine\n name: Sum of logs\n mode: combine-log\n pattern: a ln b ln +\n commutative: true\n output: a b * ln\n explain: "ln {a} + ln {b} = ln({a}·{b})."\n tags: [log]\n\n - id: ln-difference-combine\n name: Difference of logs\n mode: combine-log\n pattern: a ln b ln -\n output: a b / ln\n explain: "ln {a} - ln {b} = ln({a}/{b})."\n tags: [log]\n\n - id: ln-multiple-combine\n name: A multiple of a log\n mode: combine-log\n pattern: n a ln *\n when:\n n: [isRational]\n output: a n ^ ln\n explain: "{n}·ln {a} = ln({a}^{n})."\n tags: [log]\n','name: Solving by undoing\n\n# mode: isolate. Each rule undoes the outermost function on the side with the\n# unknown: ln u = r → u = e^r. The predicates hasVariable and freeOfVariable mean\n# "mentions / doesn\'t mention the unknown being solved for".\n#\n# The CAS does the rest itself: it moves terms without the unknown to the other\n# side, divides by a coefficient, and when the unknown appears in several places\n# it uses the polynomial methods (factoring, the quadratic formula) or splits a\n# product equal to 0. Every answer is checked in the original equation, so a\n# rule may give extra candidates (squaring both sides does): the wrong ones are\n# dropped, with a step saying so.\n#\n# An output can give several answers: `pm` (±) splits into two, and so does\n# `|` (or): "u r arcsin = u =pi r arcsin - = |".\n\nrules:\n - id: iso-swap\n name: Unknown on the left\n mode: isolate\n pattern: l r =\n when:\n l: [freeOfVariable]\n r: [hasVariable]\n output: r l =\n priority: 20\n explain: "Swap the sides so the unknown is on the left."\n tags: [tidy]\n\n - id: iso-ln\n name: Undo the log\n mode: isolate\n pattern: u ln r =\n when:\n u: [hasVariable]\n output: u =e r ^ =\n explain: "Raise e to each side: e^(ln {u}) = {u}."\n tags: [inverse]\n\n - id: iso-log\n name: Undo the log\n mode: isolate\n pattern: b u log r =\n when:\n u: [hasVariable]\n b: [freeOfVariable]\n output: u b r ^ =\n explain: "Raise {b} to each side: {b}^(log base {b} of {u}) = {u}."\n tags: [inverse]\n\n - id: iso-exp\n name: Undo e to a power\n mode: isolate\n pattern: =e u ^ r =\n when:\n u: [hasVariable]\n output: u r ln =\n explain: "Take ln of each side: ln(e^{u}) = {u}."\n tags: [inverse]\n\n - id: iso-exponential\n name: Undo a power of a number\n mode: isolate\n pattern: b u ^ r =\n when:\n u: [hasVariable]\n b: [freeOfVariable]\n output: u b r log =\n explain: "Take the log to base {b} of each side."\n tags: [inverse]\n\n - id: iso-square\n name: Undo the square\n mode: isolate\n pattern: u 2 ^ r =\n when:\n u: [hasVariable]\n output: u r sqrt pm =\n priority: 1\n explain: "Take the square root of each side; {u} can be positive or negative."\n tags: [inverse]\n\n - id: iso-even-power\n name: Undo an even power\n mode: isolate\n pattern: u n ^ r =\n when:\n u: [hasVariable]\n n: [isEvenWhole]\n output: u r 1 n / ^ pm =\n explain: "Take the root of each side (the {n}th root); {u} can be positive or negative."\n tags: [inverse]\n\n - id: iso-odd-power\n name: Undo an odd power\n mode: isolate\n pattern: u n ^ r =\n when:\n u: [hasVariable]\n n: [isOddWhole]\n output: u r 1 n / ^ =\n explain: "Take the root of each side (the {n}th root)."\n tags: [inverse]\n\n - id: iso-fractional-power\n name: Undo a power\n mode: isolate\n pattern: u n ^ r =\n when:\n u: [hasVariable]\n n: [isRational]\n output: u r 1 n / ^ =\n priority: -1\n explain: "Raise each side to the power 1/{n}."\n tags: [inverse]\n\n - id: iso-sqrt\n name: Undo the square root\n mode: isolate\n pattern: u sqrt r =\n when:\n u: [hasVariable]\n output: u r 2 ^ =\n explain: "Square each side (this can add answers, so each one is checked at the end)."\n tags: [inverse]\n\n - id: iso-root\n name: Undo the root\n mode: isolate\n pattern: n u root r =\n when:\n u: [hasVariable]\n n: [freeOfVariable]\n output: u r n ^ =\n explain: "Raise each side to the power {n}."\n tags: [inverse]\n\n - id: iso-reciprocal\n name: Undo the fraction\n mode: isolate\n pattern: c u / r =\n when:\n u: [hasVariable]\n c: [freeOfVariable]\n output: u c r / =\n explain: "{c}/{u} = {r}, so {u} = {c}/{r}."\n tags: [inverse]\n\n - id: iso-abs\n name: Undo the absolute value\n mode: isolate\n pattern: u abs r =\n when:\n u: [hasVariable]\n output: u r pm =\n explain: "|{u}| = {r} means {u} is {r} or -{r}."\n tags: [inverse]\n\n - id: iso-sin\n name: Undo the sine\n mode: isolate\n pattern: u sin r =\n when:\n u: [hasVariable]\n output: u r arcsin = u =pi r arcsin - = |\n explain: "Two angles in a turn have sine {r}: arcsin {r} and π - arcsin {r} (add any whole number of turns, 2πk, for the rest)."\n tags: [inverse, trig]\n\n - id: iso-cos\n name: Undo the cosine\n mode: isolate\n pattern: u cos r =\n when:\n u: [hasVariable]\n output: u r arccos pm =\n explain: "Two angles in a turn have cosine {r}: ±arccos {r} (add 2πk for the rest)."\n tags: [inverse, trig]\n\n - id: iso-tan\n name: Undo the tangent\n mode: isolate\n pattern: u tan r =\n when:\n u: [hasVariable]\n output: u r arctan =\n explain: "Take arctan of each side (add πk for the rest)."\n tags: [inverse, trig]\n\n - { id: iso-arcsin, name: Undo arcsin, mode: isolate, pattern: u arcsin r =, when: { u: [hasVariable] }, output: u r sin =, tags: [inverse], explain: "Take sin of each side." }\n - { id: iso-arccos, name: Undo arccos, mode: isolate, pattern: u arccos r =, when: { u: [hasVariable] }, output: u r cos =, tags: [inverse], explain: "Take cos of each side." }\n - { id: iso-arctan, name: Undo arctan, mode: isolate, pattern: u arctan r =, when: { u: [hasVariable] }, output: u r tan =, tags: [inverse], explain: "Take tan of each side." }\n - { id: iso-sinh, name: Undo sinh, mode: isolate, pattern: u sinh r =, when: { u: [hasVariable] }, output: u r arcsinh =, tags: [inverse], explain: "Take arcsinh of each side." }\n - { id: iso-tanh, name: Undo tanh, mode: isolate, pattern: u tanh r =, when: { u: [hasVariable] }, output: u r arctanh =, tags: [inverse], explain: "Take arctanh of each side." }\n - { id: iso-cosh, name: Undo cosh, mode: isolate, pattern: u cosh r =, when: { u: [hasVariable] }, output: u r arccosh pm =, tags: [inverse], explain: "Two numbers have cosh {r}: ±arccosh {r}." }\n - { id: iso-arcsinh, name: Undo arcsinh, mode: isolate, pattern: u arcsinh r =, when: { u: [hasVariable] }, output: u r sinh =, tags: [inverse], explain: "Take sinh of each side." }\n - { id: iso-arccosh, name: Undo arccosh, mode: isolate, pattern: u arccosh r =, when: { u: [hasVariable] }, output: u r cosh =, tags: [inverse], explain: "Take cosh of each side." }\n - { id: iso-arctanh, name: Undo arctanh, mode: isolate, pattern: u arctanh r =, when: { u: [hasVariable] }, output: u r tanh =, tags: [inverse], explain: "Take tanh of each side." }\n'],ji=['name: Complex numbers\n\n# Loaded only by createCAS({ complex: true }), where i is the imaginary unit.\n# The arithmetic (i² = -1, √-4 = 2i, (2 + 3i)(1 - i) = 5 + i, 1/(1 + i) = (1 - i)/2)\n# and Re, Im, conj, arg, |z| are the normal form\'s (src/cas/form.js); unknowns\n# count as real, so Re(x + 3i) = x. Write a complex unknown as a + bi.\n\noperators:\n - { symbol: re, arity: 1, label: real part }\n - { symbol: im, arity: 1, label: imaginary part }\n - { symbol: conj, arity: 1, label: complex conjugate }\n - { symbol: arg, arity: 1, label: argument }\n\nrules:\n - id: euler\n name: Euler\'s formula\n pattern: =e u ^\n when:\n u: [hasImaginaryPart, isConstant]\n output: =e u re ^ u im cos =i u im sin * + *\n explain: "e^(a + bi) = e^a (cos b + i sin b)."\n tags: [complex]\n\n - id: ln-negative\n name: Log of a negative number\n pattern: u ln\n when:\n u: [isNegativeConstant]\n output: u neg ln =i =pi * +\n explain: "{u} = |{u}|·e^(iπ), so ln {u} = ln |{u}| + iπ (the principal value)."\n tags: [complex]\n\n - id: ln-complex\n name: Log of a complex number\n pattern: u ln\n when:\n u: [hasImaginaryPart, isConstant]\n output: u abs ln u arg =i * +\n explain: "ln z = ln |z| + i arg z (the principal value)."\n tags: [complex]\n\n - id: i-to-the-i\n name: i to the power i\n pattern: =i =i ^\n output: =e =pi 2 / neg ^\n explain: "i = e^(iπ/2), so i^i = e^(i·iπ/2) = e^(-π/2) (the principal value)."\n tags: [complex]\n'],Ci={normal:"Work out the numbers and collect like terms.","simplify.cancel":"Cancel the factors the top and bottom share.","simplify.expand":"Multiplying out gives something shorter.","simplify.factor":"Factoring gives something shorter.",expand:"Multiply out the brackets.",factor:"Write it as a product of factors.","factor.common":"Take out the common factor {common}.","factor.polynomial":"Factor what is left: {roots}.",together:"Write it as one fraction over a common denominator.",cancel:"Cancel the factors the top and bottom share: {cancelled}.","solve.move":"Keep the terms with {v} on the left and move the others to the right.","solve.divide":"Divide both sides by {by}.","solve.multiply":"Multiply both sides by {by}.","solve.one-side":"Move everything to one side, so the equation reads … = 0.","solve.factor":"Factor the left side.","solve.zero-product":"A product is 0 exactly when one of its factors is 0.","solve.split":"There are two cases; solve each.","solve.quadratic":"The quadratic formula with a = {a}, b = {b}, c = {c}: {v} = (-b ± √(b² - 4ac)) / 2a, and b² - 4ac = {D}.","solve.no-real":"b² - 4ac = {D} is negative, so there are no real solutions.","solve.quadratic-complex":"The quadratic formula with a = {a}, b = {b}, c = {c}: {v} = (-b ± √(b² - 4ac)) / 2a. b² - 4ac = {D} is negative, so its square root is imaginary: √({D}) = {root}.","solve.roots":"{v}^{n} = {r} has {n} solutions, spaced evenly round a circle: |{r}|^(1/{n})·(cos θ + i sin θ), with θ = (arg {r} + 2πk)/{n} for k = 0 … {last}.","solve.clear-denominator":"Multiply both sides by {den} (an answer that makes it 0 is not allowed).","solve.substitute":"Write {u} for {kernel}: this is a polynomial in {u}.","solve.reject":"{value} is not a solution: {reason}.","solve.always":"This is true for every {v}.","solve.never":"This is never true, so there is no solution.","solve.unsolved":"There is no exact method here for solving for {v}; try { approximate: true }.","solve.numeric":"Found {count} solution(s) numerically.","system.eliminate":"Use one equation to remove {v} from the others.","integrate.expand":"Multiply out, then integrate term by term.","integrate.substitute":"Let {u} = {inside}, so d{u} = {a} d{v}.","integrate.back":"Put {inside} back for {u}.","integrate.parts":"By parts with u = {u} and dv = {dv} d{v}: ∫ u dv = u·v - ∫ v du, where v = {V} and du = {du} d{v}.","integrate.constant":"The number {c} comes out of the integral.","integrate.divide":"The top has at least the degree of the bottom: divide first.","integrate.partial-fractions":"Split the fraction into simple fractions, one for each factor below.","integrate.evaluate":"Evaluate {F} at {b} and at {a}, and subtract.",substitute:"Put in the values."},Li=["normal","rewrite","simplify","expand","factor","cancel","diff","differentiate","integrate","solve","solveSystem","substitute","approximate","equivalent"];class Zi{constructor(e,n,t,r,i){this.set=e,this.messages=n,this.format=t,this.read=r,this.complex=i;for(const e of Li){const n=Zi.prototype[e];this[e]=(...e)=>Ke(i,()=>n.apply(this,e))}}node(e){if(e&&"object"==typeof e&&!Array.isArray(e)&&e.type)return e;if(Array.isArray(e))return Ie(e);if("string"!=typeof e)throw new ze("expected an expression");if(this.read){const n=this.read(e);return Array.isArray(n)?Ie(n):"string"==typeof n?Ne(n):n}return Ne(e)}step(e,n,t,r,i,s={}){return function(e,n,t,r,i,s,o,a,l=[]){const u=(s??"").replace(/\{(\w+)\}/g,(e,n)=>{const t=o?.[n];return void 0===t?e:"string"==typeof t?t:a(t)});return{id:e,name:n,tags:t,from:r.s,to:i.s,path:l,before:r.s,after:i.s,explanation:u}}(e,n,t,r,i,this.messages[e]??"",s,this.format)}result(e,n,t,r={}){let i=e;if(t.approximate&&i){i=fr(i,{digits:"number"==typeof t.approximate?t.approximate:15})}return{result:i,text:i?this.format(i):"",steps:Nr(n,Ar(t.steps)),...r}}variable(e,n){if(n)return n;const t=[...Rn(e)];return 1===t.length?t[0]:t.includes("x")?"x":t[0]??"x"}tidyStep(e,n){return e.s===n.s?[]:[this.step("normal","Work out and collect",["tidy","arithmetic"],e,n)]}normal(e){return Cn(this.node(e))}rewrite(e,n,t={}){const r=this.node(e),i=this.set.view(n);if(!i.size)throw new ze(`no rules in mode "${n}" (modes: ${this.set.modes().join(", ")})`);const s=Sr(r,i,{format:this.format,order:t.order,variable:t.variable});return this.result(s.node,[...this.tidyStep(r,Cn(r)),...s.steps],t)}simplify(e,n={}){const t=this.node(e),r=[...this.tidyStep(t,Cn(t))],i=Sr(t,this.set.view("simplify"),{format:this.format});r.push(...i.steps);let s=i.node,o=null;const a=jn(s),l=[],u=0===Rn(s).size,c=u?null:Yr(a);c&&l.push({node:Kr(c),id:"simplify.cancel",name:"Cancel"});const p=Sr(Bn(Tr(a)),this.set.view("simplify"),{format:this.format});l.push({node:p.node,id:"simplify.expand",name:"Multiply out"}),"add"!==a.k||u||l.push({node:Kr(Vr(a)),id:"simplify.factor",name:"Factor"});for(const e of l)Te(e.node)<Te(s)&&(o=this.step(e.id,e.name,["shorter"],s,e.node),s=e.node);return o&&r.push(o),this.result(s,r,n)}expand(e,n={}){const t=this.node(e),r=Bn(Tr(jn(t)));return this.result(r,t.s===r.s?[]:[this.step("expand","Multiply out",["expand"],t,r)],n)}factor(e,n={}){const t=this.node(e),r=Vr(jn(t)),i=Kr(r),s=[],o=r.notes.find(e=>"factor.common"===e.id);return i.s!==Cn(t).s&&s.push(this.step(o?"factor.common":"factor","Factor",["factor"],t,i,o?{common:Bn(o.values.common)}:{})),this.result(i,s,n)}cancel(e,n={}){const t=this.node(e),r=jn(t),i=Yr(r);if(!i)return this.result(Cn(t),this.tidyStep(t,Cn(t)),n);const s=Kr(i),o=Qr(r),a=Me("/",[Bn(o.num),Bn(o.den)]),l=[];return"/"===t.op&&a.s===Cn(t).s||l.push(this.step("together","One fraction",["together"],t,a)),s.s!==a.s&&l.push(this.step("cancel","Cancel",["cancel"],a,s,{cancelled:i.cancelled.length?i.cancelled.map(e=>this.format(Bn(e))).join(", "):"numbers"})),this.result(s,l,n)}diff(e,n,t={}){const r=this.node(e),i=this.variable(r,n);let s=r;const o=[];for(let e=0;e<(t.order??1);e++){const e=Sr(Me("der",[s,ke(i)]),this.set.view("differentiate"),{format:this.format,order:"pre"}),n=Sr(e.node,this.set.view("simplify"),{format:this.format});o.push(...e.steps,...n.steps),s=n.node}return this.result(s,o,t,{variable:i})}differentiate(e,n){const t=Sr(Me("der",[e,ke(n)]),this.set.view("differentiate"),{format:this.format,order:"pre"});return Sr(t.node,this.set.view("simplify"),{format:this.format}).node}integrate(e,n,t={}){let r=this.node(e);const i=e=>void 0===e?null:this.node("number"==typeof e?String(e):e);let s=i(t.from),o=i(t.to);if(Ae(r)&&"int"===r.op){const[e,t,i,a]=r.args;n=t.token,i&&a&&(s=i,o=a),r=e}const a=this.variable(r,n),l=yi(this,r,a),u=Sr(l.node,this.set.view("simplify"),{format:this.format}),c=[...l.steps,...u.steps];if(s&&o){const e=qi(this,u.node,a,s,o,r);c.push(e.step);const n=Sr(e.value,this.set.view("simplify"),{format:this.format});return c.push(...n.steps),this.result(n.node,c,t,{antiderivative:u.node,variable:a})}let p=u.node;return t.constant&&(p=Me("+",[p,ke(String(t.constant))])),this.result(p,c,t,{variable:a})}solve(e,n,t={}){const r=this.node(e),i=this.variable(r,n),s=ti(this,r,i,t);let o=s.solutions;if(t.approximate){const e="number"==typeof t.approximate?t.approximate:15;o=o.map(n=>fr(n,{digits:e}))}const a=o.map(e=>Me("=",[ke(i),e])),l=a.length?a.reduce((e,n)=>e?Me("|",[e,n]):n,null):null;return{solutions:o,result:l,variable:i,text:s.always?`true for every ${i}`:l?this.format(l):s.unsolved.length?`no exact solution found for ${i}`:"no solution",unsolved:s.unsolved.filter(e=>!e.always),always:s.always,steps:Nr(s.steps,Ar(t.steps))}}solveSystem(e,n,t={}){const r=e.map(e=>this.node(e)),i=n??[...new Set(r.flatMap(e=>[...Rn(e)]))].sort(),s=function(e,n,t){const r=[],i=n.map(n=>{const r=ni(n)?dn([jn(n.args[0]),On(jn(n.args[1]))]):jn(n),i=t.map(n=>{const t=Cr(r,n);if(!t||Math.max(0,...t.keys())>1)throw new ze(`not linear in ${n}`);const i=t.get(1)??Ye(Pe.ZERO);if(!tn(i))throw new ze(`the coefficient of ${n} must be a number (it is ${e.format(Bn(i))})`);return i.q});let s=r;for(let e=0;e<t.length;e++)s=dn([s,gn([Ye(i[e].neg()),jn(ke(t[e]))])]);for(const e of t)if(Lr(s,e))throw new ze(`not linear in ${e}`);return{coeffs:i,rhs:On(s)}}),s=()=>i.map(e=>Xr(Bn(dn(e.coeffs.map((e,n)=>gn([Ye(e),jn(ke(t[n]))])))),Bn(e.rhs))).reduce((e,n)=>e?Me("&",[e,n]):n,null);let o=0;const a=[];for(let n=0;n<t.length&&o<i.length;n++){const l=i.findIndex((e,t)=>t>=o&&!e.coeffs[n].isZero);if(l<0)continue;[i[o],i[l]]=[i[l],i[o]];const u=s(),c=i[o],p=c.coeffs[n];c.coeffs=c.coeffs.map(e=>e.div(p)),c.rhs=gn([Ye(p.inv()),c.rhs]);for(let e=0;e<i.length;e++){if(e===o||i[e].coeffs[n].isZero)continue;const t=i[e].coeffs[n];i[e].coeffs=i[e].coeffs.map((e,n)=>e.sub(t.mul(c.coeffs[n]))),i[e].rhs=dn([i[e].rhs,gn([Ye(t.neg()),c.rhs])])}r.push(e.step("system.eliminate","Eliminate",["eliminate"],u,s(),{v:ke(t[n])})),a.push(n),o++}for(const e of i.slice(o))if(!tn(e.rhs)||!e.rhs.q.isZero)return{solution:null,steps:r,status:"none"};if(a.length<t.length)return{solution:null,steps:r,status:"many"};const l=new Map;return a.forEach((e,n)=>l.set(t[e],Bn(i[n].rhs))),{solution:l,steps:r,status:"one"}}(this,r,i),o=s.solution?Object.fromEntries([...s.solution].map(([e,n])=>[e,n])):null,a="one"===s.status?i.map(e=>`${e} = ${this.format(o[e])}`).join(", "):"none"===s.status?"no solution":"infinitely many solutions";return{solution:o,status:s.status,text:a,steps:Nr(s.steps,Ar(t.steps))}}substitute(e,n,t={}){const r=this.node(e);let i=r;for(const[e,t]of Object.entries(n))i=oi(i,e,"number"==typeof t?this.node(String(t)):this.node(t));const s=this.simplify(i,t),o=[this.step("substitute","Substitute",["substitute"],r,i)];return{...s,steps:[...Nr(o,Ar(t.steps)),...s.steps]}}defined(e){const n=this.set.view("define");return n.size?Sr(e,n,{format:this.format}).node:e}approximate(e,n={}){const t=this.defined(this.node(e));if(Rn(t).size&&!n.scope){const e=fr(Cn(t),n);return{result:e,text:this.format(e),number:null,exact:!1}}const r=ur(t,n);return{result:r.node,text:r.text,number:r.number,re:r.re,im:r.im,exact:r.exact}}equivalent(e,n){const t=this.node(e),r=this.node(n),i=this.defined(Me("-",[t,r])),s=this.simplify(i,{steps:!1}).result;if("num"===s.type&&"0"===s.token)return{equal:!0,how:"exact"};const o=[...Rn(i)];if(!o.length)try{return{equal:Math.abs(ur(i,{digits:30}).number)<1e-25,how:"numeric"}}catch{return{equal:!1,how:"numeric"}}const a=[.31,1.7,2.9,-.83,.57];let l=0;for(let e=0;e<a.length;e++){const n=Object.fromEntries(o.map((n,t)=>[n,String(a[(e+t)%a.length]+t/7)]));let t;try{t=ur(i,{digits:30,scope:n}).number}catch{continue}if(l++,Math.abs(t)>1e-20)return{equal:!1,how:"numeric"}}return{equal:l>0,how:"numeric"}}modes(){return this.set.modes()}}function zi(e={}){const n=!1===e.defaults?[]:[...Ti,...e.complex?ji:[]],{specs:t,messages:r}=function(e){yr();const n=[],t={};for(const r of e){const e="string"==typeof r?wt(r):r,i=Array.isArray(e)?e:e?.rules??[];for(const n of(Array.isArray(e)?[]:e?.operators)??[]){if(!n?.symbol)throw new Error("an operator needs a symbol");he(n.symbol)||ce({symbol:String(n.symbol),arity:"any"===n.arity?ae:Number(n.arity),label:n.label})}Object.assign(t,(Array.isArray(e)?null:e?.messages)??{});for(const e of i)n.push(e)}return{specs:n,messages:t}}([...n,...e.rules??[]]),i=Ke(e.complex,()=>wr(t));return new Zi(i,{...Ci,...r},e.format??Mi,e.read??null,Boolean(e.complex))}const Bi=new Map,Di={re:"Re",im:"Im",conj:"overline"},Fi=["Re","Im","re","im","conj","arg"];function Ri(e){const n=[],r=e=>{"op"===e.type?(e.args.forEach(r),t.operator(e.op)?(-1===t.operator(e.op).arity&&n.push(String(e.args.length)),n.push(e.op)):n.push(String(e.args.length),`\\:${Di[e.op]??e.op}`)):n.push(e.token)};return r(e),n}function Pi(e={}){const n=e.rules||e.names?null:e.complex?"complex":"default";if(n&&Bi.has(n))return Bi.get(n);const r=[...e.names??[],...e.complex?Fi:[]],i=zi({...e,read:e=>t.parse(e,r.length?{names:r}:{}),format:Mi});return n&&Bi.set(n,i),i}const Vi=new Set(["simplify","expand","factor","cancel","diff","integrate","solve","approx"]);const Wi=e=>String(e).replace(/&/g,"&").replace(/</g,"<").replace(/>/g,">").replace(/"/g,""");var Ui='/*\n * Inline Math stylesheet. Everything is under .mv; colours are left to the page.\n *\n * The numbers marked "metric" must match the constants at the top of\n * src/layout.js (line-height 1, bar 0.06em, gap 0.1em); everything else can\n * be changed freely.\n *\n * Handy hooks:\n * .mv-n[data-node="4"] one node (ids from MathZetta)\n * .mv-var .mv-num .mv-word variables, numbers, function names\n * .mv-op-frac .mv-op-pow … a kind of operation\n * .mv-hl the class highlight() adds\n * --mv-hl highlight colour\n */\n\n.mv {\n display: inline-block;\n font-family: "Inline Math Roman", "Latin Modern Roman", "STIX Two Text", "Cambria", "Times New Roman", serif;\n font-size: 1.2em;\n font-style: normal;\n font-weight: normal;\n line-height: 1; /* metric */\n white-space: nowrap;\n text-indent: 0;\n text-align: left;\n letter-spacing: 0;\n}\n.mv-display { display: block; text-align: center; margin: 0.6em 0; }\n.mv span, .mv svg { line-height: 1; }\n.mv-n { display: inline-block; border-radius: 0.12em; }\n\n/* ---- letters and signs -------------------------------------------------- */\n.mv-var { font-style: italic; padding-right: 0.03em; }\n.mv-num, .mv-word, .mv-name, .mv-ord, .mv-text, .mv-d { font-style: normal; }\n.mv-prime { margin-left: 0.04em; }\n.mv-bin { margin: 0 0.22em; }\n.mv-rel { margin: 0 0.28em; }\n.mv-punct { margin-right: 0.17em; }\n.mv-sign { margin-right: 0.04em; }\n.mv-times { display: inline-block; width: 0.06em; }\n.mv-callgap { display: inline-block; width: 0.05em; }\n.mv-fnspace { display: inline-block; width: 0.17em; }\n.mv-space { display: inline-block; width: 0.33em; }\n.mv-dx { display: inline-block; margin-left: 0.17em; }\n.mv-text { margin: 0 0.25em; }\n/* Tighter spacing in limits and exponents: n=1, x→0. */\n.mv-script .mv-rel, .mv-sup .mv-rel, .mv-sub .mv-rel { margin: 0 0.12em; }\n.mv-script .mv-bin, .mv-sup .mv-bin, .mv-sub .mv-bin { margin: 0 0.1em; }\n\n/* ---- fractions (metric: padding and border) ------------------------------ */\n.mv-frac { display: inline-flex; flex-direction: column; align-items: stretch; margin: 0 0.12em; }\n.mv-numer, .mv-denom { display: block; text-align: center; padding: 0 0.1em; }\n.mv-numer { padding-bottom: 0.1em; }\n.mv-denom { padding-top: 0.1em; border-top: 0.06em solid currentColor; }\n.mv-frac-nobar > .mv-denom { border-top: 0; }\n.mv-scaled { display: inline-block; }\n\n/* ---- scripts ----------------------------------------------------------------- */\n.mv-sup, .mv-sub { display: inline-block; margin-left: 0.04em; }\n.mv-subsup, .mv-limits { display: inline-flex; flex-direction: column; justify-content: space-between; align-items: flex-start; margin-left: 0.04em; }\n.mv-limits { margin-left: 0.02em; margin-right: 0.12em; }\n.mv-limits > .mv-lower { margin-left: -0.3em; }\n.mv-script { display: block; }\n.mv-under { display: inline-flex; flex-direction: column; align-items: center; margin-right: 0.15em; }\n.mv-under > .mv-script { margin-top: 0.05em; }\n.mv-bigop { display: inline-flex; flex-direction: column; align-items: center; margin: 0 0.12em; }\n.mv-bigop > .mv-script { display: block; margin: 0.08em 0; }\n.mv-bigop > svg { display: block; }\n\n/* ---- radicals (metric: border and padding-top) ----------------------------- */\n.mv-sqrt { display: inline-block; white-space: nowrap; }\n.mv-hook { display: inline-block; overflow: visible; margin-left: 0.05em; }\n.mv-radicand { display: inline-block; border-top: 0.06em solid currentColor; padding: 0.1em 0.1em 0 0.06em; }\n.mv-rootindex { display: inline-block; margin: 0 -0.32em 0 0.12em; }\n\n/* ---- delimiters: drawn at the full height of what they enclose -------------- */\n.mv-fence { display: inline-block; position: relative; }\n.mv-delim { position: absolute; top: 0; bottom: 0; height: 100%; }\n.mv-delim-l { left: 0.03em; }\n.mv-delim-r { right: 0.03em; }\nspan.mv-delim { width: 0.16em; border: 0 solid currentColor; box-sizing: border-box; }\n.mv-delim.mv-lbrack { border-width: 0.06em 0 0.06em 0.06em; left: 0.06em; }\n.mv-delim.mv-rbrack { border-width: 0.06em 0.06em 0.06em 0; right: 0.06em; }\n.mv-delim.mv-vert { border-left-width: 0.06em; width: 0; left: 0.07em; }\n.mv-delim.mv-vert.mv-delim-r { left: auto; right: 0.07em; }\n.mv-delim.mv-lfloor { border-width: 0 0 0.06em 0.06em; }\n.mv-delim.mv-rfloor { border-width: 0 0.06em 0.06em 0; }\n.mv-delim.mv-lceil { border-width: 0.06em 0 0 0.06em; }\n.mv-delim.mv-rceil { border-width: 0.06em 0.06em 0 0; }\n\n/* ---- shapes ----------------------------------------------------------------- */\n.mv svg { overflow: visible; }\n.mv svg path[stroke] { stroke-width: 0.065em; stroke-linecap: round; stroke-linejoin: round; }\n.mv-intsign path[stroke] { stroke-width: 0.075em; }\n.mv-bigsign { display: inline-block; margin: 0 0.06em; }\n.mv-intsign { margin-right: 0.12em; }\n\n/* ---- piecewise ------------------------------------------------------------- */\n.mv-cases { display: inline-grid; grid-template-columns: auto auto; column-gap: 1em; row-gap: 0.25em; align-items: baseline; text-align: left; margin: 0 0.1em; }\n.mv-case-value, .mv-case-cond { display: block; }\n\n/* ---- decorations: \\boxed \\cancel \\overline \\vec … --------------------------- */\n.mv-boxed { display: inline-block; border: 0.06em solid currentColor; padding: 0.16em 0.2em; }\n.mv-over { display: inline-block; border-top: 0.06em solid currentColor; padding-top: 0.08em; }\n.mv-underline { display: inline-block; border-bottom: 0.06em solid currentColor; padding-bottom: 0.06em; }\n.mv-cancel { display: inline-block; background: linear-gradient(to top right, transparent calc(50% - 0.04em), currentColor calc(50% - 0.03em), currentColor calc(50% + 0.03em), transparent calc(50% + 0.04em)); }\n.mv-accent { display: inline-block; position: relative; padding-top: 0.3em; }\n.mv-accent-mark { position: absolute; top: 0; left: 0; right: 0; text-align: center; font-size: 0.7em; line-height: 0.6; }\n\n/* ---- interaction -------------------------------------------------------------- */\n.mv-hl { background: var(--mv-hl, rgba(255, 200, 0, 0.35)); box-shadow: 0 0 0 0.08em var(--mv-hl, rgba(255, 200, 0, 0.35)); }\n.mv-clickable .mv-n { cursor: pointer; }\n.mv-clickable .mv-n:hover { outline: 1px dashed rgba(0, 0, 0, 0.25); }\n\n/* ---- steps (stepsHTML from \'@mathzetta/inlinemath/cas\') ---------------------------------------- */\n.mv-steps { margin: 0; padding-left: 1.6em; }\n.mv-step { margin: 0.5em 0 0.9em; }\n.mv-step-name { display: block; font-size: 0.85em; font-weight: 600; color: #555; }\n.mv-step-maths { display: flex; flex-wrap: wrap; align-items: center; gap: 0.4em 0.8em; margin: 0.15em 0; }\n.mv-step-arrow { color: #888; }\n.mv-step-why { margin: 0.1em 0 0; font-size: 0.9em; color: #444; }\n\n/* ---- Markdown with maths (markdownToHTML from \'@mathzetta/inlinemath/markdown\') ------------------- */\n.mv-md-math { display: inline-block; vertical-align: middle; }\n.mv-md-display { display: block; text-align: center; margin: 0.6em 0; overflow-x: auto; }\n.mv-md-block { margin: 0.8em 0; }\n.mv-md-error code { background: rgba(200, 60, 0, 0.08); color: #a33; border-bottom: 1px dotted #a33; }\n';const _i=Ui;if("undefined"!=typeof document&&!document.getElementById("inlinemath-css")){const e=document.createElement("style");e.id="inlinemath-css",e.textContent=Ui,document.head.append(e)}return e.CSS=_i,e.DEFAULTS=q,e.PATHS=s,e.View=W,e.casBlocks=function(e={}){const t=e.cas??Pi(),r=(e,s)=>{let o;try{o=t.read(e)}catch{return n.calculateBlock(e,s)}const a=o[o.length-1],l=a?.startsWith("\\:")?a.slice(2):null,u=l&&Vi.has(l);if(!u&&!("der"===a||"int"===a))return n.calculateBlock(e,s);const c=t.node(o),p=u?c.args:[c],f=e=>e?e.s:void 0;let h;try{switch(u?l:"der"===a?"derivative":"antiderivative"){case"simplify":h=t.simplify(p[0]);break;case"expand":h=t.expand(p[0]);break;case"factor":h=t.factor(p[0]);break;case"cancel":h=t.cancel(p[0]);break;case"diff":h=t.diff(p[0],f(p[1]),{order:p[2]?Number(p[2].s):1});break;case"integrate":h=t.integrate(p[0],f(p[1]),p[3]?{from:p[2].s,to:p[3].s}:{});break;case"solve":h=t.solve(p[0],f(p[1]));break;case"approx":h=t.approximate(p[0],{digits:p[1]?Number(p[1].s):15});break;case"derivative":h=t.diff(c.args[0],c.args[1].s);break;default:h=t.integrate(c)}}catch(n){return`(${e})`}if(r.last=h,!h.result)return`"${h.text}"`;const d=i.toText(Ri(h.result));return/^-?\d+(\.\d+)?$/.test(d)?d:`(${d})`};return r},e.extractMath=_,e.layout=A,e.markdownToHTML=se,e.mathCAS=Pi,e.nodeAt=Z,e.numberTree=B,e.pathOf=z,e.render=function(e,n,t={}){return new W(e,n,t)},e.renderMarkdown=ie,e.renderMarkdownInto=function(e,n,t={}){return e.innerHTML=se(n,t),e},e.select=C,e.signature=j,e.stepsHTML=function(e,n={}){return`<ol class="mv-steps">${e.map(e=>{const t=V(Ri(Ne(e.from)),{...n,highlight:e.path&&e.path.length?{path:e.path}:void 0}),r=e.to===e.from?"":`<span class="mv-step-arrow" aria-label="becomes">⟶</span>${V(Ri(Ne(e.to)),n)}`,i=e.explanation?`<p class="mv-step-why">${Wi(e.explanation)}</p>`:"";return`<li class="mv-step" data-rule="${Wi(e.id)}"><span class="mv-step-name">${Wi(e.name)}</span><div class="mv-step-maths">${t}${r}</div>${i}</li>`}).join("")}</ol>`},e.toHTML=V,e.tokensOf=Ri,e.treeOf=P,e}({},MathZetta,MathZetta,MathZetta,MathZetta);
|
|
1
|
+
/* Inline Math 0.3.0 — MIT license; MathZetta not included: load a MathZetta <script> (mathzetta.min.js or mathzetta.maths-display.min.js) first */
|
|
2
|
+
var InlineMath=function(e,t,n,r,s){"use strict";const i={"(":{fill:"M0.92,0 C0.1,0.2 0.1,0.8 0.92,1 L1,0.975 C0.48,0.75 0.48,0.25 1,0.025 Z"},")":{fill:"M0.08,0 C0.9,0.2 0.9,0.8 0.08,1 L0,0.975 C0.52,0.75 0.52,0.25 0,0.025 Z"},"{":{fill:"M1,0 C0.45,0 0.5,0.05 0.5,0.2 L0.5,0.38 C0.5,0.46 0.35,0.49 0.05,0.5 C0.35,0.51 0.5,0.54 0.5,0.62 L0.5,0.8 C0.5,0.95 0.45,1 1,1 L1,0.985 C0.68,0.985 0.64,0.95 0.64,0.8 L0.64,0.62 C0.64,0.53 0.55,0.505 0.3,0.5 C0.55,0.495 0.64,0.47 0.64,0.38 L0.64,0.2 C0.64,0.05 0.68,0.015 1,0.015 Z"},"}":{fill:"M0,0 C0.55,0 0.5,0.05 0.5,0.2 L0.5,0.38 C0.5,0.46 0.65,0.49 0.95,0.5 C0.65,0.51 0.5,0.54 0.5,0.62 L0.5,0.8 C0.5,0.95 0.55,1 0,1 L0,0.985 C0.32,0.985 0.36,0.95 0.36,0.8 L0.36,0.62 C0.36,0.53 0.45,0.505 0.7,0.5 C0.45,0.495 0.36,0.47 0.36,0.38 L0.36,0.2 C0.36,0.05 0.32,0.015 0,0.015 Z"},sqrt:{stroke:"M0,0.62 L0.18,0.55 L0.45,0.97 L0.98,0.015"},cancel:{stroke:"M0,1 L1,0"},int:{stroke:"M0.95,0.09 C0.9,0.01 0.72,0 0.66,0.12 C0.6,0.25 0.42,0.75 0.34,0.88 C0.28,0.99 0.1,0.99 0.05,0.91"},sum:{fill:"M0.04,0 L0.94,0 L0.98,0.24 L0.94,0.24 C0.9,0.1 0.8,0.07 0.62,0.07 L0.24,0.07 L0.58,0.5 L0.2,0.93 L0.64,0.93 C0.82,0.93 0.92,0.9 0.95,0.76 L0.99,0.76 L0.94,1 L0.02,1 L0.47,0.47 Z"},prod:{fill:"M0,0 L1,0 L1,0.04 L0.88,0.05 L0.88,0.95 L1,0.96 L1,1 L0.62,1 L0.62,0.96 L0.74,0.95 L0.74,0.06 L0.26,0.06 L0.26,0.95 L0.38,0.96 L0.38,1 L0,1 L0,0.96 L0.12,0.95 L0.12,0.05 L0,0.04 Z"}};function o(e,t,n=""){const r=i[e];return`<svg class="${t}" viewBox="0 0 1 1" preserveAspectRatio="none" aria-hidden="true"${n?` style="${n}"`:""}>${r.fill?`<path d="${r.fill}" fill="currentColor"/>`:`<path d="${r.stroke}" fill="none" stroke="currentColor" vector-effect="non-scaling-stroke"/>`}</svg>`}const a=.8,l=.2,u=.25,c=.7,p="−",h={"+":"add","-":"sub","*":"mul","/":"frac","^":"pow",_:"subscript",neg:"neg",pm:"pm","!":"factorial","=":"eq","===":"eq","≠":"neq","≠=":"neq","<":"lt",">":"gt","≤":"le","≥":"ge","≈":"approx","≡":"equiv","∈":"in","∉":"notin","∪":"union","∩":"intersect","→":"to","±":"pm","&":"and","|":"or","\\not":"not","\\xor":"xor","\\nand":"nand","\\nor":"nor","?:":"cases","()":"tuple","[]":"list","{}":"set","(]":"interval","[)":"interval","\\sumidx":"sum","\\prodidx":"prod",mod:"mod",pmod:"pmod",pmatrix:"matrix",bmatrix:"matrix",vmatrix:"matrix"},d={"=":"=","===":"=","≠":"≠","≠=":"≠","<":"<",">":">","≤":"≤","≥":"≥","∈":"∈","∉":"∉","→":"→","≈":"≈","≡":"≡","&":"∧","|":"∨","\\xor":"⊕","\\nand":"↑","\\nor":"↓"},f={"±":"±","∪":"∪","∩":"∩",mod:"mod"},m=["sin","cos","tan","csc","sec","cot","sinh","cosh","tanh"],g={arcsin:"sin",arccos:"cos",arctan:"tan",arcsinh:"sinh",arccosh:"cosh",arctanh:"tanh"},v=[...m,...Object.keys(g),"ln","det"],b={atan2:"atan2",max:"max",min:"min",gcd:"gcd",mean:"mean",round:"round",fixed:"fixed",expm1:"expm1",random:"random"},y={"()":["(",")"],"[]":["[","]"],"{}":["{","}"],"(]":["(","]"],"[)":["[",")"]},x=["int","lim","\\sumidx","\\prodidx"],w={"\\partial":"∂","\\nabla":"∇","\\ell":"ℓ","\\infty":"∞","\\emptyset":"∅"},k={vec:"→",hat:"ˆ",widehat:"ˆ",tilde:"˜",dot:"˙",ddot:"¨"},$=/^[acegmnopqrsuvwxyzαγεημνοπρστυχω]$/,q=e=>"symbol"===e?.type&&$.test(n.GREEK[e.value]??e.value),S=["boxed","overline","bar","underline","cancel",...Object.keys(k)],O={prefix:"mv",display:!0,fnParens:"auto",trigPowers:!0,inverseTrig:"arc",derivativeBrackets:"[",scriptFractions:"slash",cases:!0,label:!0,mathml:null,attributes:null,style:null},M=e=>String(e).replace(/&/g,"&").replace(/</g,"<").replace(/>/g,">").replace(/"/g,"""),A=e=>+e.toFixed(3)+"em",E=(e,t=a,n=l)=>({html:e,h:t,d:n});function N(...e){const t=e.flat().filter(Boolean);return{html:t.map(e=>e.html).join(""),h:Math.max(a,...t.map(e=>e.h)),d:Math.max(l,...t.map(e=>e.d))}}function I(e,t={}){const n=new L({...O,...t}),s=n.render(e,{level:0}),i=`${n.p}${n.o.display?` ${n.p}-display`:""}`,o="function"==typeof n.o.mathml?function(e,t,n,r){try{return String(e(t)).replace(/ id="mz-\d+"/g,"").replace(/^<math>/,`<math class="${n}-sr-math"${r?' display="block"':""}>`)}catch{return""}}(n.o.mathml,e,n.p,n.o.display):"",a=o?null:function(e,t){if(!1===t||null===t)return null;if("string"==typeof t)return t;try{return"function"==typeof t?t(e):r.toAudioSpeech(e)}catch{return null}}(e,n.o.label),l=null!==a||o?s.html.replace(/^<span /,'<span aria-hidden="true" '):s.html;return{html:`<span class="${i}"${null===a?"":` role="math" aria-label="${M(a)}"`}>${l}${o}</span>`,h:s.h,d:s.d}}class L{constructor(e){this.o=e,this.p=e.prefix}el(e,t,n="",r=""){return`<span class="${e.split(" ").map(e=>`${this.p}-${e}`).join(" ")}"${n?` style="${n}"`:""}${r}>${t}</span>`}text(e,t){const n=E(this.el(e,M(t)));return n.leaf={kind:e,content:M(t)},n}bin(e){return this.text("bin",e)}rel(e){return this.text("rel",e)}punct(e){return this.text("punct",e)}word(e){return this.text("word",e)}wrap(e,t,n){let r="";void 0!==e.id&&(r+=` data-node="${e.id}"`),"op"===e.type&&(r+=` data-op="${M(e.op)}"`);const s=this.o.attributes&&this.o.attributes(e)||{};for(const[e,t]of Object.entries(s))"class"!==e&&"style"!==e&&/^[A-Za-z_:][\w:.-]*$/.test(e)&&(r+=` ${e}="${M(t)}"`);const i=[s.style,this.o.style&&this.o.style(e)].filter(Boolean).join(";"),o=(n.leaf?["n",...t,n.leaf.kind]:["n",...t]).map(e=>`${this.p}-${e}`).concat(s.class?[M(s.class)]:[]).join(" "),a=n.leaf?n.leaf.content:n.html;return{html:`<span class="${o}"${i?` style="${M(i)}"`:""}${r}>${a}</span>`,h:n.h,d:n.d}}render(e,t){return"number"===e.type?this.number(e):"string"===e.type?this.wrap(e,["text"],this.text("text",e.value.replace(/^["'`]|["'`]$/g,""))):"symbol"===e.type?this.wrap(e,["symbol"],this.symbol(e.value)):this.operation(e,t)}number(e){return this.wrap(e,["number"],this.text("num",e.value.replace(/^-/,p)))}symbol(e){return n.GREEK[e]&&(e=n.GREEK[e]),w[e]?this.text("ord",w[e]):"\\+"===e||"\\-"===e?this.text("ord",e[1]):"-∞"===e?this.text("ord","−∞"):/^[A-Za-z]$/.test(e)||/^[α-ω]$/.test(e)?this.text("var",e):/^[A-Za-z]′+$/.test(e)?E(this.el("var",M(e[0]))+this.el("prime",M(e.slice(1)))):/^Δ[A-Za-z]$/.test(e)?E(this.el("ord","Δ")+this.el("var",e[1])):e.endsWith("⁻¹")?this.script(this.symbol(e.slice(0,-2)),this.text("num","−1"),{level:0}):/^\\[A-Za-z]+$/.test(e)?this.text("name",e.slice(1)):/^[A-Za-z]{2,}$/.test(e)?this.text("name",e):this.text("ord",e)}operation(e,t){const{op:r,args:s}=e,[i,o]=s,a=(e,n={})=>this.render(e,{...t,...n,forceParens:n.forceParens||!1,before:n.before||!1,leftFactor:!1}),l=h[r]??(/^[a-z0-9]+$/i.test(r)?r:"other"),u=t=>this.wrap(e,["op",`op-${l}`],t),c=(t,r)=>n.needsBrackets(e,t,r)&&"/"!==t.op?this.fence(a(t)):a(t);if(v.includes(r)||"log"===r)return u(this.named(e,t));if(b[r])return u(N(this.word(b[r]),this.fence(this.list(s,t))));if(n.isCustomFunction(r))return u(this.custom(e,t));const m=n.matrixRows(e);if(m)return u(this.matrix(e,m,t));if(y[r])return u(this.fence(this.list(s,t),...y[r]));if(("|"===r||"&"===r)&&s.length>=2&&s.every(z)){const e=e=>"|"!==e.op&&"&"!==e.op||e.op===r?a(e):this.fence(a(e));return u(N(s.map((t,n)=>n?[this.text("conj","|"===r?"or":"and"),e(t)]:[e(t)]).flat()))}if(d[r]&&2===s.length)return u(N(c(i,"left"),this.rel(d[r]),c(o,"right")));if(f[r]&&2===s.length)return u(N(c(i,"left"),this.bin(f[r]),c(o,"right")));switch(r){case"+":if(n.isMinusOneTimes(o)){const e=o.args[1],t=n.needsBrackets({op:"-"},e,"right")?this.fence(a(e)):a(e);return u(N(c(i,"left"),this.bin(p),this.wrap(o,["op","op-mul"],t)))}return"number"===o.type&&o.value.startsWith("-")?u(N(c(i,"left"),this.bin(p),this.wrap(o,["number"],this.text("num",o.value.slice(1))))):u(N(c(i,"left"),this.bin("+"),this.signed(o,c(o,"right"))));case"-":return u(N(c(i,"left"),this.bin(p),this.signed(o,c(o,"right"))));case"*":return u(this.product(e,t));case"/":return u(this.fraction(e,t));case"^":return u(this.power(e,t));case"_":{const e=n.bracketOp(i)&&n.precedenceOf(n.bracketOp(i))<100;return u(this.script(e?this.fence(a(i)):a(i,{forceParens:!0}),null,t,a(o,{level:t.level+1})))}case"neg":return u(N(this.text("sign",p),n.unaryNeedsBrackets(r,i)?this.fence(a(i)):a(i,{before:t.before})));case"pm":return u(N(this.text("sign","±"),n.unaryNeedsBrackets(r,i)?this.fence(a(i)):a(i)));case"!":return u(N(n.unaryNeedsBrackets(r,i)?this.fence(a(i)):a(i,{forceParens:!0}),this.text("ord","!")));case"\\not":return u(N(this.text("sign","¬"),n.unaryNeedsBrackets(r,i)?this.fence(a(i)):a(i)));case"pmod":return u(N(a(i),this.fence(N(this.word("mod"),this.text("space",""),a(o)))));case"sqrt":return u(this.radical(a(i)));case"root":return u(this.radical(a(o),this.render(i,{level:t.level+2})));case"abs":return u(this.fence(a(i),"|","|"));case"floor":return u(this.fence(a(i),"⌊","⌋"));case"ceil":return u(this.fence(a(i),"⌈","⌉"));case"loglog":return u(N(this.word("ln"),this.fence(N(this.word("ln"),this.fence(a(i))))));case"logloglog":return u(N(this.word("ln"),this.fence(N(this.word("ln"),this.fence(N(this.word("ln"),this.fence(a(i))))))));case"perm":return u(this.script(this.script(E(""),this.render(i,{level:t.level+1}),t),null,t,this.render(o,{level:t.level+1}),this.word("P")));case"comb":return u(this.fence(this.stack(a(i),a(o),!1)));case"?:":return u(this.o.cases?this.cases(e,t):N(a(i),this.bin("?"),a(o),this.bin(":"),a(s[2])));case"sum":case"prod":{const e={op:"sum"===r?"+":"*"},t=(t,r)=>n.needsBrackets(e,t,r?"right":"left")?this.fence(a(t)):a(t);return u(N(s.map((e,n)=>n?[this.bin("sum"===r?"+":"·"),t(e,n)]:[t(e,n)]).flat()))}case"der":return u(this.derivative(e,t));case"int":return u(this.integral(s,t));case"lim":return u(this.limit(s,t));case"\\sumidx":return u(this.bigOperator("sum",s,t));case"\\prodidx":return u(this.bigOperator("prod",s,t))}throw new Error(`Inline Math cannot draw '${r}'`)}signed(e,t){return("number"===e.type?e.value.startsWith("-"):"neg"===e.op||"pm"===e.op)&&!t.fenced?this.fence(t):t}list(e,t){return N(e.map((e,n)=>n?[this.punct(","),this.render(e,t)]:[this.render(e,t)]).flat())}product(e,t){const[r,s]=e.args;if(n.isMinusOneTimes(e))return N(this.text("sign",p),n.unaryNeedsBrackets("neg",s)?this.fence(this.render(s,t)):this.render(s,t));const i=n.bracketedSides(e);x.includes(r.op)&&(i.left=!0);const o=!e.written&&n.isImplicitProduct(r,s,i),a=function(e){for(;"op"===e.type;){if(v.includes(e.op)||"log"===e.op||b[e.op]||n.isCustomFunction(e.op))return!0;if("^"!==e.op&&"*"!==e.op)return!1;e=e.args[0]}return!1}(s),l=i.left?this.fence(this.render(r,t)):this.render(r,{...t,before:o&&!a,leftFactor:!0}),u=i.right?this.fence(this.render(s,t)):this.render(s,{...t,before:t.before});return N(l,o?E(this.el(a?"fnspace":"times","")):this.bin("cross"===e.written?"×":"·"),u)}named(e,t,n=null){const{op:r,args:s}=e,i="log"===r?s[1]:s[0];let o;o=g[r]&&"power"===this.o.inverseTrig?this.script(this.word(g[r]),this.text("num","−1"),t):this.word(r),n&&(o=this.script(o,n,t)),"log"===r&&(o=this.script(o,null,t,this.render(s[0],{level:t.level+1})));const a="auto"===this.o.fnParens&&!t.forceParens&&!t.before&&T(i),l=this.render(i,{...t,forceParens:!1,before:!1});return N(o,a?N(E(this.el("fnspace","")),l):this.fence(l))}custom(e,t){const r=n.customName(e.op),s=e.args;if(S.includes(r)&&1===s.length)return this.decorate(r,this.render(s[0],t),s[0]);return N(/^[A-Za-z]′*(⁻¹)?$/.test(r)?this.symbol(r):this.word(r),E(this.el("callgap","")),this.fence(this.list(s,t)))}decorate(e,t,n){switch(e){case"boxed":return E(this.el("boxed",t.html),t.h+.22,t.d+.22);case"cancel":return E(this.el("cancel",t.html+o("cancel",`${this.p}-cancel-line`)),t.h,t.d);case"underline":return E(this.el("underline",t.html),t.h,t.d+.12);case"overline":case"bar":return E(this.el("over"+(q(n)?" over-low":""),t.html),t.h+.14,t.d);default:{const r=q(n);return E(this.el("accent"+(r?" accent-low":""),this.el(`accent-mark accent-${e}`,k[e])+t.html),t.h+.3,t.d)}}}fraction(e,t){const[r,s]=e.args;if(t.level>0&&"slash"===this.o.scriptFractions&&T(r,!0)&&T(s,!0)){const e={...t,leftFactor:!1},i=(t,r)=>"op"!==t.type||T(t)&&(!r||"*"!==t.op||n.isMinusOneTimes(t))?this.render(t,e):this.fence(this.render(t,e)),o=N("op"===r.type&&"neg"===r.op?this.render(r,e):i(r,!1),this.text("ord","/"),i(s,!0));return t.leftFactor?this.fence(o):o}const i=t.level>0||t.inFraction||!this.o.display?.8:1,o={...t,inFraction:!0,forceParens:!1,before:!1};return this.stack(this.render(r,o),this.render(s,o),!0,i)}stack(e,t,n=!0,r=1){const s=e=>1===r?e.html:this.el("scaled",e.html,`font-size:${A(r)}`),i=n?.06:0,o=u+i/2+.1+Math.max(l,r*e.d),c=this.el("frac"+(n?"":" frac-nobar"),this.el("numer",s(e))+this.el("denom",s(t)),`vertical-align:${A(o)}`);return E(c,o+Math.max(a,r*e.h),Math.max(a,r*t.h)+Math.max(l,r*t.d)+.1+i/2-u)}power(e,t){const[r,s]=e.args,i={...t,level:t.level+1,forceParens:!1,before:!1,inFraction:!1,leftFactor:!1},o=()=>this.render(s,i);if(this.o.trigPowers&&m.includes(r.op)&&Z(s))return this.wrap(r,["op",`op-${r.op}`],this.named(r,t,o()));if("_"===r.op){const e=this.render(r.args[1],i);return this.wrap(r,["op","op-subscript"],this.script(this.render(r.args[0],{...t,forceParens:!0}),o(),t,e))}const a=n.needsBrackets(e,r,"left")||"number"===r.type&&r.value.startsWith("-")||"/"===r.op||v.includes(r.op)||x.includes(r.op)?this.fence(this.render(r,t)):this.render(r,{...t,forceParens:!0});return this.script(a,o(),t)}script(e,t,n,r=null,s=null){const i=n.level>0?.8:c,o=s?N(e,s):e;let a=t?Math.max(.42,e.h-.38,i*t.d+.12):0,l=r?Math.max(.2,e.d-.05,i*r.h-.45):0;if(t&&r){const e=.1-(a-i*t.d-(i*r.h-l));e>0&&(l+=e)}const u=e=>this.el("script",e.html,`font-size:${A(i)}`);if(t&&!r)return E(e.html+this.el("sup",t.html,`font-size:${A(i)};vertical-align:${A(a/i)}`),Math.max(o.h,a+i*t.h),Math.max(o.d,i*t.d-a));if(r&&!t)return E(o.html+this.el("sub",r.html,`font-size:${A(i)};vertical-align:${A(-l/i)}`),Math.max(o.h,i*r.h-l),Math.max(o.d,l+i*r.d));const p=a+i*t.h,h=l+i*r.d,d=this.el("subsup",u(t)+u(r),`vertical-align:${A(a)};height:${A(p+h)}`);return E(o.html+d,Math.max(o.h,p),Math.max(o.d,h))}radical(e,t=null){const n=Math.max(e.h,a)+.1+.06,r=Math.max(e.d,l),s=n+r,i=o("sqrt",`${this.p}-hook`,`height:${A(s)};width:${A(.5+.06*(s-1))};vertical-align:${A(-r)}`);let u="";if(t){const e=.8*c;u=this.el("rootindex",t.html,`font-size:${A(e)};vertical-align:${A((.55*s-r)/e)}`)}return E(this.el("sqrt",u+i+this.el("radicand",e.html)),n,r)}fence(e,t="(",n=")"){const r=Math.max(e.h,a)+Math.max(e.d,l),s=r>1.25,i=s?.1:0,u=(e,t)=>{if(!e)return{html:"",w:0};const n={"(":.26,")":.26,"{":.36,"}":.36}[e];if(n){const i=n+(s?Math.min(.2,.05*(r-1)):0);return{html:o(e,`${this.p}-delim ${this.p}-delim-${t}`,`width:${A(i)}`),w:i+.1}}const i={"[":"lbrack","]":"rbrack","|":"vert","⌊":"lfloor","⌋":"rfloor","⌈":"lceil","⌉":"rceil"}[e];return{html:this.el(`delim ${i} delim-${t}`,""),w:"|"===e?.18:.3}},c=u(t,"l"),p=u(n,"r"),h=`padding:${A(i)} ${A(p.w)} ${A(i)} ${A(c.w)}`,d=E(this.el("fence",c.html+e.html+p.html,h),Math.max(e.h,a)+i,Math.max(e.d,l)+i);return d.fenced=!0,d}derivative(e,t){const r=this.leibniz(e,t),{by:s,at:i}=n.derivativeOrder(e);if(!i)return r;const o=e.args[1],a=this.render({...o,args:[{...s,id:void 0},i]},{...t,level:t.level+1});return this.script(this.fence(r,"","|"),null,t,a)}leibniz(e,t){const{n:r,body:s,by:i,variable:o}=n.derivativeOrder(e),a={...t,level:t.level+1},l=()=>this.text("d","d"),u=()=>r>1?this.render({type:"number",value:String(r)},a):null,c={...t,inFraction:!0},p=N(l(),u()?this.script(this.render(i,c),u(),c):this.render(i,c)),h=e=>N(u()?this.script(l(),u(),c):l(),e||[]),d=t.level>0||t.inFraction||!this.o.display?.8:1;if(o)return this.stack(h(this.render(s,c)),p,!0,d);const f=n.bracketOp(s)&&n.precedenceOf(n.bracketOp(s))<100,[m,g]="("===this.o.derivativeBrackets?["(",")"]:["[","]"],v=f?this.fence(this.render(s,t),m,g):this.render(s,t);return N(this.stack(h(),p,!0,d),v)}integral(e,t){const[r,s,i,o]=e,a=e=>this.render(e,t),l=e=>e?this.render(e,{...t,level:t.level+1}):null,u=()=>this.text("var",n.firstVariable(r)||"x");let c,p=null,h=null;switch(e.length){case 1:c=u();break;case 2:n.isVariable(s)?c=a(s):(c=u(),p=l(s));break;case 3:n.isVariable(s)?(c=a(s),p=l(i)):(c=u(),p=l(s),h=l(i));break;default:c=a(s),p=l(i),h=l(o)}const d=a(r),f=E(this.el("dx",this.el("d","d")+c.html),c.h,c.d);return N(this.bigSign("int",d,p,h,t),d,f)}bigSign(e,t,n,r,s){const i=!this.o.display||s.level>0,a=Math.max(i?.6:.95,Math.max(t.h-u,t.d+u)+.12),l=o(e,`${this.p}-bigsign ${this.p}-${e}sign`,`height:${A(2*a)};width:${A(i?.38:.5)};vertical-align:${A(u-a)}`);if(!n&&!r)return E(l,u+a,a-u);const p=c,h=r||E(""),d=n||E(""),f=u+a-p*h.h;d.d;const m=this.el("limits",this.el("script",h.html,`font-size:${A(p)}`)+this.el("script lower",d.html,`font-size:${A(p)}`),`vertical-align:${A(f)};height:${A(2*a)}`);return E(l+m,u+a,a-u)}limit(e,t){const[r,s,i,o]=e,a={...t,level:t.level+1},l=e=>this.render(e,a),u=()=>this.rel("→");let c;switch(e.length){case 1:return N(this.word("lim"),E(this.el("fnspace","")),this.body(r,t));case 2:{const e=n.firstVariable(r),t="number"===s.type||"symbol"===s.type&&s.value.includes("∞");c=e&&t?N(this.text("var",e),u(),l(s)):l(s);break}case 3:c=N(l(s),u(),l(i));break;default:{const e=n.firstLeaf(o).toLowerCase().startsWith("r")?"+":p;c=N(l(s),u(),this.script(l(i),this.wrap(o,["symbol"],this.text("ord",e)),a))}}return N(this.under(this.word("lim"),c,t),this.body(r,t))}under(e,t,n){return!this.o.display||n.level>0?this.script(e,null,n,t):E(this.el("under",e.html+this.el("script",t.html,`font-size:${A(.7)}`)),e.h,Math.max(e.d,l)+.05+.7*(t.h+t.d))}body(e,t){const r=n.bracketOp(e);return r&&n.precedenceOf(r)<n.precedenceOf("*")?this.fence(this.render(e,t)):this.render(e,t)}bigOperator(e,t,n){const[r,s,i]=t,a={...n,level:n.level+1},l=s?this.render(s,a):null,p=i?this.render(i,a):null,h=this.body(r,n);if(!this.o.display||n.level>0){const t=.55,r=o(e,`${this.p}-bigsign`,`height:${A(2*t)};width:${A(.8)};vertical-align:${A(u-t)}`);return N(this.script(E(r,u+t,t-u),p,n,l),h)}const d=.68,f=c,m=o(e,`${this.p}-bigsign`,`height:${A(1.36)};width:${A("sum"===e?1:1.05)}`),g=p?1.01+f*p.d:u-d,v=e=>this.el("script",e.html,`font-size:${A(f)}`),b=this.el("bigop",(p?v(p):"")+m+(l?v(l):""),`vertical-align:${A(g)}`);return N(E(b,.93+(p?.08+f*(p.h+p.d):0),d-u+(l?.08+f*(l.h+l.d):0)),h)}matrix(e,t,r){const s=t.map(e=>e.map(e=>this.render(e,r))),i=s.map(e=>({h:Math.max(a,...e.map(e=>e.h)),d:Math.max(l,...e.map(e=>e.d))})),o=i.reduce((e,t)=>e+t.h+t.d,0)+.3*(t.length-1),c=u+o/2-i[0].h,p=s.map((t,n)=>{const r=t.map(e=>this.el("matrix-cell",e.html)).join(""),s=e.args[n];return s&&"op"===s.type&&"[]"===s.op?this.wrap(s,["op","op-list","matrix-row"],E(r)).html:r}).join(""),h=t[0].length,d=E(this.el("matrix",p,`grid-template-columns:repeat(${h},auto);vertical-align:${A(c)}`),u+o/2,o/2-u),[f,m]=n.MATRICES[e.op]??["[","]"];return this.fence(d,f,m)}cases(e,t){const n=[];let r=e;for(;"op"===r.type&&"?:"===r.op;)n.push([this.render(r.args[1],t),N(this.word("if"),this.text("space",""),this.render(r.args[0],t))]),r=r.args[2];"symbol"===r.type&&"unchanged"===r.value||n.push([this.render(r,t),this.word("otherwise")]);const s=n.map(([e,t])=>({h:Math.max(e.h,t.h),d:Math.max(e.d,t.d)})),i=s.reduce((e,t)=>e+t.h+t.d,0)+.25*(n.length-1),o=u+i/2-s[0].h,a=n.map(([e,t])=>this.el("case-value",e.html)+this.el("case-cond",t.html)).join(""),l=E(this.el("cases",a,`vertical-align:${A(o)}`),u+i/2,i/2-u);return this.fence(l,"{","")}}function T(e,t=!1){return"number"===e.type?!e.value.startsWith("-")||t:"symbol"===e.type||"op"===e.type&&("abs"===e.op||n.matrixRows(e)?!t:!t||"neg"!==e.op&&"^"!==e.op?"*"===e.op&&!n.isMinusOneTimes(e)&&e.args.every(e=>"number"===e.type&&!e.value.startsWith("-")||C(e)||"*"===e.op&&T(e,t)):T(e.args[0],!0)&&("neg"===e.op||T(e.args[1],!0)))}const j=["=","===","≠","≠=","<",">","≤","≥","≈","≡","∈","∉"],z=e=>"op"===e.type&&e.args.length>=2&&(2===e.args.length&&j.includes(e.op)||("|"===e.op||"&"===e.op)&&e.args.every(z)),C=e=>"symbol"===e.type&&(1===e.value.length||/^[α-ωΑ-Ω]$/.test(e.value)||Boolean(n.GREEK[e.value])),Z=e=>"number"===e.type&&/^[1-9]\d*$/.test(e.value)&&Number(e.value)<10;for(const e of[h,d,f,g,b,y,w,k])Object.setPrototypeOf(e,null);function B(e){const{id:t,from:n,...r}=e;return r.args&&(r.args=r.args.map(B)),r}const F=e=>n.toPostfix(e).join(" ");function D(e,t){const r=new Set;R(e,t,r);const s=[];return n.walk(e,e=>{r.has(e)&&s.push(e)}),s}function R(e,t,r){if(null!=t)if(Array.isArray(t))t.forEach(t=>R(e,t,r));else if("number"!=typeof t)if("function"!=typeof t){if("string"==typeof t){const s=F(n.parseTree(t));return void n.walk(e,e=>{F(e)===s&&r.add(e)})}if(t.path){const n=P(e,t.path);return void(n&&r.add(n))}if(t.type){const s=F(t);n.walk(e,e=>{e!==t&&F(e)!==s||r.add(e)})}}else n.walk(e,(e,n)=>{t(e,n)&&r.add(e)});else n.walk(e,e=>{e.id===t&&r.add(e)})}function P(e,t){let n=e;for(const e of t){if("op"!==n.type||!n.args[e])return null;n=n.args[e]}return n}function _(e,t){const n=[],r=e=>{if(e.id===t)return!0;if("op"!==e.type)return!1;for(let t=0;t<e.args.length;t++){if(n.push(t),r(e.args[t]))return!0;n.pop()}return!1};return r(e)?n:null}function V(e){let t=0;const r=e=>{"op"===e.type&&(e.args.forEach(r),n.operator(e.op)?.arity===n.VARIADIC&&t++),e.id=t++};return r(e),e}function W(e,t={}){const{blocks:r}=t;if("string"==typeof e)return n.parseTree(e,r?{blocks:e=>r(e,t.scope)}:{});if(Array.isArray(e))return n.fromPostfix(e);if(e&&"object"==typeof e&&e.type){if(void 0!==e.id)return e;const t=structuredClone(e);return n.walk(t,e=>{"op"!==e.type&&void 0!==e.value&&(e.value=String(e.value))}),V(t)}throw new Error("Inline Math needs an expression, standard postfix or a tree")}function U(e,t){const{colors:n,highlight:r,scope:s,blocks:i,...o}=t,a=new Map;for(const[t,r]of function(e){return e?Array.isArray(e)?e:Object.entries(e).map(([e,t])=>[/^\d+$/.test(e)?Number(e):e,t]):[]}(n))if(H(r))for(const n of D(e,t))a.set(n,`color:${r}`);const l=new Set(void 0===r?[]:D(e,r));if(!a.size&&!l.size)return o;const u=o.prefix||"mv";return{...o,style:e=>[a.get(e),o.style&&o.style(e)].filter(Boolean).join(";"),attributes:e=>{const t={...o.attributes?o.attributes(e):{}};return l.has(e)&&(t.class=[t.class,`${u}-hl`].filter(Boolean).join(" ")),t}}}function H(e){return"string"==typeof e&&/^[#\w\s.,%()/+-]+$/.test(e)&&!/url\s*\(|expression/i.test(e)}function J(e,n={}){return W(e,{...n,blocks:n.blocks??t.calculateBlock})}function K(e,n={}){return function(e,t={}){const n=W(e,t);return I(n,U(n,t)).html}(e,{...n,blocks:n.blocks??t.calculateBlock})}function Y(e,t,n){const r=(e,s)=>s===t.length?n:{...e,args:e.args.map((e,n)=>n===t[s]?r(e,s+1):e)};return B(r(e,0))}function G(e,t,{parse:n,commit:r,cancel:s,label:i="Edit",prefix:o="mv"}){const a=e.ownerDocument;if(!a||!a.body)return null;const l=a.defaultView,u=e.getBoundingClientRect(),c=a.createElement("input");c.type="text",c.className=`${o}-edit`,c.value=t,c.spellcheck=!1,c.autocomplete="off",c.setAttribute("aria-label",i);const p=()=>{c.style.width=`${Math.max(4,c.value.length+2)}ch`},h=l.getComputedStyle(e);Object.assign(c.style,{position:"absolute",left:`${u.left+l.scrollX}px`,top:`${u.top+l.scrollY+u.height/2}px`,minWidth:`${Math.max(u.width,32)}px`,fontSize:h.fontSize}),p(),a.body.appendChild(c),l.getSelection?.()?.removeAllRanges(),c.focus(),c.select();let d=!1;const f=()=>{d=!0,c.remove()};c.cancelEdit=()=>{d||(f(),s&&s())};const m=e=>{if(d)return!0;if(!e||c.value===t)return f(),s&&s(),!0;let i;try{i=n(c.value)}catch(e){return c.setAttribute("aria-invalid","true"),c.title=e.message,!1}return f(),r(i,c.value),!0};return c.addEventListener("keydown",e=>{e.stopPropagation(),"Enter"===e.key&&(e.preventDefault(),m(!0)),"Escape"===e.key&&(e.preventDefault(),m(!1))}),c.addEventListener("input",()=>{p(),c.removeAttribute("aria-invalid"),c.removeAttribute("title")}),c.addEventListener("blur",()=>{m(!0)||m(!1)}),c}class Q{constructor(e,t,n={}){this.element=e,this.options=n,this.p=n.prefix||"mv",this.handlers=[],this.clicks=[],this.active=null,this.live=X(e,n.announce,this.p),this.set(t)}set(e,{animate:t=!1,duration:n=600,easing:r="ease-in-out"}={}){const s=J(e,this.options),{html:i}=I(s,U(s,this.options));if(this.editor){const e=this.editor;this.editor=null,e.cancelEdit?.()}const o=ee(t)&&this.tree?this.snapshot():null,a=void 0!==this.tree;return this.tree=s,this.element.innerHTML=i,this.root=this.element.firstElementChild,this.handlers.length&&this.root.classList.add(`${this.p}-clickable`),this.editing&&this.root.classList.add(`${this.p}-editable`),this.active=null,(this.clicks.length||this.editing)&&this.focusable(),o&&this.morph(o,{duration:n,easing:r}),a&&this.live&&this.announce(this.spoken()),this}spoken(){const e=this.root&&this.root.getAttribute&&this.root.getAttribute("aria-label");if(e)return e;try{return r.toAudioSpeech(this.tree)}catch{return""}}announce(e){return this.say(this.live,e)}say(e,t){if(!e)return this;e.textContent="";const n=()=>{e.textContent=t};return"function"==typeof requestAnimationFrame?requestAnimationFrame(()=>requestAnimationFrame(n)):setTimeout(n,50),this}nodes(e){return D(this.tree,e)}elements(e){return this.nodes(e).map(e=>this.elementOf(e)).filter(Boolean)}elementOf(e){return void 0===e.id?null:this.root.querySelector(`[data-node="${e.id}"]`)}highlight(e,t=`${this.p}-hl`){return this.elements(e).forEach(e=>e.classList.add(t)),this}unhighlight(e=null,t=`${this.p}-hl`){return(null===e?this.root.querySelectorAll(`.${t}`):this.elements(e)).forEach(e=>e.classList.remove(t)),this}color(e,t){return this.elements(e).forEach(e=>{e.style.color=t||""}),this}on(e,t){const n=e=>{const n=e.target.closest?.("[data-node]");if(!n||!this.root.contains(n))return;const r=Number(n.dataset.node),s=D(this.tree,r)[0];t({node:s,id:r,path:_(this.tree,r),element:n,event:e})};this.element.addEventListener(e,n);const r=[e,n];return this.handlers.push(r),this.root.classList.add(`${this.p}-clickable`),"click"===e&&(this.clicks.push(t),this.keyboard()),()=>{this.element.removeEventListener(e,n),this.clicks=this.clicks.filter(e=>e!==t),this.handlers=this.handlers.filter(e=>e!==r),!this.handlers.length&&this.root&&this.root.classList.remove(`${this.p}-clickable`)}}destroy(){if(this.editor){const e=this.editor;this.editor=null,e.cancelEdit?.()}for(const[e,t]of this.handlers)this.element.removeEventListener(e,t);this.handlers=[],this.clicks=[],this.keyListener&&this.element.removeEventListener("keydown",this.keyListener),this.editListener&&this.element.removeEventListener("dblclick",this.editListener),this.keyListener=this.editListener=null,this.keysOn=this.editOn=!1;for(const e of new Set([this.live,this.partsLive]))e&&"view"===e.dataset?.mvMadeBy&&e.remove();return this.live=this.partsLive=null,this}editable({toText:e,onEdit:t}={}){if("function"!=typeof e)throw new Error("editable needs { toText } (import { toText } from 'mathzetta/text')");return this.editing={toText:e,onEdit:t},this.root&&this.root.classList&&this.root.classList.add(`${this.p}-editable`),this.keyboard(),!this.editOn&&this.element.addEventListener&&(this.editOn=!0,this.editListener=e=>{const t=e.target.closest?.("[data-node]");t&&this.root.contains(t)&&(e.preventDefault(),this.edit(D(this.tree,Number(t.dataset.node))[0]))},this.element.addEventListener("dblclick",this.editListener)),this}edit(e=this.tree,{returnFocus:t=!1}={}){if(!this.editing)throw new Error("call editable({ toText }) first");const n="object"==typeof e&&e&&e.type?e:this.nodes(e)[0];if(!n)return null;const s=_(this.tree,n.id)||[],i=this.elementOf(n)||this.root;let o="Edit";try{o=`Edit ${r.toAudioSpeech(n)}`}catch{}const a=()=>{t&&this.root.focus&&this.root.focus()};return this.editor=G(i,this.editing.toText(n),{label:o,prefix:this.p,parse:e=>J(e,this.options),commit:(e,n)=>{this.set(Y(this.tree,s,e),{animate:!0});const r=P(this.tree,s);t&&r&&this.focusPart(r===this.tree?null:r),a(),this.editing.onEdit&&this.editing.onEdit({tree:this.tree,text:this.editing.toText(this.tree),path:s,part:n})},cancel:a}),this.editor}focusable(){this.root&&this.root.setAttribute&&(this.root.setAttribute("tabindex","0"),this.root.getAttribute("aria-label")||(this.root.setAttribute("role","math"),this.root.setAttribute("aria-label",this.spoken())),this.root.setAttribute("aria-description",this.editing?"Arrow keys move between parts, F2 edits one.":"Arrow keys move between parts, Enter selects one."))}keyboard(){this.focusable(),!this.keysOn&&this.element.addEventListener&&(this.keysOn=!0,this.partsLive=this.live||X(this.element,!0,this.p),this.keyListener=e=>this.key(e),this.element.addEventListener("keydown",this.keyListener))}key(e){if(!this.root||!this.root.contains(e.target))return;const t=this.active;let n;switch(e.key){case"ArrowDown":n=t?this.partsOf(t)[0]:this.partsOf(this.tree)[0];break;case"ArrowUp":n=t?this.outerOf(t):void 0;break;case"ArrowRight":n=t?this.neighbor(t,1):this.partsOf(this.tree)[0];break;case"ArrowLeft":n=t?this.neighbor(t,-1):void 0;break;case"Home":case"Escape":n=null;break;case"F2":if(!this.editing)return;return e.preventDefault(),void this.edit(t||this.tree,{returnFocus:!0});case"Enter":case" ":{e.preventDefault();const n=t||this.tree,r=this.elementOf(n)||this.root,s={node:n,id:n.id,path:_(this.tree,n.id),element:r,event:e};for(const e of this.clicks)e(s);return}default:return}e.preventDefault(),void 0!==n&&this.focusPart(n)}focusPart(e){const t=`${this.p}-focus`;this.root.querySelectorAll(`.${t}`).forEach(e=>e.classList.remove(t)),this.active=e;const n=e&&this.elementOf(e);n&&n.classList.add(t);let s="";try{s=e?r.toAudioSpeech(e):this.spoken()}catch{s=""}return this.say(this.partsLive,s),this}partsOf(e){const t=[],n=e=>{this.elementOf(e)?t.push(e):"op"===e.type&&e.args.forEach(n)};return e&&"op"===e.type&&e.args.forEach(n),t}outerOf(e){const t=_(this.tree,e.id);for(let e=t?t.length-1:-1;e>0;e--){const n=P(this.tree,t.slice(0,e));if(n&&this.elementOf(n))return n}return null}neighbor(e,t){const n=this.partsOf(this.outerOf(e)||this.tree),r=n.indexOf(e);return r<0?void 0:n[r+t]}segments(e={}){return r.toSpeechSegments(this.tree,e)}showSegment(e,t=`${this.p}-hl`){return this.unhighlight(null,t),e&&void 0!==e.id&&this.highlight(e.id,t),this}snapshot(){const e=new Map,t=n=>{const r=this.elementOf(n);if(r){const t=F(n);e.has(t)||e.set(t,[]),e.get(t).push({rect:r.getBoundingClientRect(),node:n,sig:t})}"op"===n.type&&n.args.forEach(t)};return t(this.tree),e}morph(e,{duration:t,easing:n}){if("undefined"==typeof Element||!Element.prototype.animate)return;const r=t=>{if("op"===t.type)for(const n of t.args){const t=e.get(F(n)),s=t?t.findIndex(e=>e.node===n):-1;s>-1&&t.splice(s,1),r(n)}},s=i=>{const o=this.elementOf(i),a=o&&e.get(F(i));if(a&&a.length){const{rect:e,node:s}=a.shift();r(s);const i=o.getBoundingClientRect(),l=e.left-i.left,u=e.top-i.top,c=i.width?e.width/i.width:1,p=i.height?e.height/i.height:1;return void((Math.abs(l)+Math.abs(u)>.5||Math.abs(c-1)+Math.abs(p-1)>.01)&&o.animate([{transformOrigin:"0 0",transform:`translate(${l}px, ${u}px) scale(${c}, ${p})`},{transformOrigin:"0 0",transform:"none"}],{duration:t,easing:n}))}"op"===i.type?i.args.forEach(s):o&&o.animate([{opacity:0},{opacity:0},{opacity:1}],{duration:t,easing:n})};s(this.tree)}}function X(e,t,n){if(!t)return null;if("object"==typeof t&&1===t.nodeType)return t;if("undefined"==typeof document||!e.insertAdjacentElement)return null;const r=e.nextElementSibling;if(r&&"view"===r.dataset?.mvMadeBy&&r.classList.contains(`${n}-sr-only`))return r;const s=document.createElement("span");return s.dataset.mvMadeBy="view",s.className=`${n}-sr-only`,s.setAttribute("aria-live","polite"),s.setAttribute("aria-atomic","true"),e.insertAdjacentElement("afterend",s),s}function ee(e){return!!e&&("always"===e||!("function"==typeof matchMedia&&matchMedia("(prefers-reduced-motion: reduce)").matches))}const te=Symbol.for("inlinemath.expressions"),ne=new Set(["symbol","number"]);function re(e){return e?"symbol"===e.type?e.value:"op"===e.type&&"_"===e.op&&2===e.args.length&&"symbol"===e.args[0].type&&ne.has(e.args[1].type)?`${e.args[0].value}_${e.args[1].value}`:null:null}function se(e){const{id:t,...n}=e;return n.args&&(n.args=n.args.map(se)),n}function ie(e,t){const n=(e,r)=>{if(!r&&void 0!==e.from)return t(e.from);const{id:s,from:i,...o}=e;return o.args&&(o.args=o.args.map(e=>n(e,!1))),o};return n(e,!0)}const oe=new Set;function ae(e,t){let r=!1;const s=new Set,i=(e,o=oe)=>{const a=re(e);if(null!==a){if(!s.has(a)&&!o.has(a)){const e=t(a);if(e){r=!0,s.add(a);const t={...i(B(e)),from:a};return s.delete(a),t}}return e}if(e.args){const t=function(e){const[t,r]=e.args,s=e=>e&&"symbol"===e.type?e.value:null;switch(e.op){case"der":return"="===r?.op?s(r.args[0])&&{name:s(r.args[0]),where:e=>0===e,index:1}:s(r)&&{name:s(r),where:e=>e<=1};case"int":{const i=s(r)??(3===e.args.length||1===e.args.length?n.firstVariable(t)||"x":null);return i&&{name:i,where:e=>0===e||1===e&&s(r)===i}}case"lim":return"→"===r?.op&&s(r.args[0])&&{name:s(r.args[0]),where:e=>0===e,index:1};case"\\sumidx":case"\\prodidx":return("="===r?.op||"∈"===r?.op)&&s(r.args[0])&&{name:s(r.args[0]),where:e=>0===e,index:1};default:return null}}(e);if(!t)return{...e,args:e.args.map(e=>i(e,o))};const r=new Set([...o,t.name]);return{...e,args:e.args.map((e,n)=>n===t.index?{...e,args:e.args.map((e,t)=>i(e,0===t?r:o))}:i(e,t.where(n)?r:o))}}return e},o=i(e);return{tree:r?se(o):e,changed:r}}const le="[-+]?(?:\\d+\\.?\\d*|\\.\\d+)",ue=new RegExp(`^(${le})\\s*\\.\\.\\s*(${le})(?:\\s+step\\s+(${le}))?(?:\\s*=\\s*(${le}))?$`);function ce(e){const t=/^\s*\[\[([\s\S]*)\]\]\s*$/.exec(e);if(!t||/\]\s*,\s*\[/.test(t[1]))return null;const n=t[1].trim(),r=ue.exec(n);if(r){const e=Number(r[1]),t=Number(r[2]);if(!(t>e))return null;const n=void 0!==r[3]?Number(r[3]):Number.isInteger(e)&&Number.isInteger(t)?1:(t-e)/100;if(!(n>0))return null;const s=void 0!==r[4]?Math.min(t,Math.max(e,Number(r[4]))):e;return{kind:"slider",min:e,max:t,step:n,default:String(s)}}if(n.includes("|")){const e=n.split("|").map(e=>e.trim()).filter(Boolean);if(e.length)return{kind:"dropdown",options:e,default:e[0]}}return{kind:"textbox",default:n}}const pe=Symbol("set on the page");class he{constructor(){this.owners=new Map,this.chosen=new Map,this.listeners=new Set}definitions(e){const t=new Map;for(const[n,r]of this.owners)if(n!==e)for(const[e,n]of r)t.delete(e),t.set(e,n);return t}textOf(e){const t=this.chosen.get(e.name);return t&&t.key===e.key?t.text:e.text}get(e){const t=this.definitions().get(e);return t?this.textOf(t):void 0}names(){return[...this.definitions().keys()]}set(e,t){t=String(t);const n=this.definitions().get(e);if(n&&n.input){const r=this.chosen.get(e);if(r&&r.key===n.key&&r.text===t)return this;this.chosen.set(e,{key:n.key,text:t})}else{const n=new Map(this.owners.get(pe));n.set(e,{name:e,text:t,key:`page:${t}`,input:null}),this.owners.delete(pe),this.owners.set(pe,n)}return this.notify(null,e),this}clear(e){return void 0===e?(this.owners.clear(),this.chosen.clear()):(this.owners.get(pe)?.delete(e),this.chosen.delete(e)),this.notify(null,e),this}subscribe(e){return this.listeners.add(e),()=>this.listeners.delete(e)}own(e,t){const n=this.owners.get(e);var r,s;(r=n,s=t,(r?.size??0)===(s?.size??0)&&[...r??[]].every(([e,t])=>s?.get(e)?.key===t.key))?t&&this.owners.set(e,t):(t&&t.size?this.owners.set(e,t):this.owners.delete(e),this.notify(e))}notify(e,t){for(const n of[...this.listeners])n(e,t)}}function de(){return new he}const fe=de(),me=new RegExp("(\\d+)","g");function ge(e,{delimiters:t=["$$","$","\\[","\\("]}={}){const n=[];let r="",s=0;const i=String(e).replace(/[\uE000-\uE003]/g,"�"),o=e=>0===e||"\n"===i[e-1],a=function(e){const t=new Map,n=e=>/^( {4}|\t)/.test(e);let r=0,s=!0,i=!1,o=-1;for(const a of e.split("\n")){const e=!a.trim();o>-1&&!e&&!n(a)&&(t.set(o,r-1),o=-1),o<0&&!e&&n(a)&&s&&!i&&(o=r),e||n(a)||(i=Oe.test(a)||i&&/^\s/.test(a)),s=e,r+=a.length+1}o>-1&&t.set(o,e.length);return t}(i);let l=-1;const u=new Set,c=(e,t,r)=>(n.push({source:e,display:t,raw:r,start:s,end:s+r.length}),`${n.length-1}`);for(;s<i.length;){if(a.has(s)){r+=i.slice(s,a.get(s)),s=a.get(s);continue}if(o(s)){const e=/^( {0,3})(`{3,}|~{3,})([^\n]*)\n?/.exec(i.slice(s));if(e){const t=e[2],n=new RegExp(`\\n {0,3}${"`"===t[0]?"`":"~"}{${t.length},}[ \\t]*(?=\\n|$)`),o=i.slice(s+e[0].length),a=n.exec(`\n${o}`),l=a?o.slice(0,Math.max(0,a.index-1)):o,u=e[0].length+(a?a.index-1+a[0].length:o.length),p=i.slice(s,s+u);"math"===e[3].trim()?r+=c(l,!0,p):r+=p,s+=u;continue}}const e=i[s];if("`"===e){const e=/^`+/.exec(i.slice(s))[0],t=i.indexOf(e,s+e.length);if(t>-1){r+=i.slice(s,t+e.length),s=t+e.length;continue}r+=e,s+=e.length;continue}if("\\"===e){const e=i.slice(s,s+2),n="\\["===e?"\\]":"\\("===e?"\\)":null;if(n&&t.includes(e)){const t=u.has(n)?-1:i.indexOf(n,s+2);if(t<0&&u.add(n),t>-1){r+=c(i.slice(s+2,t),"\\["===e,i.slice(s,t+2)),s=t+2;continue}}r+=e,s+=2;continue}if("$"===e)if("$"===i[s+1]&&t.includes("$$")){const e=i.indexOf("$$",s+2);if(e>-1){r+=c(i.slice(s+2,e),!0,i.slice(s,e+2)),s=e+2;continue}}else if(t.includes("$")&&i[s+1]&&!/\s/.test(i[s+1])&&s+1>=l){const{end:e,stop:t}=ve(i,s+1);if(e>-1){r+=c(i.slice(s+1,e),!1,i.slice(s,e+1)),s=e+1;continue}l=t}r+=e,s++}return{text:r,math:n}}function ve(e,t){for(let n=t;n<e.length;n++){const t=e[n];if("\\"!==t){if("`"===t)return{end:-1,stop:n};if("\n"===t&&/^\n[ \t]*\n/.test(e.slice(n,n+64)))return{end:-1,stop:n};if("$"===t&&!/\s/.test(e[n-1])&&!/\d/.test(e[n+1]??"")&&"$"!==e[n+1])return{end:n,stop:n}}else n++}return{end:-1,stop:e.length}}const be=e=>String(e).replace(/&/g,"&").replace(/</g,"<").replace(/>/g,">").replace(/"/g,"""),ye=/^\s*([A-Za-z\u0370-\u03ff](?:_\{?\w+\}?)?)\s*=\s*([^=<>≤≥]+)$/;function xe(e,r,s,i){const{text:o,math:a}=ge(e,r),l=s?s.definitions(i):new Map,u=e=>s?s.textOf(e):e.text,c={...r.scope??{}},p={},h=new Map,d=new Set,f=[],m=e=>{const t=new Map;return n=>{const r=l.get(n);if(!r)return null;if(!t.has(n)){let s=null;try{s=J(u(r),e)}catch{}t.set(n,s)}return t.get(n)}};let g=!0;const v=a.map((e,s)=>{const{source:i,display:o}=e;g&&i.includes("{{")&&((()=>{for(const e of Object.keys(p))delete p[e];Object.assign(p,c);for(const e of l.keys())delete p[e];let e=[...l.values()];for(;e.length;){const n=e.filter(e=>{try{const n=t.calculate(u(e),p);if("number"==typeof n.value||"bigint"==typeof n.value||Array.isArray(n.value))return p[e.name]=n.exact?n.text:n.value,!1}catch{}return!0});if(n.length===e.length)break;e=n}const r={},s=m({});for(const e of l.keys()){const t=s(e);if(t)try{r[e]=n.toPostfix(ae(t,t=>t===e?null:s(t)).tree)}catch{}}p[te]=r})(),g=!1);const a=o?"mv-md-display":"mv-md-math",v=(e,t="")=>`<span class="${a}${t}" data-mv-md="${s}">${e}</span>`;try{const n={...r.math,display:o,blocks:r.blocks,scope:p},a=function(e){let t=e.trim();const n=t.startsWith("_");n&&(t=t.slice(1).trimStart());let r=t.indexOf(":="),s=2;r<0&&n&&(r=t.search(/(?<![<>!≤≥=])=(?!=)/),s=1);const i=n?{error:"a hidden $_…$ saves a variable: $_A := 2+2$"}:null;if(r<=0)return i;const o=t.slice(0,r).trim(),a=t.slice(r+s).trim();let l=null;try{l=/\{\{/.test(o)?null:re(J(o))}catch{}return null!==l&&a?{hidden:n,lhs:o,name:l,rhs:a,input:ce(a)}:i}(i);if(a&&a.error)throw new Error(a.error);if(a){const{name:t,input:r,hidden:i}=a,o=r?{name:t,text:r.default,input:r,key:`input:${JSON.stringify(r)}`}:{name:t,text:a.rhs,input:null,key:`expr:${a.rhs}`,start:e.start,end:e.end};let c="";if(r){const e=function(e,t){const{input:n,name:r}=e,s=`class="mv-md-input mv-md-${n.kind}" data-mv-var="${be(r)}" aria-label="${be(r)}"`;if("dropdown"===n.kind)return`<select ${s}>${n.options.map(e=>`<option value="${be(e)}"${e===t?" selected":""}>${be(e)}</option>`).join("")}</select>`;return"slider"===n.kind?`<input type="range" ${s} min="${n.min}" max="${n.max}" step="${n.step}" value="${be(t)}"><output class="mv-md-output" data-mv-out="${be(r)}">${be(t)}</output>`:`<input type="text" ${s} value="${be(t)}" size="${Math.max(4,t.length+1)}" spellcheck="false" autocomplete="off">`}(o,u(o));c=i?e:`${K(a.lhs,n)}<span class="mv-md-assign" aria-hidden="true">≔</span>${e}`,d.add(s)}else{const e=ae(J(a.rhs,n),m(n)).tree;if(!i){const t=V({type:"op",op:"=",args:[B(J(a.lhs)),void 0===e.id?e:B(e)]});f[s]=t,c=function(e,t="mv"){return e.replace(`<span class="${t}-rel">=</span>`,`<span class="${t}-rel ${t}-rel-def">≔</span>`).replace(/(aria-label="[^"]*?) equals /,"$1 is defined as ").replace("<mo>=</mo>","<mo>≔</mo>")}(K(t,n),n.prefix)}}return l.delete(t),l.set(t,o),h.set(t,o),g=!0,i&&!r?"":v(c,r?" mv-md-input-def":"")}const{tree:b,changed:y}=ae(J(i,n),m(n));y&&V(b),f[s]=b;const x=K(b,n);return!y&&!1!==r.define&&function(e,n,r){const s=ye.exec(e);if(!s||/\{\{/.test(s[2]))return!1;const i=s[1].replace(/[{}]/g,"");if(r.has(i))return!1;try{const e=t.calculate(s[2],n);if("number"==typeof e.value||"bigint"==typeof e.value||Array.isArray(e.value))return n[i]=e.exact?e.text:e.value,!0}catch{}return!1}(i,c,l)&&(g=!0),v(x)}catch(t){return`<span class="mv-md-error" data-mv-md="${s}" title="${be(t.message)}"><code>${be(e.raw)}</code></span>`}});return{text:o,math:a,drawn:v,defs:h,inputs:d,trees:f}}const we=/^(https?:|mailto:|#|\/|\.{0,2}\/|[^:]*$)/i,ke=e=>we.test(e.trim())?be(e.trim()):"#",$e=/\uE002(\d+)\uE003/g;function qe(e,t,n,r=[]){const s=e=>(r.push(e),`${r.length-1}`),i=e=>(e=>e.replace(/"/g,'"').replace(/</g,"<").replace(/>/g,">").replace(/&/g,"&"))(n(e).replace($e,(e,t)=>(r[Number(t)]??"").replace(/<[^>]*>/g,"")));let o=e;o=o.replace(/(`+)([\s\S]*?[^`])\1(?!`)/g,(e,t,r)=>s(`<code>${be(n(r.trim()))}</code>`)),o=o.replace(/\\([\\`*_{}[\]()#+\-.!|~$<>"'])/g,(e,t)=>s(be(t))),o=o.replace(/<((?:https?:\/\/|mailto:)[^\s>]+)>/g,(e,t)=>s(`<a href="${ke(t)}">${be(t)}</a>`)),t.html&&(o=o.replace(/<\/?[A-Za-z][^>]*>/g,e=>s(e))),o=o.replace(/!\[([^\[\]]*)\]\(\s*((?:[^\s()]|\([^\s()]*\))+)(?:\s+"([^"]*)")?\s*\)/g,(e,t,n,r)=>s(`<img src="${ke(i(n))}" alt="${be(i(t))}"${r?` title="${be(i(r))}"`:""}>`)),o=o.replace(/\[([^\[\]]+)\]\(\s*((?:[^\s()]|\([^\s()]*\))+)(?:\s+"([^"]*)")?\s*\)/g,(e,o,a,l)=>s(`<a href="${ke(i(a))}"${l?` title="${be(i(l))}"`:""}>${qe(o,t,n,r)}</a>`)),o=o.replace(/&(?!#\d{1,7};|#x[0-9a-f]{1,6};|[a-z][a-z0-9]{1,31};)/gi,"&").replace(/</g,"<").replace(/>/g,">").replace(/"/g,"""),o=o.replace(/(\*\*\*|___)(?=\S)([\s\S]*?\S)\1/g,"<strong><em>$2</em></strong>"),o=o.replace(/(\*\*\*|___)(?=\S)([^*_]*?\S)(\*\*|__)(?![*_])([\s\S]*?\S)(\*|_)(?![*_])/g,"<em><strong>$2</strong>$4</em>"),o=o.replace(/(\*\*\*|___)(?=\S)([^*_]*?\S)(\*|_)(?![*_])([\s\S]*?\S)(\*\*|__)(?![*_])/g,"<strong><em>$2</em>$4</strong>"),o=o.replace(/(\*\*|__)(?=\S)([\s\S]*?\S)\1/g,"<strong>$2</strong>"),o=o.replace(/(^|[^*\w])\*(?=\S)([\s\S]*?\S)\*(?!\*)/g,"$1<em>$2</em>"),o=o.replace(/(^|[^_\w])_(?=\S)([\s\S]*?\S)_(?![_\w])/g,"$1<em>$2</em>"),o=o.replace(/~~(?=\S)([\s\S]*?\S)~~/g,"<del>$1</del>"),o=o.replace(/( {2,}|\\)\n/g,"<br>\n");for(let e=0;e<8&&/\uE002\d+\uE003/.test(o);e++)o=o.replace($e,(e,t)=>r[Number(t)]??"");return o}const Se=/^( {0,3})(#{1,6}\s|>|```|~~~|([-*+]|\d{1,9}[.)])\s|(\*[ \t]*){3,}$|(-[ \t]*){3,}$|(_[ \t]*){3,}$)/,Oe=/^( {0,3})([-*+]|\d{1,9}[.)])(\s+|$)/,Me=/^\s*\|?\s*:?-+:?\s*(\|\s*:?-+:?\s*)*\|?\s*$/,Ae=e=>Se.test(e)&&!/^ {0,3}[-=]+\s*$/.test(e)&&!/^ {0,3}(?!1[.)])\d{1,9}[.)]\s/.test(e);function Ee(e){const t=e.trim();let n=t.length;for(;n>0&&"#"===t[n-1];)n--;return n===t.length?t:0===n?"":/[ \t]/.test(t[n-1])?t.slice(0,n).trimEnd():t}function Ne(e,t,n,r=0){const s=[];let i=0;const o=e=>qe(e,t,n);if(r>100)return`<p>${o(e.join("\n"))}</p>`;for(;i<e.length;){const a=e[i];if(!a.trim()){i++;continue}const l=/^ {0,3}(`{3,}|~{3,})\s*([^\s`]*)/.exec(a);if(l){const t=[];for(i++;i<e.length&&!new RegExp(`^ {0,3}${"`"===l[1][0]?"`":"~"}{${l[1].length},}\\s*$`).test(e[i]);)t.push(e[i++]);i++;const r=l[2]?` class="language-${be(l[2])}"`:"";s.push(`<pre><code${r}>${be(n(t.join("\n")))}</code></pre>`);continue}const u=/^ {0,3}(#{1,6})[ \t]+/.exec(a);if(u){s.push(`<h${u[1].length}>${o(Ee(a.slice(u[0].length)))}</h${u[1].length}>`),i++;continue}if(/^ {0,3}((\*[ \t]*){3,}|(-[ \t]*){3,}|(_[ \t]*){3,})$/.test(a)){s.push("<hr>"),i++;continue}if(/^ {0,3}>/.test(a)){const o=[];for(;i<e.length&&e[i].trim()&&(/^ {0,3}>/.test(e[i])||o.length);)o.push(e[i].replace(/^ {0,3}> ?/,"")),i++;s.push(`<blockquote>\n${Ne(o,t,n,r+1)}\n</blockquote>`);continue}const c=Oe.exec(a);if(c){const o=/\d/.test(c[2]),a=o?parseInt(c[2],10):1,l=[];let u=!1;for(;i<e.length;){const t=Oe.exec(e[i]);if(!t||/\d/.test(t[2])!==o)break;const n=t[0].length,r=[e[i].slice(n)];for(i++;i<e.length;){const t=e[i];if(!t.trim()){const t=e[i+1];if(void 0!==t&&t.startsWith(" ".repeat(Math.min(n,4)))&&t.trim()){r.push(""),u=!0,i++;continue}void 0!==t&&Oe.test(t)&&(u=!0);break}if(t.startsWith(" ".repeat(Math.min(n,4))))r.push(t.slice(Math.min(n,4)));else{if(Oe.test(t)||Se.test(t))break;r.push(t)}i++}for(l.push(r);i<e.length&&!e[i].trim()&&void 0!==e[i+1]&&Oe.test(e[i+1]);)i++}const p=o?"ol":"ul",h=l.map(e=>{let s=Ne(e,t,n,r+1);return u||(s=s.replace(/^<p>([\s\S]*?)<\/p>/,"$1").replace(/\n<p>([\s\S]*?)<\/p>/g,"\n$1")),`<li>${s}</li>`});s.push(`<${p}${o&&1!==a?` start="${a}"`:""}>\n${h.join("\n")}\n</${p}>`);continue}if(a.includes("|")&&void 0!==e[i+1]&&Me.test(e[i+1])&&e[i+1].includes("-")){const t=e=>e.trim().replace(/^\|/,"").replace(/\|$/,"").split(/(?<!\\)\|/).map(e=>e.trim()),n=t(e[i+1]).map(e=>e.startsWith(":")&&e.endsWith(":")?"center":e.endsWith(":")?"right":e.startsWith(":")?"left":""),r=(e,t,r)=>`<${e}${n[r]?` style="text-align:${n[r]}"`:""}>${o(t)}</${e}>`,l=t(a);i+=2;const u=[];for(;i<e.length&&e[i].trim()&&e[i].includes("|");)u.push(t(e[i++]));s.push(`<table>\n<thead><tr>${l.map((e,t)=>r("th",e,t)).join("")}</tr></thead>\n<tbody>\n${u.map(e=>`<tr>${l.map((t,n)=>r("td",e[n]??"",n)).join("")}</tr>`).join("\n")}\n</tbody>\n</table>`);continue}if(/^( {4}|\t)/.test(a)){const t=[];for(;i<e.length&&(/^( {4}|\t)/.test(e[i])||!e[i].trim());)t.push(e[i++].replace(/^( {4}|\t)/,""));for(;t.length&&!t[t.length-1].trim();)t.pop();s.push(`<pre><code>${be(n(t.join("\n")))}</code></pre>`);continue}const p=[];for(;i<e.length&&e[i].trim()&&(!p.length||!Ae(e[i]));){if(p.length&&/^ {0,3}(=+|-+)\s*$/.test(e[i])){const t="="===e[i].trim()[0]?1:2;s.push(`<h${t}>${o(p.join("\n"))}</h${t}>`),p.length=0,i++;break}p.push(e[i].replace(/^ {0,3}/,"")),i++}p.length&&s.push(`<p>${o(p.join("\n"))}</p>`)}return s.join("\n")}function Ie(e,t={},n=e=>e){return Ne(String(e).replace(/\r\n?/g,"\n").replace(/[\uE002\uE003]/g,"�").split("\n"),t,n)}function Le({text:e,math:t,drawn:n},r){return(r.render?r.render(e):Ie(e,r,e=>e.replace(me,(e,n)=>t[Number(n)]?.raw??""))).replace(new RegExp("<p>\\s*(\\d+)\\s*</p>","g"),(e,r)=>t[Number(r)].display&&n[Number(r)]?`<div class="mv-md-block">${n[Number(r)]}</div>`:e).replace(me,(e,t)=>n[Number(t)]??"").replace(/<p>\s*<\/p>\n?/g,"")}const Te=new WeakMap,je=new Set;function ze(){for(const e of je)e.connected()&&!e.element.isConnected&&e.stop(!0)}const Ce=new Map,Ze=-1,Be="\\:",Fe=e=>"string"==typeof e&&e.startsWith(Be)&&e.length>2;function De(e){if(!e||!e.symbol)throw new Error("operator needs a symbol");if(!Number.isInteger(e.arity)||e.arity<0&&e.arity!==Ze)throw new Error(`operator "${e.symbol}" needs an integer arity >= 0, or VARIADIC`);if(e.commutative&&2!==e.arity)throw new Error(`only binary operators can be commutative ("${e.symbol}")`);const t={symbol:e.symbol,arity:e.arity,commutative:!!e.commutative,fold:"function"==typeof e.fold?e.fold:null,label:e.label||e.symbol};return Ce.set(t.symbol,t),t}const Re=Object.freeze({symbol:Be,arity:Ze,commutative:!1,fold:null,label:"function"});function Pe(e){const t=Ce.get(e);return t||(Fe(e)?{...Re,symbol:e,label:e.slice(2)}:null)}function _e(e){return Ce.has(e)||Fe(e)}const Ve=e=>Number.isFinite(e)&&Number.isInteger(e)?e:null,We=e=>Number.isFinite(e)?e:null;!function(){De({symbol:"+",arity:2,commutative:!0,label:"add",fold:(e,t)=>We(e+t)}),De({symbol:"-",arity:2,label:"subtract",fold:(e,t)=>We(e-t)}),De({symbol:"*",arity:2,commutative:!0,label:"multiply",fold:(e,t)=>We(e*t)}),De({symbol:"/",arity:2,label:"divide",fold:(e,t)=>0===t?null:Ve(e/t)}),De({symbol:"^",arity:2,label:"power",fold:(e,t)=>Number.isInteger(t)&&Math.abs(t)<=64?We(e**t):null}),De({symbol:"neg",arity:1,label:"negate",fold:e=>We(-e)}),De({symbol:"pm",arity:1,label:"plus or minus"}),De({symbol:"±",arity:2,label:"plus or minus"}),De({symbol:"mod",arity:2,label:"modulo",fold:(e,t)=>0===t?null:Ve((e%t+t)%t)}),De({symbol:"!",arity:1,label:"factorial",fold:e=>Number.isInteger(e)&&e>=0&&e<=18?[...Array(e).keys()].reduce((e,t)=>e*(t+1),1):null}),De({symbol:"_",arity:2,label:"subscript"}),De({symbol:"der",arity:2,label:"derivative"}),De({symbol:"int",arity:Ze,label:"integral"}),De({symbol:"lim",arity:Ze,label:"limit"}),De({symbol:"\\sumidx",arity:Ze,label:"sum over an index"}),De({symbol:"\\prodidx",arity:Ze,label:"product over an index"}),De({symbol:"abs",arity:1,label:"absolute value",fold:e=>We(Math.abs(e))}),De({symbol:"floor",arity:1,label:"floor",fold:e=>We(Math.floor(e))}),De({symbol:"ceil",arity:1,label:"ceiling",fold:e=>We(Math.ceil(e))}),De({symbol:"round",arity:2,label:"round",fold:(e,t)=>Number.isInteger(t)?We(Math.round(e*10**t)/10**t):null}),De({symbol:"fixed",arity:2,label:"fixed",fold:()=>null}),De({symbol:"sqrt",arity:1,label:"square root",fold:e=>Ve(Math.sqrt(e))}),De({symbol:"root",arity:2,label:"nth root",fold:(e,t)=>Ve(Math.round(t**(1/e))**e===t?Math.round(t**(1/e)):NaN)});for(const e of["sin","cos","tan","csc","sec","cot","sinh","cosh","tanh","arcsin","arccos","arctan","arcsinh","arccosh","arctanh","ln","loglog","logloglog","expm1"])De({symbol:e,arity:1,label:e});De({symbol:"log",arity:2,label:"log to a base"}),De({symbol:"atan2",arity:2,label:"atan2"}),De({symbol:"perm",arity:2,label:"permutations"}),De({symbol:"comb",arity:2,label:"combinations"}),De({symbol:"random",arity:0,label:"random"});for(const e of["max","min","gcd","mean","sum","prod"])De({symbol:e,arity:Ze,label:e});for(const e of["()","[]","{}","(]","[)"])De({symbol:e,arity:Ze,label:"group"});for(const e of["pmatrix","bmatrix","vmatrix"])De({symbol:e,arity:Ze,label:"matrix"});De({symbol:"det",arity:1,label:"determinant"});for(const e of["=","===","≠","≠=","<",">","≤","≥","∈","∉","∪","∩","≈","≡","→","pmod","&","|","\\xor","\\nand","\\nor"])De({symbol:e,arity:2,label:e});De({symbol:"\\not",arity:1,label:"not"}),De({symbol:"?:",arity:3,label:"if then else"})}();const Ue="num",He="sym",Je="op",Ke=Object.freeze([]);class Ye extends Error{constructor(e){super(e),this.name="ExprError"}}function Ge(e){if("number"!=typeof e||!Number.isFinite(e))throw new Ye(`not a finite number: ${e}`);const t=(n=e,Object.is(n,-0)?"0":String(n));var n;return Object.freeze({type:Ue,token:t,value:e,args:Ke,s:t})}function Qe(e){if("string"!=typeof e||""===e)throw new Ye("symbol needs a non-empty token");return Object.freeze({type:He,token:e,value:null,args:Ke,s:e})}function Xe(e){const t=/^(-?)0*(\d+?)(?:\.(\d*?)0*)?$/.exec(String(e));if(!t)throw new Ye(`not an exact decimal: ${e}`);const[,n,r,s=""]=t,i=s?`${r}.${s}`:r,o=/^0(\.0*)?$/.test(i)?"0":n+i;return Object.freeze({type:Ue,token:o,value:Number(o),args:Ke,s:o})}const et=/^-?\d+(\.\d+)?$/;function tt(e){const t=String(e);if(et.test(t))return Xe(t);if(""!==t&&!/\s/.test(t)){const e=Number(t);if(Number.isFinite(e))return Ge(e)}return Qe(t)}function nt(e,t){const n=Pe(e);if(!n)throw new Ye(`unknown operator "${e}"`);if(n.arity!==Ze&&t.length!==n.arity)throw new Ye(`"${e}" takes ${n.arity} operand(s), got ${t.length}`);const r=Object.freeze(t.slice()),s=n.arity===Ze?` ${r.length}`:"",i=`${r.length?r.map(e=>e.s).join(" "):""}${r.length,""}${s} ${e}`.trimStart();return Object.freeze({type:Je,op:e,token:e,value:null,args:r,s:i})}const rt=e=>e.type===Ue,st=e=>e.type===Je;function it(e){return ot(function(e){const t=String(e).trim();return""===t?[]:t.split(/\s+/)}(e))}function ot(e){if(!Array.isArray(e))throw new Ye("fromPostfix needs an array of tokens");if(0===e.length)throw new Ye("empty expression");const t=[];for(let n=0;n<e.length;n++){const r=String(e[n]);if(_e(r)){let e=Pe(r).arity;if(e===Ze){const s=t.pop();if(e=s&&s.type===Ue&&Number.isInteger(s.value)&&s.value>=0?s.value:-1,e<0)throw new Ye(`"${r}" at position ${n+1} takes any number of operands, so a count must come before it`)}if(t.length<e)throw new Ye(`"${r}" at position ${n+1} needs ${e} operand(s), only ${t.length} on the stack`);const s=t.splice(t.length-e,e);t.push(nt(r,s))}else t.push(tt(r))}if(1!==t.length){const n=[...new Set(e.filter(e=>!_e(e)))];throw new Ye(`expression leaves ${t.length} values on the stack; it should leave exactly 1. Read as operands: ${n.join(", ")} — is one of those meant to be an operator?`)}return t[0]}function at(e){if(e.type!==Je)return 0;let t=0;for(const n of e.args)t=Math.max(t,at(n));return t+1}function lt(e){if(e.type!==Je)return 1;let t=1;for(const n of e.args)t+=lt(n);return t}function ut(e,t=[]){if(e.type!==Je)t.push(e.token);else for(const n of e.args)ut(n,t);return t}function ct(e){return e.type===Ue||e.type!==He&&e.args.every(ct)}function pt(e,t="pre",n=[],r=[]){"pre"===t&&r.push({node:e,path:n});for(let s=0;s<e.args.length;s++)pt(e.args[s],t,n.concat(s),r);return"post"===t&&r.push({node:e,path:n}),r}function ht(e,t,n){if(0===t.length)return n;const[r,...s]=t,i=e.args.slice();return i[r]=ht(i[r],s,n),nt(e.op,i)}class dt extends Error{constructor(e){super(e),this.name="CasError"}}const ft=1e5,mt=e=>e<0n?-e:e,gt=e=>0n===e?0:mt(e).toString(2).length;function vt(e,t){for(e=mt(e),t=mt(t);t;)[e,t]=[t,e%t];return e}class bt{constructor(e,t=1n){if(0n===t)throw new dt("division by zero");t<0n&&(e=-e,t=-t);const n=vt(e,t)||1n;if(this.n=e/n,this.d=t/n,gt(this.n)>ft||gt(this.d)>ft)throw new dt("a number too large to keep exactly")}static of(e){return new bt(BigInt(e))}add(e){return new bt(this.n*e.d+e.n*this.d,this.d*e.d)}sub(e){return new bt(this.n*e.d-e.n*this.d,this.d*e.d)}mul(e){return new bt(this.n*e.n,this.d*e.d)}div(e){if(0n===e.n)throw new dt("division by zero");return new bt(this.n*e.d,this.d*e.n)}neg(){return new bt(-this.n,this.d)}abs(){return this.n<0n?this.neg():this}inv(){return bt.ONE.div(this)}pow(e){if((e=BigInt(e))<0n)return this.inv().pow(-e);if((0n===this.n||1n===mt(this.n))&&1n===this.d)return 0n===e||-1n===this.n&&e%2n==0n?bt.ONE:this;if(BigInt(Math.max(gt(this.n),gt(this.d)))*e>BigInt(ft))throw new dt("a power too large to work out exactly");return new bt(this.n**e,this.d**e)}get isZero(){return 0n===this.n}get isOne(){return 1n===this.n&&1n===this.d}get isInteger(){return 1n===this.d}get sign(){return this.n<0n?-1:this.n>0n?1:0}equals(e){return this.n===e.n&&this.d===e.d}compare(e){const t=this.n*e.d,n=e.n*this.d;return t<n?-1:t>n?1:0}floor(){const e=this.n/this.d;return new bt(this.n<0n&&e*this.d!==this.n?e-1n:e)}ceil(){return this.neg().floor().neg()}toNumber(){const e=Number(this.n),t=Number(this.d);if(Number.isFinite(e)&&Number.isFinite(t))return e/t;const n=BigInt(Math.max(gt(this.n),gt(this.d))-1e3);return Number(this.n>>n)/Number(this.d>>n)}toString(){return 1n===this.d?String(this.n):`${this.n}/${this.d}`}}function yt(e){const t=/^(-?)(\d*)(?:\.(\d*))?(?:[eE]([+-]?\d+))?$/.exec(String(e));if(!t||""===t[2]&&!t[3])return null;const[,n,r,s="",i="0"]=t;let o=new bt(BigInt((r||"0")+s),10n**BigInt(s.length));const a=Number(i);return a&&(o=o.mul(bt.of(10).pow(a))),n?o.neg():o}function xt(e,t){if(e<2n)return e;if(t>=gt(e))return 1n;const n=BigInt(t);let r=1n<<BigInt(Math.ceil(gt(e)/t));for(;;){const t=((n-1n)*r+e/r**(n-1n))/n;if(t>=r)break;r=t}for(;r**n>e;)r--;for(;(r+1n)**n<=e;)r++;return r}bt.ZERO=new bt(0n),bt.ONE=new bt(1n),bt.MINUS_ONE=new bt(-1n),bt.HALF=new bt(1n,2n);const wt=(()=>{const e=[],t=new Uint8Array(1e4);for(let n=2;n<t.length;n++)if(!t[n]){e.push(BigInt(n));for(let e=n*n;e<t.length;e+=n)t[e]=1}return e})();function kt(e,t){const n=BigInt(t);let r=1n,s=1n,i=e;for(const e of wt){if(e*e>i)break;if(i%e)continue;let t=0n;for(;i%e===0n;)i/=e,t++;r*=e**(t/n),s*=e**(t%n)}if(i>1n){const e=function(e,t){if(e<0n)return null;if(e<2n)return e;const n=xt(e,t);return n**BigInt(t)===e?n:null}(i,t);null!==e?r*=e:s*=i}return{outside:r,inside:s}}const $t=new Set(["pi","e","π"]),qt={complex:!1};function St(e,t){const n=qt.complex;qt.complex=Boolean(e);try{return t()}finally{qt.complex=n}}const Ot=e=>$t.has(e)||qt.complex&&"i"===e,Mt=e=>qt.complex&&"atom"===e.k&&"sym"===e.node.type&&"i"===e.node.token,At=e=>({k:"num",q:e}),Et=At(bt.ONE),Nt=At(bt.ZERO),It=At(bt.HALF),Lt=e=>"num"===e.k,Tt=e=>({k:"atom",node:e}),jt=new WeakMap;function zt(e){let t=jt.get(e);return void 0===t&&jt.set(e,t=fn(e).s),t}function Ct(e){if("num"===e.k)return 0;if("atom"===e.k)return"sym"===e.node.type&&Ot(e.node.token)?0:1;if("add"===e.k)return Math.max(...e.terms.map(e=>Ct(e.x)));let t=0;for(const n of e.fs){const e=Ct(n.b);e&&(t+=e*(Lt(n.e)?n.e.q.toNumber():1))}return t}function Zt(e,t){return"num"===e.k?t&&!Lt(t)?3:0:Mt(e)?1.5:"atom"===e.k&&"sym"===e.node.type?Ot(e.node.token)?t&&!Lt(t)?3:1:2:"atom"===e.k?3:4}const Bt=(e,t)=>e<t?-1:e>t?1:0;function Ft(e){const t=new Map,n=(e,n)=>{"atom"!==e.k||"sym"!==e.node.type||Ot(e.node.token)||t.set(e.node.token,(t.get(e.node.token)??0)+n)};if("mul"===e.k)for(const t of e.fs)n(t.b,Lt(t.e)?t.e.q.toNumber():1);else n(e,1);return t}function Dt(e,t){const n=Ct(t.x)-Ct(e.x);if(n)return n;const r=Ft(e.x),s=Ft(t.x);for(const e of[...new Set([...r.keys(),...s.keys()])].sort()){const t=(s.get(e)??0)-(r.get(e)??0);if(t)return t}return Bt(zt(e.x),zt(t.x))}function Rt(e,t){return e.isOne?t:e.isZero?Nt:Wt([At(e),t])}function Pt(e){if("num"===e.k)return{coef:e.q,rest:null};if("mul"!==e.k||e.c.isOne)return{coef:bt.ONE,rest:e};const t=1===e.fs.length&&Lt(e.fs[0].e)&&e.fs[0].e.q.isOne?e.fs[0].b:{k:"mul",c:bt.ONE,fs:e.fs};return{coef:e.c,rest:t}}function _t(e){let t=bt.ZERO;const n=new Map,r=(e,t)=>{const r=zt(t),s=n.get(r);s?s.coef=s.coef.add(e):n.set(r,{coef:e,x:t})};for(const n of e)if("num"===n.k)t=t.add(n.q);else if("add"===n.k){t=t.add(n.c);for(const e of n.terms)r(e.coef,e.x)}else{const{coef:e,rest:t}=Pt(n);r(e,t)}const s=[...n.values()].filter(e=>!e.coef.isZero);return s.length?t.isZero&&1===s.length?Rt(s[0].coef,s[0].x):(s.sort(Dt),{k:"add",c:t,terms:s}):At(t)}function Vt(e,t){if(!Lt(t))return e.isOne?{coef:bt.ONE,fs:[]}:{coef:bt.ONE,fs:[{b:At(e),e:t}]};const n=t.q;if(n.isInteger)return{coef:e.pow(n.n),fs:[]};if(e.isZero){if(n.sign<0)throw new dt("division by zero");return{coef:bt.ZERO,fs:[]}}if(e.isOne)return{coef:bt.ONE,fs:[]};if(e.sign<0){if(n.d%2n==1n){const{coef:r,fs:s}=Vt(e.neg(),t);return{coef:n.n%2n==0n?r:r.neg(),fs:s}}if(qt.complex&&2n===n.d){const{coef:r,fs:s}=Vt(e.neg(),t);return{coef:r,fs:[...s,{b:Jt,e:At(new bt(n.n))}]}}return{coef:bt.ONE,fs:[{b:At(e),e:t}]}}if(!e.isInteger){const r=Vt(new bt(e.n),t),s=Vt(new bt(e.d),At(n.neg()));return{coef:r.coef.mul(s.coef),fs:[...r.fs,...s.fs]}}const r=n.floor(),s=n.sub(r);if(BigInt(gt(e.n))*s.n>BigInt(ft)||s.d>1000n)return{coef:bt.ONE,fs:[{b:At(e),e:t}]};let i=r.isZero?bt.ONE:e.pow(r.n);const{outside:o,inside:a}=kt(e.n**s.n,Number(s.d));i=i.mul(new bt(o));return{coef:i,fs:a>1n?[{b:At(new bt(a)),e:At(new bt(1n,s.d))}]:[]}}function Wt(e){let t=bt.ONE;const n=new Map,r=(e,t)=>{const r=zt(e),s=n.get(r);s?s.e=_t([s.e,t]):n.set(r,{b:e,e:t})};for(const n of e)if("num"===n.k)t=t.mul(n.q);else if("mul"===n.k){t=t.mul(n.c);for(const e of n.fs)r(e.b,e.e)}else r(n,Et);if(t.isZero)return Nt;const s=[],i=new Map;for(const e of n.values())if(!Lt(e.e)||!e.e.q.isZero){if("num"===e.b.k){if(Lt(e.e)&&!e.e.q.isInteger&&e.b.q.sign>0&&e.b.q.isInteger){const t=e.e.q.toString(),n=i.get(t);n?n.n*=e.b.q.n:i.set(t,{n:e.b.q.n,e:e.e});continue}const n=Vt(e.b.q,e.e);t=t.mul(n.coef),s.push(...n.fs);continue}if("mul"===e.b.k&&Lt(e.e)&&e.e.q.isInteger){const n=Ut(e.b,e.e);"mul"===n.k?(t=t.mul(n.c),s.push(...n.fs)):"num"===n.k?t=t.mul(n.q):s.push({b:n,e:Et});continue}s.push(e)}for(const{n:e,e:n}of i.values()){const r=Vt(new bt(e),n);t=t.mul(r.coef),s.push(...r.fs)}if(t.isZero)return Nt;const o=new Map;for(const e of s){const t=zt(e.b),n=o.get(t);n?n.e=_t([n.e,e.e]):o.set(t,{...e})}let a=[...o.values()].filter(e=>!(Lt(e.e)&&e.e.q.isZero));if(qt.complex){a=a.flatMap(e=>{if(!Mt(e.b)||!Lt(e.e)||!e.e.q.isInteger)return[e];const n=(e.e.q.n%4n+4n)%4n;return n>=2n&&(t=t.neg()),n%2n?[{b:e.b,e:Et}]:[]});const e=a.filter(e=>"add"===e.b.k&&Lt(e.e)&&e.e.q.isInteger&&Yt(e.b)),n=a.some(e=>Mt(e.b)),r=e.every(e=>(e.e.q.sign<0?-e.e.q.n:e.e.q.n)<=60n);if(e.length&&r&&(e.length>1||n||!e[0].e.q.isOne)){const r=a.filter(t=>!e.includes(t)&&!Mt(t.b));let s=n?[Jt]:[Et];for(const t of e){const e=t.e.q.sign<0?Xt(t.b):t.b;for(let n=0n;n<(t.e.q.sign<0?-t.e.q.n:t.e.q.n);n++)s=Gt(s,bn(e))}return Wt([At(t),_t(s),...r.map(e=>Ht(e.b,e.e))])}}if(a.some(e=>"num"===e.b.k&&Lt(e.e)&&e.e.q.compare(bt.ONE)>=0))return Wt([At(t),...a.map(e=>"num"===e.b.k?Ut(e.b,e.e):{k:"mul",c:bt.ONE,fs:[e]})]);if(!a.length)return At(t);if(1===a.length&&!t.isOne&&"add"===a[0].b.k&&Lt(a[0].e)&&a[0].e.q.isOne){const e=a[0].b;return _t([At(t.mul(e.c)),...e.terms.map(e=>Rt(t.mul(e.coef),e.x))])}return t.isOne&&1===a.length&&Lt(a[0].e)&&a[0].e.q.isOne?a[0].b:(a=a.sort((e,t)=>Zt(e.b,e.e)-Zt(t.b,t.e)||Bt(zt(e.b),zt(t.b))),{k:"mul",c:t,fs:a})}function Ut(e,t){if(qt.complex&&Lt(t)&&t.q.isInteger){if(Mt(e))return Wt([{k:"mul",c:bt.ONE,fs:[{b:e,e:t}]}]);if("add"===e.k&&Yt(e)&&!t.q.isOne)return Wt([{k:"mul",c:bt.ONE,fs:[{b:e,e:t}]}])}if(Lt(t)){if(t.q.isZero){if(Lt(e)&&e.q.isZero)throw new dt("0^0 is undefined");return Et}if(t.q.isOne)return e}if(Lt(e)){const n=Vt(e.q,t);if(!n.fs.length)return At(n.coef);if(n.fs.some(e=>Mt(e.b)))return Wt([At(n.coef),...n.fs.map(e=>({k:"mul",c:bt.ONE,fs:[e]}))]);const r={k:"mul",c:n.coef,fs:n.fs};return n.coef.isOne&&1===n.fs.length&&Lt(n.fs[0].e)&&n.fs[0].e.q.isOne?n.fs[0].b:r}if(qt.complex&&Lt(t)&&2n===t.q.d&&Yt(e)){const n=Qt(e);if(n&&Lt(n.im)&&!n.im.q.isZero){const e=e=>Ut(e,At(bt.of(2))),r=Ut(_t([e(n.re),e(n.im)]),It),s=Ut(Wt([_t([r,n.re]),At(bt.HALF)]),It),i=Ut(Wt([_t([r,nn(n.re)]),At(bt.HALF)]),It);return Ut(_t([s,Wt([At(bt.of(n.im.q.sign)),i,Jt])]),At(new bt(t.q.n)))}}if("mul"===e.k){if(Lt(t)&&t.q.isInteger)return Wt([At(e.c.pow(t.q.n)),...e.fs.map(e=>Ht(e.b,Wt([e.e,t])))]);if(!e.c.isOne&&e.c.sign>0)return Wt([Ut(At(e.c),t),Ut({k:"mul",c:bt.ONE,fs:e.fs},t)]);if(e.c.isOne&&1===e.fs.length){const[n]=e.fs;if(Lt(n.e)&&Lt(t)&&1n===n.e.q.n&&n.e.q.d%2n==1n)return Ht(n.b,Wt([n.e,t]))}}return{k:"mul",c:bt.ONE,fs:[{b:e,e:t}]}}function Ht(e,t){return Lt(t)&&t.q.isZero?Et:Lt(e)?Ut(e,t):Lt(t)&&t.q.isOne?e:{k:"mul",c:bt.ONE,fs:[{b:e,e:t}]}}const Jt=Tt(Qe("i")),Kt=e=>qt.complex&&fn(e).s.split(" ").includes("i");function Yt(e){return qt.complex&&Kt(e)&&0===vn(fn(e)).size}function Gt(e,t){const n=[];for(const r of e)for(const e of t)n.push(Wt([r,e]));return bn(_t(n))}function Qt(e){const t=[],n=[];for(const r of bn(e)){const{coef:e,rest:s}=Pt(r),i=s?yn(s):[],o=i.filter(e=>Mt(e)),a=i.filter(e=>!Mt(e));if(a.some(e=>Kt(e)))return null;(o.length?n:t).push(Wt([At(e),...a]))}return{re:_t(t),im:_t(n)}}function Xt(e){const t=Qt(e);if(!t)return Ut(e,At(bt.MINUS_ONE));const n=_t([Ut(t.re,At(bt.of(2))),Ut(t.im,At(bt.of(2)))]);return Wt([_t([t.re,Wt([At(bt.MINUS_ONE),t.im,Jt])]),Ut(n,At(bt.MINUS_ONE))])}const en={re:([e])=>Qt(e)?.re??null,im:([e])=>Qt(e)?.im??null,conj:([e])=>{const t=Qt(e);return t?_t([t.re,Wt([At(bt.MINUS_ONE),t.im,Jt])]):null},arg:([e])=>{const t=Qt(e);return t?an("atan2",[t.im,t.re]):null},abs:([e])=>{const t=Qt(e);return!t||Lt(t.im)&&t.im.q.isZero?null:Ut(_t([Ut(t.re,At(bt.of(2))),Ut(t.im,At(bt.of(2)))]),It)}},tn={Re:"re",re:"re",Im:"im",im:"im",conj:"conj",overline:"conj",bar:"conj",arg:"arg"},nn=e=>Wt([At(bt.MINUS_ONE),e]),rn=(e,t)=>Wt([e,Ut(t,At(bt.MINUS_ONE))]),sn=3000n,on={abs:([e])=>Lt(e)?At(e.q.abs()):"mul"!==e.k||e.c.isOne?null:Wt([At(e.c.abs()),an("abs",[Pt(e).rest])]),floor:([e])=>Lt(e)?At(e.q.floor()):null,ceil:([e])=>Lt(e)?At(e.q.ceil()):null,"!":([e])=>{if(!Lt(e)||!e.q.isInteger||e.q.sign<0||e.q.n>sn)return null;let t=1n;for(let n=2n;n<=e.q.n;n++)t*=n;return At(new bt(t))},mod:([e,t])=>Lt(e)&&Lt(t)&&!t.q.isZero?At(e.q.sub(t.q.mul(e.q.div(t.q).floor()))):null,max:e=>e.every(Lt)&&e.length?e.reduce((e,t)=>t.q.compare(e.q)>0?t:e):null,min:e=>e.every(Lt)&&e.length?e.reduce((e,t)=>t.q.compare(e.q)<0?t:e):null,gcd:e=>e.length&&e.every(e=>Lt(e)&&e.q.isInteger)?At(new bt(e.reduce((e,t)=>vt(e,t.q.n),0n))):null,log:([e,t])=>{if(!Lt(e)||!Lt(t)||e.q.sign<=0||t.q.sign<=0||e.q.isOne)return null;if(t.q.isOne)return Nt;const n=Math.log(t.q.toNumber())/Math.log(e.q.toNumber());if(!Number.isFinite(n))return null;for(let r=1;r<=12;r++){const s=Math.round(n*r);if(!(Math.abs(n*r-s)>1e-9||0===s)&&(Math.abs(s)<=256&&e.q.pow(BigInt(s)).equals(t.q.pow(BigInt(r)))))return At(new bt(BigInt(s),BigInt(r)))}return null},comb:([e,t])=>Lt(e)&&Lt(t)&&e.q.isInteger&&t.q.isInteger&&e.q.sign>=0&&t.q.sign>=0&&e.q.n<=sn?At(function(e,t){if(t>e)return bt.ZERO;t>e-t&&(t=e-t);let n=1n;for(let r=1n;r<=t;r++)n=n*(e-t+r)/r;return new bt(n)}(e.q.n,t.q.n)):null,perm:([e,t])=>{if(!(Lt(e)&&Lt(t)&&e.q.isInteger&&t.q.isInteger&&e.q.sign>=0&&t.q.sign>=0&&e.q.n<=sn))return null;if(t.q.n>e.q.n)return Nt;let n=1n;for(let r=0n;r<t.q.n;r++)n*=e.q.n-r;return At(new bt(n))}};function an(e,t){if(qt.complex&&en[e]){const n=en[e](t);if(n)return n}const n=on[e];if(n){const e=n(t);if(e)return e}return Tt(nt(e,t.map(fn)))}const ln=new Map;function un(e){const t=qt.complex?`ℂ ${e.s}`:e.s,n=ln.get(t);if(n)return n;const r=function(e){if("num"===e.type){const t=yt(e.token);if(!t)throw new dt(`not an exact number: ${e.token}`);return At(t)}if("sym"===e.type)return"π"===e.token?Tt(Qe("pi")):Tt(e);const t=e.args.map(un);switch(e.op){case"+":return _t(t);case"-":return((e,t)=>_t([e,nn(t)]))(t[0],t[1]);case"neg":return nn(t[0]);case"*":return Wt(t);case"/":return rn(t[0],t[1]);case"^":return Ut(t[0],t[1]);case"sqrt":return Ut(t[0],It);case"root":return Ut(t[1],Ut(t[0],At(bt.MINUS_ONE)));default:{const n=e.op.startsWith("\\:")?e.op.slice(2):null;return n&&qt.complex&&tn[n]&&1===t.length?an(tn[n],t):n&&_e(n)&&Pe(n).arity===t.length?an(n,t):an(e.op,t)}}}(e);return ln.size>2e4&&ln.clear(),ln.set(t,r),r}const cn=e=>fn(un(e)),pn=e=>Xe(String(e));function hn(e){return e.isInteger?pn(e.n):nt("/",[pn(e.n),pn(e.d)])}const dn=new WeakMap;function fn(e){let t=dn.get(e);return t||dn.set(e,t=function(e){switch(e.k){case"num":return hn(e.q);case"atom":return e.node;case"mul":return function(e,t){const n=[],r=[];for(const e of t)Lt(e.e)&&e.e.q.sign<0?r.push(mn(e.b,At(e.e.q.neg()))):n.push(mn(e.b,e.e));let s=1n!==e.n&&-1n!==e.n||!n.length?gn([pn(e.n),...n]):gn(n);-1n===e.n&&n.length&&(s=nt("neg",[s]));1n!==e.d&&r.unshift(pn(e.d));return r.length?nt("/",[s,gn(r)]):s}(e.c,e.fs);case"add":return function(e){let t=null;const n=e=>qt.complex&&Kt(e.x)&&0===vn(fn(e.x)).size,r=[...e.terms.filter(e=>!n(e)),...e.terms.filter(n)],s=e.c,i=()=>{s.isZero||(t=t?s.sign<0?nt("-",[t,hn(s.neg())]):nt("+",[t,hn(s)]):hn(s))};let o=!1;for(const e of r)!o&&n(e)&&(i(),o=!0),t=t?e.coef.sign<0?nt("-",[t,fn(Rt(e.coef.neg(),e.x))]):nt("+",[t,fn(Rt(e.coef,e.x))]):fn(Rt(e.coef,e.x));o||i();return t}(e);default:throw new Error(`bad form ${e.k}`)}}(e)),t}function mn(e,t){const n=fn(e);if(Lt(t)){const e=t.q;if(e.isOne)return n;if(1n===e.n&&2n===e.d)return nt("sqrt",[n]);if(1n===e.n)return nt("root",[pn(e.d),n])}return nt("^",[n,fn(t)])}const gn=e=>e.reduce((e,t)=>e?nt("*",[e,t]):t,null);function vn(e,t=new Set){if("sym"===e.type)Ot(e.token)||t.add(e.token);else if(st(e))for(const n of e.args)vn(n,t);return t}function bn(e){if("add"!==e.k)return[e];const t=e.terms.map(e=>Rt(e.coef,e.x));return e.c.isZero||t.push(At(e.c)),t}function yn(e){if("num"===e.k)return[e];if("mul"!==e.k)return[e];const t=e.c.isOne?[]:[At(e.c)];for(const n of e.fs)t.push(Ht(n.b,n.e));return t}const xn="_",wn=new WeakMap;function kn(e,t){return[...t,...Pe(e.op)?.arity===Ze?[String(e.args.length)]:[],e.op].join(" ")}function $n(e,t){let n=wn.get(e);n||wn.set(e,n=new Map);const r=n.get(t);if(r)return r;const s=function(e,t){const n={key:xn,slots:[e]};if(e.type!==Je||t<=0)return[n];const r=e.args.map(e=>$n(e,t-1)),s=[n],i=new Array(r.length).fill(0);for(;;){const t=[],n=[];for(let e=0;e<r.length;e++){const s=r[e][i[e]];t.push(s.key);for(const e of s.slots)n.push(e)}if(s.push({key:kn(e,t),slots:n}),s.length>=4096)break;let o=r.length-1;for(;o>=0&&!(++i[o]<r[o].length);o--)i[o]=0;if(o<0)break}return s}(e,t);return n.set(t,s),s}function qn(e){return e.type!==Je?xn:kn(e,e.args.map(qn))}function Sn(e,t=[]){if(e.type!==Je)t.push(e);else for(const n of e.args)Sn(n,t);return t}const On=new Map,Mn=new Map;class An extends Error{constructor(e){super(e),this.name="RequirementError"}}function En(e,t,n=""){On.set(e,{name:e,fn:t,doc:n,arity:Math.max(0,t.length-1)})}function Nn(e,t,n=""){Mn.set(e,{name:e,fn:t,doc:n})}function In(e){return On.get(e)||null}function Ln(e){return Mn.get(e)||null}const Tn=e=>e.type===Ue;function jn(e,t){return e.type===Je&&(e.op===t||e.args.some(e=>jn(e,t)))}En("always",()=>!0,"matches anything"),En("never",()=>!1,"matches nothing"),En("isLeaf",e=>e.type!==Je,"a bare operand, not an operation"),En("isCompound",e=>e.type===Je,"an operation, not a bare operand"),En("isSymbol",e=>e.type===He,"a non-numeric operand such as x"),En("isOperation",(e,t)=>e.type===Je&&e.op===t,"is this specific operation"),En("notOperation",(e,t)=>!(e.type===Je&&e.op===t),"is anything except this operation"),En("isNumber",Tn,"a numeric literal"),En("isInteger",e=>Tn(e)&&Number.isInteger(e.value),"a whole number"),En("isPositive",e=>Tn(e)&&e.value>0,"greater than zero"),En("isNegative",e=>Tn(e)&&e.value<0,"less than zero"),En("isNonNegative",e=>Tn(e)&&e.value>=0,"zero or greater"),En("isZero",e=>Tn(e)&&0===e.value,"exactly 0"),En("isOne",e=>Tn(e)&&1===e.value,"exactly 1"),En("isNonZero",e=>Tn(e)&&0!==e.value,"a number that is provably not 0"),En("isNotZeroLiteral",e=>!(Tn(e)&&0===e.value),"anything except a literal 0"),En("isPositiveInteger",e=>Tn(e)&&Number.isInteger(e.value)&&e.value>0,"a whole number above 0"),En("isNegativeInteger",e=>Tn(e)&&Number.isInteger(e.value)&&e.value<0,"a whole number below 0"),En("isEven",e=>Tn(e)&&Number.isInteger(e.value)&&e.value%2==0,"a whole even number"),En("isOdd",e=>Tn(e)&&Number.isInteger(e.value)&&1===Math.abs(e.value%2),"a whole odd number"),En("greaterThan",(e,t)=>Tn(e)&&e.value>Number(t),"above a given value"),En("lessThan",(e,t)=>Tn(e)&&e.value<Number(t),"below a given value"),En("isValue",(e,t)=>Tn(e)&&e.value===Number(t),"equals a given number"),En("isNumeric",ct,"contains no symbols: a constant (it need not fold to a number: 1 sin)"),En("hasSymbol",e=>!ct(e),"mentions a symbol somewhere, so it is not just a number"),En("isVar",(e,t)=>e.type===He&&e.token===String(t),"is exactly this symbol"),En("contains",(e,t)=>ut(e).includes(String(t)),"mentions this operand somewhere"),En("isFree",(e,t)=>!ut(e).includes(String(t)),"never mentions this operand"),En("hasOperation",(e,t)=>jn(e,String(t)),"uses this operation somewhere inside"),En("equals",(e,t)=>e.s===String(t),"is exactly this postfix expression");const zn=e=>e.type===Je?null:e.token;function Cn(e){if("string"==typeof e)return{name:e,args:[]};if(Array.isArray(e)&&e.length>0&&"string"==typeof e[0])return{name:e[0],args:e.slice(1)};throw new An(`bad requirement: ${JSON.stringify(e)}`)}Nn("freeOf",(e,t)=>{const n=zn(t);return null!==n&&!ut(e).includes(n)},"the first operand never mentions the second"),Nn("dependsOn",(e,t)=>{const n=zn(t);return null!==n&&ut(e).includes(n)},"the first operand does mention the second"),Nn("sameAs",(...e)=>e.every(t=>t.s===e[0].s),"these operands are structurally identical"),Nn("differs",(...e)=>new Set(e.map(e=>e.s)).size===e.length,"these operands are all different"),Nn("sameValue",(...e)=>e.every(e=>Tn(e))&&e.every(t=>t.value===e[0].value),"these operands are the same number");const Zn="simplify";class Bn extends Error{constructor(e,t){super(t?`rule "${t}": ${e}`:e),this.name="RuleError",this.ruleId=t}}const Fn=/^[A-Za-z_][A-Za-z0-9_]*$/;function Dn(e,t){if(rt(e))return{literal:e.value};const n=e.token;if(n.startsWith("=")){const e=n.slice(1);if(""===e)throw new Bn('"=" needs an operand after it',t);return{token:e}}if(!Fn.test(n))throw new Bn(`"${n}" is not a usable slot name; use letters, digits and _`,t);if(_e(n))throw new Bn(`slot name "${n}" collides with an operator`,t);return{name:n}}function Rn(e){if(!st(e))return[e];const t=e.args.map(Rn),n=Pe(e.op),r=[];for(const s of function(e){let t=[[]];for(const n of e){const e=[];for(const r of t)for(const t of n)e.push(r.concat([t]));if(t=e,t.length>64)return t.slice(0,64)}return t}(t))if(r.push(nt(e.op,s)),n.commutative&&2===s.length&&s[0].s!==s[1].s&&r.push(nt(e.op,[s[1],s[0]])),r.length>=64)break;return r}function Pn(e,t=[]){return"op"===e.kind?e.args.forEach(e=>Pn(e,t)):"const"===e.kind&&e.free&&t.push(e.node.token),t}function _n(e){if(!e||"object"!=typeof e)throw new Bn("rule must be a mapping");const t=e.id||e.name;if(!t)throw new Bn("rule needs an id");if(!e.pattern)throw new Bn("rule needs a pattern",t);if(void 0===e.output||null===e.output)throw new Bn("rule needs an output",t);let n;try{n=it(String(e.pattern))}catch(e){if(e instanceof Ye)throw new Bn(`bad pattern: ${e.message}`,t);throw e}const r=Sn(n).map(e=>Dn(e,t)),s=new Set(r.filter(e=>e.name).map(e=>e.name)),i=function(e,t,n){const r=[],s=e.when||{};if("object"!=typeof s||Array.isArray(s))throw new Bn('"when" must map slot names to lists of requirements',n);for(const[e,i]of Object.entries(s)){if(!t.has(e))throw new Bn(`"when" mentions "${e}", which is not a slot in the pattern`,n);const s=Array.isArray(i)?i:[i];for(const t of s){const{name:s,args:i}=Cn(t),o=In(s);if(!o)throw new Bn(`unknown requirement "${s}"`,n);r.push({slot:e,name:s,args:i,fn:o.fn})}}return r}(e,s,t),o=function(e,t,n){const r=[],s=e.require||[];if(!Array.isArray(s))throw new Bn('"require" must be a list of relations',n);for(const e of s){const{name:s,args:i}=Cn(e),o=Ln(s);if(!o)throw new Bn(`unknown relation "${s}"`,n);if(i.length<2)throw new Bn(`relation "${s}" needs at least two operands`,n);for(const e of i)if("string"==typeof e&&!t.has(e)&&Fn.test(e))throw new Bn(`relation "${s}" mentions "${e}", which is not a slot in the pattern`,n);r.push({name:s,args:i,fn:o.fn})}return r}(e,s,t),a=function(e,t,n){let r;try{r=it(e)}catch(t){throw new Bn(`bad output "${e}": ${t.message}`,n)}const s=e=>st(e)?{kind:"op",op:e.op,args:e.args.map(s)}:rt(e)?{kind:"const",node:e}:t.has(e.token)?{kind:"slot",name:e.token}:e.token.startsWith("=")?{kind:"const",node:Qe(e.token.slice(1))}:{kind:"const",node:e,free:!0};return s(r)}(String(e.output),s,t),l=e.commutative?Rn(n):[n],u=[],c=new Set;for(const e of l){const n=qn(e),r=Sn(e).map(e=>Dn(e,t)),s=n+"\0"+r.map(e=>e.name??(void 0!==e.literal?`#${e.literal}`:`=${e.token}`)).join(",");c.has(s)||(c.add(s),u.push({key:n,slots:r}))}const p={id:String(t),name:e.name?String(e.name):String(t),pattern:String(e.pattern),patternTree:n,output:String(e.output),outputTemplate:a,explain:e.explain?String(e.explain).trim():"",mode:e.mode?String(e.mode):Zn,tags:Array.isArray(e.tags)?e.tags.map(String):[],priority:Number.isFinite(e.priority)?e.priority:0,fold:!!e.fold,commutative:!!e.commutative,enabled:void 0===e.enabled||!!e.enabled,when:i,require:o,slots:[...s],depth:at(n),bindings:u,freeSymbols:Pn(a),source:e};for(const e of u)e.rule=p;return p}function Vn(e){const t={};for(const n of e.when)(t[n.slot]||=[]).push(n.args.length?[n.name,...n.args]:n.name);const n={id:e.id};return e.name!==e.id&&(n.name=e.name),e.mode!==Zn&&(n.mode=e.mode),n.pattern=e.pattern,Object.keys(t).length&&(n.when=t),e.require.length&&(n.require=e.require.map(e=>[e.name,...e.args])),n.output=e.output,e.explain&&(n.explain=e.explain),e.fold&&(n.fold=!0),e.commutative&&(n.commutative=!0),e.priority&&(n.priority=e.priority),e.tags.length&&(n.tags=e.tags),e.enabled||(n.enabled=!1),n}class Wn extends Error{constructor(e,t){super(null==t?e:`${e} (line ${t+1})`),this.name="YamlError",this.line=t}}class Un{constructor(e){this.records=e,this.i=0,this.pushed=[]}peek(){if(this.pushed.length)return this.pushed[this.pushed.length-1];for(;this.i<this.records.length&&this.records[this.i].blank;)this.i++;return this.i<this.records.length?this.records[this.i]:null}next(){if(this.pushed.length)return this.pushed.pop();const e=this.peek();return e&&this.i++,e}push(e){this.pushed.push(e)}}const Hn=e=>"-"===e||e.startsWith("- ");function Jn(e){let t=null,n=0;for(let r=0;r<e.length;r++){const s=e[r];if(t)s===t?"'"===t&&"'"===e[r+1]?r++:t=null:'"'===t&&"\\"===s&&r++;else if('"'===s||"'"===s)t=s;else if("["===s||"{"===s)n++;else if("]"===s||"}"===s)n--;else if(":"===s&&0===n&&(r+1===e.length||" "===e[r+1])){const t=e.slice(0,r).trim();return""===t?null:{key:Kn(t),rest:e.slice(r+1).trim()}}}return null}function Kn(e){return e.length>=2&&'"'===e[0]&&'"'===e[e.length-1]?JSON.parse(e):e.length>=2&&"'"===e[0]&&"'"===e[e.length-1]?e.slice(1,-1).replace(/''/g,"'"):e}function Yn(e){const t=new Un(function(e){return String(e).split(/\r?\n/).map((e,t)=>{const n=e.search(/\S/);if(-1===n)return{raw:e,n:t,indent:0,text:"",blank:!0};const r=function(e){let t=null;for(let n=0;n<e.length;n++){const r=e[n];if(t)r===t?"'"===t&&"'"===e[n+1]?n++:t=null:'"'===t&&"\\"===r&&n++;else if('"'===r||"'"===r)t=r;else if("#"===r&&(0===n||/\s/.test(e[n-1])))return e.slice(0,n)}return e}(e.slice(n)).trimEnd();return{raw:e,n:t,indent:n,text:r,blank:""===r}})}(e));let n=t.peek();if(n&&"---"===n.text&&(t.next(),n=t.peek()),!n)return null;const r=Qn(t,n.indent),s=t.peek();if(s&&"..."!==s.text&&"---"!==s.text)throw new Wn(`unexpected content "${s.text}"`,s.n);return r}const Gn=/^[|>][-+]?\d*$/;function Qn(e,t){const n=e.peek();return!n||n.indent<t?null:Hn(n.text)?Xn(e,n.indent):Jn(n.text)?function(e,t){const n={};for(;;){const r=e.peek();if(!r||r.indent!==t)break;const s=Jn(r.text);if(!s)break;e.next();const{key:i,rest:o}=s;if(""===o){const r=e.peek();r&&r.indent>t?n[i]=Qn(e,r.indent):r&&r.indent===t&&Hn(r.text)?n[i]=Xn(e,t):n[i]=null}else Gn.test(o)?n[i]=er(e,o,t):n[i]=tr(o,r.n)}return n}(e,n.indent):(e.next(),Gn.test(n.text)?er(e,n.text,n.indent-1):tr(n.text,n.n))}function Xn(e,t){const n=[];for(;;){const r=e.peek();if(!r||r.indent!==t||!Hn(r.text))break;if(e.next(),"-"===r.text){const r=e.peek();n.push(r&&r.indent>t?Qn(e,r.indent):null);continue}if(Gn.test(r.text.slice(2).trim())){n.push(er(e,r.text.slice(2).trim(),t));continue}const s=r.text.slice(2),i=t+2+(s.length-s.trimStart().length);e.push({raw:r.raw,n:r.n,indent:i,text:s.trim(),blank:!1}),n.push(Qn(e,i))}return n}function er(e,t,n){const r=t[0],s=(t.match(/[-+]/)||[""])[0],i=(t.match(/\d+/)||[null])[0];let o=i?n+Number(i):null;const a=[];for(;e.i<e.records.length;){const t=e.records[e.i];if(""===t.raw.trim()){a.push(""),e.i++;continue}const r=t.raw.search(/\S/);if(r<=n)break;if(null===o&&(o=r),r<o)break;a.push(t.raw.slice(o)),e.i++}for(;a.length&&""===a[a.length-1];)a.pop();let l;if("|"===r)l=a.join("\n");else{const e=[];for(const t of a)""===t?e.push("\n"):e.length&&"\n"!==e[e.length-1]?e[e.length-1]+=" "+t:e.push(t);l=e.join("").replace(/\n(?!$)/g,"\n")}return"-"===s?l:"+"===s?l+"\n":""===l?"":l+"\n"}function tr(e,t){const n=e.trim();return""===n||"~"===n||"null"===n||"Null"===n||"NULL"===n?null:"true"===n||"True"===n||"TRUE"===n||"false"!==n&&"False"!==n&&"FALSE"!==n&&("["===n[0]||"{"===n[0]?function(e,t){const n={text:e,i:0,line:t},r=rr(n);if(nr(n),n.i<n.text.length)throw new Wn(`unexpected "${n.text.slice(n.i)}" in flow value`,t);return r}(n,t):'"'===n[0]||"'"===n[0]?Kn(n):/^[-+]?(\d+\.?\d*|\.\d+)([eE][-+]?\d+)?$/.test(n)?Number(n):n)}const nr=e=>{for(;e.i<e.text.length&&/\s/.test(e.text[e.i]);)e.i++};function rr(e){nr(e);const t=e.text[e.i];return"["===t?function(e){e.i++;const t=[];for(;;){if(nr(e),e.i>=e.text.length)throw new Wn("unterminated [",e.line);if("]"===e.text[e.i])return e.i++,t;if(t.push(rr(e)),nr(e),","===e.text[e.i])e.i++;else if("]"!==e.text[e.i])throw new Wn(`expected , or ] near "${e.text.slice(e.i)}"`,e.line)}}(e):"{"===t?function(e){e.i++;const t={};for(;;){if(nr(e),e.i>=e.text.length)throw new Wn("unterminated {",e.line);if("}"===e.text[e.i])return e.i++,t;const n=String(rr(e));if(nr(e),":"!==e.text[e.i])throw new Wn(`expected : after "${n}"`,e.line);if(e.i++,t[n]=rr(e),nr(e),","===e.text[e.i])e.i++;else if("}"!==e.text[e.i])throw new Wn(`expected , or } near "${e.text.slice(e.i)}"`,e.line)}}(e):tr(function(e){const t=e.text[e.i];if('"'===t||"'"===t){const n=e.i;for(e.i++;e.i<e.text.length;)if("\\"===e.text[e.i]&&'"'===t)e.i+=2;else if(e.text[e.i]===t){if("'"!==t||"'"!==e.text[e.i+1])return e.i++,e.text.slice(n,e.i);e.i+=2}else e.i++;throw new Wn("unterminated quoted string",e.line)}const n=e.i;for(;e.i<e.text.length;){const t=e.text[e.i];if(","===t||"]"===t||"}"===t)break;if(":"===t){const t=e.text[e.i+1];if(void 0===t||/[\s,\]}]/.test(t))break}e.i++}return e.text.slice(n,e.i).trim()}(e),e.line)}const sr=/^(true|false|null|yes|no|on|off|~)$/i;function ir(e){if(null==e)return"null";if("boolean"==typeof e)return e?"true":"false";if("number"==typeof e){if(!Number.isFinite(e))throw new Wn(`cannot serialize ${e}`);return String(e)}const t=String(e);return function(e){return!!(""===e||/^\s|\s$/.test(e)||/[\u0000-\u001f\u007f]/.test(e)||/^[-?:,[\]{}#&*!|>'"%@`]/.test(e)||/: |\s#/.test(e)||sr.test(e)||/^[-+]?(\d+\.?\d*|\.\d+)([eE][-+]?\d+)?$/.test(e))}(t)?JSON.stringify(t):t}const or=e=>null==e||"object"!=typeof e;function ar(e){return Array.isArray(e)?`[${e.map(ar).join(", ")}]`:e&&"object"==typeof e?`{${Object.entries(e).map(([e,t])=>`${ir(e)}: ${ar(t)}`).join(", ")}}`:ir(e)}function lr(e){return Array.isArray(e)?!!e.every(e=>or(e)||Array.isArray(e)&&e.every(or))&&ar(e).length<=72:!(!e||"object"!=typeof e)&&(Object.values(e).every(e=>or(e)||Array.isArray(e)&&e.every(or))&&ar(e).length<=72)}function ur(e){const t=[];return cr(e,0,t),t.length?t.join("\n")+"\n":""}function cr(e,t,n){const r=" ".repeat(t);if(Array.isArray(e)){if(0===e.length)return void n.push(r+"[]");for(const r of e)pr(r,t,n)}else{if(e&&"object"==typeof e){const s=Object.entries(e).filter(([,e])=>void 0!==e);if(0===s.length)return void n.push(r+"{}");for(const[e,r]of s)hr(e,r,t,n);return}!function(e,t,n){if("string"==typeof e&&e.includes("\n")){n.push(t+"|-");for(const r of e.replace(/\n+$/,"").split("\n"))n.push(t+" "+r);return}n.push(t+ir(e))}(e,r,n)}}function pr(e,t,n){const r=" ".repeat(t);if(null!==e&&"object"==typeof e&&!lr(e)){const s=[];if(cr(e,t+2,s),0===s.length)return void n.push(r+"-");n.push(r+"- "+s[0].slice(t+2));for(let e=1;e<s.length;e++)n.push(s[e]);return}if(null===e||"object"!=typeof e)if("string"==typeof e&&e.includes("\n")){n.push(r+"- |-");for(const r of e.replace(/\n+$/,"").split("\n"))n.push(" ".repeat(t+4)+r)}else n.push(r+"- "+ir(e));else n.push(r+"- "+ar(e))}function hr(e,t,n,r){const s=" ".repeat(n),i=ir(e);if("string"==typeof t&&t.includes("\n")){r.push(`${s}${i}: |-`);for(const e of t.replace(/\n+$/,"").split("\n"))r.push(" ".repeat(n+2)+e)}else{if(null!==t&&"object"==typeof t)return lr(t)?void r.push(`${s}${i}: ${ar(t)}`):(r.push(`${s}${i}:`),void cr(t,Array.isArray(t)?n:n+2,r));r.push(`${s}${i}: ${ir(t)}`)}}class dr{constructor(e=[]){this.index=new Map,this.rules=[],this.maxDepth=0,this.name="",this.views=new Map;for(const t of e)this.add(t)}add(e){const t=e&&e.bindings?e:_n(e);if(this.rules.some(e=>e.id===t.id))throw new Bn(`duplicate rule id "${t.id}"`);return this.rules.push(t),t.enabled&&this.link(t),t.depth>this.maxDepth&&(this.maxDepth=t.depth),this.views.clear(),t}view(e){if(!e)return this;let t=this.views.get(e);return t||(t=new dr(this.rules.filter(t=>t.mode===e)),t.name=this.name,this.views.set(e,t)),t}modes(){return[...new Set(this.rules.map(e=>e.mode))].sort((e,t)=>e===Zn?-1:t===Zn?1:e.localeCompare(t))}link(e){for(const t of e.bindings){let e=this.index.get(t.key);e||this.index.set(t.key,e=[]),e.push(t),e.sort((e,t)=>t.rule.priority-e.rule.priority||t.rule.depth-e.rule.depth)}}remove(e){const t=this.rules.findIndex(t=>t.id===e);return-1!==t&&(this.rules.splice(t,1),this.reindex(),!0)}setEnabled(e,t){const n=this.get(e);return!!n&&(n.enabled=!!t,this.reindex(),!0)}reindex(){this.index=new Map,this.maxDepth=0,this.views.clear();for(const e of this.rules)e.enabled&&this.link(e),e.depth>this.maxDepth&&(this.maxDepth=e.depth)}get(e){return this.rules.find(t=>t.id===e)||null}candidates(e){return this.index.get(e)||null}get size(){return this.rules.length}static fromYaml(e,{strict:t=!0}={}){const n=Yn(e);return dr.fromSpecs(n,{strict:t})}static fromSpecs(e,{strict:t=!0}={}){let n=e,r="";if(e&&!Array.isArray(e)&&"object"==typeof e&&(n=e.rules,r=e.name?String(e.name):""),!Array.isArray(n))throw new Bn('expected a list of rules, or a mapping with a "rules" list');const s=new dr;s.name=r;const i=[];for(let e=0;e<n.length;e++)try{s.add(n[e])}catch(t){i.push(`#${e+1}: ${t.message}`)}if(i.length&&t)throw new Bn(`${i.length} rule(s) failed to compile:\n ${i.join("\n ")}`);return s.errors=i,s}toSpecs(){return this.rules.map(Vn)}toYaml(){const e=this.toSpecs();return this.name?ur({name:this.name,rules:e}):ur(e)}keyReport(){return[...this.index.entries()].map(([e,t])=>({key:e,rules:t.map(e=>e.rule.id)})).sort((e,t)=>e.key.localeCompare(t.key))}}function fr(e,t){const n=Object.create(null),r=e.slots;for(let e=0;e<r.length;e++){const s=r[e],i=t[e];if(void 0!==s.literal){if(!rt(i)||i.value!==s.literal)return null;continue}if(void 0!==s.token){if(i.s!==s.token)return null;continue}const o=n[s.name];if(void 0!==o){if(o.s!==i.s)return null}else n[s.name]=i}return n}function mr(e,t){for(const n of e.when){const e=t[n.slot];if(void 0===e)return!1;if(!n.fn(e,...n.args))return!1}for(const n of e.require){const e=n.args.map(e=>void 0!==t[e]?t[e]:e);if(!n.fn(...e))return!1}return!0}function gr(e,t){return t.rule.priority-e.rule.priority||t.rule.depth-e.rule.depth}function vr(e,t){const n=[];if(0===t.maxDepth)return n;for(const{key:r,slots:s}of function(e,t){const n=$n(e,t),r=[];for(const e of n)e.key!==xn&&r.push(e);return r}(e,t.maxDepth)){const e=t.candidates(r);if(e)for(const t of e){const e=fr(t,s);e&&(mr(t.rule,e)&&n.push({rule:t.rule,binding:t,key:r,bound:e}))}}return n.sort(gr)}function br(e,t){switch(e.kind){case"slot":{const n=t[e.name];if(!n)throw new Error(`output references unbound slot "${e.name}"`);return n}case"const":return e.node;case"op":return nt(e.op,e.args.map(e=>br(e,t)));default:throw new Error(`bad output template: ${JSON.stringify(e)}`)}}const yr=4e5,xr=()=>new dt("a number too large to approximate"),wr=e=>e<0n?-e:e;class kr{constructor(e){this.P=e,this.S=10n**BigInt(e),this.cache=new Map}fromQ(e){return e.n*this.S/e.d}mul(e,t){return e*t/this.S}div(e,t){if(0n===t)throw new dt("division by zero");return e*this.S/t}sqrt(e){if(e<0n)throw new dt("the square root of a negative number is not real");return xt(e*this.S,2)}series(e,t){let n=0n,r=e;for(let e=1;0n!==r;e++)if(n+=r,r=t(r,e),e>1e5)throw new dt("a series did not converge");return n}atanhInv(e){const t=BigInt(e),n=t*t;let r=this.S/t,s=0n;for(let e=1n;0n!==r;e+=2n)s+=r/e,r/=n;return s}atanInv(e){const t=BigInt(e),n=t*t;let r=this.S/t,s=0n;for(let e=1n,t=1n;0n!==r;e+=2n,t=-t)s+=t*r/e,r/=n;return s}get pi(){return this.memo("pi",()=>16n*this.atanInv(5)-4n*this.atanInv(239))}get ln2(){return this.memo("ln2",()=>2n*this.atanhInv(3))}get e(){return this.memo("e",()=>this.exp(this.S))}memo(e,t){return this.cache.has(e)||this.cache.set(e,t()),this.cache.get(e)}exp(e){const t=(e+(e>=0n?this.ln2/2n:-this.ln2/2n))/this.ln2;if(t>BigInt(yr))throw xr();if(t<-BigInt(yr))return 0n;const n=e-t*this.ln2,r=this.series(this.S,(e,t)=>e*n/this.S/BigInt(t));return t>=0n?r<<t:r>>-t}ln(e){if(e<=0n)throw new dt("the log of a number that is not positive is not real");let t=0n,n=e;for(;n>=this.S;)n>>=1n,t++;for(;n<this.S/2n;)n<<=1n,t--;const r=this.div(n-this.S,n+this.S),s=this.mul(r,r);let i=r,o=0n;for(let e=1n;0n!==i;e+=2n)o+=i/e,i=this.mul(i,s);return 2n*o+t*this.ln2}sin(e){const t=2n*this.pi;let n=e%t;n>this.pi&&(n-=t),n<-this.pi&&(n+=t);const r=this.mul(n,n);return this.series(n,(e,t)=>-e*r/this.S/BigInt(2*t*(2*t+1)))}cos(e){return this.sin(e+this.pi/2n)}atan(e){if(wr(e)>this.S){const t=this.pi/2n;return(e>0n?t:-t)-this.atan(this.div(this.S,e))}let t=e;for(let e=0;e<2;e++)t=this.div(t,this.S+this.sqrt(this.S+this.mul(t,t)));const n=this.mul(t,t);let r=t,s=0n;for(let e=1n,t=1n;0n!==r;e+=2n,t=-t)s+=t*r/e,r=this.mul(r,n);return 4n*s}asin(e){if(wr(e)>this.S)throw new dt("arcsin of a number beyond ±1 is not real");return wr(e)===this.S?e>0n?this.pi/2n:-this.pi/2n:this.atan(this.div(e,this.sqrt(this.S-this.mul(e,e))))}}function $r(e,t,n){if(n>0n)return e.atan(e.div(t,n));if(n<0n)return e.atan(e.div(t,n))+(t>=0n?e.pi:-e.pi);if(0n===t)throw new dt("the argument of 0 is undefined");return t>0n?e.pi/2n:-e.pi/2n}const qr={add:(e,t)=>[e[0]+t[0],e[1]+t[1]],sub:(e,t)=>[e[0]-t[0],e[1]-t[1]],mul:(e,t,n)=>[e.mul(t[0],n[0])-e.mul(t[1],n[1]),e.mul(t[0],n[1])+e.mul(t[1],n[0])],div(e,t,n){const r=e.mul(n[0],n[0])+e.mul(n[1],n[1]);if(0n===r)throw new dt("division by zero");return[e.div(e.mul(t[0],n[0])+e.mul(t[1],n[1]),r),e.div(e.mul(t[1],n[0])-e.mul(t[0],n[1]),r)]},abs:(e,t)=>e.sqrt(e.mul(t[0],t[0])+e.mul(t[1],t[1])),exp(e,t){const n=e.exp(t[0]);return[e.mul(n,e.cos(t[1])),e.mul(n,e.sin(t[1]))]},ln(e,t){const n=qr.abs(e,t);if(0n===n)throw new dt("the log of 0 is undefined");return[e.ln(n),$r(e,t[1],t[0])]},pow(e,t,n,r){if(0n===t[0]&&0n===t[1])return[0n,0n];if(r&&r.isInteger){let n=r.n<0n?-r.n:r.n,s=[e.S,0n],i=t;for(;n>0n;)1n&n&&(s=qr.mul(e,s,i)),i=qr.mul(e,i,i),n>>=1n;return r.n<0n?qr.div(e,[e.S,0n],s):s}return qr.exp(e,qr.mul(e,n,qr.ln(e,t)))},sinh:(e,t)=>(e.exp(t)-e.exp(-t))/2n,cosh:(e,t)=>(e.exp(t)+e.exp(-t))/2n},Sr={sin:(e,[t,n])=>[e.mul(e.sin(t),qr.cosh(e,n)),e.mul(e.cos(t),qr.sinh(e,n))],cos:(e,[t,n])=>[e.mul(e.cos(t),qr.cosh(e,n)),-e.mul(e.sin(t),qr.sinh(e,n))],tan:(e,t)=>qr.div(e,Sr.sin(e,t),Sr.cos(e,t)),ln:(e,t)=>qr.ln(e,t),sqrt:(e,t)=>qr.exp(e,qr.mul(e,[e.S/2n,0n],qr.ln(e,t))),sinh:(e,[t,n])=>[e.mul(qr.sinh(e,t),e.cos(n)),e.mul(qr.cosh(e,t),e.sin(n))],cosh:(e,[t,n])=>[e.mul(qr.cosh(e,t),e.cos(n)),e.mul(qr.sinh(e,t),e.sin(n))]},Or=e=>({q:e}),Mr=([e,t])=>0n===t?{f:e}:{z:[e,t]};function Ar(e,t,n){const r=e=>((e,t)=>t.z??[Er(e,t),0n])(n,t[e]);switch(e.op){case"+":return Mr(qr.add(r(0),r(1)));case"-":return Mr(qr.sub(r(0),r(1)));case"neg":return Mr([-r(0)[0],-r(0)[1]]);case"*":return Mr(qr.mul(n,r(0),r(1)));case"/":return Mr(qr.div(n,r(0),r(1)));case"^":return Mr(qr.pow(n,r(0),r(1),t[1].q));case"sqrt":return Mr(Sr.sqrt(n,r(0)));case"root":return Mr(qr.pow(n,r(1),qr.div(n,[n.S,0n],r(0)),t[0].q?.inv()));case"abs":return{f:qr.abs(n,r(0))};case"arg":return{f:$r(n,r(0)[1],r(0)[0])};case"re":return{f:r(0)[0]};case"im":return{f:r(0)[1]};case"conj":return Mr([r(0)[0],-r(0)[1]]);case"log":return Mr(qr.div(n,qr.ln(n,r(1)),qr.ln(n,r(0))));default:{const s=Sr[e.op];if(!s||1!==t.length)throw new dt(`no complex value for ${e.op}`);return Mr(s(n,r(0)))}}}function Er(e,t){return t.q?e.fromQ(t.q):t.f}const Nr={sin:(e,t)=>e.sin(t),cos:(e,t)=>e.cos(t),tan:(e,t)=>e.div(e.sin(t),e.cos(t)),sec:(e,t)=>e.div(e.S,e.cos(t)),csc:(e,t)=>e.div(e.S,e.sin(t)),cot:(e,t)=>e.div(e.cos(t),e.sin(t)),arcsin:(e,t)=>e.asin(t),arccos:(e,t)=>e.pi/2n-e.asin(t),arctan:(e,t)=>e.atan(t),sinh:(e,t)=>(e.exp(t)-e.exp(-t))/2n,cosh:(e,t)=>(e.exp(t)+e.exp(-t))/2n,tanh:(e,t)=>{const n=e.exp(t),r=e.exp(-t);return e.div(n-r,n+r)},arcsinh:(e,t)=>e.ln(t+e.sqrt(e.mul(t,t)+e.S)),arccosh:(e,t)=>{if(t<e.S)throw new dt("arccosh of a number below 1 is not real");return e.ln(t+e.sqrt(e.mul(t,t)-e.S))},arctanh:(e,t)=>{if(wr(t)>=e.S)throw new dt("arctanh of a number beyond ±1 is not real");return e.ln(e.div(e.S+t,e.S-t))/2n},ln:(e,t)=>e.ln(t),loglog:(e,t)=>e.ln(e.ln(t)),logloglog:(e,t)=>e.ln(e.ln(e.ln(t))),expm1:(e,t)=>e.exp(t)-e.S};function Ir(e,t,n){if("num"===e.type)return Or(yt(e.token));if("sym"===e.type){if("pi"===e.token||"π"===e.token)return{f:t.pi};if("e"===e.token)return{f:t.e};if("i"===e.token&&qt.complex)return{z:[0n,t.S]};if(n&&e.token in n){const t=n[e.token],r="number"==typeof t||"string"==typeof t||"bigint"==typeof t?yt(String(t)):null;if(!r)throw new dt(`the value of ${e.token} is not a number`);return Or(r)}throw new dt(`${e.token} has no value`)}qt.complex&&e.op.startsWith("\\:")&&tn[e.op.slice(2)]&&(e=nt(tn[e.op.slice(2)],e.args));const r=e.args.map(e=>Ir(e,t,n));if(r.some(e=>e.z)||["re","im","conj","arg"].includes(e.op)||function(e,t){if(!qt.complex)return!1;const n=e=>e.q?e.q.sign<0:void 0!==e.f&&e.f<0n;return"sqrt"===e.op||"ln"===e.op||"log"===e.op?n(t["log"===e.op?1:0])||"log"===e.op&&n(t[0]):"^"===e.op?n(t[0])&&!(t[1].q&&t[1].q.d%2n==1n):"root"===e.op&&n(t[1])&&!(t[0].q&&t[0].q.isInteger&&t[0].q.n%2n==1n)}(e,r))return Ar(e,r,t);const s=r.every(e=>e.q),i=e=>Er(t,r[e]);switch(e.op){case"+":return s?Or(r[0].q.add(r[1].q)):{f:i(0)+i(1)};case"-":return s?Or(r[0].q.sub(r[1].q)):{f:i(0)-i(1)};case"neg":return r[0].q?Or(r[0].q.neg()):{f:-r[0].f};case"*":return s?Or(r[0].q.mul(r[1].q)):{f:t.mul(i(0),i(1))};case"/":return s?Or(r[0].q.div(r[1].q)):{f:t.div(i(0),i(1))};case"^":return Tr(t,r[0],r[1]);case"sqrt":return Tr(t,r[0],Or(bt.HALF));case"root":return Tr(t,r[1],r[0].q?Or(r[0].q.inv()):{f:t.div(t.S,r[0].f)});case"abs":return r[0].q?Or(r[0].q.abs()):{f:wr(r[0].f)};case"floor":return Or(r[0].q?r[0].q.floor():new bt(Lr(r[0].f,t.S)));case"ceil":return Or(r[0].q?r[0].q.ceil():new bt(-Lr(-r[0].f,t.S)));case"log":return{f:t.div(t.ln(i(1)),t.ln(i(0)))};case"atan2":return{f:$r(t,i(0),i(1))};case"max":case"min":if(!r.length)throw new dt(`${e.op} of nothing`);return s?Or(r.map(e=>e.q).reduce((t,n)=>("max"===e.op?n.sub(t).sign>0:n.sub(t).sign<0)?n:t)):{f:r.map((e,t)=>i(t)).reduce((t,n)=>"max"===e.op?n>t?n:t:n<t?n:t)};case"sum":return s?Or(r.reduce((e,t)=>e.add(t.q),bt.ZERO)):{f:r.reduce((e,t,n)=>e+i(n),0n)};case"prod":return s?Or(r.reduce((e,t)=>e.mul(t.q),bt.ONE)):{f:r.reduce((e,n,r)=>t.mul(e,i(r)),t.S)};case"mean":if(!r.length)throw new dt("mean of nothing");return s?Or(r.reduce((e,t)=>e.add(t.q),bt.ZERO).div(new bt(BigInt(r.length)))):{f:r.reduce((e,t,n)=>e+i(n),0n)/BigInt(r.length)};case"mod":{if(s){if(r[1].q.isZero)throw new dt("mod 0 is undefined");return Or(r[0].q.sub(r[1].q.mul(r[0].q.div(r[1].q).floor())))}const e=i(1);if(0n===e)throw new dt("mod 0 is undefined");return{f:i(0)-t.mul(e,Lr(t.div(i(0),e),t.S)*t.S)}}case"round":{if(!r[1].q?.isInteger)throw new dt("round needs a whole number of places");const e=10n**wr(r[1].q.n),n=r[0].q??new bt(i(0),t.S),s=r[1].q.sign>=0,o=(s?n.mul(new bt(e)):n.div(new bt(e))).add(bt.HALF).floor();return Or(s?o.div(new bt(e)):o.mul(new bt(e)))}case"!":{if(!r[0].q?.isInteger||r[0].q.sign<0)throw new dt("factorial is only worked out for whole numbers");let e=1n;for(let t=2n;t<=r[0].q.n;t++)if(e*=t,0n==(255n&t)&>(e)>yr)throw xr();return Or(new bt(e))}default:{const n=Nr[e.op];if(!n||1!==r.length)throw new dt(`no numeric value for ${e.op}`);return{f:n(t,i(0))}}}}const Lr=(e,t)=>{const n=e/t;return e<0n&&n*t!==e?n-1n:n};function Tr(e,t,n){if(n.q&&n.q.isInteger){if(t.q)return Or(t.q.pow(n.q.n));let r=n.q.n;const s=r<0n;s&&(r=-r);let i=e.S,o=t.f;for(;r>0n;){if(1n&r&&(i=e.mul(i,o)),o=e.mul(o,o),gt(i)>yr+4*e.P||gt(o)>8e5){if(s)return{f:0n};throw xr()}r>>=1n}return{f:s?e.div(e.S,i):i}}const r=Er(e,t);if(0n===r){if(n.q?n.q.sign>0:n.f>0n)return Or(bt.ZERO);throw new dt("0 to a power that is not positive is undefined")}if(r<0n){if(n.q&&n.q.d%2n==1n){const t=Tr(e,{f:-r},n).f;return{f:n.q.n%2n==0n?t:-t}}throw new dt("a negative number to a fractional power is not real")}if(n.q&&1n===wr(n.q.n)&&n.q.d<=64n){const t=xt(r*e.S**(n.q.d-1n),Number(n.q.d));return{f:n.q.n<0n?e.div(e.S,t):t}}return{f:e.exp(e.mul(Er(e,n),e.ln(r)))}}function jr(e,t,n){const r=e<0n?"-":"",s=wr(e);if(0n===s)return{sign:"",digits:"0",point:1};const i=s.toString(),o=i.length-t.P;let a=i.slice(0,n);i.length>n&&i[n]>="5"&&(a=(BigInt(a)+1n).toString());let l=o;return a.length>n&&(a=a.slice(0,n),l++),{sign:r,digits:a.replace(/0+$/,"")||"0",point:l}}function zr({sign:e,digits:t,point:n}){if("0"===t)return"0";if(n>21||n<-6){return`${e}${t.length>1?`${t[0]}.${t.slice(1)}`:t}e${n-1}`}return n<=0?`${e}0.${"0".repeat(-n)}${t}`:n>=t.length?`${e}${t}${"0".repeat(n-t.length)}`:`${e}${t.slice(0,n)}.${t.slice(n)}`}function Cr(e){let t=0n,n=0n,r=e.d;for(;r%2n==0n;)r/=2n,t++;for(;r%5n==0n;)r/=5n,n++;const s=t>n?t:n;let i=wr(e.n)*10n**s/e.d;if(0n===i)return 1;for(;i%10n==0n;)i/=10n;return i.toString().length}function Zr(e){let t=e.d;for(;t%2n==0n;)t/=2n;for(;t%5n==0n;)t/=5n;return 1n===t}function Br(e){const t=/^(-?[\d.]+)e(-?\d+)$/.exec(e);return t?nt("*",[Xe(t[1]),nt("^",[Xe("10"),Xe(t[2])])]):Xe(e)}function Fr(e,{digits:t=15,scope:n}={}){if(!Number.isInteger(t)||t<1||t>1e5)throw new dt("digits must be a whole number from 1 to 100000");let r=t+25,s=null;for(let i=0;i<4;i++){const o=new kr(r),a=Ir(e,o,n);if(a.z){const e=Rr(a.z,o,t);if(e.retry&&i<3){r+=e.retry;continue}return void 0===e.real?e:Dr(e.real,o,t,null)}if(a.q&&a.q.isInteger&&wr(a.q.n).toString().length<=t)return{text:a.q.n.toString(),node:Xe(a.q.n.toString()),number:Number(a.q.n),re:Number(a.q.n),im:0,exact:!0};const l=Er(o,a);if(0n===l&&(!a.q||!a.q.isZero)&&i<3){s=null,r*=4;continue}const u=jr(l,o,t);if(s&&u.point<-10&&s.point-u.point>=(r-s.P)/2)return{text:"0",node:Xe("0"),number:0,re:0,im:0,exact:!1};if(!(u.point<-10&&i<3)||s&&s.point===u.point)return Dr(l,o,t,a.q);s={point:u.point,P:r},r+=10-u.point}throw new dt("could not approximate")}function Dr(e,t,n,r){const s=zr(jr(e,t,n));return{text:s,node:Br(s),number:Number(s),re:Number(s),im:0,exact:Boolean(r)&&Zr(r)&&Cr(r)<=n}}function Rr([e,t],n,r){const s=10n**BigInt(Math.max(0,n.P-r-12)),i=e=>wr(e)>s;if(!i(t))return{real:e};const o=jr(t,n,r);if(o.point<-10&&i(t))return{retry:10-o.point};const a=zr(o),l="1"===a?"i":"-1"===a?"-i":`${a}i`,u="1"===a?Qe("i"):nt("*",[Br(a.replace(/^-/,"")),Qe("i")]);if(!i(e))return{text:l,node:a.startsWith("-")?nt("neg",[u]):u,number:NaN,re:0,im:Number(a),exact:!1};const c=zr(jr(e,n,r)),p=a.startsWith("-"),h="1"===a.replace(/^-/,"")?Qe("i"):nt("*",[Br(a.replace(/^-/,"")),Qe("i")]);return{text:`${c} ${p?"-":"+"} ${l.replace(/^-/,"")}`,node:nt(p?"-":"+",[Br(c),h]),number:NaN,re:Number(c),im:Number(a),exact:!1}}function Pr(e,t={}){const n=e=>(e=>0===vn(e).size)(e)?"num"===e.type&&/^-?\d+$/.test(e.token)?e:Fr(e,t).node:st(e)?nt(e.op,e.args.map(n)):e;return n(e)}const _r={variable:null},Vr=(e,t)=>null!==t&&vn(e).has(t);function Wr(e){if("num"===e.type)return yt(e.token);if(st(e)&&"/"===e.op&&e.args.every(e=>"num"===e.type)){const t=yt(e.args[0].token),n=yt(e.args[1].token);return t&&n&&!n.isZero?t.div(n):null}return null}const Ur=e=>0===vn(e).size;function Hr(e,t,n){const r=function(e){const t=un(e);return"num"===t.k?t.q.isZero?t.q:null:"atom"===t.k&&"sym"===t.node.type&&"pi"===t.node.token?yt("1"):"mul"===t.k&&1===t.fs.length&&"atom"===t.fs[0].b.k&&"pi"===t.fs[0].b.node.token&&"num"===t.fs[0].e.k&&t.fs[0].e.q.isOne?t.c:null}(e);if(!r)return!1;const[s,i="1"]=String(t).split("/");return n(r.compare(yt(s).div(yt(i))))}function Jr(e){if(!Ur(e))return NaN;try{const{number:t}=Fr(e,{digits:30});return Math.sign(t)}catch{return NaN}}function Kr(){In("hasVariable")||(En("hasVariable",e=>Vr(e,_r.variable),"mentions the variable being solved for"),En("freeOfVariable",e=>null!==_r.variable&&!Vr(e,_r.variable),"does not mention the variable being solved for"),En("isRational",e=>null!==Wr(e),"an exact number: 3, -2, 1/2"),En("isWhole",e=>Wr(e)?.isInteger??!1,"a whole number (any size)"),En("isEvenWhole",e=>{const t=Wr(e);return Boolean(t?.isInteger&&t.n%2n==0n)},"an even whole number"),En("isOddWhole",e=>{const t=Wr(e);return Boolean(t?.isInteger&&t.n%2n!=0n)},"an odd whole number"),En("isPositiveRational",e=>(Wr(e)?.sign??0)>0,"an exact number above 0"),En("isNegativeRational",e=>(Wr(e)?.sign??0)<0,"an exact number below 0"),En("isConstant",Ur,"has no unknowns (numbers, π and e only)"),En("notOne",e=>{const t=Wr(e);return!t||!t.isOne},"anything except the number 1"),En("notMinusOne",e=>{const t=Wr(e);return!t||!t.equals(yt("-1"))},"anything except the number -1"),En("hasMinusSign",e=>function(e){const t=un(e);return"num"===t.k?t.q.sign<0:"mul"===t.k&&t.c.sign<0}(e),"written with a leading minus: -x, -2x, -π/6"),En("piMultipleAtLeast",(e,t)=>Hr(e,t,e=>e>=0),"a multiple of π, at least k·π"),En("piMultipleAbove",(e,t)=>Hr(e,t,e=>e>0),"a multiple of π, above k·π"),En("piMultipleBelow",(e,t)=>Hr(e,t,e=>e<0),"a multiple of π, below k·π"),En("piMultipleAtMost",(e,t)=>Hr(e,t,e=>e<=0),"a multiple of π, at most k·π"),En("isPositiveConstant",e=>Jr(e)>0,"no unknowns, and above 0 (e, π, √2, 3)"),En("isNegativeConstant",e=>Jr(e)<0,"no unknowns, and below 0"),En("hasImaginaryPart",e=>{if(!qt.complex)return!1;const t=Qt(un(e));return Boolean(t)&&!("num"===t.im.k&&t.im.q.isZero)},"complex mode: has a nonzero imaginary part (unknowns count as real)"),En("isSymbolNode",e=>"sym"===e.type&&!$t.has(e.token),"a single unknown such as x"))}function Yr(e){const t=new Map;for(const n of e){const e=n.id??n.name;if(!e)throw new Error(`a rule needs an id (pattern ${n.pattern})`);t.set(String(e),{...t.get(String(e))??{},...n})}const n=[...t.values()].map(e=>{const t={...e};try{void 0!==t.pattern&&(t.pattern=function(e){const t=it(e),n=e=>"num"===e.type||("sym"===e.type?e.token.startsWith("="):e.args.every(n)),r=e=>"sym"===e.type?Qe(e.token.slice(1)):"num"===e.type?e:nt(e.op,e.args.map(r)),s=e=>"sym"===e.type?Qe(`=${e.token}`):"num"===e.type?e:nt(e.op,e.args.map(s)),i=e=>"op"!==e.type?e:n(e)?s(cn(r(e))):nt(e.op,e.args.map(i));return i(t).s}(String(t.pattern)))}catch(e){throw new Error(`rule "${t.id}": bad pattern "${t.pattern}": ${e.message}`)}return"hidden"===t.step&&(t.tags=[...t.tags??[],"hidden"]),t});return dr.fromSpecs(n,{strict:!0})}function Gr(e,t,n,r){return e.explain?e.explain.replace(/\{(\w+)\}/g,(e,s)=>"result"===s?n?r(n):e:t[s]?r(t[s]):e).trim():""}const Qr=e=>st(e)&&("+"===e.op||"-"===e.op),Xr=e=>st(e)&&("*"===e.op||"/"===e.op);function*es(e,t,{order:n="pre"}={}){for(const r of function(e,t,{order:n="post"}={}){const r=[];for(const{node:s,path:i}of pt(e,n))for(const e of vr(s,t))r.push({...e,node:s,path:i});return r}(e,t,{order:n})){const t=br(r.rule.outputTemplate,r.bound);yield{rule:r.rule,bound:r.bound,path:r.path,before:r.node,after:t,next:()=>cn(ht(e,r.path,t))}}for(const{node:r,path:s}of pt(e,n)){const n=Qr(r);if(!n&&!Xr(r))continue;const i=n?bn(un(r)):yn(un(r));if(i.length<3)continue;const o=n?_t:Wt;for(let n=0;n<i.length;n++)for(let r=n+1;r<i.length;r++){const a=fn(o([i[n],i[r]]));for(const l of vr(a,t)){const t=br(l.rule.outputTemplate,l.bound),u=i.filter((e,t)=>t!==n&&t!==r);yield{rule:l.rule,bound:l.bound,path:s,before:a,after:t,next:()=>cn(ht(e,s,fn(o([un(t),...u]))))}}}}}function ts(e,t,{format:n,order:r="pre",maxSteps:s=200,variable:i=null}={}){const o=_r.variable;_r.variable=i;try{let i=cn(e);const o=new Set([i.s]),a=[];for(let e=0;e<s;e++){let e=null;for(const n of es(i,t,{order:r})){const t=n.next();if(t.s!==i.s&&!o.has(t.s)){e={c:n,next:t};break}}if(!e)break;const{c:s,next:l}=e;a.push({id:s.rule.id,name:s.rule.name,tags:s.rule.tags,from:i.s,to:l.s,path:s.path,before:s.before.s,after:s.after.s,explanation:Gr(s.rule,s.bound,cn(s.after),n)}),i=l,o.add(i.s)}return{node:i,steps:a}}finally{_r.variable=o}}const ns={full:[],normal:["hidden"],brief:["hidden","tidy","identity","value","split","base","arithmetic"]},rs=(e,t)=>"all"===t||"*"===t||Array.isArray(t)&&t.some(t=>t===e.id||e.tags?.includes(t));function ss(e){if(!1===e)return null;if(void 0===e||!0===e)return{show:"all",hide:ns.normal,explain:!0};if("string"==typeof e){if(!ns[e])throw new Error(`steps: "${e}" is not one of ${Object.keys(ns).join(", ")}`);return{show:"all",hide:ns[e],explain:!0}}const t=e.detail??"normal";if(!ns[t])throw new Error(`steps.detail: "${t}" is not one of ${Object.keys(ns).join(", ")}`);return{show:e.show??"all",hide:[...ns[t],...e.hide??[]],explain:e.explain??!0}}function is(e,t){if(!t)return[];const n=[];let r=null;for(const s of e){if(!(rs(s,t.show)&&!rs(s,t.hide))){r=r??{from:s.from,ids:[]},r.ids.push(s.id);continue}const e={...s};r&&(e.from=r.from,e.also=r.ids,e.path=null,r=null);!0===t.explain||!1!==t.explain&&rs(s,t.explain)||delete e.explanation,n.push(e)}if(r&&n.length){const t=n[n.length-1];t.to=e[e.length-1].to,t.also=[...t.also??[],...r.ids]}return n}const os=At(bt.ONE),as=(e,t)=>"atom"===e.k&&"sym"===e.node.type&&e.node.token===t;function ls(e){switch(e.k){case"num":default:return e;case"atom":return"op"===e.node.type?an(e.node.op,e.node.args.map(e=>ls(un(e)))):e;case"add":return _t(bn(e).map(ls));case"mul":{let t=[At(e.c)];for(const n of e.fs){const e=ls(n.b);if("add"===e.k&&Lt(n.e)&&n.e.q.isInteger&&n.e.q.sign>0&&n.e.q.n<=BigInt(60))for(let r=0n;r<n.e.q.n;r++)t=us(t,bn(e));else t=us(t,[Ht(e,n.e)])}return _t(t)}}}function us(e,t){const n=[];for(const r of e)for(const e of t)n.push(Wt([r,e]));return bn(_t(n))}function cs(e,t){const n=new Map;for(const r of bn(ls(e))){const{coef:e,rest:s}=Pt(r);let i=0;const o=[At(e)];for(const e of s?yn(s):[]){const{b:n,e:r}="mul"===e.k&&1===e.fs.length&&e.c.isOne?e.fs[0]:{b:e,e:os};if(as(n,t)){if(!Lt(r)||!r.q.isInteger||r.q.sign<0)return null;i+=Number(r.q.n)}else{if(ps(n,t)||ps(r,t))return null;o.push(e)}}n.set(i,_t([n.get(i)??At(bt.ZERO),Wt(o)]))}for(const[e,t]of n)Lt(t)&&t.q.isZero&&n.delete(e);return n}const ps=(e,t)=>vn(fn(e)).has(t);function hs(e){if(!e)return null;const t=Math.max(0,...e.keys());if(t>256)return null;const n=[];for(let r=0;r<=t;r++){const t=e.get(r)??At(bt.ZERO);if(!Lt(t))return null;n.push(t.q)}return n}function ds(e,t){const n=un(Qe(t));return _t(e.map((e,t)=>Wt([At(e),Ut(n,At(bt.of(t)))])))}const fs=e=>{const t=e.slice();for(;t.length>1&&t[t.length-1].isZero;)t.pop();return t},ms=(e,t)=>e.reduceRight((e,n)=>e.mul(t).add(n),bt.ZERO);function gs(e,t){const n=e.length-1,r=new Array(n);let s=bt.ZERO;for(let i=n;i>=1;i--)s=e[i].add(s.mul(t)),r[i-1]=s;return r}function vs(e){if(0n===(e=(e=>e<0n?-e:e)(e)))return null;if(e>10n**14n)return null;const t=[];let n=e;for(let e=2n;e*e<=n;e+=2n===e?1n:2n){if(n%e)continue;let r=0;for(;n%e===0n;)n/=e,r++;t.push([e,r])}n>1n&&t.push([n,1]);let r=[1n];for(const[e,n]of t){const t=[];for(const s of r)for(let r=0,i=1n;r<=n;r++,i*=e)t.push(s*i);if(r=t,r.length>2e4)return null}return r.sort((e,t)=>e<t?-1:e>t?1:0)}function bs(e){let t=fs(e);const n=[];for(;t.length>1&&t[0].isZero;)n.push(bt.ZERO),t=t.slice(1);if(t.length<=1)return{roots:n,rest:t};const r=t.reduce((e,t)=>e*t.d/vt(e,t.d),1n),s=t.map(e=>e.n*r/e.d),i=vs(s[0]),o=vs(s[s.length-1]);if(!i||!o)return{roots:n,rest:t};const a=new Map;for(const e of i)for(const t of o)for(const n of[1n,-1n]){const r=new bt(n*e,t);a.set(r.toString(),r)}const l=[...a.values()].sort((e,t)=>e.compare(t));for(const e of l)for(;t.length>1&&ms(t,e).isZero;)n.push(e),t=gs(t,e);return{roots:n.sort((e,t)=>e.compare(t)),rest:t}}function ys(e){if("num"===e.k)return{coef:e.q,factors:[],notes:[]};if("atom"===e.k)return{coef:bt.ONE,factors:[{base:e,exp:os}],notes:[]};if("mul"===e.k){let t=e.c;const n=[],r=[];for(const s of e.fs)if("add"===s.b.k&&Lt(s.e)&&s.e.q.isInteger){const e=ys(s.b);t=t.mul(e.coef.pow(s.e.q.n));for(const t of e.factors)n.push({base:t.base,exp:Wt([t.exp,s.e])});r.push(...e.notes)}else n.push({base:s.b,exp:s.e});return xs(t,n,r)}return function(e){const t=bn(e),n=[],r=t.map(e=>{const{coef:t,rest:n}=Pt(e);return{coef:t,fs:n?yn(n).map(ks):[]}}),s=r.reduce((e,t)=>({n:vt(e.n,t.coef.n),d:e.d*t.coef.d/vt(e.d,t.coef.d)}),{n:0n,d:1n});let i=new bt(s.n||1n,s.d);ws(e)<0&&(i=i.neg());const o=[];for(const e of r[0].fs){if(!Lt(e.e)||e.e.q.sign<=0)continue;let t=e.e.q;const n=zt(e.b);let s=!0;for(const e of r.slice(1)){const r=e.fs.find(e=>zt(e.b)===n&&Lt(e.e)&&e.e.q.sign>0);if(!r){s=!1;break}r.e.q.compare(t)<0&&(t=r.e.q)}s&&o.push({base:e.b,exp:At(t)})}let a=e;if(!i.isOne||o.length){const e=Wt([At(i),...o.map(e=>Ht(e.base,e.exp))]);a=_t(t.map(t=>Wt([t,Ut(e,At(bt.MINUS_ONE))]))),n.push({id:"factor.common",values:{common:e}})}const l="add"===a.k?function(e,t){const n=[...$s(e)];for(const r of n){const s=hs(cs(e,r));if(!s||s.length<3)continue;if(1!==n.length)break;const{roots:i,rest:o}=bs(s);if(!i.length)break;const a=[];let l=o[o.length-1]??bt.ONE;const u=o.map(e=>e.div(l)),c=[...i].sort((e,t)=>e.abs().compare(t.abs())||t.sign-e.sign);for(const e of c){const n=ds([new bt(-e.n),new bt(e.d)],r);a.push({base:n,exp:os}),l=l.div(new bt(e.d)),t.push({id:"factor.root",values:{root:At(e),factor:n}})}if(u.length>1){const e=u.reduce((e,t)=>e*t.d/vt(e,t.d),1n),t=u.map(t=>t.mul(new bt(e))),n=t.reduce((e,t)=>vt(e,t.n),0n)||1n;l=l.mul(new bt(n,e)),a.push({base:ds(t.map(e=>e.div(new bt(n))),r),exp:os})}return xs(l,a,[])}const r=bn(e);if(2===r.length){const[e,n]=r;for(const r of[2,3]){const s=qs(e,r),i=qs(nn(n),r),o=3===r?qs(n,r):null;if(s&&i&&2===r){t.push({id:"factor.squares",values:{a:s,b:i}});const e=ys(_t([s,nn(i)])),n=ys(_t([s,i]));return xs(e.coef.mul(n.coef),[...e.factors,...n.factors],[...e.notes,...n.notes])}if(3===r&&s&&(i||o)){const e=i??o,n=i?-1:1;t.push({id:n<0?"factor.cubes-difference":"factor.cubes-sum",values:{a:s,b:e}});const r=_t(n<0?[s,nn(e)]:[s,e]),a=_t([Ut(s,At(bt.of(2))),n<0?Wt([s,e]):nn(Wt([s,e])),Ut(e,At(bt.of(2)))]),l=ys(r);return xs(l.coef,[...l.factors,{base:a,exp:os}],l.notes)}}}return{coef:bt.ONE,factors:[{base:e,exp:os}],notes:[]}}(a,n):ys(a);return xs(i.mul(l.coef),[...o,...l.factors],[...n,...l.notes.filter(e=>!n.includes(e))])}(e)}function xs(e,t,n){const r=new Map;for(const e of t){const t=zt(e.base),n=r.get(t);n?n.exp=_t([n.exp,e.exp]):r.set(t,{...e})}return{coef:e,factors:[...r.values()].filter(e=>!(Lt(e.exp)&&e.exp.q.isZero)),notes:n}}const ws=e=>Pt(bn(e)[0]).coef.sign;const ks=e=>"mul"===e.k&&e.c.isOne&&1===e.fs.length?{b:e.fs[0].b,e:e.fs[0].e}:{b:e,e:os},$s=e=>vn(fn(e));function qs(e,t){const{coef:n,rest:r}=Pt(e);if(n.sign<0)return null;const s=function(e,t){const n=e=>{if(e<0n)return null;let n=0n,r=1n;for(;r**BigInt(t)<=e;)r*=2n;for(;n<r-1n;){const s=(n+r)/2n;s**BigInt(t)<=e?n=s:r=s}return n**BigInt(t)===e?n:null},r=n(e.n),s=n(e.d);return null!==r&&null!==s?new bt(r,s):null}(n,t);if(!s)return null;const i=[At(s)];for(const e of r?yn(r).map(ks):[]){if(!Lt(e.e))return null;const n=e.e.q.div(bt.of(t));if(!n.isInteger)return null;i.push(Ht(e.b,At(n)))}return Wt(i)}function Ss({coef:e,factors:t}){const n=[],r=[];for(const e of t){const t=Lt(e.exp)&&e.exp.q.sign<0,s=t?At(e.exp.q.neg()):e.exp,i=fn(Ht(e.base,s));(t?r:n).push(i)}const s=e=>e.reduce((e,t)=>e?nt("*",[e,t]):t,null),i=e.n<0n?-e.n:e.n;let o=n.length?s(1n===i?n:[fn(At(new bt(i))),...n]):fn(At(new bt(i)));return e.n<0n&&(o=nt("neg",[o])),1n!==e.d&&r.unshift(fn(At(new bt(e.d)))),r.length?nt("/",[o,s(r)]):o}function Os(e){if("mul"!==e.k)return{num:e,den:os};const t=[At(new bt(e.c.n))],n=[At(new bt(e.c.d))];for(const r of e.fs)Lt(r.e)&&r.e.q.sign<0?n.push(Ht(r.b,At(r.e.q.neg()))):t.push(Ht(r.b,r.e));return{num:Wt(t),den:Wt(n)}}function Ms(e){if("add"!==e.k)return Os(e);const t=bn(e).map(Os),n=new Map;let r=1n;for(const e of t){const{coef:t,rest:s}=Pt(e.den);r=r*t.n/vt(r,t.n);for(const e of s?yn(s).map(ks):[]){const t=zt(e.b),r=n.get(t);(!r||Lt(e.e)&&Lt(r.e)&&e.e.q.compare(r.e.q)>0)&&n.set(t,e)}}const s=Wt([At(new bt(r)),...[...n.values()].map(e=>Ht(e.b,e.e))]);if(Lt(s)&&s.q.isOne)return{num:e,den:os};return{num:ls(_t(t.map(e=>Wt([e.num,s,Ut(e.den,At(bt.MINUS_ONE))])))),den:s}}function As(e){const{num:t,den:n}=Ms(e);if(Lt(n)&&n.q.isOne)return null;const r=ys(t),s=ys(n),i=new Set(r.factors.map(e=>zt(e.base))),o=s.factors.filter(e=>i.has(zt(e.base))),a=[...r.factors,...s.factors.map(e=>({base:e.base,exp:nn(e.exp)}))];return{...xs(r.coef.div(s.coef),a,[...r.notes,...s.notes]),canceled:o.map(e=>e.base)}}const Es=(e,t)=>nt("=",[e,t]),Ns=cn(nt("+",[Qe("x"),nt("neg",[Qe("x")])])),Is=e=>st(e)&&"="===e.op;function Ls(e,t,n,r={}){const s=[],i=(t,n,r,i,o,a={})=>s.push(e.step(t,n,r,i,o,a));i.raw=e=>s.push(e);const o=Is(t)?t:Es(t,Ns),a=Es(cn(o.args[0]),cn(o.args[1]));a.s!==o.s&&i("normal","Work out each side",["tidy","arithmetic"],o,a);const l=[],u=[],c=new Set;l.numeric=c,Bs(e,a,n,r,i,l,u,0);const p=[],h=new Set;for(const t of l.map(t=>c.has(t)?t:(t=>ts(t,e.set.view("simplify"),{format:e.format}).node)(t))){const e=t.s;if(h.has(e))continue;h.add(e);const r=c.has(t)?null:zs(o,n,t);r?i("solve.reject","Check the answer",["check"],Es(Qe(n),t),Es(Qe(n),t),{value:t,reason:r}):p.push(t)}return p.sort(Ts),{solutions:p,unsolved:u,steps:s,always:u.some(e=>e.always)}}function Ts(e,t){const n=js(e),r=js(t);return null===n||null===r?e.s<t.s?-1:1:(Math.abs(n.im)>0)-(Math.abs(r.im)>0)||n.re-r.re||n.im-r.im}function js(e){if(vn(e).size)return null;try{const{re:t,im:n}=Fr(e,{digits:20});return{re:t,im:n}}catch{return null}}function zs(e,t,n){const[r,s]=e.args,i=new Set([...vn(r),...vn(s),...vn(n)]);if(i.delete(t),i.size)return null;const o=e=>Cs(e,t,n);try{const e=Fr(o(r),{digits:40}),t=Fr(o(s),{digits:40}),n=Math.max(1,Math.hypot(e.re,e.im),Math.hypot(t.re,t.im));return Math.hypot(e.re-t.re,e.im-t.im)>1e-12*n?"it does not make the two sides equal":null}catch(e){return`the original equation has no value there (${e.message})`}}function Cs(e,t,n){return"sym"===e.type?e.token===t?n:e:st(e)?nt(e.op,e.args.map(e=>Cs(e,t,n))):e}const Zs=24;function Bs(e,t,n,r,s,i,o,a){if(a>Zs)return Ws(e,t,n,r,s,i,o);const l=function(e){const t=[],n=e=>{if(st(e)&&"|"===e.op)return void e.args.forEach(n);if(!Is(e))return void t.push(e);const r=e.args[1],s=pt(r,"pre").find(({node:e})=>st(e)&&"pm"===e.op);if(!s)return void t.push(e);const i=s.node.args[0],o=cn(ht(r,s.path,i)),a=cn(ht(r,s.path,nt("neg",[i])));n(Es(e.args[0],o)),a.s!==o.s&&n(Es(e.args[0],a))};return n(e),t}(t);if(l.length>1){s("solve.split","Two cases",["split"],t,l.reduce((e,t)=>e?nt("|",[e,t]):t,null));for(const t of l)Bs(e,t,n,r,s,i,o,a+1);return}if(1===l.length&&l[0].s!==t.s)return Bs(e,l[0],n,r,s,i,o,a+1);const[u,c]=t.args;if("sym"===u.type&&u.token===n&&!ps(un(c),n))return void i.push(c);const p=_t([un(u),nn(un(c))]);if(!ps(p,n))return Lt(p)&&p.q.isZero?(s("solve.always","Always true",["check"],t,t,{v:n}),void o.push(Object.assign(Object.create(t),{always:!0}))):void s("solve.never","No solution",["check"],t,t,{v:n});const h=bn(p).filter(e=>ps(e,n)),d=bn(p).filter(e=>!ps(e,n)),f=_t(h),m=nn(_t(d));if(qt.complex){const l=cs(p,n);if(l&&[...l.values()].every(e=>!ps(e,n))&&Math.max(...l.keys())>=2){const u=Es(fn(p),Ns);return u.s!==t.s&&s("solve.one-side","Everything on one side",["move"],t,u,{v:n}),_s(e,p,l,n,r,s,i,o,a,u)}}if(1===h.length)return Fs(e,t,f,m,n,r,s,i,o,a);const g=Es(fn(p),Ns),v=cs(p,n);if(v&&[...v.values()].every(e=>!ps(e,n))&&Math.max(...v.keys())>=2)return g.s!==t.s&&s("solve.one-side","Everything on one side",["move"],t,g,{v:n}),_s(e,p,v,n,r,s,i,o,a,g);const b=ys(p),y=b.factors.filter(e=>ps(e.base,n)&&!(Lt(e.exp)&&e.exp.q.sign<0));if(y.length>=2||1===y.length&&b.factors.length>1){const l=Es(Ss(b),Ns);g.s!==t.s&&s("solve.one-side","Everything on one side",["move"],t,g,{v:n}),l.s!==g.s&&s("solve.factor","Factor",["factor"],g,l,{});const u=y.map(e=>Es(fn(e.base),Ns));u.length>1&&s("solve.zero-product","A product is zero when a factor is",["split"],l,u.reduce((e,t)=>e?nt("|",[e,t]):t,null),{});for(const t of u)Bs(e,t,n,r,s,i,o,a+1);return}const x=Ms(p);if(ps(x.den,n)){const l=Es(fn(x.num),Ns);return s("solve.clear-denominator","Clear the denominator",["move"],t,l,{den:fn(x.den)}),Bs(e,l,n,r,s,i,o,a+1)}const w=h.filter(e=>!Ps(e,n));if(1===w.length&&/\b(sqrt|root|abs)\b/.test(fn(w[0]).s))return Fs(e,t,w[0],nn(_t(bn(p).filter(e=>e!==w[0]))),n,r,s,i,o,a);const k=function(e,t){const n=fn(e),r=new Map;for(const{node:e}of pt(n,"pre"))if(st(e)&&vn(e).has(t))if("^"!==e.op||vn(e.args[0]).has(t))["sin","cos","tan","ln","sqrt","abs"].includes(e.op)&&e.args[0].s===t&&r.set(e.s,e);else{const n=un(e.args[1]),{coef:s,rest:i}=Pt(n);if(i&&s.isInteger&&fn(i).s===t){const n=fn(Ut(un(e.args[0]),un(Qe(t))));r.set(n.s,n)}}const s="u"===t?"w":"u";for(const e of r.values()){const r=Vs(n,e,t,s);if(!r||vn(r).has(t))continue;const i=un(r),o=cs(i,s);if(o&&Math.max(...o.keys())>=1)return{kernel:un(e),poly:i,symbol:s}}return null}(p,n);if(k){const t=k.symbol;s("solve.substitute","Substitute",["substitute"],g,Es(fn(k.poly),Ns),{u:Qe(t),kernel:fn(k.kernel)});const l=[];Bs(e,Es(fn(k.poly),Ns),t,r,s,l,o,a+1);for(const t of l)Bs(e,Es(fn(k.kernel),t),n,r,s,i,o,a+1);return}return Ws(e,g,n,r,s,i,o)}function Fs(e,t,n,r,s,i,o,a,l,u){let c=Es(fn(n),fn(r));c.s!==t.s&&o("solve.move","Move the terms",["move"],t,c,{v:s});const{coef:p,rest:h}=Pt(n),d=h?yn(h):[],f=Wt([At(p),...d.filter(e=>!ps(e,s))]);if(!Lt(f)||!f.q.isOne){const e=Wt(d.filter(e=>ps(e,s))),t=Es(fn(e),fn(rn(r,f))),n=Lt(f)&&!f.q.isInteger&&(1n===f.q.n||-1n===f.q.n);o(n?"solve.multiply":"solve.divide",n?"Multiply both sides":"Divide both sides",["move"],c,t,{by:fn(n?At(f.q.inv()):f),v:s}),c=t}if("sym"===c.args[0].type&&c.args[0].token===s)return void a.push(c.args[1]);const m=un(c.args[1]);if(Lt(m)&&m.q.isZero){const t=un(c.args[0]),n=yn(t).filter(e=>ps(e,s)&&!Ds(e));if(n.length>1||n.length<yn(t).filter(e=>ps(e,s)).length){const t=n.map(e=>Es(fn(Rs(e)),Ns));o("solve.zero-product","A product is zero when a factor is",["split"],c,t.reduce((e,t)=>e?nt("|",[e,t]):t,null),{});for(const n of t)Bs(e,n,s,i,o,a,l,u+1);return}}const g=ts(c,e.set.view("isolate"),{format:e.format,maxSteps:1,variable:s});return g.steps.length?(function(e,t){for(const n of t)e.raw(n)}(o,g.steps),Bs(e,g.node,s,i,o,a,l,u+1)):Ws(e,c,s,i,o,a,l)}const Ds=e=>"mul"===e.k&&e.c.isOne&&1===e.fs.length&&Lt(e.fs[0].e)&&e.fs[0].e.q.sign<0,Rs=e=>"mul"===e.k&&e.c.isOne&&1===e.fs.length&&Lt(e.fs[0].e)&&e.fs[0].e.q.sign>0?e.fs[0].b:e,Ps=(e,t)=>{const n=cs(e,t);return Boolean(n)&&[...n.values()].every(e=>!ps(e,t))};function _s(e,t,n,r,s,i,o,a,l,u){const c=Math.max(...n.keys()),p=hs(n);if(qt.complex&&c>=3&&c<=64&&p&&p.every((e,t)=>0===t||t===c||e.isZero)&&!p[0].isZero){const t=p[0].neg().div(p[c]),n=Ut(At(t.abs()),At(new bt(1n,BigInt(c)))),s=[];for(let r=0;r<c;r++){const i=Wt([At(new bt(BigInt((t.sign<0?1:0)+2*r),BigInt(c))),un(Qe("pi"))]),o=nt("*",[fn(n),nt("+",[nt("cos",[fn(i)]),nt("*",[Qe("i"),nt("sin",[fn(i)])])])]);s.push(ts(o,e.set.view("simplify"),{format:e.format}).node)}return i("solve.roots","All n roots",["complex"],u,s.map(e=>Es(Qe(r),e)).reduce((e,t)=>e?nt("|",[e,t]):t),{v:r,n:String(c),last:String(c-1),r:fn(At(t))}),void o.push(...s)}if(p){const{roots:n}=bs(p);if(n.length){const n=ys(t),c=Es(Ss(n),Ns);if(n.factors.length>1||n.factors.some(e=>!(Lt(e.exp)&&e.exp.q.isOne))){i("solve.factor","Factor",["factor"],u,c,{});const t=n.factors.filter(e=>ps(e.base,r)).map(e=>Es(fn(e.base),Ns));t.length>1&&i("solve.zero-product","A product is zero when a factor is",["split"],c,t.reduce((e,t)=>e?nt("|",[e,t]):t,null),{});for(const n of t)Bs(e,n,r,s,i,o,a,l+1);return}}}if(2===c){const e=n.get(2),t=n.get(1)??At(bt.ZERO),s=n.get(0)??At(bt.ZERO),a=_t([Ut(t,At(bt.of(2))),Wt([At(bt.of(-4)),e,s])]);if(Lt(a)&&a.q.sign<0&&!qt.complex)return void i("solve.no-real","No real solutions",["quadratic"],u,u,{D:fn(a)});const l=Wt([At(bt.of(2)),e]),c=Ut(a,At(bt.HALF)),p=fn(rn(_t([nn(t),c]),l)),h=fn(rn(_t([nn(t),nn(c)]),l)),d=p.s===h.s?Es(Qe(r),p):nt("|",[Es(Qe(r),p),Es(Qe(r),h)]);return i(qt.complex&&Lt(a)&&a.q.sign<0?"solve.quadratic-complex":"solve.quadratic","The quadratic formula",["quadratic"],u,d,{a:fn(e),b:fn(t),c:fn(s),D:fn(a),root:fn(c),v:r}),o.push(p),void(h.s!==p.s&&o.push(h))}return Ws(e,u,r,s,i,o,a)}function Vs(e,t,n,r){if(e.s===t.s)return Qe(r);if(!st(e))return e;if("^"===e.op&&"^"===t.op&&e.args[0].s===t.args[0].s){const t=un(e.args[1]),{coef:s,rest:i}=Pt(t);if(i&&fn(i).s===n&&s.isInteger)return nt("^",[Qe(r),fn(At(s))])}return nt(e.op,e.args.map(e=>Vs(e,t,n,r)))}function Ws(e,t,n,r,s,i,o){if(r.approximate){const e="number"==typeof r.approximate?r.approximate:15,o=un(nt("-",[t.args[0],t.args[1]])),a=qt.complex?hs(cs(o,n)):null,l=a&&a.length>2?function(e,t){const n=e.length-1,r=e[n],s=e.map(e=>e/r),i=(e,t)=>{let r=1,i=0;for(let o=n-1;o>=0;o--)[r,i]=[r*e-i*t+s[o],r*t+i*e];return[r,i]};let o=Array.from({length:n},(e,t)=>[1.3*Math.cos(2*Math.PI*t/n+.4),1.3*Math.sin(2*Math.PI*t/n+.4)]);for(let e=0;e<500;e++){let e=0;if(o=o.map(([t,r],s)=>{let[a,l]=i(t,r);for(let e=0;e<n;e++){if(e===s)continue;const n=t-o[e][0],i=r-o[e][1],u=n*n+i*i;[a,l]=[(a*n+l*i)/u,(l*n-a*i)/u]}return e=Math.max(e,Math.hypot(a,l)),[t-a,r-l]}),e<1e-15)break}const a=e=>Math.abs(e)<1e-12?0:Number(e.toPrecision(t));return o.map(([e,t])=>[a(e),a(t)]).sort((e,t)=>(0!==e[1])-(0!==t[1])||e[0]-t[0]||e[1]-t[1]).map(([e,t])=>{const n=Us(e);if(0===t)return n;const r=nt("*",[Us(Math.abs(t)),Qe("i")]);return 0===e?t<0?nt("neg",[r]):r:nt(t<0?"-":"+",[n,r])})}(a.map(e=>e.toNumber()),Math.min(e,14)):function(e,t,n){const r=un(nt("-",[e.args[0],e.args[1]])),s=fn(r),i=e=>{try{return Fr(Cs(s,t,Hs(e)),{digits:30}).number}catch{return NaN}},o=[],a=[];for(let e=-400;e<=400;e++)a.push(Math.sign(e)*(Math.abs(e)/20)**2);for(let e=0;e+1<a.length;e++){let t=a[e],r=a[e+1],s=i(t);const l=i(r);if(Number.isNaN(s)||Number.isNaN(l))continue;if(0===s){o.push(Hs(t));continue}if(s*l>0)continue;for(let e=0;e<200&&r-t>1e-16*Math.abs(t);e++){const e=(t+r)/2,n=i(e);if(Number.isNaN(n))break;s*n<=0?r=e:(t=e,s=n)}const u=(t+r)/2;Math.abs(i(u))<1e-6&&o.push(Hs(Number(u.toPrecision(Math.min(n,15)))))}return o}(t,n,e);for(const e of l)i.numeric?.add(e);return s("solve.numeric","Numeric solutions",["numeric"],t,l.length?l.map(e=>Es(Qe(n),e)).reduce((e,t)=>e?nt("|",[e,t]):t):t,{v:n,count:String(l.length)}),void i.push(...l)}s("solve.unsolved","No exact method",["unsolved"],t,t,{v:n}),o.push(t)}const Us=e=>Xe(String(e).includes("e")?e.toFixed(20):String(e)),Hs=e=>Xe(Number.isInteger(e)?String(e):e.toFixed(17));const Js=(e,t)=>nt("int",[e,"string"==typeof t?Qe(t):t]);function Ks(e,t,n,r=0){if(r>6)throw new dt("integration went too deep");const s=[],i=e.set.view("integrate"),o=ts(t,e.set.view("simplify"),{format:e.format});s.push(...o.steps);let a=cn(Js(o.node,n));for(let t=0;t<40;t++){const t=ts(a,i,{format:e.format});s.push(...t.steps),a=t.node;const n=pt(a,"pre").find(({node:e})=>{return st(t=e)&&"int"===t.op&&2===t.args.length;var t});if(!n)return{node:a,steps:s};const o=Ys(e,n.node,r);if(!o)throw new dt(`no rule for ∫ ${e.format(n.node.args[0])} d${n.node.args[1].token}`);s.push(...o.steps),a=cn(ht(a,n.path,o.node))}throw new dt("integration did not finish")}function Ys(e,t,n){const[r,s]=t.args,i=s.token,o=un(r),a=function(e,t){const{num:n,den:r}=Ms(e),s=ys(n),i=ys(r),o=s.coef.div(i.coef);if(o.isOne||!ps(e,t))return null;const a=Wt([...s.factors.map(e=>Ht(e.base,e.exp)),...i.factors.map(e=>Ht(e.base,nn(e.exp)))]);return{c:o,rest:a}}(o,i);if(a){const n=nt("*",[fn(At(a.c)),Js(fn(a.rest),s)]);return{node:n,steps:[e.step("integrate.constant","Take the number out",["split"],t,n,{c:fn(At(a.c))})]}}const l=ls(o);if(fn(l).s!==r.s&&"add"===l.k){const n=Js(fn(l),s);return{node:n,steps:[e.step("integrate.expand","Multiply out",["expand"],t,n,{})]}}const u=function(e,t){const n=new Map;for(const{node:r}of pt(e,"pre")){if(!st(r))continue;const e="^"===r.op?r.args:"/"===r.op?[r.args[1]]:"der"===r.op||"int"===r.op?[]:1===r.args.length||"root"===r.op?[r.args[r.args.length-1]]:[];for(const r of e){if("sym"===r.type||!vn(r).has(t))continue;const e=cs(un(r),t);if(!e||1!==Math.max(...e.keys()))continue;const s=e.get(1);ps(s,t)||Lt(s)&&s.q.isZero||n.set(r.s,{node:r,a:s})}}for(const r of n.values()){if(!vn(Gs(e,r.node,Qe("§"))).has(t))return r}return null}(r,i);if(u){const s="u"===i?"t":"u",o=Gs(r,u.node,Qe(s));if(!vn(o).has(i)){const r=Ks(e,cn(o),s,n+1),a=cn(Cs(r.node,s,u.node)),l=fn(rn(un(a),u.a));return{node:l,steps:[e.step("integrate.substitute","Substitute",["substitute"],t,cn(Js(o,s)),{u:Qe(s),inside:u.node,a:fn(u.a),v:i}),...r.steps,e.step("integrate.back","Substitute back",["substitute"],r.node,l,{u:Qe(s),inside:u.node})]}}}const c=function(e,t,n,r){const{num:s,den:i}=Ms(n);if(!ps(i,r))return null;const o=hs(cs(s,r)),a=hs(cs(i,r));if(!o||!a||a.length<2)return null;const l=un(Qe(r)),u=e=>ds(e,r);if(o.length>=a.length){const{q:n,r:s}=function(e,t){const n=fs(t);let r=fs(e);const s=n[n.length-1];if(s.isZero)throw new dt("division by the zero polynomial");const i=new Array(Math.max(1,r.length-n.length+1)).fill(bt.ZERO);for(;r.length>=n.length&&(1!==r.length||!r[0].isZero);){const e=r.length-n.length,t=r[r.length-1].div(s);if(i[e]=t,r=fs(r.map((r,s)=>s>=e&&s-e<n.length?r.sub(t.mul(n[s-e])):r)),r.length-1<e+n.length-1&&r[r.length-1].isZero)break;if(r.length<n.length)break}return{q:fs(i),r:r}}(o,a),i=Js(fn(_t([u(n),rn(u(s),u(a))])),Qe(r));return{node:i,steps:[e.step("integrate.divide","Divide the polynomials",["divide"],t,i,{})]}}const{roots:c,rest:p}=bs(a),h=new Set(c.map(String)).size===c.length;if(!c.length||!h||1!==p.length)return null;const d=(e=>e.length<=1?[bt.ZERO]:e.slice(1).map((e,t)=>e.mul(bt.of(t+1))))(a),f=c.map(e=>rn(At(ms(o,e).div(ms(d,e))),_t([l,At(e.neg())]))),m=Js(fn(_t(f)),Qe(r));return{node:m,steps:[e.step("integrate.partial-fractions","Partial fractions",["partial-fractions"],t,m,{})]}}(e,t,o,i);return c||function(e,t,n,r,s){if(s>=6)return null;const i=yn(n),o=i.filter(e=>Qs(e,r)||!ps(e,r)),a=i.filter(e=>!o.includes(e));if(1!==a.length)return null;const l=Wt(o),u=a[0];if(!ps(l,r))return null;const c=fn(u),p=st(c)?c.op:"";let h,d,f;"ln"===p||"arctan"===p||"arcsin"===p?(h=u,d=l):(h=l,d=u);try{f=Ks(e,fn(d),r,s+1)}catch{return null}const m=un(e.differentiate(fn(h),r)),g=Wt([h,un(f.node)]),v=Js(fn(Wt([m,un(f.node)])),Qe(r)),b=cn(nt("-",[fn(g),v]));return{node:b,steps:[e.step("integrate.parts","Integration by parts",["parts"],t,b,{u:fn(h),dv:fn(d),V:f.node,du:fn(m),v:r})]}}(e,t,o,i,n)}function Gs(e,t,n){return e.s===t.s?n:st(e)?nt(e.op,e.args.map(e=>Gs(e,t,n))):e}const Qs=(e,t)=>{const n=cs(e,t);return Boolean(n)&&[...n.values()].every(e=>!ps(e,t))&&Math.max(...n.keys())>=1};function Xs(e,t,n,r,s,i){for(const e of[r,s])if(vn(e).has("∞")||/∞|infinity/.test(e.s))throw new dt("integrals to infinity need limits, which this CAS does not do yet");if(i&&!vn(r).size&&!vn(s).size){const o=Fr(r,{digits:20}).number,a=Fr(s,{digits:20}).number,l=[...vn(i)].filter(e=>e!==n);if(!l.length){const[r,s]=o<=a?[o,a]:[a,o];for(const o of function(e,t){const n=[],r={tan:"cos",sec:"cos",csc:"sin",cot:"sin"};return pt(e,"pre").forEach(({node:e})=>{if(!st(e))return;let s=null;"/"===e.op?s=e.args[1]:"^"===e.op&&"num"===e.args[1].type&&e.args[1].value<0||"^"===e.op&&st(e.args[1])&&"neg"===e.args[1].op?s=e.args[0]:r[e.op]&&(s=nt(r[e.op],[e.args[0]])),s&&vn(s).has(t)&&!n.some(e=>e.s===s.s)&&n.push(s)}),n}(i,n)){let i=[];try{i=e.solve(nt("=",[o,Xe("0")]),n,{steps:!1}).solutions}catch{continue}for(const o of i){const i=Fr(o,{digits:20});if(!Number.isFinite(i.number)||i.im||i.number<r||i.number>s)continue;if(i.number>r&&i.number<s)throw new dt(`the integrand has no value at ${n} = ${e.format(o)}, between the limits, so F(b) - F(a) would be wrong`);let a=NaN;try{a=Fr(cn(Cs(t,n,o)),{digits:15}).number}catch{}if(!Number.isFinite(a))throw new dt(`the integral diverges at ${n} = ${e.format(o)}: F has no value at that limit`)}}}for(let e=0;!l.length&&e<=64;e++){const t=o+(a-o)*(e+.5)/65;try{const e=Fr(Cs(i,n,Xe(t.toFixed(15))),{digits:15}).number;if(!Number.isFinite(e))throw new dt("not finite")}catch(e){throw new dt(`the integrand has no value at ${n} = ${t.toPrecision(6)}, between the limits, so F(b) - F(a) would be wrong`)}}}const o=e=>cn(Cs(t,n,e)),a=cn(nt("-",[o(s),o(r)])),l=nt("-",[o(s),o(r)]);return{value:a,step:e.step("integrate.evaluate","Between the limits",["evaluate"],t,l,{a:r,b:s,F:t,v:n})}}const ei={"=":1,"≠":1,"<":1,">":1,"≤":1,"≥":1,"+":2,"-":2,"±":2,"*":3,"/":3,neg:4,pm:4,"^":5},ti={pi:"π","≤":"≤","≥":"≥"};function ni(e){return ai(e).text}function ri(e,t,n=!1){return e.prec<t||n&&e.prec===t?`(${e.text})`:e.text}const si=e=>"op"===e.type?e.op:null,ii=e=>e.text.startsWith("-"),oi={"()":["(",")"],"[]":["[","]"],"{}":["{","}"],"(]":["(","]"],"[)":["[",")"]};function ai(e){if("num"===e.type)return{text:e.token,prec:e.token.startsWith("-")?4:9};if("sym"===e.type)return{text:ti[e.token]??e.token,prec:9};const t=e.args.map(ai),n=ei[e.op];switch(e.op){case"+":case"-":case"±":{const r="+"===e.op&&["+","-"].includes(si(e.args[1])),s=ii(t[1])?`(${t[1].text})`:r?t[1].text:ri(t[1],n,!0);return{text:`${ri(t[0],n)} ${"±"===e.op?"±":e.op} ${s}`,prec:n}}case"*":{const r=ri(t[0],n),s=ii(t[1])?`(${t[1].text})`:"*"===si(e.args[1])?t[1].text:ri(t[1],n,!0);return{text:"num"===e.args[0].type&&"num"!==e.args[1].type&&!/^[\d(-]/.test(s)||"sym"===e.args[1].type&&"i"===e.args[1].token&&!/[\dA-Za-z]$/.test(r)?`${r}${s}`:`${r}·${s}`,prec:n}}case"/":return{text:`${ri(t[0],n)}/${ri(t[1],n,!0)}`,prec:n};case"^":return{text:`${ri(t[0],n+1)}^${ri(t[1],n)}`,prec:n};case"neg":return{text:`-${ri(t[0],3)}`,prec:4};case"pm":return{text:`±${ri(t[0],4)}`,prec:4};case"!":return{text:`${ri(t[0],9)}!`,prec:6};case"abs":return{text:`|${t[0].text}|`,prec:9};case"root":return{text:`root(${t[0].text}, ${t[1].text})`,prec:9};case"der":return"op"===e.args[1].type&&"="===e.args[1].op?{text:`d/d${t[1].text.split(" = ")[0]} (${t[0].text}) at ${t[1].text}`,prec:1}:{text:`d/d${t[1].text} (${t[0].text})`,prec:6};case"int":return{text:4===t.length?`∫ from ${t[2].text} to ${t[3].text} of ${t[0].text} d${t[1].text}`:`∫ ${t[0].text} d${t[1].text}`,prec:1};case"|":return{text:`${t[0].text} or ${t[1].text}`,prec:0};case"_":return{text:`${ri(t[0],9)}_${t[1].prec>=9&&!/\s/.test(t[1].text)?t[1].text:`(${t[1].text})`}`,prec:9};case"()":case"[]":case"{}":case"(]":case"[)":return{text:`${oi[e.op][0]}${t.map(e=>e.text).join(", ")}${oi[e.op][1]}`,prec:9};case"&":return{text:`${t[0].text} and ${t[1].text}`,prec:0};default:return void 0!==n?{text:`${ri(t[0],n)} ${e.op} ${ri(t[1],n,!0)}`,prec:n}:{text:`${e.op.replace(/^\\:?/,"")}(${t.map(e=>e.text).join(", ")})`,prec:9}}}const li=['name: Differentiation\n\n# `u v der` means d(u)/dv (MathZetta\'s postfix: mathzetta/docs/postfix.md). Every rule here rewrites one derivative into smaller\n# derivatives, so differentiating always terminates: the expressions sitting\n# under a `D` get strictly smaller at every step.\n#\n# The variable is a slot, not a fixed letter, so these rules work for d/dx,\n# d/dt or anything else. That is what freeOf and dependsOn are for: they ask\n# whether one operand mentions whatever the variable slot bound to.\n#\n# Where two rules share a structure key, requirements keep them apart and\n# priority picks the one that reads better. The constant-multiple rule outranks\n# the product rule for exactly that reason.\n\nrules:\n # ---- the two base cases ----------------------------------------------\n - id: d-constant\n name: Derivative of a constant\n mode: differentiate\n pattern: c v der\n require:\n - [freeOf, c, v]\n output: "0"\n priority: 10\n explain: "{c} does not change when {v} changes, so its rate of change is 0."\n tags: [base]\n\n - id: d-variable\n name: Derivative of the variable\n mode: differentiate\n pattern: u v der\n require:\n - [sameAs, u, v]\n output: "1"\n priority: 10\n explain: "{v} changes exactly as fast as itself, so the rate is 1."\n tags: [base]\n\n # ---- splitting a derivative into smaller ones ------------------------\n - id: d-sum\n name: Sum rule\n mode: differentiate\n pattern: u w + v der\n output: u v der w v der +\n explain: "Differentiate {u} and {w} separately, then add the two results."\n tags: [split]\n\n - id: d-difference\n name: Difference rule\n mode: differentiate\n pattern: u w - v der\n output: u v der w v der -\n explain: "Differentiate {u} and {w} separately, then subtract the second from the first."\n tags: [split]\n\n - id: d-negate\n name: Derivative of a negative\n mode: differentiate\n pattern: u neg v der\n output: u v der neg\n explain: "The minus sign just carries through to the derivative of {u}."\n tags: [split]\n\n - id: d-constant-multiple\n name: Constant multiple rule\n mode: differentiate\n pattern: c u * v der\n commutative: true\n require:\n - [freeOf, c, v]\n - [dependsOn, u, v]\n output: c u v der *\n priority: 5\n explain: "{c} is only a scale factor, so it comes along unchanged while {u} is differentiated."\n tags: [split]\n\n - id: d-constant-divisor\n name: Dividing by a constant\n mode: differentiate\n pattern: u c / v der\n require:\n - [freeOf, c, v]\n output: u v der c /\n priority: 5\n explain: "Dividing by {c} is only a scale factor, so differentiate {u} and keep the division."\n tags: [split]\n\n - id: d-product\n name: Product rule\n mode: differentiate\n pattern: u w * v der\n require:\n - [dependsOn, u, v]\n - [dependsOn, w, v]\n output: u v der w * u w v der * +\n explain: "Differentiate {u} and keep {w}, then keep {u} and differentiate {w}, and add the two."\n tags: [split]\n\n - id: d-quotient\n name: Quotient rule\n mode: differentiate\n pattern: u w / v der\n output: u v der w * u w v der * - w 2 ^ /\n explain: "Bottom times the derivative of the top, minus top times the derivative of the bottom, all over {w} squared."\n tags: [split]\n\n # ---- powers -----------------------------------------------------------\n - id: d-power-of-variable\n name: Power rule\n mode: differentiate\n pattern: u n ^ v der\n require:\n - [sameAs, u, v]\n - [freeOf, n, v]\n output: n u n 1 - ^ *\n fold: true\n priority: 6\n explain: "Bring the {n} down in front and drop the power by one."\n tags: [power]\n\n - id: d-power-chain\n name: Power rule with the chain rule\n mode: differentiate\n pattern: u n ^ v der\n require:\n - [freeOf, n, v]\n - [dependsOn, u, v]\n output: n u n 1 - ^ * u v der *\n fold: true\n explain: "Bring the {n} down and drop the power by one, then multiply by the derivative of {u}."\n tags: [power, chain]\n\n - id: d-exponential-base\n name: Derivative of a constant to a power\n mode: differentiate\n pattern: a u ^ v der\n require:\n - [freeOf, a, v]\n - [dependsOn, u, v]\n output: a u ^ a ln * u v der *\n explain: "A constant base gives itself back, multiplied by the natural log of {a} and the derivative of {u}."\n tags: [power, chain]\n\n # ---- the standard functions, each with its chain-rule factor ---------\n # e^u is `=e u ^`: the base is the literal symbol e. Outranks the general\n # a^u rule (which would give e^u · ln e · u\').\n - id: d-exp\n name: Derivative of e to a power\n mode: differentiate\n pattern: =e u ^ v der\n require:\n - [dependsOn, u, v]\n output: =e u ^ u v der *\n priority: 7\n explain: "e to a power is its own derivative, times the derivative of {u}."\n tags: [chain]\n\n - id: d-ln\n name: Derivative of a natural log\n mode: differentiate\n pattern: u ln v der\n output: u v der u /\n explain: "The derivative of {u} over {u} itself."\n tags: [chain]\n\n - id: d-sqrt\n name: Derivative of a square root\n mode: differentiate\n pattern: u sqrt v der\n output: u v der 2 u sqrt * /\n explain: "The derivative of {u}, over twice the square root of {u}."\n tags: [chain]\n\n - id: d-sin\n name: Derivative of sine\n mode: differentiate\n pattern: u sin v der\n output: u cos u v der *\n explain: "Sine differentiates to cosine, times the derivative of {u}."\n tags: [chain, trig]\n\n - id: d-cos\n name: Derivative of cosine\n mode: differentiate\n pattern: u cos v der\n output: u sin u v der * neg\n explain: "Cosine differentiates to minus sine, times the derivative of {u}."\n tags: [chain, trig]\n\n - id: d-tan\n name: Derivative of tangent\n mode: differentiate\n pattern: u tan v der\n output: u v der u cos 2 ^ /\n explain: "The derivative of {u}, over cosine squared of {u}."\n tags: [chain, trig]\n\n # ---- the rest of the standard functions -----------------------------\n - id: d-csc\n name: Derivative of cosecant\n mode: differentiate\n pattern: u csc v der\n output: u csc u cot * u v der * neg\n explain: "Cosecant differentiates to minus cosecant times cotangent, times the derivative of {u}."\n tags: [chain, trig]\n\n - id: d-sec\n name: Derivative of secant\n mode: differentiate\n pattern: u sec v der\n output: u sec u tan * u v der *\n explain: "Secant differentiates to secant times tangent, times the derivative of {u}."\n tags: [chain, trig]\n\n - id: d-cot\n name: Derivative of cotangent\n mode: differentiate\n pattern: u cot v der\n output: u v der u sin 2 ^ / neg\n explain: "Minus the derivative of {u}, over sine squared of {u}."\n tags: [chain, trig]\n\n - id: d-arcsin\n name: Derivative of arcsine\n mode: differentiate\n pattern: u arcsin v der\n output: u v der 1 u 2 ^ - sqrt /\n explain: "The derivative of {u}, over the square root of 1 minus {u} squared."\n tags: [chain, trig]\n\n - id: d-arccos\n name: Derivative of arccosine\n mode: differentiate\n pattern: u arccos v der\n output: u v der 1 u 2 ^ - sqrt / neg\n explain: "Minus the derivative of {u}, over the square root of 1 minus {u} squared."\n tags: [chain, trig]\n\n - id: d-arctan\n name: Derivative of arctangent\n mode: differentiate\n pattern: u arctan v der\n output: u v der 1 u 2 ^ + /\n explain: "The derivative of {u}, over 1 plus {u} squared."\n tags: [chain, trig]\n\n - id: d-sinh\n name: Derivative of hyperbolic sine\n mode: differentiate\n pattern: u sinh v der\n output: u cosh u v der *\n explain: "Hyperbolic sine differentiates to hyperbolic cosine, times the derivative of {u}."\n tags: [chain, hyperbolic]\n\n - id: d-cosh\n name: Derivative of hyperbolic cosine\n mode: differentiate\n pattern: u cosh v der\n output: u sinh u v der *\n explain: "Hyperbolic cosine differentiates to hyperbolic sine — no minus sign, unlike cosine — times the derivative of {u}."\n tags: [chain, hyperbolic]\n\n - id: d-tanh\n name: Derivative of hyperbolic tangent\n mode: differentiate\n pattern: u tanh v der\n output: u v der u cosh 2 ^ /\n explain: "The derivative of {u}, over hyperbolic cosine squared of {u}."\n tags: [chain, hyperbolic]\n\n - id: d-arcsinh\n name: Derivative of inverse hyperbolic sine\n mode: differentiate\n pattern: u arcsinh v der\n output: u v der u 2 ^ 1 + sqrt /\n explain: "The derivative of {u}, over the square root of {u} squared plus 1."\n tags: [chain, hyperbolic]\n\n - id: d-arccosh\n name: Derivative of inverse hyperbolic cosine\n mode: differentiate\n pattern: u arccosh v der\n output: u v der u 2 ^ 1 - sqrt /\n explain: "The derivative of {u}, over the square root of {u} squared minus 1."\n tags: [chain, hyperbolic]\n\n - id: d-arctanh\n name: Derivative of inverse hyperbolic tangent\n mode: differentiate\n pattern: u arctanh v der\n output: u v der 1 u 2 ^ - /\n explain: "The derivative of {u}, over 1 minus {u} squared."\n tags: [chain, hyperbolic]\n\n # log base a: `a u log` in MathZetta\'s postfix\n - id: d-log\n name: Derivative of a logarithm\n mode: differentiate\n pattern: a u log v der\n require:\n - [freeOf, a, v]\n output: u v der u a ln * /\n explain: "The derivative of {u}, over {u} times the natural log of {a}."\n tags: [chain]\n\n - id: d-abs\n name: Derivative of an absolute value\n mode: differentiate\n pattern: u abs v der\n output: u u abs / u v der *\n explain: "The absolute value keeps the sign of {u}: {u} over its absolute value, times the derivative of {u}."\n tags: [chain]\n\n # n-th root: `n u root`\n - id: d-root\n name: Derivative of a root\n mode: differentiate\n pattern: n u root v der\n require:\n - [freeOf, n, v]\n output: u v der n n u root n 1 - ^ * /\n fold: true\n explain: "The derivative of {u}, over {n} times the {n}th root of {u} to the power {n} minus 1."\n tags: [chain]\n','name: More derivatives\n\n# Derivative rules the CAS adds to rules/calculus.yaml (which calcvidnew also uses).\n\nrules:\n - id: d-general-power\n name: A power with the variable in both places\n mode: differentiate\n pattern: u w ^ v der\n require:\n - [dependsOn, u, v]\n - [dependsOn, w, v]\n output: u w ^ w v der u ln * w u v der * u / + *\n explain: "Write {u}^{w} as e^({w} ln {u}) and use the chain rule: the derivative is {u}^{w} times the derivative of {w} ln {u}."\n tags: [chain]\n','name: Integrals\n\n# mode: integrate. `f v 2 int` is ∫ f dv (MathZetta\'s postfix; the 2 counts f and v).\n# Each rule turns one integral into smaller ones, or into an answer. The CAS also\n# tries, when no rule fits: multiplying out, a linear substitution (∫ f(ax + b) dx\n# from the rule for ∫ f(u) du), and integration by parts for polynomial × e^, sin,\n# cos, ln, arctan. Definite integrals are the antiderivative between the limits.\n#\n# Patterns see the normal form: 1/x is "1 x /", x^-2 is "1 x 2 ^ /", √x is "x sqrt",\n# 1/√(1 - x²) is "1 x 2 ^ neg 1 + sqrt /".\n\nrules:\n # ---- splitting -----------------------------------------------------------\n - id: i-sum\n name: Sum rule\n mode: integrate\n pattern: u w + v 2 int\n output: u v 2 int w v 2 int +\n explain: "Integrate {u} and {w} separately, and add."\n tags: [split]\n\n - id: i-difference\n name: Difference rule\n mode: integrate\n pattern: u w - v 2 int\n output: u v 2 int w v 2 int -\n explain: "Integrate {u} and {w} separately, and subtract."\n tags: [split]\n\n - id: i-negate\n name: A minus sign\n mode: integrate\n pattern: u neg v 2 int\n output: u v 2 int neg\n explain: "The minus sign comes out of the integral."\n tags: [split]\n\n - id: i-constant-multiple\n name: Constant multiple\n mode: integrate\n pattern: c u * v 2 int\n commutative: true\n require:\n - [freeOf, c, v]\n - [dependsOn, u, v]\n output: c u v 2 int *\n priority: 5\n explain: "{c} doesn\'t change with {v}, so it comes out of the integral."\n tags: [split]\n\n - id: i-constant-divisor\n name: Dividing by a constant\n mode: integrate\n pattern: u c / v 2 int\n require:\n - [freeOf, c, v]\n - [dependsOn, u, v]\n output: u v 2 int c /\n priority: 5\n explain: "Dividing by {c} comes out of the integral."\n tags: [split]\n\n - id: i-constant-over\n name: A constant over something\n mode: integrate\n pattern: c u / v 2 int\n require:\n - [freeOf, c, v]\n - [dependsOn, u, v]\n when:\n c: [notOne]\n output: c 1 u / v 2 int *\n priority: 4\n explain: "{c} comes out of the integral, leaving ∫ 1/{u}."\n tags: [split]\n\n # ---- the table -----------------------------------------------------------\n - id: i-constant\n name: Integral of a constant\n mode: integrate\n pattern: c v 2 int\n require:\n - [freeOf, c, v]\n output: c v *\n priority: 10\n explain: "A constant {c} integrates to {c}·{v}."\n tags: [base]\n\n - id: i-variable\n name: Integral of the variable\n mode: integrate\n pattern: u v 2 int\n require:\n - [sameAs, u, v]\n output: v 2 ^ 2 /\n priority: 10\n explain: "∫ {v} d{v} = {v}²/2."\n tags: [base]\n\n - id: i-power\n name: Power rule\n mode: integrate\n pattern: u n ^ v 2 int\n require:\n - [sameAs, u, v]\n - [freeOf, n, v]\n when:\n n: [notMinusOne]\n output: v n 1 + ^ n 1 + /\n explain: "Add 1 to the power and divide by the new power: {result}."\n tags: [power]\n\n - id: i-reciprocal\n name: Integral of 1/x\n mode: integrate\n pattern: 1 u / v 2 int\n require:\n - [sameAs, u, v]\n output: v abs ln\n explain: "∫ 1/{v} d{v} = ln|{v}| (the power rule can\'t divide by 0 here)."\n tags: [log]\n\n - id: i-reciprocal-power\n name: Power rule (a power below)\n mode: integrate\n pattern: 1 u n ^ / v 2 int\n require:\n - [sameAs, u, v]\n - [freeOf, n, v]\n when:\n n: [notOne]\n output: v 1 n - ^ 1 n - /\n explain: "1/{v}^{n} is {v}^(-{n}): add 1 to the power and divide by it."\n tags: [power]\n\n - id: i-sqrt\n name: Integral of a square root\n mode: integrate\n pattern: u sqrt v 2 int\n require:\n - [sameAs, u, v]\n output: 2 v 3 2 / ^ * 3 /\n explain: "√{v} is {v}^(1/2): add 1 to the power and divide by 3/2."\n tags: [power]\n\n - id: i-reciprocal-sqrt\n name: Integral of 1/√x\n mode: integrate\n pattern: 1 u sqrt / v 2 int\n require:\n - [sameAs, u, v]\n output: 2 v sqrt *\n explain: "1/√{v} is {v}^(-1/2): add 1 to the power and divide by 1/2."\n tags: [power]\n\n - id: i-root\n name: Integral of a root\n mode: integrate\n pattern: n u root v 2 int\n require:\n - [sameAs, u, v]\n - [freeOf, n, v]\n output: v 1 n / 1 + ^ 1 n / 1 + /\n explain: "The {n}th root of {v} is {v}^(1/{n}): add 1 to the power and divide by it."\n tags: [power]\n\n - id: i-exp\n name: Integral of e^x\n mode: integrate\n pattern: =e u ^ v 2 int\n require:\n - [sameAs, u, v]\n output: =e v ^\n explain: "e^{v} is its own integral."\n tags: [exp]\n\n - id: i-exponential\n name: Integral of a^x\n mode: integrate\n pattern: a u ^ v 2 int\n require:\n - [sameAs, u, v]\n - [freeOf, a, v]\n output: a v ^ a ln /\n explain: "∫ {a}^{v} d{v} = {a}^{v} / ln {a}."\n tags: [exp]\n\n - id: i-ln\n name: Integral of ln x\n mode: integrate\n pattern: u ln v 2 int\n require:\n - [sameAs, u, v]\n output: v v ln * v -\n explain: "By parts: ∫ ln {v} d{v} = {v} ln {v} - {v}."\n tags: [log]\n\n - { id: i-sin, name: Integral of sin, mode: integrate, pattern: u sin v 2 int, require: [[sameAs, u, v]], output: v cos neg, tags: [trig], explain: "The derivative of -cos {v} is sin {v}." }\n - { id: i-cos, name: Integral of cos, mode: integrate, pattern: u cos v 2 int, require: [[sameAs, u, v]], output: v sin, tags: [trig], explain: "The derivative of sin {v} is cos {v}." }\n - { id: i-tan, name: Integral of tan, mode: integrate, pattern: u tan v 2 int, require: [[sameAs, u, v]], output: v cos abs ln neg, tags: [trig], explain: "tan = sin/cos, and -ln|cos {v}| differentiates to it." }\n - { id: i-sec-squared, name: Integral of sec², mode: integrate, pattern: 1 u cos 2 ^ / v 2 int, require: [[sameAs, u, v]], output: v tan, tags: [trig], explain: "The derivative of tan {v} is 1/cos²{v}." }\n - { id: i-sec-squared-written, name: Integral of sec², mode: integrate, pattern: u sec 2 ^ v 2 int, require: [[sameAs, u, v]], output: v tan, tags: [trig], explain: "The derivative of tan {v} is sec²{v}." }\n - { id: i-csc-squared, name: Integral of csc², mode: integrate, pattern: 1 u sin 2 ^ / v 2 int, require: [[sameAs, u, v]], output: v cot neg, tags: [trig], explain: "The derivative of -cot {v} is 1/sin²{v}." }\n - { id: i-sin-squared, name: Integral of sin², mode: integrate, pattern: u sin 2 ^ v 2 int, require: [[sameAs, u, v]], output: v 2 / 2 v * sin 4 / -, tags: [trig], explain: "sin²{v} = (1 - cos 2{v})/2, which integrates term by term." }\n - { id: i-cos-squared, name: Integral of cos², mode: integrate, pattern: u cos 2 ^ v 2 int, require: [[sameAs, u, v]], output: v 2 / 2 v * sin 4 / +, tags: [trig], explain: "cos²{v} = (1 + cos 2{v})/2, which integrates term by term." }\n - { id: i-sinh, name: Integral of sinh, mode: integrate, pattern: u sinh v 2 int, require: [[sameAs, u, v]], output: v cosh, tags: [trig], explain: "The derivative of cosh {v} is sinh {v}." }\n - { id: i-cosh, name: Integral of cosh, mode: integrate, pattern: u cosh v 2 int, require: [[sameAs, u, v]], output: v sinh, tags: [trig], explain: "The derivative of sinh {v} is cosh {v}." }\n - { id: i-arctan, name: Integral of 1/(1 + x²), mode: integrate, pattern: 1 u 2 ^ 1 + / v 2 int, require: [[sameAs, u, v]], output: v arctan, tags: [trig], explain: "The derivative of arctan {v} is 1/(1 + {v}²)." }\n - { id: i-arcsin, name: Integral of 1/√(1 - x²), mode: integrate, pattern: 1 u 2 ^ neg 1 + sqrt / v 2 int, require: [[sameAs, u, v]], output: v arcsin, tags: [trig], explain: "The derivative of arcsin {v} is 1/√(1 - {v}²)." }\n','name: Values and identities\n\n# The CAS\'s simplify rules (mode: simplify). They see expressions in normal form\n# (src/cas/form.js), as drawn: x/2, 2x - 3, -x, √x is "x sqrt",\n# ∛x is "3 x root", π/6 is "=pi 6 /", 2π/3 is "2 =pi * 3 /", e^x is "=e x ^".\n#\n# - a word is a slot (u, v, n …); a fixed symbol is written =pi, =e\n# - a number is itself; "1 2 /" is ½\n# - arithmetic (2 + 3, x + x, √8 = 2√2) is done for you before and after every rule\n# - a rule for a sum or product of two parts also fires on any two parts of a longer one\n# - tags pick what a step list shows (steps: \'brief\' hides value, identity, tidy …)\n#\n# To change one: copy it into a file of your own with the same id and edit it;\n# to turn one off: give its id with enabled: false. createCAS({ rules: [yours] }).\n\nrules:\n # ---- logs and exponentials -------------------------------------------\n - id: ln-one\n name: Log of 1\n pattern: 1 ln\n output: "0"\n explain: "e^0 = 1, so ln 1 = 0."\n tags: [value]\n\n - id: ln-e\n name: Log of e\n pattern: =e ln\n output: "1"\n explain: "e^1 = e, so ln e = 1."\n tags: [value]\n\n - id: ln-exp\n name: Log undoes e to a power\n pattern: =e u ^ ln\n output: u\n explain: "ln and e^ undo each other: ln(e^{u}) = {u}."\n tags: [inverse]\n\n - id: exp-ln\n name: e to a power undoes the log\n pattern: =e u ln ^\n output: u\n explain: "e^ and ln undo each other: e^(ln {u}) = {u} (for {u} > 0)."\n tags: [inverse]\n\n - id: exp-multiple-ln\n name: A multiple of a log in a power\n pattern: =e n u ln * ^\n when:\n n: [isRational]\n output: u n ^\n explain: "e^({n} ln {u}) = (e^(ln {u}))^{n} = {result}."\n tags: [inverse]\n\n - id: log-same-base\n name: Log of its own base\n pattern: b b log\n output: "1"\n explain: "{b}^1 = {b}, so the log of {b} to base {b} is 1."\n tags: [value]\n\n - id: log-of-power\n name: Log undoes a power of its base\n pattern: b b u ^ log\n output: u\n explain: "log base {b} and {b}^ undo each other."\n tags: [inverse]\n\n - id: power-of-log\n name: A power undoes the log to its base\n pattern: b b u log ^\n output: u\n explain: "{b}^(log base {b} of {u}) = {u}."\n tags: [inverse]\n\n # ---- roots and absolute value --------------------------------------------\n - id: sqrt-of-square\n name: Square root of a square\n pattern: u 2 ^ sqrt\n output: u abs\n explain: "√({u}²) is the size of {u}, whatever its sign: |{u}|."\n tags: [identity]\n\n - id: abs-squared\n name: Absolute value squared\n pattern: u abs 2 ^\n output: u 2 ^\n explain: "Squaring removes the sign anyway: |{u}|² = {u}²."\n tags: [identity]\n\n - id: abs-of-abs\n name: Absolute value twice\n pattern: u abs abs\n output: u abs\n explain: "|{u}| is never negative, so its absolute value is itself."\n tags: [identity]\n\n - id: abs-positive\n name: Absolute value of a positive number\n pattern: u abs\n when:\n u: [isPositiveConstant]\n output: u\n explain: "{u} is positive, so |{u}| = {u}."\n tags: [value]\n\n - id: abs-negative\n name: Absolute value of a negative number\n pattern: u abs\n when:\n u: [isNegativeConstant]\n output: u neg\n explain: "{u} is negative, so |{u}| = -({u})."\n tags: [value]\n\n - id: abs-of-exp\n name: e to a power is positive\n pattern: =e u ^ abs\n output: =e u ^\n explain: "e to any power is positive, so the absolute value changes nothing."\n tags: [identity]\n\n # ---- trigonometry: signs and turns ---------------------------------------\n - id: sin-odd\n name: Sine of a negative angle\n pattern: u sin\n when:\n u: [hasMinusSign]\n output: u neg sin neg\n explain: "sin(-θ) = -sin θ."\n tags: [symmetry]\n\n - id: cos-even\n name: Cosine of a negative angle\n pattern: u cos\n when:\n u: [hasMinusSign]\n output: u neg cos\n explain: "cos(-θ) = cos θ."\n tags: [symmetry]\n\n - id: tan-odd\n name: Tangent of a negative angle\n pattern: u tan\n when:\n u: [hasMinusSign]\n output: u neg tan neg\n explain: "tan(-θ) = -tan θ."\n tags: [symmetry]\n\n - id: sin-full-turn\n name: A full turn\n pattern: u sin\n when:\n u: [[piMultipleAtLeast, 2]]\n output: u 2 =pi * - sin\n explain: "Turning a full 2π brings you back: sin({u}) = sin({u} - 2π)."\n tags: [symmetry]\n\n - id: cos-full-turn\n name: A full turn\n pattern: u cos\n when:\n u: [[piMultipleAtLeast, 2]]\n output: u 2 =pi * - cos\n explain: "Turning a full 2π brings you back: cos({u}) = cos({u} - 2π)."\n tags: [symmetry]\n\n - id: tan-half-turn\n name: Tangent repeats every π\n pattern: u tan\n when:\n u: [[piMultipleAtLeast, 1]]\n output: u =pi - tan\n explain: "tan repeats every π: tan({u}) = tan({u} - π)."\n tags: [symmetry]\n\n - id: sin-half-turn\n name: A half turn\n pattern: u sin\n when:\n u: [[piMultipleAbove, 1], [piMultipleBelow, 2]]\n output: u =pi - sin neg\n explain: "Half a turn flips the sign: sin({u}) = -sin({u} - π)."\n tags: [symmetry]\n\n - id: cos-half-turn\n name: A half turn\n pattern: u cos\n when:\n u: [[piMultipleAbove, 1], [piMultipleBelow, 2]]\n output: u =pi - cos neg\n explain: "Half a turn flips the sign: cos({u}) = -cos({u} - π)."\n tags: [symmetry]\n\n - id: sin-second-quarter\n name: The second quarter turn\n pattern: u sin\n when:\n u: [[piMultipleAbove, 1/2], [piMultipleAtMost, 1]]\n output: =pi u - sin\n explain: "sin({u}) = sin(π - {u})."\n tags: [symmetry]\n\n - id: cos-second-quarter\n name: The second quarter turn\n pattern: u cos\n when:\n u: [[piMultipleAbove, 1/2], [piMultipleAtMost, 1]]\n output: =pi u - cos neg\n explain: "cos({u}) = -cos(π - {u})."\n tags: [symmetry]\n\n - id: tan-second-quarter\n name: The second quarter turn\n pattern: u tan\n when:\n u: [[piMultipleAbove, 1/2], [piMultipleBelow, 1]]\n output: =pi u - tan neg\n explain: "tan({u}) = -tan(π - {u})."\n tags: [symmetry]\n\n # ---- trigonometry: the standard angles -------------------------------------\n - { id: sin-0, name: Sine of 0, pattern: 0 sin, output: "0", tags: [value], explain: "sin 0 = 0." }\n - { id: sin-pi-6, name: Sine of π/6, pattern: =pi 6 / sin, output: 1 2 /, tags: [value], explain: "sin(π/6) = 1/2." }\n - { id: sin-pi-4, name: Sine of π/4, pattern: =pi 4 / sin, output: 2 sqrt 2 /, tags: [value], explain: "sin(π/4) = √2/2." }\n - { id: sin-pi-3, name: Sine of π/3, pattern: =pi 3 / sin, output: 3 sqrt 2 /, tags: [value], explain: "sin(π/3) = √3/2." }\n - { id: sin-pi-2, name: Sine of π/2, pattern: =pi 2 / sin, output: "1", tags: [value], explain: "sin(π/2) = 1." }\n - { id: sin-pi, name: Sine of π, pattern: =pi sin, output: "0", tags: [value], explain: "sin π = 0." }\n - { id: cos-0, name: Cosine of 0, pattern: 0 cos, output: "1", tags: [value], explain: "cos 0 = 1." }\n - { id: cos-pi-6, name: Cosine of π/6, pattern: =pi 6 / cos, output: 3 sqrt 2 /, tags: [value], explain: "cos(π/6) = √3/2." }\n - { id: cos-pi-4, name: Cosine of π/4, pattern: =pi 4 / cos, output: 2 sqrt 2 /, tags: [value], explain: "cos(π/4) = √2/2." }\n - { id: cos-pi-3, name: Cosine of π/3, pattern: =pi 3 / cos, output: 1 2 /, tags: [value], explain: "cos(π/3) = 1/2." }\n - { id: cos-pi-2, name: Cosine of π/2, pattern: =pi 2 / cos, output: "0", tags: [value], explain: "cos(π/2) = 0." }\n - { id: cos-pi, name: Cosine of π, pattern: =pi cos, output: "-1", tags: [value], explain: "cos π = -1." }\n - { id: tan-0, name: Tangent of 0, pattern: 0 tan, output: "0", tags: [value], explain: "tan 0 = 0." }\n - { id: tan-pi-6, name: Tangent of π/6, pattern: =pi 6 / tan, output: 3 sqrt 3 /, tags: [value], explain: "tan(π/6) = √3/3." }\n - { id: tan-pi-4, name: Tangent of π/4, pattern: =pi 4 / tan, output: "1", tags: [value], explain: "tan(π/4) = 1." }\n - { id: tan-pi-3, name: Tangent of π/3, pattern: =pi 3 / tan, output: 3 sqrt, tags: [value], explain: "tan(π/3) = √3." }\n - { id: arcsin-0, name: Arcsine of 0, pattern: 0 arcsin, output: "0", tags: [value], explain: "sin 0 = 0, so arcsin 0 = 0." }\n - { id: arcsin-half, name: Arcsine of 1/2, pattern: 1 2 / arcsin, output: =pi 6 /, tags: [value], explain: "sin(π/6) = 1/2, so arcsin(1/2) = π/6." }\n - { id: arcsin-1, name: Arcsine of 1, pattern: 1 arcsin, output: =pi 2 /, tags: [value], explain: "sin(π/2) = 1, so arcsin 1 = π/2." }\n - { id: arccos-0, name: Arccosine of 0, pattern: 0 arccos, output: =pi 2 /, tags: [value], explain: "cos(π/2) = 0, so arccos 0 = π/2." }\n - { id: arccos-half, name: Arccosine of 1/2, pattern: 1 2 / arccos, output: =pi 3 /, tags: [value], explain: "cos(π/3) = 1/2, so arccos(1/2) = π/3." }\n - { id: arccos-1, name: Arccosine of 1, pattern: 1 arccos, output: "0", tags: [value], explain: "cos 0 = 1, so arccos 1 = 0." }\n - { id: arccos-minus-1, name: Arccosine of -1, pattern: -1 arccos, output: =pi, tags: [value], explain: "cos π = -1, so arccos(-1) = π." }\n - { id: arctan-0, name: Arctangent of 0, pattern: 0 arctan, output: "0", tags: [value], explain: "tan 0 = 0, so arctan 0 = 0." }\n - { id: arctan-1, name: Arctangent of 1, pattern: 1 arctan, output: =pi 4 /, tags: [value], explain: "tan(π/4) = 1, so arctan 1 = π/4." }\n - { id: sinh-0, name: sinh of 0, pattern: 0 sinh, output: "0", tags: [value], explain: "sinh 0 = 0." }\n - { id: cosh-0, name: cosh of 0, pattern: 0 cosh, output: "1", tags: [value], explain: "cosh 0 = 1." }\n - { id: tanh-0, name: tanh of 0, pattern: 0 tanh, output: "0", tags: [value], explain: "tanh 0 = 0." }\n\n - { id: arctan-sqrt3, name: Arctangent of √3, pattern: 3 sqrt arctan, output: =pi 3 /, tags: [value], explain: "tan(π/3) = √3, so arctan √3 = π/3." }\n - { id: arctan-sqrt3-over-3, name: Arctangent of √3/3, pattern: 3 sqrt 3 / arctan, output: =pi 6 /, tags: [value], explain: "tan(π/6) = √3/3, so arctan(√3/3) = π/6." }\n\n # atan2(y, x): the angle of the point (x, y), in (-π, π]\n - id: atan2-right\n name: The angle of a point to the right\n pattern: y x atan2\n when:\n x: [isPositiveConstant]\n output: y x / arctan\n explain: "For x > 0, atan2(y, x) = arctan(y/x)."\n tags: [value]\n - id: atan2-left-up\n name: The angle of a point to the left\n pattern: y x atan2\n when:\n x: [isNegativeConstant]\n y: [isPositiveConstant]\n output: y x / arctan =pi +\n explain: "For x < 0 and y > 0, atan2(y, x) = arctan(y/x) + π."\n tags: [value]\n - id: atan2-left-down\n name: The angle of a point to the left\n pattern: y x atan2\n when:\n x: [isNegativeConstant]\n y: [isNegativeConstant]\n output: y x / arctan =pi -\n explain: "For x < 0 and y < 0, atan2(y, x) = arctan(y/x) - π."\n tags: [value]\n - { id: atan2-negative-axis, name: The angle of a point on the negative axis, pattern: 0 x atan2, when: { x: [isNegativeConstant] }, output: =pi, tags: [value], explain: "A point on the negative x-axis is at angle π." }\n - { id: atan2-up, name: Straight up, pattern: y 0 atan2, when: { y: [isPositiveConstant] }, output: =pi 2 /, tags: [value], explain: "A point straight up is at angle π/2." }\n - { id: atan2-down, name: Straight down, pattern: y 0 atan2, when: { y: [isNegativeConstant] }, output: =pi 2 / neg, tags: [value], explain: "A point straight down is at angle -π/2." }\n\n # the odd inverses take the sign out; arccos(-u) = π - arccos u\n - id: arcsin-odd\n name: Arcsine of a negative\n pattern: u arcsin\n when:\n u: [hasMinusSign]\n output: u neg arcsin neg\n explain: "arcsin(-x) = -arcsin x."\n tags: [symmetry]\n\n - id: arctan-odd\n name: Arctangent of a negative\n pattern: u arctan\n when:\n u: [hasMinusSign]\n output: u neg arctan neg\n explain: "arctan(-x) = -arctan x."\n tags: [symmetry]\n\n - id: arccos-negative\n name: Arccosine of a negative\n pattern: u arccos\n when:\n u: [hasMinusSign]\n output: =pi u neg arccos -\n explain: "arccos(-x) = π - arccos x."\n tags: [symmetry]\n\n # ---- trigonometry: identities --------------------------------------------\n - id: pythagorean\n name: sin² + cos² = 1\n pattern: u sin 2 ^ u cos 2 ^ +\n commutative: true\n output: "1"\n explain: "sin²{u} + cos²{u} = 1 for every angle."\n tags: [identity]\n\n - id: pythagorean-multiple\n name: sin² + cos² = 1\n pattern: a u sin 2 ^ * a u cos 2 ^ * +\n commutative: true\n output: a\n explain: "{a}·sin²{u} + {a}·cos²{u} = {a}(sin²{u} + cos²{u}) = {a}."\n tags: [identity]\n\n - id: one-minus-sin-squared\n name: 1 - sin² = cos²\n pattern: u sin 2 ^ neg 1 +\n output: u cos 2 ^\n explain: "1 - sin²{u} = cos²{u}."\n tags: [identity]\n\n - id: one-minus-cos-squared\n name: 1 - cos² = sin²\n pattern: u cos 2 ^ neg 1 +\n output: u sin 2 ^\n explain: "1 - cos²{u} = sin²{u}."\n tags: [identity]\n\n - id: sin-over-cos\n name: sin/cos is tan\n pattern: u sin u cos /\n output: u tan\n explain: "sin {u} / cos {u} = tan {u}."\n tags: [identity]\n\n - id: cos-over-sin\n name: cos/sin is cot\n pattern: u cos u sin /\n output: u cot\n explain: "cos {u} / sin {u} = cot {u}."\n tags: [identity]\n\n - id: sin-arcsin\n name: sin undoes arcsin\n pattern: u arcsin sin\n output: u\n explain: "sin(arcsin {u}) = {u}."\n tags: [inverse]\n\n - id: cos-arccos\n name: cos undoes arccos\n pattern: u arccos cos\n output: u\n explain: "cos(arccos {u}) = {u}."\n tags: [inverse]\n\n - id: tan-arctan\n name: tan undoes arctan\n pattern: u arctan tan\n output: u\n explain: "tan(arctan {u}) = {u}."\n tags: [inverse]\n\n - id: cosh-squared-minus-sinh-squared\n name: cosh² - sinh² = 1\n pattern: u cosh 2 ^ u sinh 2 ^ -\n output: "1"\n explain: "cosh²{u} - sinh²{u} = 1."\n tags: [identity]\n\n # ---- logs: opt-in rewrites (run with cas.rewrite(x, \'expand-log\') or \'combine-log\') ----\n - id: ln-product\n name: Log of a product\n mode: expand-log\n pattern: a b * ln\n output: a ln b ln +\n explain: "ln({a}·{b}) = ln {a} + ln {b} (for positive {a}, {b})."\n tags: [log]\n\n - id: ln-quotient\n name: Log of a quotient\n mode: expand-log\n pattern: a b / ln\n output: a ln b ln -\n explain: "ln({a}/{b}) = ln {a} - ln {b} (for positive {a}, {b})."\n tags: [log]\n\n - id: ln-power\n name: Log of a power\n mode: expand-log\n pattern: a n ^ ln\n output: n a ln *\n explain: "ln({a}^{n}) = {n}·ln {a} (for positive {a})."\n tags: [log]\n\n - id: ln-root\n name: Log of a square root\n mode: expand-log\n pattern: a sqrt ln\n output: a ln 2 /\n explain: "ln √{a} = ½ ln {a}."\n tags: [log]\n\n - id: ln-sum-combine\n name: Sum of logs\n mode: combine-log\n pattern: a ln b ln +\n commutative: true\n output: a b * ln\n explain: "ln {a} + ln {b} = ln({a}·{b})."\n tags: [log]\n\n - id: ln-difference-combine\n name: Difference of logs\n mode: combine-log\n pattern: a ln b ln -\n output: a b / ln\n explain: "ln {a} - ln {b} = ln({a}/{b})."\n tags: [log]\n\n - id: ln-multiple-combine\n name: A multiple of a log\n mode: combine-log\n pattern: n a ln *\n when:\n n: [isRational]\n output: a n ^ ln\n explain: "{n}·ln {a} = ln({a}^{n})."\n tags: [log]\n','name: Solving by undoing\n\n# mode: isolate. Each rule undoes the outermost function on the side with the\n# unknown: ln u = r → u = e^r. The predicates hasVariable and freeOfVariable mean\n# "mentions / doesn\'t mention the unknown being solved for".\n#\n# The CAS does the rest itself: it moves terms without the unknown to the other\n# side, divides by a coefficient, and when the unknown appears in several places\n# it uses the polynomial methods (factoring, the quadratic formula) or splits a\n# product equal to 0. Every answer is checked in the original equation, so a\n# rule may give extra candidates (squaring both sides does): the wrong ones are\n# dropped, with a step saying so.\n#\n# An output can give several answers: `pm` (±) splits into two, and so does\n# `|` (or): "u r arcsin = u =pi r arcsin - = |".\n\nrules:\n - id: iso-swap\n name: Unknown on the left\n mode: isolate\n pattern: l r =\n when:\n l: [freeOfVariable]\n r: [hasVariable]\n output: r l =\n priority: 20\n explain: "Swap the sides so the unknown is on the left."\n tags: [tidy]\n\n - id: iso-ln\n name: Undo the log\n mode: isolate\n pattern: u ln r =\n when:\n u: [hasVariable]\n output: u =e r ^ =\n explain: "Raise e to each side: e^(ln {u}) = {u}."\n tags: [inverse]\n\n - id: iso-log\n name: Undo the log\n mode: isolate\n pattern: b u log r =\n when:\n u: [hasVariable]\n b: [freeOfVariable]\n output: u b r ^ =\n explain: "Raise {b} to each side: {b}^(log base {b} of {u}) = {u}."\n tags: [inverse]\n\n - id: iso-exp\n name: Undo e to a power\n mode: isolate\n pattern: =e u ^ r =\n when:\n u: [hasVariable]\n output: u r ln =\n explain: "Take ln of each side: ln(e^{u}) = {u}."\n tags: [inverse]\n\n - id: iso-exponential\n name: Undo a power of a number\n mode: isolate\n pattern: b u ^ r =\n when:\n u: [hasVariable]\n b: [freeOfVariable]\n output: u b r log =\n explain: "Take the log to base {b} of each side."\n tags: [inverse]\n\n - id: iso-square\n name: Undo the square\n mode: isolate\n pattern: u 2 ^ r =\n when:\n u: [hasVariable]\n output: u r sqrt pm =\n priority: 1\n explain: "Take the square root of each side; {u} can be positive or negative."\n tags: [inverse]\n\n - id: iso-even-power\n name: Undo an even power\n mode: isolate\n pattern: u n ^ r =\n when:\n u: [hasVariable]\n n: [isEvenWhole]\n output: u r 1 n / ^ pm =\n explain: "Take the root of each side (the {n}th root); {u} can be positive or negative."\n tags: [inverse]\n\n - id: iso-odd-power\n name: Undo an odd power\n mode: isolate\n pattern: u n ^ r =\n when:\n u: [hasVariable]\n n: [isOddWhole]\n output: u r 1 n / ^ =\n explain: "Take the root of each side (the {n}th root)."\n tags: [inverse]\n\n - id: iso-fractional-power\n name: Undo a power\n mode: isolate\n pattern: u n ^ r =\n when:\n u: [hasVariable]\n n: [isRational]\n output: u r 1 n / ^ =\n priority: -1\n explain: "Raise each side to the power 1/{n}."\n tags: [inverse]\n\n - id: iso-sqrt\n name: Undo the square root\n mode: isolate\n pattern: u sqrt r =\n when:\n u: [hasVariable]\n output: u r 2 ^ =\n explain: "Square each side (this can add answers, so each one is checked at the end)."\n tags: [inverse]\n\n - id: iso-root\n name: Undo the root\n mode: isolate\n pattern: n u root r =\n when:\n u: [hasVariable]\n n: [freeOfVariable]\n output: u r n ^ =\n explain: "Raise each side to the power {n}."\n tags: [inverse]\n\n - id: iso-reciprocal\n name: Undo the fraction\n mode: isolate\n pattern: c u / r =\n when:\n u: [hasVariable]\n c: [freeOfVariable]\n output: u c r / =\n explain: "{c}/{u} = {r}, so {u} = {c}/{r}."\n tags: [inverse]\n\n - id: iso-abs\n name: Undo the absolute value\n mode: isolate\n pattern: u abs r =\n when:\n u: [hasVariable]\n output: u r pm =\n explain: "|{u}| = {r} means {u} is {r} or -{r}."\n tags: [inverse]\n\n - id: iso-sin\n name: Undo the sine\n mode: isolate\n pattern: u sin r =\n when:\n u: [hasVariable]\n output: u r arcsin = u =pi r arcsin - = |\n explain: "Two angles in a turn have sine {r}: arcsin {r} and π - arcsin {r} (add any whole number of turns, 2πk, for the rest)."\n tags: [inverse, trig]\n\n - id: iso-cos\n name: Undo the cosine\n mode: isolate\n pattern: u cos r =\n when:\n u: [hasVariable]\n output: u r arccos pm =\n explain: "Two angles in a turn have cosine {r}: ±arccos {r} (add 2πk for the rest)."\n tags: [inverse, trig]\n\n - id: iso-tan\n name: Undo the tangent\n mode: isolate\n pattern: u tan r =\n when:\n u: [hasVariable]\n output: u r arctan =\n explain: "Take arctan of each side (add πk for the rest)."\n tags: [inverse, trig]\n\n - { id: iso-arcsin, name: Undo arcsin, mode: isolate, pattern: u arcsin r =, when: { u: [hasVariable] }, output: u r sin =, tags: [inverse], explain: "Take sin of each side." }\n - { id: iso-arccos, name: Undo arccos, mode: isolate, pattern: u arccos r =, when: { u: [hasVariable] }, output: u r cos =, tags: [inverse], explain: "Take cos of each side." }\n - { id: iso-arctan, name: Undo arctan, mode: isolate, pattern: u arctan r =, when: { u: [hasVariable] }, output: u r tan =, tags: [inverse], explain: "Take tan of each side." }\n - { id: iso-sinh, name: Undo sinh, mode: isolate, pattern: u sinh r =, when: { u: [hasVariable] }, output: u r arcsinh =, tags: [inverse], explain: "Take arcsinh of each side." }\n - { id: iso-tanh, name: Undo tanh, mode: isolate, pattern: u tanh r =, when: { u: [hasVariable] }, output: u r arctanh =, tags: [inverse], explain: "Take arctanh of each side." }\n - { id: iso-cosh, name: Undo cosh, mode: isolate, pattern: u cosh r =, when: { u: [hasVariable] }, output: u r arccosh pm =, tags: [inverse], explain: "Two numbers have cosh {r}: ±arccosh {r}." }\n - { id: iso-arcsinh, name: Undo arcsinh, mode: isolate, pattern: u arcsinh r =, when: { u: [hasVariable] }, output: u r sinh =, tags: [inverse], explain: "Take sinh of each side." }\n - { id: iso-arccosh, name: Undo arccosh, mode: isolate, pattern: u arccosh r =, when: { u: [hasVariable] }, output: u r cosh =, tags: [inverse], explain: "Take cosh of each side." }\n - { id: iso-arctanh, name: Undo arctanh, mode: isolate, pattern: u arctanh r =, when: { u: [hasVariable] }, output: u r tanh =, tags: [inverse], explain: "Take tanh of each side." }\n'],ui=['name: Complex numbers\n\n# Loaded only by createCAS({ complex: true }), where i is the imaginary unit.\n# The arithmetic (i² = -1, √-4 = 2i, (2 + 3i)(1 - i) = 5 + i, 1/(1 + i) = (1 - i)/2)\n# and Re, Im, conj, arg, |z| are the normal form\'s (src/cas/form.js); unknowns\n# count as real, so Re(x + 3i) = x. Write a complex unknown as a + bi.\n\noperators:\n - { symbol: re, arity: 1, label: real part }\n - { symbol: im, arity: 1, label: imaginary part }\n - { symbol: conj, arity: 1, label: complex conjugate }\n - { symbol: arg, arity: 1, label: argument }\n\nrules:\n - id: euler\n name: Euler\'s formula\n pattern: =e u ^\n when:\n u: [hasImaginaryPart, isConstant]\n output: =e u re ^ u im cos =i u im sin * + *\n explain: "e^(a + bi) = e^a (cos b + i sin b)."\n tags: [complex]\n\n - id: ln-negative\n name: Log of a negative number\n pattern: u ln\n when:\n u: [isNegativeConstant]\n output: u neg ln =i =pi * +\n explain: "{u} = |{u}|·e^(iπ), so ln {u} = ln |{u}| + iπ (the principal value)."\n tags: [complex]\n\n - id: ln-complex\n name: Log of a complex number\n pattern: u ln\n when:\n u: [hasImaginaryPart, isConstant]\n output: u abs ln u arg =i * +\n explain: "ln z = ln |z| + i arg z (the principal value)."\n tags: [complex]\n\n - id: i-to-the-i\n name: i to the power i\n pattern: =i =i ^\n output: =e =pi 2 / neg ^\n explain: "i = e^(iπ/2), so i^i = e^(i·iπ/2) = e^(-π/2) (the principal value)."\n tags: [complex]\n'],ci={normal:"Work out the numbers and collect like terms.","simplify.cancel":"Cancel the factors the top and bottom share.","simplify.expand":"Multiplying out gives something shorter.","simplify.factor":"Factoring gives something shorter.",expand:"Multiply out the brackets.",factor:"Write it as a product of factors.","factor.common":"Take out the common factor {common}.","factor.polynomial":"Factor what is left: {roots}.",together:"Write it as one fraction over a common denominator.",cancel:"Cancel the factors the top and bottom share: {canceled}.","solve.move":"Keep the terms with {v} on the left and move the others to the right.","solve.divide":"Divide both sides by {by}.","solve.multiply":"Multiply both sides by {by}.","solve.one-side":"Move everything to one side, so the equation reads … = 0.","solve.factor":"Factor the left side.","solve.zero-product":"A product is 0 exactly when one of its factors is 0.","solve.split":"There are two cases; solve each.","solve.quadratic":"The quadratic formula with a = {a}, b = {b}, c = {c}: {v} = (-b ± √(b² - 4ac)) / 2a, and b² - 4ac = {D}.","solve.no-real":"b² - 4ac = {D} is negative, so there are no real solutions.","solve.quadratic-complex":"The quadratic formula with a = {a}, b = {b}, c = {c}: {v} = (-b ± √(b² - 4ac)) / 2a. b² - 4ac = {D} is negative, so its square root is imaginary: √({D}) = {root}.","solve.roots":"{v}^{n} = {r} has {n} solutions, spaced evenly round a circle: |{r}|^(1/{n})·(cos θ + i sin θ), with θ = (arg {r} + 2πk)/{n} for k = 0 … {last}.","solve.clear-denominator":"Multiply both sides by {den} (an answer that makes it 0 is not allowed).","solve.substitute":"Write {u} for {kernel}: this is a polynomial in {u}.","solve.reject":"{value} is not a solution: {reason}.","solve.always":"This is true for every {v}.","solve.never":"This is never true, so there is no solution.","solve.unsolved":"There is no exact method here for solving for {v}; try { approximate: true }.","solve.numeric":"Found {count} solution(s) numerically.","system.eliminate":"Use one equation to remove {v} from the others.","integrate.expand":"Multiply out, then integrate term by term.","integrate.substitute":"Let {u} = {inside}, so d{u} = {a} d{v}.","integrate.back":"Put {inside} back for {u}.","integrate.parts":"By parts with u = {u} and dv = {dv} d{v}: ∫ u dv = u·v - ∫ v du, where v = {V} and du = {du} d{v}.","integrate.constant":"The number {c} comes out of the integral.","integrate.divide":"The top has at least the degree of the bottom: divide first.","integrate.partial-fractions":"Split the fraction into simple fractions, one for each factor below.","integrate.evaluate":"Evaluate {F} at {b} and at {a}, and subtract.",substitute:"Put in the values."},pi=["normal","rewrite","simplify","expand","factor","cancel","diff","differentiate","integrate","solve","solveSystem","substitute","approximate","equivalent"];class hi{constructor(e,t,n,r,s){this.set=e,this.messages=t,this.format=n,this.read=r,this.complex=s;for(const e of pi){const t=hi.prototype[e];this[e]=(...e)=>St(s,()=>t.apply(this,e))}}node(e){return this.atPoints(this.read_(e))}read_(e){if(e&&"object"==typeof e&&!Array.isArray(e)&&e.type)return e;if(Array.isArray(e))return ot(e);if("string"!=typeof e)throw new dt("expected an expression");if(this.read){const t=this.read(e);return Array.isArray(t)?ot(t):"string"==typeof t?it(t):t}return it(e)}atPoints(e){if(!e||!st(e)||!e.s.includes("= der"))return e;const t=e.args.map(e=>this.atPoints(e)),[n,r]=t;if("der"===e.op&&st(r)&&"="===r.op&&"sym"===r.args[0].type){const e=r.args[0].token;return this.substitute(this.diff(n,e).result,{[e]:r.args[1].s}).result}return nt(e.op,t)}step(e,t,n,r,s,i={}){return function(e,t,n,r,s,i,o,a,l=[]){const u=(i??"").replace(/\{(\w+)\}/g,(e,t)=>{const n=o?.[t];return void 0===n?e:"string"==typeof n?n:a(n)});return{id:e,name:t,tags:n,from:r.s,to:s.s,path:l,before:r.s,after:s.s,explanation:u}}(e,t,n,r,s,this.messages[e]??"",i,this.format)}result(e,t,n,r={}){let s=e;if(n.approximate&&s){s=Pr(s,{digits:"number"==typeof n.approximate?n.approximate:15})}return{result:s,text:s?this.format(s):"",steps:is(t,ss(n.steps)),...r}}variable(e,t){if(t&&!/^\\?[A-Za-z\u0370-\u03FF][A-Za-z0-9_\u0370-\u03FF′]*$/.test(t))throw new dt(`"${t}" is not a variable name; for a derivative at a point write der(f, x = a)`);if(t)return t;const n=[...vn(e)];return 1===n.length?n[0]:n.includes("x")?"x":n[0]??"x"}tidyStep(e,t){return e.s===t.s?[]:[this.step("normal","Work out and collect",["tidy","arithmetic"],e,t)]}normal(e){return cn(this.node(e))}rewrite(e,t,n={}){const r=this.node(e),s=this.set.view(t);if(!s.size)throw new dt(`no rules in mode "${t}" (modes: ${this.set.modes().join(", ")})`);const i=ts(r,s,{format:this.format,order:n.order,variable:n.variable});return this.result(i.node,[...this.tidyStep(r,cn(r)),...i.steps],n)}simplify(e,t={}){const n=this.node(e),r=[...this.tidyStep(n,cn(n))],s=ts(n,this.set.view("simplify"),{format:this.format});r.push(...s.steps);let i=s.node,o=null;const a=un(i),l=[],u=0===vn(i).size,c=u?null:As(a);c&&l.push({node:Ss(c),id:"simplify.cancel",name:"Cancel"});const p=ts(fn(ls(a)),this.set.view("simplify"),{format:this.format});l.push({node:p.node,id:"simplify.expand",name:"Multiply out"}),"add"!==a.k||u||l.push({node:Ss(ys(a)),id:"simplify.factor",name:"Factor"});for(const e of l)lt(e.node)<lt(i)&&(o=this.step(e.id,e.name,["shorter"],i,e.node),i=e.node);return o&&r.push(o),this.result(i,r,t)}expand(e,t={}){const n=this.node(e),r=fn(ls(un(n)));return this.result(r,n.s===r.s?[]:[this.step("expand","Multiply out",["expand"],n,r)],t)}factor(e,t={}){const n=this.node(e),r=ys(un(n)),s=Ss(r),i=[],o=r.notes.find(e=>"factor.common"===e.id);return s.s!==cn(n).s&&i.push(this.step(o?"factor.common":"factor","Factor",["factor"],n,s,o?{common:fn(o.values.common)}:{})),this.result(s,i,t)}cancel(e,t={}){const n=this.node(e),r=un(n),s=As(r);if(!s)return this.result(cn(n),this.tidyStep(n,cn(n)),t);const i=Ss(s),o=Ms(r),a=nt("/",[fn(o.num),fn(o.den)]),l=[];return"/"===n.op&&a.s===cn(n).s||l.push(this.step("together","One fraction",["together"],n,a)),i.s!==a.s&&l.push(this.step("cancel","Cancel",["cancel"],a,i,{canceled:s.canceled.length?s.canceled.map(e=>this.format(fn(e))).join(", "):"numbers"})),this.result(i,l,t)}diff(e,t,n={}){const r=this.node(e),s=this.variable(r,t);let i=r;const o=[];for(let e=0;e<(n.order??1);e++){const e=ts(nt("der",[i,Qe(s)]),this.set.view("differentiate"),{format:this.format,order:"pre"}),t=ts(e.node,this.set.view("simplify"),{format:this.format});o.push(...e.steps,...t.steps),i=t.node}return this.result(i,o,n,{variable:s})}differentiate(e,t){const n=ts(nt("der",[e,Qe(t)]),this.set.view("differentiate"),{format:this.format,order:"pre"});return ts(n.node,this.set.view("simplify"),{format:this.format}).node}integrate(e,t,n={}){let r=this.node(e);const s=e=>void 0===e?null:this.node("number"==typeof e?String(e):e);let i=s(n.from),o=s(n.to);if(st(r)&&"int"===r.op){const[e,n,s,a]=r.args;t=n.token,s&&a&&(i=s,o=a),r=e}const a=this.variable(r,t),l=Ks(this,r,a),u=ts(l.node,this.set.view("simplify"),{format:this.format}),c=[...l.steps,...u.steps];if(i&&o){const e=Xs(this,u.node,a,i,o,r);c.push(e.step);const t=ts(e.value,this.set.view("simplify"),{format:this.format});return c.push(...t.steps),this.result(t.node,c,n,{antiderivative:u.node,variable:a})}let p=u.node;return n.constant&&(p=nt("+",[p,Qe(String(n.constant))])),this.result(p,c,n,{variable:a})}solve(e,t,n={}){const r=this.node(e),s=this.variable(r,t),i=Ls(this,r,s,n);let o=i.solutions;if(n.approximate){const e="number"==typeof n.approximate?n.approximate:15;o=o.map(t=>Pr(t,{digits:e}))}const a=o.map(e=>nt("=",[Qe(s),e])),l=a.length?a.reduce((e,t)=>e?nt("|",[e,t]):t,null):null;return{solutions:o,result:l,variable:s,text:i.always?`true for every ${s}`:l?this.format(l):i.unsolved.length?`no exact solution found for ${s}`:"no solution",unsolved:i.unsolved.filter(e=>!e.always),always:i.always,steps:is(i.steps,ss(n.steps))}}solveSystem(e,t,n={}){const r=e.map(e=>this.node(e)),s=t??[...new Set(r.flatMap(e=>[...vn(e)]))].sort(),i=function(e,t,n){const r=[],s=t.map(t=>{const r=Is(t)?_t([un(t.args[0]),nn(un(t.args[1]))]):un(t),s=n.map(t=>{const n=cs(r,t);if(!n||Math.max(0,...n.keys())>1)throw new dt(`not linear in ${t}`);const s=n.get(1)??At(bt.ZERO);if(!Lt(s))throw new dt(`the coefficient of ${t} must be a number (it is ${e.format(fn(s))})`);return s.q});let i=r;for(let e=0;e<n.length;e++)i=_t([i,Wt([At(s[e].neg()),un(Qe(n[e]))])]);for(const e of n)if(ps(i,e))throw new dt(`not linear in ${e}`);return{coeffs:s,rhs:nn(i)}}),i=()=>s.map(e=>Es(fn(_t(e.coeffs.map((e,t)=>Wt([At(e),un(Qe(n[t]))])))),fn(e.rhs))).reduce((e,t)=>e?nt("&",[e,t]):t,null);let o=0;const a=[];for(let t=0;t<n.length&&o<s.length;t++){const l=s.findIndex((e,n)=>n>=o&&!e.coeffs[t].isZero);if(l<0)continue;[s[o],s[l]]=[s[l],s[o]];const u=i(),c=s[o],p=c.coeffs[t];c.coeffs=c.coeffs.map(e=>e.div(p)),c.rhs=Wt([At(p.inv()),c.rhs]);for(let e=0;e<s.length;e++){if(e===o||s[e].coeffs[t].isZero)continue;const n=s[e].coeffs[t];s[e].coeffs=s[e].coeffs.map((e,t)=>e.sub(n.mul(c.coeffs[t]))),s[e].rhs=_t([s[e].rhs,Wt([At(n.neg()),c.rhs])])}r.push(e.step("system.eliminate","Eliminate",["eliminate"],u,i(),{v:Qe(n[t])})),a.push(t),o++}for(const e of s.slice(o))if(!Lt(e.rhs)||!e.rhs.q.isZero)return{solution:null,steps:r,status:"none"};if(a.length<n.length)return{solution:null,steps:r,status:"many"};const l=new Map;return a.forEach((e,t)=>l.set(n[e],fn(s[t].rhs))),{solution:l,steps:r,status:"one"}}(this,r,s),o=i.solution?Object.fromEntries([...i.solution].map(([e,t])=>[e,t])):null,a="one"===i.status?s.map(e=>`${e} = ${this.format(o[e])}`).join(", "):"none"===i.status?"no solution":"infinitely many solutions";return{solution:o,status:i.status,text:a,steps:is(i.steps,ss(n.steps))}}substitute(e,t,n={}){const r=this.node(e);let s=r;for(const[e,n]of Object.entries(t))s=Cs(s,e,"number"==typeof n?this.node(String(n)):this.node(n));const i=this.simplify(s,n),o=[this.step("substitute","Substitute",["substitute"],r,s)];return{...i,steps:[...is(o,ss(n.steps)),...i.steps]}}defined(e){const t=this.set.view("define");return t.size?ts(e,t,{format:this.format}).node:e}approximate(e,t={}){const n=this.defined(this.node(e));if(vn(n).size&&!t.scope){const e=Pr(cn(n),t);return{result:e,text:this.format(e),number:null,exact:!1}}const r=Fr(n,t);return{result:r.node,text:r.text,number:r.number,re:r.re,im:r.im,exact:r.exact}}equivalent(e,t){const n=this.node(e),r=this.node(t),s=this.defined(nt("-",[n,r])),i=this.simplify(s,{steps:!1}).result;if("num"===i.type&&"0"===i.token)return{equal:!0,how:"exact"};const o=[...vn(s)];if(!o.length)try{return{equal:Math.abs(Fr(s,{digits:30}).number)<1e-25,how:"numeric"}}catch{return{equal:!1,how:"numeric"}}const a=[.31,1.7,2.9,-.83,.57];let l=0;for(let e=0;e<a.length;e++){const t=Object.fromEntries(o.map((t,n)=>[t,String(a[(e+n)%a.length]+n/7)]));let n;try{n=Fr(s,{digits:30,scope:t}).number}catch{continue}if(l++,Math.abs(n)>1e-20)return{equal:!1,how:"numeric"}}return{equal:l>0,how:"numeric"}}modes(){return this.set.modes()}}function di(e={}){const t=!1===e.defaults?[]:[...li,...e.complex?ui:[]],{specs:n,messages:r}=function(e){Kr();const t=[],n={};for(const r of e){const e="string"==typeof r?Yn(r):r,s=Array.isArray(e)?e:e?.rules??[];for(const t of(Array.isArray(e)?[]:e?.operators)??[]){if(!t?.symbol)throw new Error("an operator needs a symbol");_e(t.symbol)||De({symbol:String(t.symbol),arity:"any"===t.arity?Ze:Number(t.arity),label:t.label})}Object.assign(n,(Array.isArray(e)?null:e?.messages)??{});for(const e of s)t.push(e)}return{specs:t,messages:n}}([...t,...e.rules??[]]),s=St(e.complex,()=>Yr(n));return new hi(s,{...ci,...r},e.format??ni,e.read??null,Boolean(e.complex))}const fi=Symbol.for("inlinemath.expressions"),mi=new Map,gi={re:"Re",im:"Im",conj:"overline"},vi=["Re","Im","re","im","conj","arg"];function bi(e){const t=[],r=e=>{"op"===e.type?(e.args.forEach(r),n.operator(e.op)?(-1===n.operator(e.op).arity&&t.push(String(e.args.length)),t.push(e.op)):t.push(String(e.args.length),`\\:${gi[e.op]??e.op}`)):t.push(e.token)};return r(e),t}function yi(e={}){const t=e.rules||e.names?null:e.complex?"complex":"default";if(t&&mi.has(t))return mi.get(t);const r=[...e.names??[],...e.complex?vi:[]],s=di({...e,read:e=>n.parse(e,r.length?{names:r}:{}),format:ni});return t&&mi.set(t,s),s}const xi=new Set(["simplify","expand","factor","cancel","diff","integrate","solve","approx"]),wi={integral:"integrate",differentiate:"diff",approximate:"approx",simp:"simplify"};const ki=e=>String(e).replace(/&/g,"&").replace(/</g,"<").replace(/>/g,">").replace(/"/g,""");var $i='/*\n * Inline Math stylesheet. Everything is under .mv; colors are left to the page.\n *\n * The numbers marked "metric" must match the constants at the top of\n * src/layout.js (line-height 1, bar 0.06em, gap 0.1em); everything else can\n * be changed freely.\n *\n * Handy hooks:\n * .mv-n[data-node="4"] one node (ids from MathZetta)\n * .mv-var .mv-num .mv-word variables, numbers, function names\n * .mv-op-frac .mv-op-pow … a kind of operation\n * .mv-hl the class highlight() adds\n * --mv-hl highlight color\n */\n\n.mv {\n display: inline-block;\n font-family: "Inline Math Roman", "Latin Modern Roman", "STIX Two Text", "Cambria", "Times New Roman", serif;\n font-size: 1.2em;\n font-style: normal;\n font-weight: normal;\n line-height: 1; /* metric */\n white-space: nowrap;\n text-indent: 0;\n text-align: left;\n letter-spacing: 0;\n}\n.mv-display { display: block; text-align: center; margin: 0.6em 0; }\n.mv span, .mv svg { line-height: 1; }\n.mv-n { display: inline-block; border-radius: 0.12em; }\n\n/* ---- letters and signs -------------------------------------------------- */\n.mv-var { font-style: italic; padding-right: 0.03em; }\n.mv-num, .mv-word, .mv-name, .mv-ord, .mv-text, .mv-d, .mv-conj { font-style: normal; }\n.mv-prime { margin-left: 0.04em; }\n.mv-bin { margin: 0 0.22em; }\n.mv-rel { margin: 0 0.28em; }\n.mv-conj { margin: 0 0.6em; } /* x = 2 or x = 3 */\n.mv-punct { margin-right: 0.17em; }\n.mv-sign { margin-right: 0.04em; }\n.mv-times { display: inline-block; width: 0.06em; }\n.mv-callgap { display: inline-block; width: 0.05em; }\n.mv-fnspace { display: inline-block; width: 0.17em; }\n.mv-space { display: inline-block; width: 0.33em; }\n.mv-dx { display: inline-block; margin-left: 0.17em; }\n.mv-text { margin: 0 0.25em; }\n/* Tighter spacing in limits and exponents: n=1, x→0. */\n.mv-script .mv-rel, .mv-sup .mv-rel, .mv-sub .mv-rel { margin: 0 0.12em; }\n.mv-script .mv-bin, .mv-sup .mv-bin, .mv-sub .mv-bin { margin: 0 0.1em; }\n\n/* ---- fractions (metric: padding and border) ------------------------------ */\n.mv-frac { display: inline-flex; flex-direction: column; align-items: stretch; margin: 0 0.12em; }\n.mv-numer, .mv-denom { display: block; text-align: center; padding: 0 0.1em; }\n.mv-numer { padding-bottom: 0.1em; }\n.mv-denom { padding-top: 0.1em; border-top: 0.06em solid currentColor; }\n.mv-frac-nobar > .mv-denom { border-top: 0; }\n.mv-scaled { display: inline-block; }\n\n/* ---- scripts ----------------------------------------------------------------- */\n.mv-sup, .mv-sub { display: inline-block; margin-left: 0.04em; }\n.mv-subsup, .mv-limits { display: inline-flex; flex-direction: column; justify-content: space-between; align-items: flex-start; margin-left: 0.04em; }\n.mv-limits { margin-left: 0.02em; margin-right: 0.12em; }\n.mv-limits > .mv-lower { margin-left: -0.3em; }\n.mv-script { display: block; }\n.mv-under { display: inline-flex; flex-direction: column; align-items: center; margin-right: 0.15em; }\n.mv-under > .mv-script { margin-top: 0.05em; }\n.mv-bigop { display: inline-flex; flex-direction: column; align-items: center; margin: 0 0.12em; }\n.mv-bigop > .mv-script { display: block; margin: 0.08em 0; }\n.mv-bigop > svg { display: block; }\n\n/* ---- radicals (metric: border and padding-top) ----------------------------- */\n.mv-sqrt { display: inline-block; white-space: nowrap; }\n.mv-hook { display: inline-block; overflow: visible; margin-left: 0.05em; }\n.mv-radicand { display: inline-block; border-top: 0.06em solid currentColor; padding: 0.1em 0.1em 0 0.06em; }\n.mv-rootindex { display: inline-block; margin: 0 -0.32em 0 0.12em; }\n\n/* ---- delimiters: drawn at the full height of what they enclose -------------- */\n.mv-fence { display: inline-block; position: relative; }\n.mv-delim { position: absolute; top: 0; bottom: 0; height: 100%; }\n.mv-delim-l { left: 0.03em; }\n.mv-delim-r { right: 0.03em; }\nspan.mv-delim { width: 0.16em; border: 0 solid currentColor; box-sizing: border-box; }\n.mv-delim.mv-lbrack { border-width: 0.06em 0 0.06em 0.06em; left: 0.06em; }\n.mv-delim.mv-rbrack { border-width: 0.06em 0.06em 0.06em 0; right: 0.06em; }\n.mv-delim.mv-vert { border-left-width: 0.06em; width: 0; left: 0.07em; }\n.mv-delim.mv-vert.mv-delim-r { left: auto; right: 0.07em; }\n.mv-delim.mv-lfloor { border-width: 0 0 0.06em 0.06em; }\n.mv-delim.mv-rfloor { border-width: 0 0.06em 0.06em 0; }\n.mv-delim.mv-lceil { border-width: 0.06em 0 0 0.06em; }\n.mv-delim.mv-rceil { border-width: 0.06em 0.06em 0 0; }\n\n/* ---- shapes ----------------------------------------------------------------- */\n.mv svg { overflow: visible; }\n.mv svg path[stroke] { stroke-width: 0.065em; stroke-linecap: round; stroke-linejoin: round; }\n.mv-intsign path[stroke] { stroke-width: 0.075em; }\n.mv-bigsign { display: inline-block; margin: 0 0.06em; }\n.mv-intsign { margin-right: 0.12em; }\n\n/* ---- piecewise ------------------------------------------------------------- */\n.mv-cases { display: inline-grid; grid-template-columns: auto auto; column-gap: 1em; row-gap: 0.25em; align-items: baseline; text-align: left; margin: 0 0.1em; }\n.mv-case-value, .mv-case-cond { display: block; }\n.mv-matrix { display: inline-grid; column-gap: 0.8em; row-gap: 0.3em; align-items: baseline; justify-items: center; margin: 0 0.15em; }\n.mv-matrix-row { display: contents; }\n.mv-matrix-cell { display: block; }\n\n/* ---- decorations: \\boxed \\cancel \\overline \\vec … --------------------------- */\n.mv-boxed { display: inline-block; border: 0.06em solid currentColor; padding: 0.16em 0.2em; }\n.mv-over { display: inline-block; position: relative; padding-top: 0.14em; }\n.mv-over::before { content: \'\'; position: absolute; left: 0; right: 0; top: 0.21em; border-top: 0.06em solid currentColor; } /* metric */\n.mv-over-low::before { top: 0.48em; }\n.mv-underline { display: inline-block; border-bottom: 0.06em solid currentColor; padding-bottom: 0.06em; }\n.mv-cancel { display: inline-block; position: relative; }\n.mv-cancel-line { position: absolute; left: 0; top: 0; width: 100%; height: 100%; overflow: visible; pointer-events: none; }\n.mv-accent { display: inline-block; position: relative; padding-top: 0.3em; }\n.mv-accent-mark { position: absolute; top: -0.27em; left: 0; right: 0; text-align: center; font-size: 0.7em; line-height: 0.6; } /* metric: measured over F, h, A */\n/* ˆ ˜ ˙ ¨ are spacing marks that sit high in their em: full size, pulled down onto the letter */\n.mv-accent-hat, .mv-accent-widehat, .mv-accent-tilde, .mv-accent-dot, .mv-accent-ddot { font-size: 1em; line-height: 1; top: 0.02em; }\n/* over an italic letter the mark leans with it, right of the box\'s center */\n.mv-accent:has(> .mv-var) > .mv-accent-mark { transform: translateX(0.1em); }\n/* a letter with no ascender (x, u, α; layout.js adds -low): the mark comes down to its top */\n.mv-accent-low > .mv-accent-mark { top: 0.08em; }\n.mv-accent-low > .mv-accent-hat, .mv-accent-low > .mv-accent-widehat, .mv-accent-low > .mv-accent-tilde, .mv-accent-low > .mv-accent-dot, .mv-accent-low > .mv-accent-ddot { top: 0.31em; }\n\n/* ---- interaction -------------------------------------------------------------- */\n.mv-hl { background: var(--mv-hl, rgba(255, 200, 0, 0.35)); box-shadow: 0 0 0 0.08em var(--mv-hl, rgba(255, 200, 0, 0.35)); }\n/* Windows high contrast (and other forced colors) drops backgrounds and shadows: outline a highlight instead */\n@media (forced-colors: active) {\n .mv-hl { outline: 0.08em solid Highlight; outline-offset: 0.04em; }\n}\n.mv-clickable .mv-n { cursor: pointer; }\n.mv-editable .mv-n:hover { outline: 1px dashed rgba(0, 0, 0, 0.25); }\n/* the box editing a part in place (view.editable, or a Markdown textbox variable) */\n.mv-edit { transform: translateY(-50%); z-index: 1000; box-sizing: content-box; padding: 0.1em 0.35em; font-family: inherit;\n border: 1px solid #1a5fb4; border-radius: 0.25em; background: #fff; color: #111; box-shadow: 0 2px 8px rgba(0, 0, 0, 0.18); }\n.mv-edit[aria-invalid="true"] { border-color: #c33; outline: 2px solid #c33; }\n/* the live region a view announces steps through ({ announce: true }): read, never seen */\n.mv-sr-only, .mv-sr-math { position: absolute; width: 1px; height: 1px; margin: -1px; padding: 0; overflow: hidden; clip: rect(0 0 0 0); white-space: nowrap; border: 0; }\n.mv-clickable .mv-n:hover { outline: 1px dashed rgba(0, 0, 0, 0.25); }\n/* the keyboard: the expression is one tab stop, and the part the arrow keys are on is ringed */\n.mv[tabindex]:focus-visible { outline: 0.1em solid #1a5fb4; outline-offset: 0.12em; }\n.mv[tabindex]:focus .mv-focus { outline: 0.1em solid #1a5fb4; outline-offset: 0.06em; border-radius: 0.1em; }\n/* while a part is ringed, the whole expression\'s ring steps back so the part is the one that stands out */\n.mv[tabindex]:focus-visible:has(.mv-focus) { outline: 1px dashed #1a5fb4; }\n@media (forced-colors: active) {\n .mv[tabindex]:focus-visible, .mv[tabindex]:focus .mv-focus { outline-color: Highlight; }\n}\n\n/* ---- steps (stepsHTML from \'@mathzetta/inlinemath/cas\') ---------------------------------------- */\n.mv-steps { margin: 0; padding-left: 1.6em; }\n.mv-step { margin: 0.5em 0 0.9em; }\n.mv-step-name { display: block; font-size: 0.85em; font-weight: 600; color: #555; }\n.mv-step-maths { display: flex; flex-wrap: wrap; align-items: center; gap: 0.4em 0.8em; margin: 0.15em 0; }\n.mv-step-arrow { color: #888; }\n.mv-step-why { margin: 0.1em 0 0; font-size: 0.9em; color: #444; }\n\n/* ---- Markdown with math (markdownToHTML from \'@mathzetta/inlinemath/markdown\') ------------------- */\n.mv-md-math { display: inline-block; vertical-align: middle; }\n.mv-md-display { display: block; text-align: center; margin: 0.6em 0; overflow-x: auto; }\n.mv-md-block { margin: 0.8em 0; }\n.mv-md-error code { background: rgba(200, 60, 0, 0.08); color: #a33; border-bottom: 1px dotted #a33; }\n/* saved variables: $A := 2+2$ draws A ≔ 2 + 2; $A := [[…]]$ an input that sets A */\n.mv-md-input-def { display: inline-flex; align-items: center; gap: 0.3em; }\n.mv-md-assign { margin: 0 0.1em; }\n.mv-md-input { font: inherit; font-size: 0.9em; }\ninput.mv-md-textbox { font-family: inherit; padding: 0.05em 0.3em; field-sizing: content; min-width: 3ch; }\ninput.mv-md-textbox[aria-invalid="true"] { outline: 2px solid #c33; outline-offset: 1px; }\ninput.mv-md-slider { vertical-align: middle; }\n.mv-md-output { font-variant-numeric: tabular-nums; min-width: 2ch; }\n';const qi=$i;if("undefined"!=typeof document&&!document.getElementById("inlinemath-css")){const e=document.createElement("style");e.id="inlinemath-css",e.textContent=$i,document.head.append(e)}return Object.defineProperty(e,"toText",{enumerable:!0,get:function(){return s.toText}}),e.CSS=qi,e.DEFAULTS=O,e.PATHS=i,e.View=Q,e.casBlocks=function(e={}){const n=e.cas??yi(),r=void 0===e.steps?{}:{steps:e.steps},i=(e,o)=>{let a;try{a=n.read(e)}catch{return t.calculateBlock(e,o)}const l=o&&o[fi];l&&(a=a.flatMap(e=>Object.hasOwn(l,e)?l[e]:[e]));const u=a[a.length-1],c=u?.startsWith("\\:")?wi[u.slice(2)]??u.slice(2):null,p=c&&xi.has(c),h="der"===u||"int"===u;if(!p&&!h)return t.calculateBlock(e,o);const d=n.node(a),f=h&&d.op!==u,m=p?d.args:[d],g=e=>e?e.s:void 0,v=(e,t,s)=>{if(!t||"="!==t.op)return n.diff(e,g(t),{...r,order:s});const i=t.args[0].s,o=n.diff(e,i,{...r,order:s}),a=n.substitute(o.result,{[i]:t.args[1].s},r);return{...a,steps:[...o.steps??[],...a.steps??[]]}};let b;try{switch(f?"simplify-read":p?c:"der"===u?"derivative":"antiderivative"){case"simplify-read":b=n.simplify(d,r);break;case"simplify":b=n.simplify(m[0],r);break;case"expand":b=n.expand(m[0],r);break;case"factor":b=n.factor(m[0],r);break;case"cancel":b=n.cancel(m[0],r);break;case"diff":b=v(m[0],m[1],m[2]?Number(m[2].s):1);break;case"integrate":b=n.integrate(m[0],g(m[1]),{...r,...m[3]?{from:m[2].s,to:m[3].s}:{}});break;case"solve":b=n.solve(m[0],g(m[1]),r);break;case"approx":b=n.approximate(m[0],{...r,digits:m[1]?Number(m[1].s):15});break;case"derivative":b=v(d.args[0],d.args[1],1);break;default:b=n.integrate(d,void 0,r)}}catch(t){return`(${e})`}if(i.last=b,!b.result)return`"${b.text}"`;const y=s.toText(bi(b.result));return/^-?\d+(\.\d+)?$/.test(y)?y:`(${y})`};return i},e.createVariables=de,e.extractMath=ge,e.layout=I,e.markdownToHTML=function(e,t={}){return Le(xe(e,t,t.variables||null),t)},e.mathCAS=yi,e.nodeAt=P,e.numberTree=V,e.pathOf=_,e.render=function(e,t,n={}){return new Q(e,t,n)},e.renderMarkdown=Ie,e.renderMarkdownInto=function(e,t,n={}){const r=void 0===n.variables?fe:n.variables||null;ze();const s=Te.get(e);s&&s.stop(s.store!==r);let i=xe(t,n,r,e);if(e.innerHTML=Le(i,n),!r)return Te.delete(e),e;r.own(e,i.defs);let o=e.isConnected;const a=t=>{const s=t.target,i=s&&s.dataset&&s.dataset.mvVar;if(void 0!==i&&e.contains(s)){if("text"===s.type)try{J(s.value,{blocks:n.blocks,scope:{}}),s.removeAttribute("aria-invalid")}catch{return void s.setAttribute("aria-invalid","true")}r.set(i,s.value)}},l=s=>{const o=s.target.closest?.("[data-node]"),a=o&&o.closest("[data-mv-md]");if(!a||!e.contains(a))return;const l=Number(a.dataset.mvMd),u=i.trees[l];if(!u)return;const c=Number(o.dataset.node),p=_(u,c)||[];let h=null;for(let e=p.length;e>=0&&!h;e--){const t=P(u,p.slice(0,e));t&&void 0!==t.from&&(h={node:t,depth:e})}const d=h&&r.definitions().get(h.node.from);if(d&&d.input&&"textbox"===d.input.kind){s.preventDefault();const t=d.name,i=e.ownerDocument.querySelector(`[data-mv-var="${CSS.escape(t)}"]`),a=n.editable&&n.editable.toText;if(!a)return void(i&&(i.focus(),i.select()));const l=e=>J(e),c=P(u,p);return void G(o,a(ie(c,l)),{label:`Edit ${t}`,parse:e=>J(e,{blocks:n.blocks}),commit:e=>{const n=Y(ie(h.node,l),p.slice(h.depth),e);r.set(t,a(n))}})}const f=d&&i.defs.get(d.name),m=f&&f.key===d.key&&void 0!==f.start?{...i.math[l],start:f.start,end:f.end,raw:t.slice(f.start,f.end)}:i.math[l];e.dispatchEvent(new CustomEvent("inlinemath:select",{bubbles:!0,detail:{index:l,start:m.start,end:m.end,raw:m.raw,source:m.source,id:c,path:p}}))};e.addEventListener("input",a),e.addEventListener("change",a),e.addEventListener("dblclick",l);const u=r.subscribe(s=>{s!==e&&(e.isConnected?(o=!0,ze(),(()=>{const s=xe(t,n,r,e);s.drawn.forEach((t,n)=>{if(t===i.drawn[n]||s.inputs.has(n))return;const r=e.querySelector(`[data-mv-md="${n}"]`);r&&(r.outerHTML=t)});for(const t of e.querySelectorAll("[data-mv-var], [data-mv-out]")){const e=s.defs.get(t.dataset.mvVar??t.dataset.mvOut);if(!e)continue;const n=r.textOf(e);void 0!==t.dataset.mvOut?t.textContent=n:t.value!==n&&t!==t.ownerDocument?.activeElement&&(t.value=n)}i=s})()):o&&c(!0))});function c(t){u(),e.removeEventListener("input",a),e.removeEventListener("change",a),e.removeEventListener("dblclick",l),je.delete(p),Te.delete(e),t&&r.own(e,null)}const p={element:e,store:r,stop:c,connected:()=>o};return je.add(p),Te.set(e,p),e},e.select=D,e.shouldAnimate=ee,e.signature=F,e.stepsHTML=function(e,t={}){return`<ol class="mv-steps">${e.map(e=>{const n=K(bi(it(e.from)),{...t,highlight:e.path&&e.path.length?{path:e.path}:void 0}),r=e.to===e.from?"":`<span class="mv-step-arrow" aria-label="becomes">⟶</span>${K(bi(it(e.to)),t)}`,s=e.explanation?`<p class="mv-step-why">${ki(e.explanation)}</p>`:"";return`<li class="mv-step" data-rule="${ki(e.id)}"><span class="mv-step-name">${ki(e.name)}</span><div class="mv-step-maths">${n}${r}</div>${s}</li>`}).join("")}</ol>`},e.toHTML=K,e.tokensOf=bi,e.treeOf=J,e.variables=fe,e}({},MathZetta,MathZetta,MathZetta,MathZetta);
|